package com.hys.app.service.system.impl;

import cn.hutool.core.collection.CollUtil;
import com.hys.app.model.system.dto.DictDataCreateDTO;
import com.hys.app.model.system.dto.DictDataQueryParams;
import com.hys.app.model.system.dto.DictDataUpdateDTO;
import com.hys.app.converter.system.DictDataConverter;
import com.hys.app.framework.database.WebPage;
import com.hys.app.framework.exception.ServiceException;
import com.hys.app.mapper.system.DictDataMapper;
import com.hys.app.model.system.dos.DictDataDO;
import com.hys.app.model.system.dos.DictTypeDO;
import com.hys.app.service.system.DictDataManager;
import com.hys.app.service.system.DictTypeManager;
import com.hys.app.framework.util.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * 字典数据 Service 实现类
 */
@Service
@Slf4j
public class DictDataManagerImpl implements DictDataManager {

    /**
     * 排序 dictType > sort
     */
    private static final Comparator<DictDataDO> COMPARATOR_TYPE_AND_SORT = Comparator
            .comparing(DictDataDO::getDictType)
            .thenComparingInt(DictDataDO::getSort);

    @Resource
    private DictTypeManager dictTypeManager;

    @Resource
    private DictDataMapper dictDataMapper;

    @Autowired
    private DictDataConverter converter;

    @Override
    public List<DictDataDO> getDictDataList(String dictType) {
        List<DictDataDO> list = dictDataMapper.selectListByDictType(dictType);
        list.sort(COMPARATOR_TYPE_AND_SORT);
        return list;
    }

    @Override
    public WebPage<DictDataDO> getDictDataPage(DictDataQueryParams reqVO) {
        return dictDataMapper.selectPage(reqVO);
    }

    @Override
    public List<DictDataDO> getEnabledDictDataListByType(String dictType) {
        List<DictDataDO> list = dictDataMapper.selectListByTypeAndStatus(dictType);
        list.sort(COMPARATOR_TYPE_AND_SORT);
        return list;
    }

    @Override
    public DictDataDO getDictData(Long id) {
        return dictDataMapper.selectById(id);
    }

    @Override
    public Long createDictData(DictDataCreateDTO reqVO) {
        // 校验正确性
        validateDictDataForCreateOrUpdate(null, reqVO.getValue(), reqVO.getDictType());

        // 如果是默认值，则修改其他字段值为非默认
        if(reqVO.getDefaultFlag()){
            dictDataMapper.updateToNotDefault(reqVO.getDictType());
        }

        // 插入字典类型
        DictDataDO dictData = converter.convert(reqVO);
        dictDataMapper.insert(dictData);
        return dictData.getId();
    }

    @Override
    public void updateDictData(DictDataUpdateDTO reqVO) {
        // 校验正确性
        validateDictDataForCreateOrUpdate(reqVO.getId(), reqVO.getValue(), reqVO.getDictType());

        // 如果是默认值，则修改其他字段值为非默认
        if(reqVO.getDefaultFlag()){
            dictDataMapper.updateToNotDefault(reqVO.getDictType());
        }

        // 更新字典类型
        DictDataDO updateObj = converter.convert(reqVO);
        dictDataMapper.updateById(updateObj);
    }

    @Override
    public void deleteDictData(Long id) {
        // 校验是否存在
        validateDictDataExists(id);

        // 删除字典数据
        dictDataMapper.deleteById(id);
    }

    @Override
    public long countByDictType(String dictType) {
        return dictDataMapper.selectCountByDictType(dictType);
    }

    private void validateDictDataForCreateOrUpdate(Long id, String value, String dictType) {
        // 校验自己存在
        validateDictDataExists(id);
        // 校验字典类型有效
        validateDictTypeExists(dictType);
        // 校验字典数据的值的唯一性
        validateDictDataValueUnique(id, dictType, value);
    }

    public void validateDictDataValueUnique(Long id, String dictType, String value) {
        DictDataDO dictData = dictDataMapper.selectByDictTypeAndValue(dictType, value);
        if (dictData == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的字典数据
        if (id == null) {
            throw new ServiceException("已经存在该值的字典数据");
        }
        if (!dictData.getId().equals(id)) {
            throw new ServiceException("已经存在该值的字典数据");
        }
    }

    public void validateDictDataExists(Long id) {
        if (id == null) {
            return;
        }
        DictDataDO dictData = dictDataMapper.selectById(id);
        if (dictData == null) {
            throw new ServiceException("当前字典数据不存在");
        }
    }

    public void validateDictTypeExists(String type) {
        DictTypeDO dictType = dictTypeManager.getDictType(type);
        if (dictType == null) {
            throw new ServiceException("当前字典类型不存在");
        }
    }

    @Override
    public void validateDictDataList(String dictType, Collection<String> values) {
        if (CollUtil.isEmpty(values)) {
            return;
        }
        Map<String, DictDataDO> dictDataMap = CollectionUtils.convertMap(
                dictDataMapper.selectByDictTypeAndValues(dictType, values), DictDataDO::getValue);
        // 校验
        values.forEach(value -> {
            DictDataDO dictData = dictDataMap.get(value);
            if (dictData == null) {
                throw new ServiceException("当前字典数据不存在");
            }
        });
    }

    @Override
    public DictDataDO getDictData(String dictType, String value) {
        return dictDataMapper.selectByDictTypeAndValue(dictType, value);
    }

    @Override
    public DictDataDO parseDictData(String dictType, String label) {
        return dictDataMapper.selectByDictTypeAndLabel(dictType, label);
    }

}
