package com.ruoyi.ems.service.impl;

import com.ruoyi.ems.domain.EmsCls;
import com.ruoyi.ems.mapper.EmsClsMapper;
import com.ruoyi.ems.model.TreeEntity;
import com.ruoyi.ems.service.IEmsClsService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 能源分类Service业务层处理
 *
 * @author ruoyi
 * @date 2024-07-10
 */
@Service
public class EmsClsServiceImpl implements IEmsClsService {
    @Autowired
    private EmsClsMapper emsClsMapper;

    /**
     * 查询能源分类
     *
     * @param id 能源分类主键
     * @return 能源分类
     */
    @Override
    public EmsCls selectEmsClsById(Long id) {
        return emsClsMapper.selectEmsClsById(id);
    }

    /**
     * 查询能源分类列表
     *
     * @param emsCls 能源分类
     * @return 能源分类
     */
    @Override
    public List<EmsCls> selectEmsClsList(EmsCls emsCls) {
        return emsClsMapper.selectEmsClsList(emsCls);
    }

    @Override
    public List<TreeEntity> selectEmsClsTreeList(EmsCls emsCls) {
        List<EmsCls> list = emsClsMapper.selectEmsClsList(emsCls);
        return buildEmsClsTree(list);
    }

    /**
     * 新增能源分类
     *
     * @param emsCls 能源分类
     * @return 结果
     */
    @Override
    public int insertEmsCls(EmsCls emsCls) {
        return emsClsMapper.insertEmsCls(emsCls);
    }

    /**
     * 修改能源分类
     *
     * @param emsCls 能源分类
     * @return 结果
     */
    @Override
    public int updateEmsCls(EmsCls emsCls) {
        return emsClsMapper.updateEmsCls(emsCls);
    }

    /**
     * 批量删除能源分类
     *
     * @param ids 需要删除的能源分类主键
     * @return 结果
     */
    @Override
    public int deleteEmsClsByIds(Long[] ids) {
        return emsClsMapper.deleteEmsClsByIds(ids);
    }

    /**
     * 删除能源分类信息
     *
     * @param id 能源分类主键
     * @return 结果
     */
    @Override
    public int deleteEmsClsById(Long id) {
        return emsClsMapper.deleteEmsClsById(id);
    }

    public List<TreeEntity> buildEmsClsTree(List<EmsCls> list) {
        Map<String, List<EmsCls>> groupedByParent = list.stream().collect(Collectors.groupingBy(EmsCls::getParentCode));
        List<TreeEntity> retCols = buildEmsClsTreeSub("-1", groupedByParent);
        retCols.sort(Comparator.comparing(TreeEntity::getId));
        return retCols;
    }

    public List<TreeEntity> buildEmsClsTreeSub(String code, Map<String, List<EmsCls>> map) {
        List<TreeEntity> retList = new ArrayList<>();
        List<EmsCls> list = map.get(code);

        if (CollectionUtils.isNotEmpty(list)) {
            for (EmsCls item : list) {
                TreeEntity tree = new TreeEntity(item);
                tree.setChildren(buildEmsClsTreeSub(item.getCode(), map));
                retList.add(tree);
            }
        }

        return retList;
    }
}
