package com.ssj.sys.utils;

import com.ssj.framework.basic.config.bean.Config;
import com.ssj.framework.basic.config.service.ConfigService;
import com.ssj.framework.core.util.RedisUtil;
import com.ssj.framework.core.util.SystemResourceLocator;
import org.springframework.stereotype.Component;

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


/**
 *
 * 类名称：SystemResourceLocator<br>
 * 类描述：系统属性资源存储类.<br>
 * 便于在其他地方调用,但添加的时候不能有重名.除非显示调用需要覆盖的接口<br>
 * @version v1.0
 *
 */

@Component
public class SystemResource extends SystemResourceLocator {


    /**
     * 项目启动时加载数
     * 启动各子项目时：全量添加到redis，为保证数据的统一，覆盖旧数据，其它系统更新config配置的时候一定要先同步更新到数据库
     */
    @PostConstruct
    public void  init() {
        //启动各子项目时：全量添加到redis，为保证数据的统一，覆盖旧数据，其它系统更新配置的时候一定要先同步更新到数据库
        redisUtil= (RedisUtil) SystemResourceLocator.getBean(RedisUtil.class);
        Map<Object,Object>  resourceMap= new ResourceReaderTable().readResource();
        Set<Object> keySets= resourceMap.keySet();
        for (Object key:keySets) {
            redisUtil.set(key.toString(), resourceMap.get(key).toString());
        }
    }


    /**
     * 刷新系统的配置属性.清空原来的属性值,并从系统属性文件和属性表中读取最新值.
     */
    public synchronized static void refresh() {
        Map<Object,Object>  resourceMap= new SystemResource().new ResourceReaderTable().readResource();
        Set<Object> keySets= resourceMap.keySet();
        for (Object key:keySets) {
            redisUtil.set(key.toString(), resourceMap.get(key).toString());
        }
    }

    private class ResourceReaderTable implements ResourceReader {
        private final Map<Object, Object> map = new HashMap<Object, Object>();

        public Map<Object, Object> readResource() {
            ConfigService sysConfigService =  SystemResourceLocator.getBean(ConfigService.class);
            List<Config> list = sysConfigService.findAll();
            // 属性表中的编码和编码值放到map中
            for (Config config : list) {
                map.put(config.getParamCode(), config.getParamVal());
            }
            return map;
        }

    }


    private interface ResourceReader {
        Map<Object, Object> readResource();
    }



}
