package com.zehong.framework.systemsetting;

import com.zehong.system.domain.SysSetting;
import com.zehong.system.service.ISysSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

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

/**
 * @author gengd
 * 启动时加载数据库初始化系统配置
 */
@Component
public class SystemSetting implements CommandLineRunner {

    /**
     * 系统配置是否启用 0启用 1禁用
     */
    private final String IS_ACTIVE = "0";

    /**
     * 系统类型 0后台 1前台
     */
    private final String SYSTEM_TYPE = "0";

    /**
     * 后台系统配置参数
     */
    private Map<String,String> systemServiceSettingMap = new HashMap<>(256);

    /**
     * 前台系统配置参数
     */
    private Map<String,String> systemWebSettingMap = new HashMap<>(256);

    @Autowired
    private ISysSettingService iSysSettingService;

    @Override
    public void run(String... args) throws Exception {
        setSystemSettingMap();
    }

    /**
     * 刷新系统配置
     */
    public void freshSettings(){
        systemServiceSettingMap.clear();
        systemWebSettingMap.clear();
        setSystemSettingMap();
    }

    /**
     * 加载数据库系统配置，放入系统缓存
     */
    private void setSystemSettingMap(){
        SysSetting sysSetting = new SysSetting();
        sysSetting.setIsDel(IS_ACTIVE);
        List<SysSetting> sysSettingList = iSysSettingService.selectSysSettingList(sysSetting);
        for(SysSetting setting : sysSettingList){
            if (SYSTEM_TYPE.equals(setting.getSystemType())) {
                systemServiceSettingMap.put(setting.getSystemKey(), setting.getSystemValue());
            } else {
                systemWebSettingMap.put(setting.getSystemKey(), setting.getSystemValue());
            }
        }
    }

    /**
     * 获取后台系统参数
     * @param systemKey 系统参数key
     * @return
     */
    public String getSystemServiceSetting(String systemKey){
        return systemServiceSettingMap.get(systemKey);
    }

    /**
     * 获取前台参数
     * @return
     */
    public Map<String,String> getSystemWebSetting(){
        return systemWebSettingMap;
    }
}
