package com.dsk.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsk.common.constant.CacheNames;
import com.dsk.common.constant.TenantConstants;
import com.dsk.common.constant.UserConstants;
import com.dsk.common.core.domain.PageQuery;
import com.dsk.common.core.domain.model.DskAccessTokenVO;
import com.dsk.common.core.page.TableDataInfo;
import com.dsk.common.core.service.ConfigService;
import com.dsk.common.exception.ServiceException;
import com.dsk.common.tenant.helper.TenantHelper;
import com.dsk.common.utils.JsonUtils;
import com.dsk.common.utils.StringUtils;
import com.dsk.common.utils.redis.CacheUtils;
import com.dsk.common.utils.spring.SpringUtils;
import com.dsk.system.domain.SysConfig;
import com.dsk.system.domain.SysTenant;
import com.dsk.system.mapper.SysConfigMapper;
import com.dsk.system.mapper.SysTenantMapper;
import com.dsk.system.service.ISysConfigService;
import jodd.bean.BeanException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 参数配置 服务层实现
 *
 * @author Lion Li
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysConfigServiceImpl implements ISysConfigService, ConfigService {

    private final SysConfigMapper baseMapper;

    private final SysTenantMapper tenantMapper;

    @Override
    public TableDataInfo<SysConfig> selectPageConfigList(SysConfig config, PageQuery pageQuery) {
        Map<String, Object> params = config.getParams();
        LambdaQueryWrapper<SysConfig> lqw = new LambdaQueryWrapper<SysConfig>()
                .like(StringUtils.isNotBlank(config.getConfigName()), SysConfig::getConfigName, config.getConfigName())
                .eq(StringUtils.isNotBlank(config.getConfigType()), SysConfig::getConfigType, config.getConfigType())
                .like(StringUtils.isNotBlank(config.getConfigKey()), SysConfig::getConfigKey, config.getConfigKey())
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        SysConfig::getCreateTime, params.get("beginTime"), params.get("endTime"));
        Page<SysConfig> page = baseMapper.selectPage(pageQuery.build(), lqw);
        return TableDataInfo.build(page);
    }

    /**
     * 查询参数配置信息
     *
     * @param configId 参数配置ID
     * @return 参数配置信息
     */
    @Override
    @DS("master")
    public SysConfig selectConfigById(Long configId) {
        return baseMapper.selectById(configId);
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Cacheable(cacheNames = CacheNames.SYS_CONFIG, key = "#configKey")
    @Override
    public String selectConfigByKey(String configKey) {
        SysConfig retConfig = baseMapper.selectOne(new LambdaQueryWrapper<SysConfig>()
                .eq(SysConfig::getConfigKey, configKey));
        if (ObjectUtil.isNotNull(retConfig)) {
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

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

    /**
     * 查询参数配置列表
     *
     * @param config 参数配置信息
     * @return 参数配置集合
     */
    @Override
    public List<SysConfig> selectConfigList(SysConfig config) {
        Map<String, Object> params = config.getParams();
        LambdaQueryWrapper<SysConfig> lqw = new LambdaQueryWrapper<SysConfig>()
                .like(StringUtils.isNotBlank(config.getConfigName()), SysConfig::getConfigName, config.getConfigName())
                .eq(StringUtils.isNotBlank(config.getConfigType()), SysConfig::getConfigType, config.getConfigType())
                .like(StringUtils.isNotBlank(config.getConfigKey()), SysConfig::getConfigKey, config.getConfigKey())
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        SysConfig::getCreateTime, params.get("beginTime"), params.get("endTime"));
        return baseMapper.selectList(lqw);
    }

    /**
     * 新增参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @CachePut(cacheNames = CacheNames.SYS_CONFIG, key = "#config.configKey")
    @Override
    public String insertConfig(SysConfig config) {
        int row = baseMapper.insert(config);
        if (row > 0) {
            return config.getConfigValue();
        }
        throw new ServiceException("操作失败");
    }

    /**
     * 新增参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public void insertTenantConfig(SysConfig config) {
        //重复验证
        boolean exists = baseMapper.exists(Wrappers.<SysConfig>lambdaQuery().eq(SysConfig::getConfigKey, config.getConfigKey()));
        if(exists){
            throw new BeanException("当前配置键已存在！");
        }

        List<SysConfig> list = new ArrayList<>();
        SysConfig admin = new SysConfig();
        BeanUtil.copyProperties(config, admin);
        admin.setTenantId(TenantConstants.DEFAULT_TENANT_ID);
        list.add(admin);

        List<SysTenant> sysTenants = tenantMapper.selectList();
        if (!CollectionUtils.isEmpty(sysTenants)) {
            for (SysTenant sysTenant : sysTenants) {
                SysConfig bean = new SysConfig();
                BeanUtil.copyProperties(config, bean);
                bean.setTenantId(sysTenant.getTenantId());
                list.add(bean);
            }
        }

        boolean b = baseMapper.insertBatch(list);
        if (!b) {
            throw new ServiceException("操作失败");
        }
    }

    /**
     * 修改参数配置
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @CachePut(cacheNames = CacheNames.SYS_CONFIG, key = "#config.configKey")
    @Override
    public String updateConfig(SysConfig config) {
        int row = 0;
        if (config.getConfigId() != null) {
            SysConfig temp = baseMapper.selectById(config.getConfigId());
            if (!StringUtils.equals(temp.getConfigKey(), config.getConfigKey())) {
                CacheUtils.evict(CacheNames.SYS_CONFIG, temp.getConfigKey());
            }
            row = baseMapper.updateById(config);
        } else {
            row = baseMapper.update(config, new LambdaQueryWrapper<SysConfig>()
                    .eq(SysConfig::getConfigKey, config.getConfigKey()));
        }
        if (row > 0) {
            return config.getConfigValue();
        }
        throw new ServiceException("操作失败");
    }

    /**
     * 批量删除参数信息
     *
     * @param configIds 需要删除的参数ID
     */
    @Override
    public void deleteConfigByIds(Long[] configIds) {
        for (Long configId : configIds) {
            SysConfig config = selectConfigById(configId);
            if (StringUtils.equals(UserConstants.YES, config.getConfigType())) {
                throw new ServiceException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey()));
            }
            CacheUtils.evict(CacheNames.SYS_CONFIG, config.getConfigKey());
        }
        baseMapper.deleteBatchIds(Arrays.asList(configIds));
    }

    /**
     * 加载参数缓存数据
     */
    @Override
    public void loadingConfigCache() {
        List<SysConfig> configsList = selectConfigList(new SysConfig());
        configsList.forEach(config ->
                CacheUtils.put(CacheNames.SYS_CONFIG, config.getConfigKey(), config.getConfigValue()));
    }

    /**
     * 清空参数缓存数据
     */
    @Override
    public void clearConfigCache() {
        CacheUtils.clear(CacheNames.SYS_CONFIG);
    }

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

    /**
     * 校验参数键名是否唯一
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public boolean checkConfigKeyUnique(SysConfig config) {
        long configId = ObjectUtil.isNull(config.getConfigId()) ? -1L : config.getConfigId();
        SysConfig info = baseMapper.selectOne(new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getConfigKey, config.getConfigKey()));
        if (ObjectUtil.isNotNull(info) && info.getConfigId() != configId) {
            return false;
        }
        return true;
    }

    @Override
    public DskAccessTokenVO getDskAccessToken() {
        List<SysConfig> dskName = queryListByKey("dsk");
        Assert.notEmpty(dskName, "大司空数据APPkey配置异常");
        Map<String, Object> dskConfig = new HashMap<>();
        for (SysConfig sysConfig : dskName) {
            dskConfig.put(sysConfig.getConfigKey(), sysConfig.getConfigValue());
        }

        String domain = (String) dskConfig.get("dsk-Domain");
        String accessTokenAPI = (String) dskConfig.get("dsk-accessTokenAPI");
        String appkey = (String) dskConfig.get("dsk-Appkey");
        String appSecret = (String) dskConfig.get("dsk-AppSecret");


        Map<String, Object> dskAccessTokenDto = new HashMap<>();
        dskAccessTokenDto.put("appKey", appkey);
        dskAccessTokenDto.put("appSecret", appSecret);

        String post = HttpUtil.post("https://"+domain + accessTokenAPI, JsonUtils.toJsonString(dskAccessTokenDto));
        Assert.notEmpty(post, "大司空数据accessTokenAPI响应异常");
        log.info("大司空数据accessToken API响应:" + post);
        Dict dict = JsonUtils.parseMap(post);
        Object dataObj = dict.getObj("data");
        if (dict.getInt("code") != 200 || ObjectUtil.isEmpty(dataObj)) {
            throw new ServiceException("API数据accessTokenAPI响应异常", 500);
        }
        return BeanUtil.toBean(dataObj, DskAccessTokenVO.class);
    }

    /**
     * 根据参数 key 获取参数值
     *
     * @param configKey 参数 key
     * @return 参数值
     */
    @Override
    public String getConfigValue(String configKey) {
        return SpringUtils.getAopProxy(this).selectConfigByKey(configKey);
    }


    public List<SysConfig> queryListByKey(String keyName) {
        LambdaQueryWrapper<SysConfig> dsk = new LambdaQueryWrapper<SysConfig>().likeRight(SysConfig::getConfigKey, keyName);
        return TenantHelper.ignore(() -> baseMapper.selectList(dsk));
    }

}
