package cn.com.qmth.stmms.ms.core.cache;

import cn.com.qmth.stmms.ms.core.domain.ParamSetting;
import cn.com.qmth.stmms.ms.core.repository.ParamSettingRepo;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ParamCache {
    private static final Logger LOGGER = LoggerFactory.getLogger(ParamCache.class);

    public static Map<Long, ParamSetting> paramMap = new HashMap<>();

    @Autowired
    private ParamSettingRepo paramSettingRepo;

    @PostConstruct
    public void init() {
        //系统启动中。。。加载codeMap
        List<ParamSetting> paramSettings = paramSettingRepo.findAll();
        for (ParamSetting param : paramSettings) {
            paramMap.put(param.getWorkId(), param);
        }
        LOGGER.info("加载参数成功：{}", JSONObject.toJSONString(paramMap));
    }

    @PreDestroy
    public void destroy() {
        //系统运行结束
        paramMap.clear();
    }

    public static void resetParam(ParamSetting paramSetting) {
        paramMap.put(paramSetting.getWorkId(), paramSetting);
        LOGGER.info("修改参数后重新加载成功：{}", JSONObject.toJSONString(paramMap));
    }
}
