package com.dsk.cscec.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dsk.cscec.domain.DCustomerClass;
import com.dsk.cscec.domain.vo.DCustomerClassTreeVo;
import com.dsk.cscec.mapper.DCustomerClassMapper;
import com.dsk.cscec.service.DCustomerClassService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * (DCustomerClass)表服务实现类
 *
 * @author sxk
 * @since 2024-06-19 17:03:19
 */
@Service("dCustomerClassService")
public class DCustomerClassServiceImpl extends ServiceImpl<DCustomerClassMapper, DCustomerClass> implements DCustomerClassService {
    @Resource
    private DCustomerClassMapper baseMapper;

    /**
     * 查询物资类别树
     */
    @Override
    public List<DCustomerClassTreeVo> queryMaterialClassTree() {
        List<DCustomerClassTreeVo> finalTree = new ArrayList<>();
        //构建树
        List<DCustomerClass> originList = baseMapper.selectList(null);
        originList.forEach(item -> {
            //筛选分供资源分类并添加根节点
            if ("分供资源分类".equals(item.getCustomerClassName()) &&
                    item.getLevelNo() == 0 &&
                    "Y".equals(item.getIsvalid())) {
                DCustomerClassTreeVo rootVo = BeanUtil.toBean(item, DCustomerClassTreeVo.class);
                finalTree.add(rootVo);
                //递归添加物资类别子节点
                this.addChild(rootVo, BeanUtil.copyToList(originList, DCustomerClassTreeVo.class));
            }
        });
        return finalTree;
    }

    /**
     * 递归添加物资类别子节点
     */
    private void addChild(DCustomerClassTreeVo parent, List<DCustomerClassTreeVo> tree) {
        tree.forEach(item -> {
            if (item.getParentId().equals(parent.getCustomerClassId())) {
                parent.getChildren().add(item);
                addChild(item, tree);
            }
        });
    }
}

