package com.clx.performance.config;

import com.clx.open.sdk.callback.OpenCallBackClient;
import com.clx.open.sdk.request.OpenRequestClient;
import lombok.Data;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Getter
@Configuration
@ConfigurationProperties(prefix = "third") // 配置 文件的前缀
@Slf4j
public class ThirdAppConfig implements InitializingBean {

    // 这里的名字要和yml中的对应字段名称一致
    public static Map<String, AppConfig> config = new HashMap<>();

    public Map<String, OpenCallBackClient> openCallBackClientMap = new HashMap<>();

    public Map<String, OpenRequestClient> openRequestClientMap = new HashMap<>();


    // 注意此处的 static 关键字
    public static AppConfig getConfig(String appNo) {
        return config.get(appNo);
    }

    public void setConfig(List<AppConfig> appConfigs) {
        config = appConfigs.stream().collect(Collectors.toMap(AppConfig::getAppNo, value -> value));
    }

    public OpenCallBackClient getOpenCallBackClient(String appNo) {
        OpenCallBackClient openCallBackClient = openCallBackClientMap.get(appNo);
        if (openCallBackClient == null) {
            log.info("当前appNo:{}对应的client不存在", appNo);
            throw new RuntimeException("当前appNo对应的client不存在");
        }
        return openCallBackClient;
    }

    public OpenRequestClient getOpenRequestClient(String appNo) {
        OpenRequestClient openRequestClient = openRequestClientMap.get(appNo);
        if (openRequestClient == null) {
            log.info("当前appNo:{}对应的client不存在", appNo);
            throw new RuntimeException("当前appNo对应的client不存在");
        }
        return openRequestClient;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (config.isEmpty()) {
            log.info("third app config is empty");
            return;
        }

        for (Map.Entry<String, AppConfig> entry : config.entrySet()) {
            String key = entry.getKey();
            AppConfig value = entry.getValue();
            openCallBackClientMap.put(key, new OpenCallBackClient(value.getUrl(), value.getAppNo(), value.getSecret()));
            openRequestClientMap.put(key, new OpenRequestClient(value.getUrl(), value.getAppNo(), value.getSecret()));
        }
    }

    @Data
    public static class AppConfig {

        private String appNo;
        private String secret;
        private String url;
    }


}
