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.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DictTypeService {

    @Autowired
    private Auth auth;

    @Autowired
    private IDictTypeRepository dictTypeRepository;
    @Autowired
    private IDictDataRepository dictDataRepository;

    /**
     * 条件查询分页列表
     *
     * @param criteria
     * @return
     */
    public Map<String, Object> pageList(SystemDictCriteria criteria) {
        // 该方法返回的一定是分页数据
        criteria.setPaginationFlag(true);
        Map<String, Object> resultMap = new HashMap<>();
        List<SystemDictType> list = dictTypeRepository.selectByCriteria(criteria);
        resultMap.put("list", list);
        resultMap.put("totalCount", dictTypeRepository.selectByCriteriaCount(criteria));
        return resultMap;
    }

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

    /**
     * 保存字典
     *
     * @param dictType
     */
    public void save(SystemDictType dictType) throws NotLoginException {
        User user = auth.getUserReq();
        if (StringUtils.isBlank(dictType.getId())) {
            // 新增
            dictType.create(user.getDisplayName());
            dictTypeRepository.insert(dictType);
        } else {
            // 修改
            SystemDictType old = dictTypeRepository.selectById(dictType.getId());
            if (old == null)
                throw new ValidationException("无效的字典ID");
            old.modify(dictType.getName(), dictType.getDictType(), user.getDisplayName());
            dictTypeRepository.update(old);
        }
    }

    /**
     * 字典详情
     *
     * @param id
     * @return
     */
    public SystemDictType detailById(String id) {
        return dictTypeRepository.selectById(id);
    }

    /**
     * 根据ID删除字典
     *
     * @param id
     */
    public void removeById(String id) {
        SystemDictType dictType = dictTypeRepository.selectById(id);
        if (dictType == null)
            throw new ValidationException("无效的字典ID");
        // 删除字典相关数据
        dictTypeRepository.softDeleteById(id);
        dictDataRepository.softDeleteByDictType(dictType.getDictType());
    }

}
