package nc.api.qc.resource;

import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.trade.business.HYSuperDMO;
import nc.impl.qc.c003.maintain.ReportMaintainImpl;
import nc.itf.qc.c003.maintain.IReportMaintain;
import nc.vo.pub.BusinessException;
import nc.vo.pub.VOStatus;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.model.transfer.bill.ClientBillCombinServer;
import nc.vo.qc.c003.entity.ReportItemVO;
import nc.vo.qc.c003.entity.ReportVO;
import nc.vo.qc.c003.util.ReportVOInfoUtils;
import nc.vo.scmpub.res.billtype.QCBillType;
import nc.vo.scmpub.util.ArrayUtil;
import nc.vo.scmpub.util.CollectionUtils;
import nccloud.api.rest.utils.NCCRestUtils;
import nccloud.api.rest.utils.ResultMessageUtil;
import nccloud.base.exception.ExceptionUtils;
import nccloud.framework.service.ServiceLocator;
import nccloud.pubitf.arap.arappub.IArapBillPubUtilService;
import nccloud.pubitf.riart.pflow.CloudPFlowContext;
import nccloud.pubitf.riart.pflow.ICloudScriptPFlowService;
import nccloud.pubitf.scmpub.pub.service.ISCMPubQueryService;
import org.json.JSONString;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * QMS将检验结果回传至ERP质检报告中
 */
@Path("qc/qcconclusion")
public class QcconclusionRestResource extends QcBaseRestResource {

    HYSuperDMO dmo = null;

    public HYSuperDMO getSuperDMO() {
        if (dmo == null) {
            dmo = new HYSuperDMO();
        }
        return dmo;
    }

    /**
     * QMS将检验结果回传至ERP质检报告中
     *
     * @param str
     * @return
     */

    @POST
    @Path("/updateByqms")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString updateByqms(JSONString str) throws BusinessException {
        InvocationInfoProxy.getInstance().setGroupId("0001A110000000000677");
        NCCRestUtils.initInvocationInfo();
        String json = str.toJSONString();
        Map<String, Object> billMap = (Map) fromJson(json, Map.class);
//        List<ReportVO> list = (List<ReportVO>) billMap.get("list");
        //获取全部质检报告
        List<Map<String, Object>> itemMaps = (List) billMap.get("items");
        List<String> list=new ArrayList<String>();
        for (Map<String, Object> itemMap : itemMaps) {
            list.add((String) itemMap.get("id"));
        }
        ReportVO[] vos = (ReportVO[])((ISCMPubQueryService) NCLocator.getInstance().lookup(ISCMPubQueryService.class)).billquery(ReportVO.class, list.toArray(new String[list.size()]));
        // 1. 创建新数组（长度与原数组一致）
        ReportVO[] updatevos = new ReportVO[vos.length];

// 2. 遍历原数组，对每个元素进行深度克隆
        for (int i = 0; i < vos.length; i++) {
            if (vos[i] != null) {
                // 假设ReportVO重写了clone()方法，实现深度克隆
                updatevos[i] = (ReportVO) vos[i].clone();
            }
        }
        for (ReportVO vo : vos) {
            // 先判断vo和其HVO是否为null（避免NPE）
            if (vo == null || vo.getHVO() == null) {
                continue;
            }
            Object pkReportbill = vo.getHVO().getPk_reportbill();
            // 校验HVO的pk_reportbill是否为必填（不为null）
            if (pkReportbill == null) {
                continue;
            }

            for (Map<String, Object> itemMap : itemMaps) {
                // 校验itemMap的id是否为必填（存在且不为null）
                if (itemMap == null || !itemMap.containsKey("id") || itemMap.get("id") == null) {
                    continue;
                }
                // 比较id是否匹配（双方都已校验非null）
                if (!itemMap.get("id").equals(pkReportbill)) {
                    continue;
                }

                // 匹配成功，更新状态
                vo.getHVO().setStatus(VOStatus.UPDATED);

                // 处理数量字段（存在且不为null才赋值）
                // 检验主数量
                if (itemMap.containsKey("nchecknum") && itemMap.get("nchecknum") instanceof Double) {
                    vo.getHVO().setNchecknum(new UFDouble((Double) itemMap.get("nchecknum")));
                }
                // 检验数量
                if (itemMap.containsKey("ncheckastnum") && itemMap.get("ncheckastnum") instanceof Double) {
                    vo.getHVO().setNcheckastnum(new UFDouble((Double) itemMap.get("ncheckastnum")));
                }
                // 合格主数量
                if (itemMap.containsKey("neliginum") && itemMap.get("neliginum") instanceof Double) {
                    vo.getHVO().setNeliginum(new UFDouble((Double) itemMap.get("neliginum")));
                }
                // 合格数量
                if (itemMap.containsKey("neligiastnum") && itemMap.get("neligiastnum") instanceof Double) {
                    vo.getHVO().setNeligiastnum(new UFDouble((Double) itemMap.get("neligiastnum")));
                }
                // 不合格主数量
                if (itemMap.containsKey("nuneliginum") && itemMap.get("nuneliginum") instanceof Double) {
                    vo.getHVO().setNuneliginum(new UFDouble((Double) itemMap.get("nuneliginum")));
                }
                // 不合格数量
                if (itemMap.containsKey("nuneligiastnum") && itemMap.get("nuneligiastnum") instanceof Double) {
                    vo.getHVO().setNuneligiastnum(new UFDouble((Double) itemMap.get("nuneligiastnum")));
                }

                this.appendPseudoColumn(vo);

                // 处理子列表（先判断是否为有效列表）
                Object childrenObj = itemMap.get("children");
                if (!(childrenObj instanceof List)) {
                    continue;
                }
                List<Map<String, Object>> mapList = (List<Map<String, Object>>) childrenObj;
                if (mapList.isEmpty()) {
                    continue;
                }

                // 处理BVO数组（先判断数组是否为null）
                ReportItemVO[] bvos = vo.getBVO();
                if (bvos == null) {
                    continue;
                }

                for (int i = 0; i < bvos.length; i++) {
                    ReportItemVO bvo = bvos[i];
                    // 跳过null的BVO
                    if (bvo == null) {
                        continue;
                    }
                    // 校验BVO的reportbill_b是否为必填（不为null）
                    String bvoCrowno = bvo.getPk_reportbill_b();
                    if (bvoCrowno == null) {
                        continue;
                    }

                    for (Map<String, Object> childMap : mapList) {
                        // 校验childMap的reportbill_b是否为必填（存在且不为null）
                        if (childMap == null || !childMap.containsKey("reportbill_b") || childMap.get("reportbill_b") == null) {
                            continue;
                        }
                        // 比较reportbill_b是否匹配
                        if (!bvoCrowno.equals(childMap.get("reportbill_b"))) {
                            continue;
                        }

                        // 匹配成功，更新子项字段（存在且不为null才赋值）
                        bvo.setStatus(VOStatus.UPDATED);
                        // 子项数量
                        if (childMap.containsKey("nnum") && childMap.get("nnum") instanceof Double) {
                            bvo.setNnum(new UFDouble((Double) childMap.get("nnum")));
                        }
                        // 处理判断状态
                        if (childMap.containsKey("fprocessjudge") && childMap.get("fprocessjudge") instanceof Double) {
                            bvo.setFprocessjudge(((Double) childMap.get("fprocessjudge")).intValue());
                        }
                    }
                }
            }
        }
//        this.doSaveAndCombine(vos);
        IReportMaintain reportMaintain=((IReportMaintain) NCLocator.getInstance().lookup(IReportMaintain.class));
        ReportVO[] resultVos=  reportMaintain.saveBase(vos,new Object(),updatevos);
        //质检报告更新
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("data", resultVos);
        returnMap.put("success", true);
        return ResultMessageUtil.toJSON(returnMap);
    }

    private void doSaveAndCombine(ReportVO[] billVos) {
        CloudPFlowContext context = new CloudPFlowContext();
        context.setBillType(QCBillType.ReportBill.getCode());
        context.setTrantype(billVos[0].getHVO().getVtrantypecode());
        context.setBillVos(billVos);
        context.setActionName("SAVEBASE");
        ICloudScriptPFlowService service = (ICloudScriptPFlowService) NCLocator.getInstance().lookup(ICloudScriptPFlowService.class);
        ReportVO[] retVOs = null;
        try {
            Object ret = service.exeScriptPFlow(context);
            if (ret instanceof ReportVO[]) {
                retVOs = (ReportVO[]) ret;
            } else {
                retVOs = (ReportVO[]) ((Object[]) ret)[0];
            }
        } catch (Exception e) {
            ExceptionUtils.wrapException(e);
        }
        if (!ArrayUtil.isEmpty(retVOs)) {
            ClientBillCombinServer<ReportVO> util = new ClientBillCombinServer();
            this.processDelBody(billVos);
            util.combine(billVos, retVOs);
            retVOs = ReportVOInfoUtils.synchBatchCodeData(billVos);
        }

    }
    private void processDelBody(ReportVO[] vos) {
        ReportItemVO[] bodys = vos[0].getBVO();
        List<ReportItemVO> realbody = new ArrayList();

        for(ReportItemVO body : bodys) {
            if (body.getStatus() != 3) {
                realbody.add(body);
            }
        }

        vos[0].setBVO((ReportItemVO[]) CollectionUtils.listToArray(realbody));
    }
    private void appendPseudoColumn(ReportVO vo) {
        ReportItemVO[] bodyvos = vo.getBVO();
        if (bodyvos != null && bodyvos.length > 0) {
            for(int i = 0; i < bodyvos.length; ++i) {
                bodyvos[i].setAttributeValue("pseudocolumn", i);
            }
        }

    }
}
