package com.czg.service.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.czg.exception.CzgException;
import com.czg.resp.CzgResult;
import com.czg.sa.StpKit;
import com.czg.service.system.mapper.SysParamsMapper;
import com.czg.system.dto.SysParamsDTO;
import com.czg.system.entity.SysParams;
import com.czg.system.service.SysParamsService;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;

import java.util.*;

/**
 * 服务层实现。
 *
 * @author mac
 * @since 2025-02-07
 */
@Slf4j
@DubboService
public class SysParamsServiceImpl extends ServiceImpl<SysParamsMapper, SysParams> implements SysParamsService {

    @Override
    public CzgResult<List<SysParamsDTO>> getParamsByType(Integer type) {
        List<SysParams> sysParamsList = list(new QueryWrapper().eq(SysParams::getParamType, type));
        List<SysParamsDTO> sysParamsDTOList = new ArrayList<>();
        for (SysParams sysParams : sysParamsList) {
            sysParamsDTOList.add(BeanUtil.toBean(sysParams, SysParamsDTO.class));
        }
        return CzgResult.success(sysParamsDTOList);
    }

    @Override
    public CzgResult<String> insertParams(SysParamsDTO paramsDTO) {
        // 查询 paramCode 是否存在
        SysParams sysParams = getOne(new QueryWrapper().eq(SysParams::getParamCode, paramsDTO.getParamCode()));
        if (sysParams != null) {
            return CzgResult.failure("参数编码已存在");
        }

        Long userId = StpKit.USER.getLoginId(1L);

        // 新增参数
        sysParams = new SysParams();
        sysParams.setParamCode(paramsDTO.getParamCode())
                .setParamValue(paramsDTO.getParamValue())
                .setParamType(paramsDTO.getParamType())
                .setRemark(paramsDTO.getRemark())
                .setCreateUserId(userId);

        save(sysParams);

        return CzgResult.success(sysParams.getParamCode());
    }

    @Override
    @Caching(evict = {
            @CacheEvict(cacheNames = "params:entity", allEntries = true),
            @CacheEvict(cacheNames = "params", key = "#paramsDTO.paramCode")
    })
    public CzgResult<String> updateParams(SysParamsDTO paramsDTO) {
        // 查询 paramCode 是否存在
        SysParams sysParams = getOne(new QueryWrapper().eq(SysParams::getParamCode, paramsDTO.getParamCode())
                .ne(SysParams::getParamCode, paramsDTO.getParamCode()));
        if (sysParams != null) {
            return CzgResult.failure("参数编码已存在");
        }

        Long userId = StpKit.USER.getLoginId(1L);

        // 修改参数
        sysParams = getById(paramsDTO.getParamCode());

        if (!sysParams.getParamCode().equals(paramsDTO.getParamCode())) {
            return CzgResult.failure("参数编码不能修改");
        }
        sysParams.setParamValue(paramsDTO.getParamValue())
                .setParamType(paramsDTO.getParamType())
                .setRemark(paramsDTO.getRemark())
                .setUpdateUserId(userId);

        updateById(sysParams);

        return CzgResult.success(sysParams.getParamCode());
    }

    @Override
    @Caching(evict = {
            @CacheEvict(cacheNames = "params:entity", allEntries = true),
            @CacheEvict(cacheNames = "params", key = "#code")
    })
    public CzgResult<Boolean> deleteParams(String code) {
        SysParams sysParams = getById(code);
        if (sysParams == null) {
            return CzgResult.failure("参数不存在");
        }

        removeById(code);
        return CzgResult.success(true);
    }

    @Override
    public CzgResult<SysParamsDTO> getParamsByCode(String code) {
        SysParams sysParams = getMapper().getSysParam(code);
        if (sysParams == null) {
            return CzgResult.failure("参数不存在");
        }

        SysParamsDTO sysParamsDTO = BeanUtil.toBean(sysParams, SysParamsDTO.class);

        return CzgResult.success(sysParamsDTO);
    }

    private SysParams getSysParam(String code) {
        return getMapper().getSysParam(code);
    }

    @Override
    public String getSysParamValue(String code) {
        SysParams sysParam = getSysParam(code);
        if (sysParam == null) {
            log.error("参数不存在，参数编码：{}", code);
            return "";
        }
        if (sysParam.getParamValue() == null) {
            log.error("参数值为空，参数编码：{}", code);
            return "";
        }
        return sysParam.getParamValue();
    }

    @Cacheable(cacheNames = "params:entity", key = "#type")
    @Override
    public Map<String, String> getParamsByMap(String type, Set<String> keyList) throws CzgException {
        Map<String, String> map = new HashMap<>();
        for (String key : keyList) {
            SysParams sysParam = getSysParam(key);
            if (sysParam == null || StrUtil.isBlank(sysParam.getParamValue())) {
                throw new CzgException("sysParam的类型" + type + " 的 " + key + "参数不存在");
            }
            map.put(key, sysParam.getParamValue());
        }
        return map;
    }

    @Cacheable(cacheNames = "params:paramType", key = "#paramType")
    @Override
    public List<SysParamsDTO> getByParamType(String paramType) throws CzgException {
        return listAs(query().eq(SysParams::getParamType, paramType), SysParamsDTO.class);
    }
}
