package com.mortals.xhx.utils;

import com.alibaba.fastjson.JSONObject;
import com.mortals.xhx.feign.system.param.IParamFeign;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author karlhoo
 */
@Component
@CommonsLog
@ConditionalOnProperty("spring.cloud.stream.bindings.system-param-input.destination")
public class GlobalSystemParamUtil {
    @Autowired
    @SuppressWarnings("all")
    private IParamFeign paramFeign;
    private static Map<String, String> paramMap = new ConcurrentHashMap<>(16);

    public static String getParamStringValue(String key) {
        return paramMap.get(key);
    }


    public static String getParamStringValue(String key,String defaultValue) {
        if(StringUtils.isEmpty(paramMap.get(key))){
            return defaultValue;
        }
        return paramMap.get(key);
    }

    public static Long getParamLongValue(String key) {
        try {
            return Long.parseLong(paramMap.get(key));
        } catch (Exception e) {
            return null;
        }
    }

    public static Integer getParamIntValue(String key) {
        try {
            return Integer.parseInt(paramMap.get(key));
        } catch (Exception e) {
            return null;
        }
    }


    public static Integer getParamIntValue(String key,Integer defaultValue) {
        if(StringUtils.isEmpty(paramMap.get(key))){
            return defaultValue;
        }
        return Integer.parseInt(paramMap.get(key));
    }

    @PostConstruct
    public void init() {
        log.info("开始加载系统参数...");
        String paramString = paramFeign.getAllParamValue();
        if (ObjectUtils.isEmpty(paramString)) {
            log.info("系统参数加载完成，size:0");
            return;
        }
        JSONObject jsonObject = JSONObject.parseObject(paramString);
        if (!jsonObject.isEmpty()) {
            jsonObject.keySet().forEach(k -> paramMap.put(k, jsonObject.getString(k)));
        }
        log.info("系统参数加载完成，size:" + paramMap.size());
    }

/*    public void updateParam(ParamEntity param) {
        log.info("更新系统参数 key:" + param.getParamKey() + " value:" + param.getParamValue());
        paramMap.put(param.getParamKey(), param.getParamValue());
    }*/
}
