package co.yixiang.yshop.module.system.service.dict;

import cn.hutool.core.collection.CollUtil;
import co.yixiang.yshop.framework.common.enums.CommonStatusEnum;
import co.yixiang.yshop.framework.common.pojo.PageResult;
import co.yixiang.yshop.framework.common.util.collection.CollectionUtils;
import co.yixiang.yshop.module.system.controller.admin.dict.vo.data.*;
import co.yixiang.yshop.module.system.convert.dict.DictDataConvert;
import co.yixiang.yshop.module.system.dal.dataobject.dict.DictDataDO;
import co.yixiang.yshop.module.system.dal.dataobject.dict.DictTypeDO;
import co.yixiang.yshop.module.system.dal.mysql.dict.DictDataMapper;
import co.yixiang.yshop.module.system.enums.DistributorDictEnum;
import co.yixiang.yshop.module.system.enums.agreement.AgreementTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.annotations.VisibleForTesting;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

import static co.yixiang.yshop.framework.common.exception.util.ServiceExceptionUtil.exception;
import static co.yixiang.yshop.module.system.enums.DictTypeConstants.*;
import static co.yixiang.yshop.module.system.enums.DistributorDictEnum.DISTRIBUTOR_PURCHASE;
import static co.yixiang.yshop.module.system.enums.ErrorCodeConstants.*;

/**
 * 字典数据 Service 实现类
 *
 * @author ruoyi
 */
@Service
@Slf4j
public class DictDataServiceImpl implements DictDataService {

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

    @Resource
    private DictTypeService dictTypeService;

    @Resource
    private DictDataMapper dictDataMapper;

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

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

    @Override
    public List<DictDataDO> getDictDataList(DictDataExportReqVO reqVO) {
        List<DictDataDO> list = dictDataMapper.selectList(reqVO);
        list.sort(COMPARATOR_TYPE_AND_SORT);
        return list;
    }

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

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

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

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

        // 更新字典类型
        DictDataDO updateObj = DictDataConvert.INSTANCE.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);
    }

    @VisibleForTesting
    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 exception(DICT_DATA_VALUE_DUPLICATE);
        }
        if (!dictData.getId().equals(id)) {
            throw exception(DICT_DATA_VALUE_DUPLICATE);
        }
    }

    @VisibleForTesting
    public void validateDictDataExists(Long id) {
        if (id == null) {
            return;
        }
        DictDataDO dictData = dictDataMapper.selectById(id);
        if (dictData == null) {
            throw exception(DICT_DATA_NOT_EXISTS);
        }
    }

    @VisibleForTesting
    public void validateDictTypeExists(String type) {
        DictTypeDO dictType = dictTypeService.getDictType(type);
        if (dictType == null) {
            throw exception(DICT_TYPE_NOT_EXISTS);
        }
        if (!CommonStatusEnum.ENABLE.getStatus().equals(dictType.getStatus())) {
            throw exception(DICT_TYPE_NOT_ENABLE);
        }
    }

    @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 exception(DICT_DATA_NOT_EXISTS);
            }
            if (!CommonStatusEnum.ENABLE.getStatus().equals(dictData.getStatus())) {
                throw exception(DICT_DATA_NOT_ENABLE, dictData.getLabel());
            }
        });
    }

    @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);
    }


    @Override
    public DictDataRespVO getAgreement(Integer type) {
        LambdaQueryWrapper<DictDataDO> qw = new LambdaQueryWrapper<>();
        if (type.equals(AgreementTypeEnum.USER.getType())) {
            qw.eq(DictDataDO::getLabel, USER_AGREEMENT);
        } else {
            qw.eq(DictDataDO::getLabel, PRIVACY_AGREEMENT);
        }
        DictDataDO dictDataDO = dictDataMapper.selectOne(qw);
        return DictDataConvert.INSTANCE.convert(dictDataDO);
    }

    @Override
    public DictDataRespVO getDefaultHead() {
        LambdaQueryWrapper<DictDataDO> qw = new LambdaQueryWrapper<>();
        DictDataDO dictDataDO = dictDataMapper.selectOne(qw.eq(DictDataDO::getLabel, DEFAULT_HEAD));
        return DictDataConvert.INSTANCE.convert(dictDataDO);
    }

    @Override
    public String getDictDataStr(String dictType, String label) {
        DictDataDO dictDataDO = dictDataMapper.selectByDictTypeAndLabel(dictType, label);
        return dictDataDO.getValue();
    }

    @Override
    public Integer getDictDataInt(String dictType, String label) {
        DictDataDO dictDataDO = dictDataMapper.selectByDictTypeAndLabel(dictType, label);
        return Integer.valueOf(dictDataDO.getValue());
    }

    @Override
    public List<DictDataRespVO> getDistributorConfig() {
        List<DictDataRespVO> dictDataRespVOS = new ArrayList<>();
        DistributorDictEnum[] enums = DistributorDictEnum.values();
        for (DistributorDictEnum dictEnum : enums) {
            DictDataDO dictDataDO = dictDataMapper.selectByDictTypeAndLabel(dictEnum.getDictType(), dictEnum.getLabel());
            DictDataRespVO dictDataRespVO = DictDataConvert.INSTANCE.convert(dictDataDO);
            dictDataRespVOS.add(dictDataRespVO);
        }
        return dictDataRespVOS;
    }

    @Override
    public void updateDistributorConfig(List<DictDataUpdateReqVO> reqVO) {
        for (DictDataUpdateReqVO req : reqVO) {
            // 自动返佣
            if(DISTRIBUTOR_PURCHASE.getDictType().equals(req.getDictType())){
                dictDataMapper.updateProductDistributionPurchase(req.getValue());
            }
            this.updateDictData(req);
        }
    }

    @Override
    public void updateDictByLabel(String label, String value) {
        dictDataMapper.updateDictByLabel(label, value);
    }
}
