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

import com.zzsmart.qomo.kn.cost.manage.entity.AppSceneCostStandardDetail;
import com.zzsmart.qomo.kn.cost.manage.entity.AppSceneCostStandardResult;
import com.zzsmart.qomo.kn.cost.manage.vo.BomTreeInfoVO;

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<AppSceneCostStandardResult> sourceData, Map<String, AppSceneCostStandardResult> 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, AppSceneCostStandardResult> materialMap = sourceData.stream().filter(s->s.getMaterialNumber()!=null)
                .collect(Collectors.toMap(
                        // Key extractor
                        AppSceneCostStandardResult::getMaterialNumber,
                        // Value mapper
                        detail -> detail,
                        // Merger function to handle duplicates
                        (existing, replacement) -> existing
                ));

//        Map<String, AppSceneCostStandardDetail> materialMap = sourceData.stream().filter(s -> s.getMaterialNumber() != null).collect(Collectors.toMap(AppSceneCostStandardDetail::getMaterialNumber, vo -> vo));
        //查找最顶端的父类节点
        if (parentDataMap == null || (parentDataMap != null && parentDataMap.size() < 1)) {
            parentDataMap = sourceData.stream().filter(s -> s.getLayer().equals("0")).collect(Collectors.toMap(AppSceneCostStandardResult::getMaterialNumber, vo -> vo));
        }
        //查找有父节点的子节点
        Map<String, List<AppSceneCostStandardResult>> childDataMap = sourceData.stream().filter(s -> s.getParentMatnr() != null).collect(Collectors.groupingBy(AppSceneCostStandardResult::getParentMatnr));
        //查找有父节点的子节点
//        //1.把BOM信息分成按照层级分组
//        Map<Integer, List<AppSceneCostStandardDetail>> levelMap = sourceData.stream().filter(s -> s.getLevel() != null).collect(Collectors.groupingBy(CostStandardDetail::getLevel));
//        //2.对每层进行排序
//        for (Integer level : levelMap.keySet()) {
//            List<AppSceneCostStandardDetail> levelList = levelMap.get(level);
//            List<AppSceneCostStandardDetail> sortedCostDetails = levelList.stream().sorted(Comparator.comparing(AppSceneCostStandardDetail::getSort)).collect(Collectors.toList());
//            levelMap.put(level, sortedCostDetails);
//        }
//        TreeMap<Integer, List<AppSceneCostStandardDetail>> levelTreeMap = new TreeMap<>(levelMap);
        //3.构建BOM树
        if (parentDataMap.size() > 0) {
            for (AppSceneCostStandardResult 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, AppSceneCostStandardResult> materialMap, Map<String, List<AppSceneCostStandardResult>> childDataMap, List<BomTreeInfoVO> result) {
        if (parentBomTreeInfoVO != null) {
            //4.根据物料号查找子节点
            List<AppSceneCostStandardResult> childs = childDataMap.get(parentBomTreeInfoVO.getMaterialNumber());
            if (childs != null && childs.size() > 0) {
                parentBomTreeInfoVO.setHasChildren(true);
            } else {
                parentBomTreeInfoVO.setHasChildren(false);
                return parentBomTreeInfoVO;
            }
            //构造父节点下的bomtree结构数据
            List<BomTreeInfoVO> children = new ArrayList<>();
            for (int j = 0; childs != null && childs.size() > 0 && j < childs.size(); j++) {
                AppSceneCostStandardResult child = childs.get(j);
                if(child.getParentMatnr().equals(child.getMaterialNumber())){
                    continue;
                }
                BomTreeInfoVO childBomTreeInfoVO = costStandardDetailChangeToBomTreeInfoVO(child);
                childBomTreeInfoVO = loopFindChildrenBuild(childBomTreeInfoVO, materialMap, childDataMap, result);
                children.add(childBomTreeInfoVO);
            }
            if(parentBomTreeInfoVO.getLevel()==0){
                int x=0;
                x++;
            }
            //对象的子节点进行排序（升序）
            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(AppSceneCostStandardResult parent) {
        if(parent.getMenge()==null){
            int x=0;
            x++;
        }
        String layer = parent.getLayer();
        int index = layer.lastIndexOf("-");
        if(index!=-1){
            layer = layer.substring(index+1,layer.length());
        }
        //layer = layer.substring(index+1,layer.length());
        BomTreeInfoVO bomTreeInfoVO = BomTreeInfoVO.builder()
                .materialNumber(parent.getMaterialNumber())
                .materialName(parent.getMaktx())
                .level(Integer.parseInt(parent.getLowOrderCode()))
                .parentMaterialNumber(parent.getParentMatnr())
                .quantity(parent.getMenge().doubleValue())
                .materialCost(parent.getMaterialCostTotal())
                .auxiliaryCost(parent.getAuxiliaryCostTotal())
                .equipCost(parent.getEquipCostTotal())
                .otherCost(parent.getOtherCostTotal())
                .laborCost(parent.getLaborCostTotal())
                .fuelCost(parent.getFuelCost())
                .materialCost(parent.getMaterialCostTotal())
                .standardCost(parent.getTotalStandardCost())
                .laborHour(parent.getLaborHourTotal())
                .machineHour(parent.getEquipHour())
                .auxiHour(parent.getAuxiHour())
                .fuelHour(parent.getFuelHour())
                .otherHour(parent.getOtherHour())
                .layer(parent.getLayer())
                //.sort(Integer.parseInt(layer))
                .build();
        return bomTreeInfoVO;
    }
}
