package com.infoepoch.pms.dispatchassistant.domain.system.dict;

import com.infoepoch.pms.dispatchassistant.common.exception.NotLoginException;
import com.infoepoch.pms.dispatchassistant.common.exception.ValidationException;
import com.infoepoch.pms.dispatchassistant.controller.basic.Auth;
import com.infoepoch.pms.dispatchassistant.domain.basic.user.User;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class DictDataService {

    @Autowired
    private Auth auth;

    @Autowired
    private IDictDataRepository dictDataRepository;

    /**
     * 条件查询分页列表
     *
     * @param criteria
     * @return
     */
    public Map<String, Object> pageList(SystemDictCriteria criteria) {
        criteria.setPaginationFlag(true);
        Map<String, Object> resultMap = new HashMap<>();
        List<SystemDictData> list = dictDataRepository.selectByCriteria(criteria);
        resultMap.put("list", list);
        resultMap.put("totalCount", dictDataRepository.selectByCriteriaCount(criteria));
        return resultMap;
    }

    /**
     * 条件查询不分页列表
     *
     * @param criteria
     * @return
     */
    public List<SystemDictData> list(SystemDictCriteria criteria) {
        criteria.setPaginationFlag(false);
        return dictDataRepository.selectByCriteria(criteria);
    }

    /**
     * 保存
     *
     * @param dictData
     * @throws NotLoginException
     */
    public void save(SystemDictData dictData) throws NotLoginException {
        User user = auth.getUserReq();
        if (StringUtils.isBlank(dictData.getId())) {
            // 新增
            dictData.create(user.getDisplayName());
            dictDataRepository.insert(dictData);
        } else {
            // 修改
            SystemDictData old = dictDataRepository.selectById(dictData.getId());
            if (old == null)
                throw new ValidationException("无效的字典值ID");
            old.modify(
                    dictData.getSort(),
                    dictData.getLabel(),
                    dictData.getValue(),
                    dictData.getCssClass(),
                    dictData.getListClass(),
                    dictData.getDefaultFlag(),
                    user.getDisplayName()
            );
            dictDataRepository.update(old);
        }
    }

    public void batchSave(List<SystemDictData> dictDataList) throws NotLoginException {
        if (CollectionUtils.isEmpty(dictDataList))
            throw new ValidationException("保存失败");
        User user = auth.getUserReq();
        List<SystemDictData> addList = new ArrayList<>();
        List<SystemDictData> updateList = new ArrayList<>();
        for (SystemDictData dictData : dictDataList) {
            if (StringUtils.isBlank(dictData.getId())) {
                dictData.create(user.getDisplayName());
                addList.add(dictData);
            } else {
                dictData.update(user.getDisplayName());
                updateList.add(dictData);
            }
        }
        if (!addList.isEmpty())
            dictDataRepository.batchInsert(addList);
        if (!updateList.isEmpty())
            dictDataRepository.batchUpdate(updateList);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    public SystemDictData detailById(String id) {
        return dictDataRepository.selectById(id);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void removeById(String id) {
        SystemDictData dictData = dictDataRepository.selectById(id);
        if (dictData == null)
            throw new ValidationException("无效的字典值ID");
        dictDataRepository.softDeleteById(id);
    }

    /**
     * @param dictType
     */
    public void removeByDictType(String dictType) {
        dictDataRepository.deleteByDictType(dictType);
    }

    /**
     * 查询字典值，不包含已删除数据
     *
     * @param dictType
     * @return
     */
    public List<SystemDictData> queryByDictType(String dictType) {
        return queryByDictType(dictType, false);
    }

    /**
     * 查询字典值
     *
     * @param dictType 字典类型
     * @param fullFlag 是否包含已删除数据
     * @return
     */
    public List<SystemDictData> queryByDictType(String dictType, boolean fullFlag) {
        List<SystemDictData> dictDataList = dictDataRepository.selectByDictType(dictType);
        if (!fullFlag) {
            if (!dictDataList.isEmpty()) {
                // 过滤掉状态为2的数据
                dictDataList = dictDataList.stream().filter(o -> o.getStatus() != 2).collect(Collectors.toList());
            }
        }
        dictDataList.sort(Comparator.comparingInt(SystemDictData::getSort));
        return dictDataList;
    }

    /**
     * 查询字典值，不包含已删除数据
     *
     * @param dictType
     * @return
     */
    public Map<String, String> queryMapByDictType(String dictType) {
        return queryMapByDictType(dictType, false);
    }

    /**
     * 查询字典值
     *
     * @param dictType
     * @param fullFlag
     * @return
     */
    public Map<String, String> queryMapByDictType(String dictType, boolean fullFlag) {
        List<SystemDictData> dictDataList = dictDataRepository.selectByDictType(dictType);
        if (!fullFlag) {
            if (!dictDataList.isEmpty()) {
                // 过滤掉状态为2的数据
                dictDataList = dictDataList.stream().filter(o -> o.getStatus() != 2).collect(Collectors.toList());
            }
        }
        Map<String, String> resultMap = new HashMap<>();
        for (SystemDictData dictData : dictDataList) {
            resultMap.put(dictData.getValue(), dictData.getLabel());
        }
        return resultMap;
    }

    /**
     * @param dictType
     * @return
     */
    public Map<String, String> queryReverseMapByDictType(String dictType) {
        return queryReverseMapByDictType(dictType, false);
    }

    /**
     * @param dictType
     * @param fullFlag
     * @return
     */
    public Map<String, String> queryReverseMapByDictType(String dictType, boolean fullFlag) {
        List<SystemDictData> dictDataList = dictDataRepository.selectByDictType(dictType);
        if (!fullFlag) {
            if (!dictDataList.isEmpty()) {
                // 过滤掉状态为2的数据
                dictDataList = dictDataList.stream().filter(o -> o.getStatus() != 2).collect(Collectors.toList());
            }
        }
        Map<String, String> resultMap = new HashMap<>();
        for (SystemDictData dictData : dictDataList) {
            resultMap.put(dictData.getLabel(), dictData.getValue());
        }
        return resultMap;
    }

}
