package com.usky.system.service.impl;


import com.usky.common.core.constants.Constants;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.core.util.Convert;
import com.usky.common.core.util.StringUtils;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.common.redis.core.RedisHelper;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.system.domain.SysConfig;
import com.usky.system.domain.constants.UserConstants;
import com.usky.system.mapper.SysConfigMapper;
import com.usky.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * 参数配置 服务层实现
 * 
 * @author yq
 */
@Service
public class SysConfigServiceImpl extends AbstractCrudService<SysConfigMapper, SysConfig> implements ISysConfigService
{
    @Autowired
    private SysConfigMapper configMapper;

    @Autowired
    private RedisHelper redisHelper;

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

    /**
     * 查询参数配置信息
     * 
     * @param configId 参数配置ID
     * @return 参数配置信息
     */
    @Override
    public SysConfig selectConfigById(Long configId)
    {
        SysConfig config = new SysConfig();
        config.setConfigId(configId);
        return configMapper.selectConfig(config);
    }

    /**
     * 根据键名查询参数配置信息
     * 
     * @param configKey 参数key
     * @return 参数键值
     */
    @Override
    public String selectConfigByKey(String configKey)
    {
        Integer tenantId = SecurityUtils.getTenantId();
        String configKey1 = configKey+tenantId;
        String configValue = Convert.toStr(redisHelper.get(getCacheKey(configKey1)));
        if (StringUtils.isNotEmpty(configValue))
        {
            return configValue;
        }
        SysConfig config = new SysConfig();
        config.setConfigKey(configKey);
        config.setTenantId(tenantId);
        SysConfig retConfig = configMapper.selectConfig(config);
        if (Objects.nonNull(retConfig))
        {
            redisHelper.set(getCacheKey(configKey1), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    /**
     * 获取验证码开关
     * 
     * @return true开启，false关闭
     */
    @Override
    public boolean selectCaptchaOnOff()
    {
        String captchaOnOff = selectConfigByKey("sys.account.captchaOnOff");
        if (StringUtils.isEmpty(captchaOnOff))
        {
            return true;
        }
        return Convert.toBool(captchaOnOff);
    }

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

    /**
     * 新增参数配置
     * 
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int insertConfig(SysConfig config)
    {
        int row = configMapper.insertConfig(config);
        if (row > 0)
        {
            redisHelper.set(getCacheKey(config.getConfigKey()+SecurityUtils.getTenantId()), config.getConfigValue());
        }
        return row;
    }

    /**
     * 修改参数配置
     * 
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public int updateConfig(SysConfig config)
    {
        int row = configMapper.updateConfig(config);
        if (row > 0)
        {
            redisHelper.set(getCacheKey(config.getConfigKey()+SecurityUtils.getTenantId()), config.getConfigValue());
        }
        return row;
    }

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

    /**
     * 加载参数缓存数据
     */
    @Override
    public void loadingConfigCache()
    {
        SysConfig config1 = new SysConfig();
        config1.setTenantId(SecurityUtils.getTenantId());
        List<SysConfig> configsList = configMapper.selectConfigList(config1);
        for (SysConfig config : configsList)
        {
            redisHelper.set(getCacheKey(config.getConfigKey()+SecurityUtils.getTenantId()), config.getConfigValue());
        }
    }

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

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

    /**
     * 校验参数键名是否唯一
     * 
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public String checkConfigKeyUnique(SysConfig config)
    {
        Long configId = Objects.isNull(config.getConfigId()) ? -1L : config.getConfigId();
        SysConfig info = configMapper.checkConfigKeyUnique(config.getConfigKey(), config.getTenantId());
        if (Objects.nonNull(info) && info.getConfigId().longValue() != configId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

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