package net.lab1024.sa.admin.util;

import com.google.common.collect.Maps;
import jakarta.annotation.Resource;
import net.lab1024.sa.base.common.exception.BusinessException;
import net.lab1024.sa.base.common.util.SmartStringUtil;
import net.lab1024.sa.base.module.support.dict.dao.DictDao;
import net.lab1024.sa.base.module.support.dict.domain.entity.DictEntity;
import net.lab1024.sa.base.module.support.dict.domain.vo.DictDataVO;
import net.lab1024.sa.base.module.support.dict.service.DictService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ValidateDictKeyUtil {

    @Resource
    private DictDao dictDao;

    @Resource
    public DictService dictService;

    public Map<String, String> validateDictCodes(List<String> dictCodes, String dictCode) {
        //通过字典编号查询数据库已存在的类型
        DictEntity dict = dictDao.selectByCode(dictCode);
        if (dict == null) {
            throw new BusinessException("字典中" + dictCode + "参数错误");
        }
        List<DictDataVO> selectByKeyCode = dictService.queryDictData(dict.getDictId());
        if (CollectionUtils.isEmpty(selectByKeyCode)) {
            throw new BusinessException("字典中" + dictCode + "参数错误");
        }

        //去重
        dictCodes = dictCodes.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());

        //获取字典集合中的valueName集合
        List<String> exitDictCodes = selectByKeyCode.stream().filter(Objects::nonNull).map(DictDataVO::getDataLabel).distinct().toList();

        //获取两个集合的非交集说明库区不存在；提示错误
        List<String> diff = SmartStringUtil.getDifference(dictCodes, exitDictCodes);
        if (CollectionUtils.isNotEmpty(diff)) {
            throw new BusinessException(diff + "不存在,请在数据字典中维护");
        }
        //封装map
        Map<String, String> map = Maps.newHashMap();
        for (DictDataVO dictDataVO : selectByKeyCode) {
            map.put(dictDataVO.getDataLabel(), dictDataVO.getDataValue());
        }

        return map;
    }
}
