package com.aucma.production.service.impl;

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

// import java.math.BigDecimal;
// import com.aucma.base.domain.BaseMaterialInfo;
// import com.aucma.base.domain.OrderBomInfo;
// import com.aucma.base.mapper.BaseMaterialinfoMapper;
// import com.aucma.base.service.IOrderBomInfoService;
// import com.aucma.base.utils.MaterialConstants;
import com.aucma.common.exception.ServiceException;
import com.aucma.common.exception.base.BaseException;
import com.aucma.common.utils.DateUtils;
import com.aucma.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.aucma.production.mapper.BaseBomInfoMapper;
import com.aucma.production.domain.BaseBomInfo;
import com.aucma.production.service.IBaseBomInfoService;

/**
 * 生产BOMService业务层处理
 *
 * @author Yinq
 * @date 2023-09-28
 */
@Service
public class BaseBomInfoServiceImpl implements IBaseBomInfoService {
    @Autowired
    private BaseBomInfoMapper baseBomInfoMapper;

//    @Autowired
//    private IOrderBomInfoService orderBomInfoService;
//
//    @Autowired
//    private BaseMaterialinfoMapper materialInfoMapper;

    /**
     * 查询生产BOM
     *
     * @param objId 生产BOM主键
     * @return 生产BOM
     */
    @Override
    public BaseBomInfo selectBaseBomInfoByObjId(Long objId) {
        return baseBomInfoMapper.selectBaseBomInfoByObjId(objId);
    }

    /**
     * 查询生产BOM列表
     *
     * @param baseBomInfo 生产BOM
     * @return 生产BOM
     */
    @Override
    public List<BaseBomInfo> selectBaseBomInfoList(BaseBomInfo baseBomInfo) {
        List<BaseBomInfo> baseBomInfos = new ArrayList<>();
        //测试查看全部BOM关系 baseBomInfo.getAncestors()为成品
        if (StringUtils.isNotEmpty(baseBomInfo.getAncestors()) && baseBomInfo.getAncestors().equals("0")) {
            baseBomInfos = baseBomInfoMapper.selectBaseBomInfoList(new BaseBomInfo());
            return baseBomInfos;
        }

        //筛选子集BOM
        if (StringUtils.isNotEmpty(baseBomInfo.getAncestors())) {
            BaseBomInfo bomInfo = new BaseBomInfo();
            bomInfo.setMaterialCode(baseBomInfo.getAncestors());
            List<BaseBomInfo> bomInfos = baseBomInfoMapper.selectBaseBomInfoList(bomInfo);
            List<BaseBomInfo> result = new ArrayList<>(bomInfos);
            if (bomInfos.size() > 0){
                getAllBomRecursion(bomInfos.get(0), result);
            }
            return result;
        }

        //筛选成品BOM
        List<BaseBomInfo> cpBomInfos = baseBomInfoMapper.selectBaseBomInfoList(baseBomInfo);
        for (BaseBomInfo bomInfo : cpBomInfos) {
            this.recursionSelectBaseBomInfoList(bomInfo);
        }

        return cpBomInfos;
    }


    /**
     * 递归筛选子集BOM
     * @param currentBom
     * @param result
     */
    private void getAllBomRecursion(BaseBomInfo currentBom,  List<BaseBomInfo> result) {
        BaseBomInfo baseBomInfo = new BaseBomInfo();
        baseBomInfo.setParentId(currentBom.getMaterialCode());
        List<BaseBomInfo> baseBomInfos = baseBomInfoMapper.selectBaseBomInfoList(baseBomInfo);
        if (baseBomInfos.size() > 0){
            result.addAll(baseBomInfos);
            for (BaseBomInfo bomInfo : baseBomInfos) {
                getAllBomRecursion(bomInfo, result);
            }
        }
    }

    /**
     * 判断生产BOM是否可下计划到工位
     *
     * @param baseBomInfo
     * @return baseBomInfo
     */
    public BaseBomInfo recursionSelectBaseBomInfoList(BaseBomInfo baseBomInfo) {
        BaseBomInfo info = new BaseBomInfo();
        info.setMaterialCode(baseBomInfo.getMaterialCode());
        info.setIsPlanToStation(0L);
        List<BaseBomInfo> baseBomInfos = baseBomInfoMapper.selectBaseBomInfoList(info);
        if (baseBomInfos.size() >= 1) {
            baseBomInfo.setIsPlanToStation(0L);
        } else {
            baseBomInfo.setIsPlanToStation(1L);
        }
        return baseBomInfo;
    }


    /**
     * 新增生产BOM
     *
     * @param baseBomInfo 生产BOM
     * @return 结果
     */
    @Override
    public int insertBaseBomInfo(BaseBomInfo baseBomInfo) {
        List<BaseBomInfo> baseBomInfos = baseBomInfoMapper.selectBaseBomInfoList(baseBomInfo);
        if (baseBomInfos.size() > 0) {
            throw new BaseException("该物料编号：" + baseBomInfo.getMaterialCode() + "已存在！");
        }
        // 当前业务改为手工维护父子关系，这里只维护树查询必需的祖级链，不再从订单BOM自动同步。
        baseBomInfo.setAncestors(buildManualAncestors(baseBomInfo.getParentId(), baseBomInfo.getMaterialCode()));
        baseBomInfo.setCreatedTime(DateUtils.getNowDate());
        return baseBomInfoMapper.insertBaseBomInfo(baseBomInfo);
    }

    /**
     * 修改生产BOM
     *
     * @param baseBomInfo 生产BOM
     * @return 结果
     */
    @Override
    public int updateBaseBomInfo(BaseBomInfo baseBomInfo) {
        BaseBomInfo oldBomInfo = baseBomInfoMapper.selectBaseBomInfoByObjId(baseBomInfo.getObjId());
        String newAncestors = buildManualAncestors(baseBomInfo.getParentId(), baseBomInfo.getMaterialCode());
        baseBomInfo.setAncestors(newAncestors);
        if (StringUtils.isNotNull(oldBomInfo) && StringUtils.isNotEmpty(oldBomInfo.getAncestors())) {
            // 手工调整树结构后，必须同步刷新下级祖级链，保证子树查询仍然命中正确成品路径。
            updateBomChildren(oldBomInfo.getMaterialCode(), newAncestors, oldBomInfo.getAncestors());
        }
        baseBomInfo.setUpdatedTime(DateUtils.getNowDate());
        return baseBomInfoMapper.updateBaseBomInfo(baseBomInfo);
    }

    /**
     * 计算手工维护场景下的祖级链
     *
     * @param parentId 父物料编号
     * @param materialCode 当前物料编号
     * @return 祖级链
     */
    private String buildManualAncestors(String parentId, String materialCode) {
        // 根节点直接以自身编码作为祖级，便于页面按成品物料快速展开整棵树。
        if (isRootNode(parentId)) {
            return materialCode;
        }
        BaseBomInfo parentBomInfo = baseBomInfoMapper.selectBaseBomInfoByMaterialCode(parentId);
        if (StringUtils.isNotNull(parentBomInfo) && StringUtils.isNotEmpty(parentBomInfo.getAncestors())) {
            // 优先沿用父节点已有祖级链，避免人工维护时额外维护完整路径字段。
            return parentBomInfo.getAncestors() + "," + materialCode;
        }
        return parentId + "," + materialCode;
    }

    /**
     * 判断是否顶级节点
     *
     * @param parentId 父物料编号
     * @return 是否顶级节点
     */
    private boolean isRootNode(String parentId) {
        return StringUtils.isEmpty(parentId) || "0".equals(parentId);
    }

    /**
     * 修改子元素关系
     *
     * @param materialCode 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    private void updateBomChildren(String materialCode, String newAncestors, String oldAncestors) {
        List<BaseBomInfo> children = baseBomInfoMapper.selectChildrenBomById(materialCode);
        for (BaseBomInfo child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            baseBomInfoMapper.updateBomChildren(children);
        }

    }

    /**
     * 批量删除生产BOM
     *
     * @param objIds 需要删除的生产BOM主键
     * @return 结果
     */
    @Override
    public int deleteBaseBomInfoByObjIds(Long[] objIds) {
        return baseBomInfoMapper.deleteBaseBomInfoByObjIds(objIds);
    }

    /**
     * 删除生产BOM信息
     *
     * @param objId 生产BOM主键
     * @return 结果
     */
    @Override
    public int deleteBaseBomInfoByObjId(Long objId) {
        return baseBomInfoMapper.deleteBaseBomInfoByObjId(objId);
    }

    /**
     * 检查生产BOM是否满足下计划条件
     *
     * @param baseBomInfoList
     */
    @Override
    public void checkBomInfo(List<BaseBomInfo> baseBomInfoList) {
        for (BaseBomInfo baseBomInfo : baseBomInfoList) {
            if (StringUtils.isEmpty(baseBomInfo.getProductLineCode())) {
                throw new ServiceException("生产BOM：" + baseBomInfo.getMaterialName() + " 未分配工位！");
            }
        }
    }

//    /**
//     * 自动同步生产BOM
//     *
//     * 当前业务已经改为全部手动维护树形BOM，这里完整注释历史同步实现，避免后续被误恢复或误调用。
//     *
//     * @param baseBomInfo
//     * @return
//     */
//    @Override
//    public List<BaseBomInfo> addAutomaticSynchronizationBOM(BaseBomInfo baseBomInfo) {
//        // 获取成品物料
//        BaseMaterialInfo materialInfo = new BaseMaterialInfo();
//        materialInfo.setMaterialSubclass(MaterialConstants.FP_MATERIAL_TYPE);
//        List<BaseMaterialInfo> baseMaterialInfos = materialInfoMapper.selectBaseMaterialInfoList(materialInfo);
//
//        // 保存成品BOM信息
//        for (BaseMaterialInfo baseMaterialInfo : baseMaterialInfos) {
//            BaseBomInfo bomInfo = new BaseBomInfo();
//            bomInfo.setMaterialCode(baseMaterialInfo.getMaterialCode());
//            List<BaseBomInfo> baseBomInfos = baseBomInfoMapper.selectBaseBomInfoList(bomInfo);
//            if (baseBomInfos.size() == 0) {
//                BaseBomInfo info = new BaseBomInfo();
//                info.setBomCode(baseMaterialInfo.getMaterialCode());
//                info.setMaterialCode(baseMaterialInfo.getMaterialCode());
//                info.setMaterialName(baseMaterialInfo.getMaterialName());
//                info.setMaterialType(MaterialConstants.FP_MATERIAL_TYPE);
//                info.setStandardAmount(new BigDecimal(1));
//                info.setPlantCode(baseMaterialInfo.getPlantCode());
//                info.setCreatedTime(DateUtils.getNowDate());
//                info.setAncestors(baseMaterialInfo.getMaterialCode());
//                try {
//                    this.insertBaseBomInfo(info);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//
//        for (BaseMaterialInfo baseMaterialInfo : baseMaterialInfos) {
//            OrderBomInfo cpPomInfo = new OrderBomInfo();
//            cpPomInfo.setParentId(baseMaterialInfo.getMaterialCode());
//            List<OrderBomInfo> orderBomInfos = orderBomInfoService.selectOrderBomInfoList(cpPomInfo);
//            if (orderBomInfos.size() == 0) {
//                continue;
//            }
//            // 根据成品产品BOM存箱体、门体
//            for (OrderBomInfo orderBomInfo : orderBomInfos) {
//                orderBomInfo.setAncestors(baseMaterialInfo.getMaterialCode());
//                // 箱体
//                if (orderBomInfo.getMaterialType().equals(MaterialConstants.BOX_MATERIAL_TYPE)) {
//                    this.saveBaseBomInfoByMaterialType(orderBomInfo, MaterialConstants.BOX_MATERIAL_TYPE);
//                }
//                // 门体
//                if (orderBomInfo.getMaterialType().equals(MaterialConstants.DOOR_MATERIAL_TYPE)) {
//                    this.saveBaseBomInfoByMaterialType(orderBomInfo, MaterialConstants.DOOR_MATERIAL_TYPE);
//                }
//            }
//        }
//
//        // 获取箱体产品BOM信息
//        BaseBomInfo selectBoxBomInfo = new BaseBomInfo();
//        selectBoxBomInfo.setMaterialType(MaterialConstants.BOX_MATERIAL_TYPE);
//        List<BaseBomInfo> boxBaseBomInfoList = baseBomInfoMapper.selectBaseBomInfoList(selectBoxBomInfo);
//        for (BaseBomInfo boxBomInfo : boxBaseBomInfoList) {
//            OrderBomInfo selectBomInfo = new OrderBomInfo();
//            selectBomInfo.setParentId(boxBomInfo.getMaterialCode());
//            List<OrderBomInfo> bomInfoList = orderBomInfoService.selectOrderBomInfoList(selectBomInfo);
//            boolean isYZXTFlag = false; // 判断BOM是否含有预装箱体
//            for (OrderBomInfo orderBomInfo : bomInfoList) {
//                if (orderBomInfo.getMaterialName().contains("预装箱体")) {
//                    isYZXTFlag = true; // 此BOM有预装箱体
//                    // 预装箱体围板
//                    if (orderBomInfo.getMaterialType().equals(MaterialConstants.COAMING_MATERIAL_TYPE)) {
//                        this.saveBaseBomInfoByMaterialType(orderBomInfo, MaterialConstants.COAMING_MATERIAL_TYPE);
//                    }
//                }
//            }
//
//            // 没有预装箱体执行以下操作
//            if (!isYZXTFlag) {
//                for (OrderBomInfo orderBomInfo : bomInfoList) {
//                    orderBomInfo.setAncestors(boxBomInfo.getAncestors());
//                    // 内胆
//                    if (orderBomInfo.getMaterialType().equals(MaterialConstants.LINER_MATERIAL_TYPE)) {
//                        this.saveBaseBomInfoByMaterialType(orderBomInfo, MaterialConstants.LINER_MATERIAL_TYPE);
//                    }
//                    // 围板
//                    if (orderBomInfo.getMaterialType().equals(MaterialConstants.COAMING_MATERIAL_TYPE)) {
//                        this.saveBaseBomInfoByMaterialType(orderBomInfo, MaterialConstants.COAMING_MATERIAL_TYPE);
//                    }
//                }
//            }
//
//        }
//
//        // 获取围板产品BOM信息
//        BaseBomInfo selectWBomInfo = new BaseBomInfo();
//        selectWBomInfo.setMaterialType(MaterialConstants.COAMING_MATERIAL_TYPE);
//        List<BaseBomInfo> boxBaseWBomInfoList = baseBomInfoMapper.selectBaseBomInfoList(selectWBomInfo);
//        for (BaseBomInfo boxBomInfo : boxBaseWBomInfoList) {
//            OrderBomInfo selectBomInfo = new OrderBomInfo();
//            selectBomInfo.setParentId(boxBomInfo.getMaterialCode());
//            List<OrderBomInfo> bomInfoList = orderBomInfoService.selectOrderBomInfoList(selectBomInfo);
//            if (boxBomInfo.getMaterialName().contains("预装箱体")) {
//                for (OrderBomInfo orderBomInfo : bomInfoList) {
//                    orderBomInfo.setAncestors(boxBomInfo.getAncestors());
//                    // 围板
//                    if (orderBomInfo.getMaterialType().equals(MaterialConstants.COAMING_MATERIAL_TYPE)) {
//                        this.saveBaseBomInfoByMaterialType(orderBomInfo, MaterialConstants.COAMING_MATERIAL_TYPE);
//                    }
//                    // 内胆
//                    if (orderBomInfo.getMaterialType().equals(MaterialConstants.LINER_MATERIAL_TYPE)) {
//                        this.saveBaseBomInfoByMaterialType(orderBomInfo, MaterialConstants.LINER_MATERIAL_TYPE);
//                    }
//                }
//            } else {
//                for (OrderBomInfo orderBomInfo : bomInfoList) {
//                    orderBomInfo.setAncestors(boxBomInfo.getAncestors());
//                    // 前板
//                    if (orderBomInfo.getMaterialType().equals(MaterialConstants.FORMER_MATERIAL_TYPE)) {
//                        this.saveBaseBomInfoByMaterialType(orderBomInfo, MaterialConstants.FORMER_MATERIAL_TYPE);
//                    }
//                    // 后板
//                    if (orderBomInfo.getMaterialType().equals(MaterialConstants.AFTER_MATERIAL_TYPE)) {
//                        this.saveBaseBomInfoByMaterialType(orderBomInfo, MaterialConstants.AFTER_MATERIAL_TYPE);
//                    }
//                }
//            }
//        }
//
//        return null;
//    }
//
//    /**
//     * 根据物料类型存生产BOM
//     *
//     * @param orderBomInfo
//     * @param materialType
//     */
//    private void saveBaseBomInfoByMaterialType(OrderBomInfo orderBomInfo, String materialType) {
//        List<BaseBomInfo> baseBomInfos = this.checkDuplicateBaseBom(orderBomInfo);
//        if (baseBomInfos.size() > 0) {
//            // 排除异常情况：生产BOM信息重复
//            return;
//        }
//        // 保存BOM信息
//        BaseBomInfo info = new BaseBomInfo();
//        info.setBomCode(orderBomInfo.getMaterialCode());
//        info.setMaterialCode(orderBomInfo.getMaterialCode());
//        info.setMaterialName(orderBomInfo.getMaterialName());
//        info.setMaterialType(materialType);
//        info.setParentId(orderBomInfo.getParentId());
//        info.setStandardAmount(orderBomInfo.getStandardAmount());
//        info.setPlantCode(orderBomInfo.getFactoryCode());
//        info.setAncestors(orderBomInfo.getAncestors());
//        try {
//            info.setCreatedTime(DateUtils.getNowDate());
//            baseBomInfoMapper.insertBaseBomInfo(info);
//        } catch (Exception e) {
//            System.out.println("+++++根据物料类型存生产BOM异常++++：" + e);
//        }
//    }
//
//    /**
//     * 检测重复生产BOM
//     *
//     * @param bomInfo
//     * @return
//     */
//    private List<BaseBomInfo> checkDuplicateBaseBom(OrderBomInfo bomInfo) {
//        BaseBomInfo baseBomOne = new BaseBomInfo();
//        baseBomOne.setMaterialCode(bomInfo.getMaterialCode());
//        baseBomOne.setParentId(bomInfo.getParentId());
//        baseBomOne.setPlantCode(bomInfo.getFactoryCode());
//        return baseBomInfoMapper.selectBaseBomInfoList(baseBomOne);
//    }

}
