package com.nantian.cloud.jljc.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nantian.cloud.jljc.entity.HKind;
import com.nantian.cloud.jljc.mapper.HKindMapper;
import com.nantian.cloud.jljc.service.HKindService;
import com.nantian.cloud.jljc.vo.TreeVo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.nantian.cloud.jljc.vo.util.TreeVoUtil.findTree;

/**
 * （慧能）行业、产品、工序表服务实现类
 */
@Service("HKindService")
public class HKindServiceImpl extends ServiceImpl<HKindMapper, HKind> implements HKindService {


    @Override
    public List<TreeVo> getTree(HKind hKind) {
        List<TreeVo> voList = baseMapper.getTree(hKind);
        String name = hKind.getName();
        List<TreeVo> treeVos = new ArrayList<>();
        if (name == null || "".equals(name)) {
            treeVos = findTree(voList);
        }else {
            treeVos = getTreeVoByLabel(voList, name);
        }
        Collections.sort(treeVos);
        return treeVos;
    }

    private List<TreeVo> getTreeVoByLabel(List<TreeVo> voList, String name) {
        List<TreeVo> newList = new ArrayList<>();
        for (TreeVo treeVo : voList) {
            if ("0".equals(treeVo.getPvalue()) || "".equals(treeVo.getPvalue()) || null==treeVo.getPvalue()) {
                if (treeVo.getLabel().contains(name)) {
                    newList.add(findName(treeVo,voList));
                }
            }
        }
        return newList;
    }

    @Override
    public List<TreeVo> treeByLeaf(String code) {
        List<TreeVo> kindTree = new ArrayList<>();
        TreeVo t =  baseMapper.treeByLeaf(code);
        kindTree.add(t);
        while(!"0".equals(t.getPvalue())){
            TreeVo vo = baseMapper.treeByLeaf(t.getPvalue());
            kindTree.add(vo);
            t = vo;
        }
        return findTree(kindTree);
    }

    public TreeVo findName(TreeVo treeVo,List<TreeVo> voList) {
        for (TreeVo vo : voList) {
            if(treeVo.getLabel().equals(vo.getPlabel())) {
                treeVo.getChildren().add(findName(vo,voList));
            }
        }
        return treeVo;
    }
}
