//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package nccloud.openapi.mmbd.bom;

import com.alibaba.fastjson.JSONObject;

import java.util.*;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import nc.bs.bd.bom.bom0202.bp.BomPubBP;
import nc.bs.bd.bom.bom0202.bp.BomUpdateBP;
import nc.bs.framework.common.NCLocator;
import nc.bs.trade.business.HYPubBO;
import nc.itf.bd.bom.bom0202.IBomBillMaintainService;
import nc.itf.bd.bom.bom0202.IBomBillQueryService;
import nc.jdbc.framework.generator.IdGenerator;
import nc.mmbd.utils.factoryparam.MMBDFactoryParameter;
import nc.uif.pub.exception.UifException;
import nc.util.mmf.framework.base.MMArrayUtil;
import nc.util.mmf.framework.base.MMValueCheck;
import nc.util.mmf.framework.gc.GCBillTransferTool;
import nc.vo.bd.bom.bom0202.entity.AggBomVO;
import nc.vo.bd.bom.bom0202.entity.BomItemVO;
import nc.vo.bd.bom.bom0202.entity.BomReplVO;
import nc.vo.bd.bom.bom0202.message.MMBDLangConstBom0202;
import nc.vo.ml.NCLangRes4VoTransl;
import nc.vo.pub.BusinessException;
import nc.vo.pub.VOStatus;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDouble;
import nccloud.api.mmbd.bom.IAPIBomBusinessService;
import nccloud.api.rest.utils.ResultMessageUtil;
import nccloud.framework.core.exception.ExceptionUtils;
//import nccloud.framework.service.ServiceLocator;
import nccloud.ws.rest.resource.AbstractNCCRestResource;
import org.json.JSONString;
@Path("mmbd/bom")
public class BomResource extends AbstractNCCRestResource {
    public BomResource() {
    }

    @POST
    @Path("operation/add")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString insert(JSONObject para) {
        List<Map<String, Object>> paramList = (List)para.get("data");
        if (MMValueCheck.isEmpty(paramList)) {
            return ResultMessageUtil.exceptionToJSON("传入数据异常，参数要包含表头信息和表体信息", "1");
        } else {
            IAPIBomBusinessService service = (IAPIBomBusinessService)NCLocator.getInstance().lookup(IAPIBomBusinessService.class);
            JSONString result = service.insert(paramList);
            return result;
        }
    }

    @POST
    @Path("add")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString insert(List<Map<String, Object>> paramList) {
        if (MMValueCheck.isEmpty(paramList)) {
            return ResultMessageUtil.exceptionToJSON("传入数据异常，参数要包含表头信息和表体信息", "1");
        } else {
            IAPIBomBusinessService service = (IAPIBomBusinessService)NCLocator.getInstance().lookup(IAPIBomBusinessService.class);
            JSONString result = service.insert(paramList);
            return result;
        }
    }

    @POST
    @Path("operation/update")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString update(JSONObject para) {
        List<Map<String, Object>> paramList = (List)para.get("data");
        if (MMValueCheck.isEmpty(paramList)) {
            return ResultMessageUtil.exceptionToJSON("传入数据异常，参数要包含表头信息和表体信息", "1");
        } else {
            IAPIBomBusinessService service = (IAPIBomBusinessService)NCLocator.getInstance().lookup(IAPIBomBusinessService.class);
            JSONString result = service.update(paramList);
            return result;
        }
    }

    @POST
    @Path("update")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString update(List<Map<String, Object>> paramList) {
        if (MMValueCheck.isEmpty(paramList)) {
            return ResultMessageUtil.exceptionToJSON("传入数据异常，参数要包含表头信息和表体信息", "1");
        } else {
            IAPIBomBusinessService service = (IAPIBomBusinessService)NCLocator.getInstance().lookup(IAPIBomBusinessService.class);
            JSONString result = service.update(paramList);
            return result;
        }
    }

    @POST
    @Path("query")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString query(Map<String, Object> paramMap) {
        if (MMValueCheck.isEmpty(paramMap)) {
            return ResultMessageUtil.exceptionToJSON("传入数据异常，未传入查询条件", "1");
        } else {
            IAPIBomBusinessService service = (IAPIBomBusinessService)NCLocator.getInstance().lookup(IAPIBomBusinessService.class);
            JSONString result = service.query(paramMap);
            return result;
        }
    }

    @POST
    @Path("bomRepl/update")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString bomReplupdate(List<Map<String, Object>> paramMap) throws BusinessException {
        if (MMValueCheck.isEmpty(paramMap)) {
            return ResultMessageUtil.exceptionToJSON("传入数据异常，未传入更新数据", "1");
        } else {
            try{


            IAPIBomBusinessService service = (IAPIBomBusinessService)NCLocator.getInstance().lookup(IAPIBomBusinessService.class);
//            List<>
            IBomBillQueryService qry = (IBomBillQueryService)NCLocator.getInstance().lookup(IBomBillQueryService.class);
            IBomBillMaintainService bomBillMaintainService =  (IBomBillMaintainService)NCLocator.getInstance().lookup(IBomBillMaintainService.class);

            List<AggBomVO> bomReplVOS = new ArrayList<>();
            for (Map<String, Object> param : paramMap) {
                String cbomid = (String) param.get("cbomid");
                String targetCbomReplaceId = (String) param.get("cbom_replaceid"); // 目标替代ID
                String targetCbomBid = (String) param.get("cbombid"); // 目标物料项ID

                // 校验必要参数
                if (MMValueCheck.isEmpty(cbomid) || MMValueCheck.isEmpty(targetCbomBid)) {
                    ExceptionUtils.wrapBusinessException("cbomid和cbombid为必传参数");
                }

                // 查询BOM数据
                AggBomVO[] aggbomvos = qry.queryAggBomByBomID(new String[]{cbomid});
                if (MMValueCheck.isEmpty(aggbomvos)) {
                    ExceptionUtils.wrapBusinessException(NCLangRes4VoTransl.getNCLangRes().getStrByID("bdpub", "0bdpub0057"));
                }

                for (AggBomVO aggBomVO : aggbomvos) {
                    BomItemVO[] bomItemVOS = aggBomVO.getChildrenVO();
                    if (MMValueCheck.isEmpty(bomItemVOS)) {
                        continue; // 无物料项则跳过
                    }

                    for (BomItemVO bomItemVO : bomItemVOS) {
                        // 匹配目标物料项
                        if (targetCbomBid.equals(bomItemVO.getCbom_bid())) {
                            BomReplVO[] replVOS = bomItemVO.getRepl();
                            List<BomReplVO> replList = MMValueCheck.isEmpty(replVOS)
                                    ? new ArrayList<>()
                                    : new ArrayList<>(Arrays.asList(replVOS));

                            boolean isUpdated = false;

                            // 存在cbom_replaceid则更新
                            if (!MMValueCheck.isEmpty(targetCbomReplaceId)) {
                                for (BomReplVO replVO : replList) {
                                    if (targetCbomReplaceId.equals(replVO.getCbom_replaceid())) {
                                        // 设置属性（复用工具方法）
                                        setReplVOProperties(replVO, param);
                                        replVO.setStatus(VOStatus.UPDATED);
                                        isUpdated = true;
                                        break;
                                    }
                                }
                            }

                            // 不存在cbom_replaceid则新增
                            if (!isUpdated && MMValueCheck.isEmpty(targetCbomReplaceId)) {
                                BomReplVO newReplVO = new BomReplVO();
                                IdGenerator idGenerator = NCLocator.getInstance().lookup(IdGenerator.class);

                                newReplVO.setCbom_replaceid(idGenerator.generate()); // 生成新ID
                                newReplVO.setCbom_bid(targetCbomBid); // 关联当前物料项

                                // 计算新行号：(原有替代项数量 + 1) * 10
                                int existingCount = replList.size();
                                int newRowNumber = (existingCount + 1) * 10;
                                newReplVO.setVrowno(String.valueOf(newRowNumber)); // 设置新行号

                                // 设置其他属性（会覆盖param中的vrowno，确保按规则生成）
                                setReplVOProperties(newReplVO, param);

                                newReplVO.setStatus(VOStatus.NEW);
                                replList.add(newReplVO);
                            }

                            // 更新物料项的替代项数组
                            bomItemVO.setRepl(replList.toArray(new BomReplVO[0]));
                        }
                    }

                    // 更新BOM
                    aggBomVO.setChildrenVO(bomItemVOS);
                    AggBomVO[] result = this.updateBomWithParam(
                            new AggBomVO[]{aggBomVO},
                            false,
                            false,
                            MMBDFactoryParameter.getMMECN001Value(
                                    aggBomVO.getParentVO().getAttributeValue("pk_org").toString()
                            ).booleanValue(),
                            true
                    );
                    bomReplVOS.addAll(Arrays.asList(result));
                }
            }


            return ResultMessageUtil.toJSON(bomReplVOS, "BOM更新成功");
            }catch (BusinessException e) {
                throw new RuntimeException(e);
            }
        }

    }
    // 提取属性设置为工具方法，减少冗余
    private void setReplVOProperties(BomReplVO replVO, Map<String, Object> param) throws UifException {
        HYPubBO hybo = new HYPubBO();
//        if (param.containsKey("pk_group")) {
//            replVO.setPk_group((String) param.get("pk_group"));
//        }
//        if (param.containsKey("pk_org_v")) {
//            replVO.setPk_org_v((String) param.get("pk_org_v"));
//        }
        if (param.containsKey("creplmaterialvid")) {

            String mrlCode= (String) param.get("creplmaterialvid");
            String mrlid=(String) hybo.findColValue("bd_material","pk_material"," code  = '" + mrlCode + "' ");

            replVO.setCreplmaterialvid(mrlid);
        }
        if (param.containsKey("cbomid")) {
            replVO.setVprodversion((String) param.get("cbomid"));
        }
        if (param.containsKey("vreplaceindex")) {
            replVO.setVreplaceindex((String) param.get("vreplaceindex"));
        }
//        if (param.containsKey("vrowno")) {
//            replVO.setVrowno((String) param.get("vrowno"));
//        }

        // 处理数字类型转换
        if (param.containsKey("ireplorder")) {
            Object ireplorderObj = param.get("ireplorder");
            if (ireplorderObj instanceof Double) {
                replVO.setIreplorder(new UFDouble((Double) ireplorderObj).intValue());
            } else if (ireplorderObj instanceof Number) {
                replVO.setIreplorder(((Number) ireplorderObj).intValue());
            }
        }

        // 处理布尔类型转换
        if (param.containsKey("bisdisplace")) {
            Object bisdisplaceObj = param.get("bisdisplace");
            if (bisdisplaceObj instanceof Boolean) {
                replVO.setBisdisplace(UFBoolean.valueOf((Boolean) bisdisplaceObj));
            } else if (bisdisplaceObj instanceof UFBoolean) {
                replVO.setBisdisplace((UFBoolean) bisdisplaceObj);
            }
        }
    }
    public AggBomVO[] updateBomWithParam(AggBomVO[] aggvos, boolean isFromBom, boolean isecn, boolean isCheckEcn,
                                         boolean isOnApprove) throws BusinessException {
        if (MMArrayUtil.isEmpty(aggvos)) {
            return null;
        }
        try {
            // 检查该BOM是否被删除，因为如果BOM树状维护将BOM删除了，不允许修改该条记录
            Set<String> bomids = new HashSet<String>();
            for (AggBomVO vo : aggvos) {
                bomids.add(vo.getPrimaryKey());
            }
            Set<String> checkResult = BomPubBP.getBomID(bomids.toArray(new String[] {}));
            if (checkResult != null && checkResult.size() < bomids.size()) {
                nc.vo.pubapp.pattern.exception.ExceptionUtils.wrappBusinessException(MMBDLangConstBom0202.getBOM_DELETED());
            }
            // 加锁 + 检查ts
            GCBillTransferTool<AggBomVO> transTool = new GCBillTransferTool<AggBomVO>(aggvos);
            // 补全前台VO
            AggBomVO[] fullBills = transTool.getClientFullInfoBill();
            // 获得修改前vo
            AggBomVO[] originBills = transTool.getOriginBills();
            BomUpdateBP bp = new BomUpdateBP();
            return bp.update(fullBills, originBills, isCheckEcn, isOnApprove, isFromBom, isecn);
        } catch (Exception e) {
            nc.vo.pubapp.pattern.exception.ExceptionUtils.marsh(e);
        }
        return null;
    }

    public String getModule() {
        return "mmbd";
    }
}
