package com.zzsmart.qomo.kn.cost.manage.util;

import com.zzsmart.qomo.kn.cost.manage.entity.CostStandardDetail;
import com.zzsmart.qomo.kn.cost.manage.vo.BomTreeInfoVO;
import com.zzsmart.qomo.kn.cost.manage.vo.CostStandardDetailVO;

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

public class BomTreeBuilder {
    public static List<BomTreeInfoVO> buildBomTree(List<CostStandardDetailVO> sourceData, Map<String, CostStandardDetailVO> parentDataMap) {
        List<BomTreeInfoVO> result = new ArrayList<>();
        if ((sourceData == null || (sourceData != null && sourceData.size() < 1)) && (parentDataMap == null || (parentDataMap != null && parentDataMap.size() < 1))) {
            return result;
        }
        //1.把BOM信息分成按照物料号分组
        Map<String, CostStandardDetailVO> materialMap = sourceData.stream().filter(s -> s.getMaterialNumber() != null).collect(Collectors.toMap(CostStandardDetailVO::getMaterialNumber, vo -> vo));
        //查找最顶端的父类节点
        if (parentDataMap == null || (parentDataMap != null && parentDataMap.size() < 1)) {
            parentDataMap = sourceData.stream().filter(s -> s.getParentMaterialNumber() == null).collect(Collectors.toMap(CostStandardDetailVO::getMaterialNumber, vo -> vo));
        }
        //查找有父节点的子节点
        Map<String, List<CostStandardDetailVO>> childDataMap = sourceData.stream().filter(s -> s.getParentMaterialNumber() != null).collect(Collectors.groupingBy(CostStandardDetailVO::getParentMaterialNumber));
        //查找有父节点的子节点
//        //1.把BOM信息分成按照层级分组
//        Map<Integer, List<CostStandardDetailVO>> levelMap = sourceData.stream().filter(s -> s.getLevel() != null).collect(Collectors.groupingBy(CostStandardDetail::getLevel));
//        //2.对每层进行排序
//        for (Integer level : levelMap.keySet()) {
//            List<CostStandardDetailVO> levelList = levelMap.get(level);
//            List<CostStandardDetailVO> sortedCostDetails = levelList.stream().sorted(Comparator.comparing(CostStandardDetailVO::getSort)).collect(Collectors.toList());
//            levelMap.put(level, sortedCostDetails);
//        }
//        TreeMap<Integer, List<CostStandardDetailVO>> levelTreeMap = new TreeMap<>(levelMap);
        //3.构建BOM树
        if (parentDataMap.size() > 0) {
            for (CostStandardDetailVO parent : parentDataMap.values()) {
                BomTreeInfoVO parentBomTreeInfoVO = costStandardDetailChangeToBomTreeInfoVO(parent);
                parentBomTreeInfoVO = loopFindChildrenBuild(parentBomTreeInfoVO, materialMap, childDataMap, result);
                if (parentBomTreeInfoVO != null) {
                    result.add(parentBomTreeInfoVO);
                }
            }
        }
        materialMap = null;
        parentDataMap = null;
        childDataMap = null;
        return result;
    }

    private static BomTreeInfoVO loopFindChildrenBuild(BomTreeInfoVO parentBomTreeInfoVO, Map<String, CostStandardDetailVO> materialMap, Map<String, List<CostStandardDetailVO>> childDataMap, List<BomTreeInfoVO> result) {
        if (parentBomTreeInfoVO != null) {
            //4.根据物料号查找子节点
            List<CostStandardDetailVO> childs = childDataMap.get(parentBomTreeInfoVO.getMaterialNumber());
            if (childs != null && childs.size() > 0) {
                parentBomTreeInfoVO.setHasChildren(true);
            } else {
                parentBomTreeInfoVO.setHasChildren(false);
            }
            //构造父节点下的bomtree结构数据
            List<BomTreeInfoVO> children = new ArrayList<>();
            for (int j = 0; childs != null && childs.size() > 0 && j < childs.size(); j++) {
                CostStandardDetailVO child = childs.get(j);
                BomTreeInfoVO childBomTreeInfoVO = costStandardDetailChangeToBomTreeInfoVO(child);
                childBomTreeInfoVO = loopFindChildrenBuild(childBomTreeInfoVO, materialMap, childDataMap, result);
                children.add(childBomTreeInfoVO);
            }
            //对象的子节点进行排序（升序）
            children = children.stream().sorted(Comparator.comparing(BomTreeInfoVO::getSort, Comparator.nullsLast(Comparator.naturalOrder()))).collect(Collectors.toList());
            parentBomTreeInfoVO.setChildren(children);
        }
        return parentBomTreeInfoVO;
    }

    /**
     * 把单行查询的数据转换为BomTreeInfoVO
     *
     * @param parent
     * @return
     */
    static BomTreeInfoVO costStandardDetailChangeToBomTreeInfoVO(CostStandardDetail parent) {
        BomTreeInfoVO bomTreeInfoVO = BomTreeInfoVO.builder().materialNumber(parent.getMaterialNumber()).materialName(parent.getMaterialName()).level(parent.getLevel()).parentMaterialNumber(parent.getParentMaterialNumber()).quantity(parent.getDosage()).unit(parent.getUnit()).auxiliaryCost(parent.getAuxiliaryCost()).equipCost(parent.getEquipConsumeCost()).otherCost(parent.getOtherCost()).laborCost(parent.getLaborCost()).accumulatedEquipCost(parent.getTotalEquipConsumeCost()).accumulatedOtherCost(parent.getTotalOtherCost()).accumulatedLaborCost(parent.getTotalLaborCost()).accumulatedMaterialCost(parent.getAuxiliaryCost()).accumulatedFuelCost(parent.getTotalEuipDepreciationCost()).sort(parent.getSort()).build();
        return bomTreeInfoVO;
    }
}
