package com.shkj.system.service.impl;

import com.shkj.common.annotation.DataSource;
import com.shkj.common.constant.Constants;
import com.shkj.common.constant.UserConstants;
import com.shkj.common.core.redis.RedisCache;
import com.shkj.common.core.text.Convert;
import com.shkj.common.enums.DataSourceType;
import com.shkj.common.exception.ServiceException;
import com.shkj.common.utils.SecurityUtils;
import com.shkj.common.utils.StringUtils;
import com.shkj.system.mapper.SysParameterMapper;
import com.shkj.system.service.ISysParameterService;
import com.shkj.system.domain.SysParameter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;


/**
 * 参数配置 服务层实现
 *
 * @author lch
 */
@Service
public class SysParameterServiceImpl implements ISysParameterService {
    @Autowired
    private SysParameterMapper configMapper;

    @Autowired
    private RedisCache redisCache;

    /**
     * 项目启动时，初始化参数到缓存
     */
//    @PostConstruct
    public void init() {
        loadingConfigCache();
    }

    /**
     * 查询参数配置信息
     *
     * @param configId 参数配置ID
     * @return 参数配置信息
     */
    @Override
    @DataSource(DataSourceType.MASTER)
    public SysParameter selectConfigById(Long configId) {
        SysParameter config = new SysParameter();
        config.setId(configId);
        config.setBranchId(SecurityUtils.getCurrentBranchId());
        return configMapper.selectConfig(config);
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Override
    public String selectConfigByKey(String configKey) {
        String configValue = Convert.toStr(redisCache.getCacheObject(getCacheKey(configKey, SecurityUtils.getCurrentBranchId())));
        if (StringUtils.isNotEmpty(configValue)) {
            return configValue;
        }
        SysParameter config = new SysParameter();
        config.setParaCode(configKey);
        config.setBranchId(SecurityUtils.getCurrentBranchId());
        SysParameter retConfig = configMapper.selectConfig(config);
        if (StringUtils.isNotNull(retConfig)) {
            redisCache.setCacheObject(getCacheKey(configKey, SecurityUtils.getCurrentBranchId()), retConfig.getParaValue());
            return retConfig.getParaValue();
        }
        return StringUtils.EMPTY;
    }

    @Override
    public String selectConfigByKey(Long branchId, String configKey) {
        SysParameter config = new SysParameter();
        config.setParaCode(configKey);
        config.setBranchId(branchId);
        SysParameter retConfig = configMapper.selectConfig(config);
        if (StringUtils.isNotNull(retConfig)) {
            redisCache.setCacheObject(getCacheKey(configKey,branchId), retConfig.getParaValue());
            return retConfig.getParaValue();
        }
        return StringUtils.EMPTY;
    }


    @Override
    public String selectErpConfigByKey(String configKey) {
        String configValue = Convert.toStr(redisCache.getCacheObject(getCacheKey(configKey, 0L)));
        if (StringUtils.isNotEmpty(configValue)) {
            return configValue;
        }
        SysParameter config = new SysParameter();
        config.setParaCode(configKey);
        config.setBranchId(0L);
        SysParameter retConfig = configMapper.selectConfig(config);
        if (StringUtils.isNotNull(retConfig)) {
            redisCache.setCacheObject(getCacheKey(configKey, 0L), retConfig.getParaValue());
            return retConfig.getParaValue();
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取验证码开关
     *
     * @return true开启，false关闭
     */
    @Override
    public boolean selectCaptchaOnOff() {
        String configKey = "sys.account.captchaOnOff";
        String configValue = Convert.toStr(redisCache.getCacheObject(getCacheKey(configKey,0L)));
        if (StringUtils.isNotEmpty(configValue)) {
            return Convert.toBool(configValue);
        }
        SysParameter config = new SysParameter();
        config.setParaCode(configKey);
        config.setBranchId(0L);
        SysParameter retConfig = configMapper.selectConfig(config);
        if (StringUtils.isNotNull(retConfig)) {
            redisCache.setCacheObject(getCacheKey(configKey, 0L), retConfig.getParaValue());
            return Convert.toBool(retConfig.getParaValue());
        }
        return true;
    }

    /**
     * 查询参数配置列表
     *
     * @param config 参数配置信息
     * @return 参数配置集合
     */
    @Override
    public List<SysParameter> selectConfigList(SysParameter config) {
        config.setBranchId(SecurityUtils.getCurrentBranchId());
        return configMapper.selectConfigList(config);
    }

    /**
     * 新增参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int insertConfig(SysParameter config) {
        config.setBranchId(SecurityUtils.getCurrentBranchId());
        int row = configMapper.insertConfig(config);
        if (row > 0) {
            redisCache.setCacheObject(getCacheKey(config.getParaCode(), SecurityUtils.getCurrentBranchId()), config.getParaValue());
        }
        return row;
    }

    /**
     * 修改参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int updateConfig(SysParameter config) {
        config.setBranchId(SecurityUtils.getCurrentBranchId());
        int row = configMapper.updateConfig(config);
        if (row > 0) {
            redisCache.setCacheObject(getCacheKey(config.getParaCode(), SecurityUtils.getCurrentBranchId()), config.getParaValue());
        }
        return row;
    }

    /**
     * 批量删除参数信息
     *
     * @param configIds 需要删除的参数ID
     * @return 结果
     */
    @Override
    public void deleteConfigByIds(Long[] configIds) {
        for (Long configId : configIds) {
            SysParameter config = selectConfigById(configId);
            if (StringUtils.equals(UserConstants.YES, config.getParaType())) {
                throw new ServiceException(String.format("内置参数【%1$s】不能删除 ", config.getParaCode()));
            }
            configMapper.deleteConfigById(configId);
            redisCache.deleteObject(getCacheKey(config.getParaCode(), SecurityUtils.getCurrentBranchId()));
        }
    }

    /**
     * 加载参数缓存数据
     */
    @Override
    public void loadingConfigCache() {
        List<SysParameter> configsList = configMapper.selectConfigList(new SysParameter());
        for (SysParameter config : configsList) {
            redisCache.setCacheObject(getCacheKey(config.getParaCode(), config.getBranchId()), config.getParaValue());
        }
    }

    /**
     * 清空参数缓存数据
     */
    @Override
    public void clearConfigCache() {
        Collection<String> keys = redisCache.keys(Constants.SYS_CONFIG_KEY + SecurityUtils.getCurrentBranchId() + "_" + "*");
        redisCache.deleteObject(keys);
    }

    /**
     * 重置参数缓存数据
     */
    @Override
    public void resetConfigCache() {
        clearConfigCache();
        loadingConfigCache();
    }

    /**
     * 校验参数键名是否唯一
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public String checkConfigKeyUnique(SysParameter config) {
        Long configId = StringUtils.isNull(config.getId()) ? -1L : config.getId();
        SysParameter info = configMapper.checkConfigKeyUnique(config.getParaCode(), SecurityUtils.getCurrentBranchId());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != configId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey, Long branchId) {
        return Constants.SYS_CONFIG_KEY + branchId + "_" + configKey;
    }
}
