package cn.gov.customs.wxjy.system.service.impl;

import cn.gov.customs.wxjy.common.constant.UserConstants;
import cn.gov.customs.wxjy.common.utils.DictUtils;
import cn.gov.customs.wxjy.common.utils.StringUtils;
import cn.gov.customs.wxjy.common.utils.uuid.SnowflakeIdWorker;
import cn.gov.customs.wxjy.system.dao.DictDataDao;
import cn.gov.customs.wxjy.system.dao.DictTypeDao;
import cn.gov.customs.wxjy.system.pojo.DictData;
import cn.gov.customs.wxjy.system.pojo.DictType;
import cn.gov.customs.wxjy.system.pojo.DictTypeQuery;
import cn.gov.customs.wxjy.system.service.DictTypeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 字典类型Service业务层处理
 *
 * @author xiong
 * @date 2025-11-07
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class DictTypeServiceImpl implements DictTypeService {
    @Autowired
    private DictTypeDao dictTypeMapper;

    @Autowired
    private DictDataDao dictDataMapper;

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

    /**
     * 根据条件分页查询字典类型
     *
     * @param dictType 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public PageInfo<DictType> selectDictTypeList(DictTypeQuery dictType) {
        PageHelper.startPage(dictType.getPageIndex(), dictType.getPageSize());
        List<DictType> list = dictTypeMapper.selectDictTypeList(dictType.getDictType(),dictType.getDictName(),dictType.getStatus(),
                dictType.getBeginTime(),dictType.getEndTime());
        return PageInfo.of(list);
    }

    /**
     * 根据所有字典类型
     *
     * @return 字典类型集合信息
     */
    @Override
    public List<DictType> selectDictTypeAll()
    {
        return dictTypeMapper.selectDictTypeAll();
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<DictData> selectDictDataByType(String dictType)
    {
        List<DictData> dictDatas = DictUtils.getDictCache(dictType);
        if (StringUtils.isNotEmpty(dictDatas))
        {
            return dictDatas;
        }
        dictDatas = dictDataMapper.selectDictDataByType(dictType);
        if (StringUtils.isNotEmpty(dictDatas))
        {
            DictUtils.setDictCache(dictType, dictDatas);
            return dictDatas;
        }
        return null;
    }

    /**
     * 根据字典类型ID查询信息
     *
     * @param PkDictType 字典类型ID
     * @return 字典类型
     */
    @Override
    public DictType selectDictTypeById(Long PkDictType)
    {
        return dictTypeMapper.selectDictTypeById(PkDictType);
    }

    /**
     * 根据字典类型查询信息
     *
     * @param dictType 字典类型
     * @return 字典类型
     */
    @Override
    public DictType selectDictTypeByType(String dictType)
    {
        return dictTypeMapper.selectDictTypeByType(dictType);
    }

    /**
     * 批量删除字典类型信息
     *
     * @param PkDictTypes 需要删除的字典ID
     */
    @Override
    public int deleteDictTypeByIds(Long[] PkDictTypes)
    {
        int i = 0;
        for (Long PkDictType : PkDictTypes)
        {
           DictType dictType = selectDictTypeById(PkDictType);
//            if (dictDataMapper.countDictDataByType(dictType.getDictType()) > 0)
//            {
//                throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
//            }
            dictTypeMapper.deleteDictTypeById(PkDictType);
            DictUtils.removeDictCache(dictType.getDictType());
            i++;
        }
        return i;
    }

    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache()
    {
        DictData dictData = new DictData();
        dictData.setStatus("0");
        Map<String, List<DictData>> dictDataMap = dictDataMapper.selectDictDataList(dictData.getDictType(),dictData.getDictLabel(),dictData.getStatus()).stream().collect(Collectors.groupingBy(DictData::getDictType));
        for (Map.Entry<String, List<DictData>> entry : dictDataMap.entrySet())
        {
            DictUtils.setDictCache(entry.getKey(), entry.getValue().stream().sorted(Comparator.comparing(DictData::getDictSort)).collect(Collectors.toList()));
        }
    }

    /**
     * 清空字典缓存数据
     */
    @Override
    public void clearDictCache()
    {
        DictUtils.clearDictCache();
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache()
    {
        clearDictCache();
        loadingDictCache();
    }

    /**
     * 新增保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    public int insertDictType(DictType dict)
    {
        dict.setPkDictType(new SnowflakeIdWorker(0, 0).nextId());
        int row = dictTypeMapper.insertDictType(dict);
        if (row > 0)
        {
            DictUtils.setDictCache(dict.getDictType(), null);
        }
        return row;
    }

    /**
     * 修改保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDictType(DictType dict)
    {
        DictType oldDict = dictTypeMapper.selectDictTypeById(dict.getPkDictType());
        dictDataMapper.updateDictDataType(oldDict.getDictType(), dict.getDictType());
        int row = dictTypeMapper.updateDictType(dict);
        if (row > 0)
        {
            List<DictData> dictDatas = dictDataMapper.selectDictDataByType(dict.getDictType());
            DictUtils.setDictCache(dict.getDictType(), dictDatas);
        }
        return row;
    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public boolean checkDictTypeUnique(DictType dict)
    {
        Long PkDictType = StringUtils.isNull(dict.getPkDictType()) ? -1L : dict.getPkDictType();
        DictType dictType = dictTypeMapper.checkDictTypeUnique(dict.getDictType());
        if (StringUtils.isNotNull(dictType) && dictType.getPkDictType().longValue() != PkDictType.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}
