package digital.laboratory.platform.entrustment.handler;

import digital.laboratory.platform.common.core.constant.CommonConstants;
import digital.laboratory.platform.common.core.util.R;
import digital.laboratory.platform.sys.entity.Dictionary;
import digital.laboratory.platform.sys.feign.RemoteDictionaryService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * App 启动类
 * 当 Spring Application 启动完成后, 会调用这个类的 run() 方法进行一些最后的初始化。
 * 我们在这个方法中从数据库加载一些全局的配置
 *
 * @author Zhang Xiaolong
 */

@Component
@RequiredArgsConstructor
public class AppStartupRunner implements ApplicationRunner {
	@Value("${dlp.entrustment.entrustmentLetterTemplate}")
	public static String entrustmentLetterTemplate;

	private final RemoteDictionaryService remoteDictionaryService;

	public static Map<String, String> entrustmentConfig  = new HashMap<>();
	public static Map<String, Dictionary> thirdSysConfig  = new HashMap<>();

	public static String getCfg(String code) {
		return entrustmentConfig.get(code);
	}
	public static Dictionary getThirdSysCfg(String key) {
		return thirdSysConfig.get(key);
	}

	/**
	 *
	 * @param args 参数
	 * @throws Exception 异常
	 *
	 * 	// @SysLog("委托受理模块初始化") 这里不能使用 @SysLog(), 因为 SysLog 还没有初始化
	 */
	@Override
	public void run(ApplicationArguments args) throws Exception {
//		BusinessCodeUtils.removeSymbols("x-*/）——0*&……%￥#@xasdf!*&^&%^ 中文、/+)(（）\n\\xx\rx");

		{
			// 加载 entrustment 在字典中的配置
			loadDictData(CommonConstants.DLP_TYPE_ENTRUSTMENT,1);
			//加载第三方系统的对接信息
			loadDictData("920f9dd9cd14281e8b488a34c649ff70",2);

			for (String key : entrustmentConfig.keySet()) {
				System.out.println(String.format("entrustmentConfig[%s]=%s", key, entrustmentConfig.get(key)));
			}
		}
	}
	//读取的数据添加到配置中
	public  void loadDictData(String type,int loadWhere)
	{
		R<List<Dictionary>> r = remoteDictionaryService.getDictionaryByType(type);
		if (Optional.ofNullable(r).isPresent() && (r.getData() != null)) {
			List<Dictionary> itemList =  r.getData();
			if(loadWhere==1)
			{
				for (Dictionary item : itemList) {
					entrustmentConfig.put(item.getCode(), item.getLabel());
				}
			}
			if(loadWhere==2)
			{
				for (Dictionary item : itemList) {
					thirdSysConfig.put(item.getLabel(),item);
				}
			}

		}
	}
}
