package nccloud.openapi.mmpac.wr;


import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Log;
import nc.bs.uif2.validation.ValidationFailure;
import nc.jdbc.framework.SQLParameter;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.util.mmf.framework.base.MMArrayUtil;
import nc.util.mmf.framework.base.MMCollectionUtil;
import nc.util.mmf.framework.base.MMNumberUtil;
import nc.util.mmf.framework.base.MMValueCheck;
import nc.vo.mmpac.wr.entity.*;
import nc.vo.mmpac.wr.enumeration.WrBillStatusEnum;
import nc.vo.pub.BusinessException;
import nc.vo.pub.VOStatus;
import nc.vo.pub.billtype.BilltypeVO;
import nc.vo.pub.lang.UFDate;
import nc.vo.pubapp.AppContext;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nccloud.api.mmpac.wr.IAPIWrMaintain;
import nccloud.api.rest.utils.NCCRestUtils;
import nccloud.api.rest.utils.ResultMessageUtil;
import nccloud.openapi.scmpub.pub.TransferCodeToPKTool;
import nccloud.ws.rest.resource.AbstractNCCRestResource;
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.*;

@Path("mmpac/wr")
public class WrResource extends AbstractNCCRestResource {

    private static String HEADTABLE = "mm_wr";

    private static String BODYTABLE = "mm_wr_product";

    private static String QUALITYTABLE = "mm_wr_quality";

    private static String SERIALNOTABLE = "mm_wr_serialno";

    private static String PICKNOTABLE = "mm_wr_pick";

    private static String GNUM_QUALITY = "ngqualitynum";
    private static String GNUM_REWORK = "ngreworknum";
    private static String GNUM_REJECT = "ngrejectnum";
    private static String GASTNUM_QUALITY = "ngqualityastnum";
    private static String GASTNUM_REWORK = "ngreworkastnum";
    private static String GASTNUM_REJECT = "ngrejectastnum";
    private static List<String> HeadUnUpdateFiled = Arrays.asList(WrVO.PK_WR, WrVO.PK_GROUP, WrVO.CWKID,
            WrVO.FBILLSTATUS, WrVO.VBILLCODE, WrVO.PK_ORG, WrVO.PK_ORG_V);
    private static List<String> BodyUnUpdateFiled = Arrays.asList(WrItemVO.PK_WR, "cbunitid", "pk_group", "pk_org",
            "pk_org_v", "pk_wr_product", "bbhasfbill", "bbhaspicked", "bbinstock", "bbisempass", "cbempass_bid",
            "cbempass_brow", "cbempasscode", "cbempassid", "cbfirstmobid", "cbfirstmoid", "cbsrctranstype", "cbsrcmoid",
            "cbsrcmobid", "cbfirstranstype", "cbmaterialid", "cbmainmaterialid", "fbsourcetype", "nbaldempinastnum",
            "nbaldempinnum", "nbcheckastnum", "nbchecknum", "nbempassastnum", "nbempassnum", "nbsldcheckastnum",
            "nbsldchecknum", "nbsldinastnum", "nbsldinnum", "vbbatchid", "vbfirstcode", "vbfirstid", "vbfirstmocode",
            "vbfirstmorowno", "vbfirstranstype", "vbfirstrowid", "vbfirstrowno", "vbfirsttype", "vbidentify",
            "vbinbatchid", "vbmainidentify", "vbmainmorowno", "vbmobillcode", "vbmoparentbillcode", "vbmorowno",
            "vbparentmorowno", "vbsalebillcode", "vbsalebillid", "vbsrccode", "vbsrcid", "vbsrcmocode", "vbsrcmorowno",
            "vbsrcrowid", "vbsrcrowno", "vbmainbomcode", "vbsrctranstype", "bbhasbckfled", "bbhaspicked", "bbsetmark");

    @POST
    @Path("saveAndApprove")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString saveAndApprove(List<Map<String, Object>> paramList) {
        if (MMValueCheck.isEmpty(paramList)) {
            return ResultMessageUtil.exceptionToJSON("传入数据异常，参数要包含表头信息和表体信息", "1");
        }
        List<AggWrVO> voList = new ArrayList<AggWrVO>();
        try {
            for (Map<String, Object> paramMap : paramList) {
                if (!paramMap.containsKey(HEADTABLE) || !paramMap.containsKey(BODYTABLE)) {
                    return ResultMessageUtil.exceptionToJSON("传入数据异常，参数要包含表头信息和表体信息", "1");
                }
                Map<String, Object> headInfo = (Map<String, Object>) paramMap.get(HEADTABLE);
                List<Map<String, Object>> itemInfos = new ArrayList<Map<String, Object>>();
                if (paramMap.get(BODYTABLE) instanceof List) {
                    itemInfos = (List<Map<String, Object>>) paramMap.get(BODYTABLE);
                } else {
                    Map<String, Object> bodyInfo = (Map<String, Object>) paramMap.get(BODYTABLE);
                    itemInfos.add(bodyInfo);
                }
                AggWrVO vo = new AggWrVO();
                WrVO head = new WrVO();
                head.setPk_group(AppContext.getInstance().getPkGroup());
                head.setStatus(VOStatus.NEW);
                for (String key : headInfo.keySet()) {
                    head.setAttributeValue(key, headInfo.get(key));
                }
                vo.setParentVO(head);
                List<WrItemVO> items = new ArrayList<WrItemVO>();
                String paramdata = NCCRestUtils.toJSONString(itemInfos).toJSONString();
                Log.getInstance("mm-mes").info("mes到生产报告参数：" + paramdata);
                for (Map<String, Object> itemMap : itemInfos) {
                    WrItemVO item = new WrItemVO();
                    item.setStatus(VOStatus.NEW);
                    boolean hasGNumFlag = false;
                    for (String key : itemMap.keySet()) {
                        if (QUALITYTABLE.equals(key)) {
                            List<Map<String, Object>> qualityInfos = (List<Map<String, Object>>) itemMap
                                    .get(QUALITYTABLE);
                            List<WrQualityVO> qualitys = this.getWrQualitys(qualityInfos);
                            item.setQualityvos(qualitys.toArray(new WrQualityVO[0]));
                        } else if (SERIALNOTABLE.equals(key)) {
                            List<Map<String, Object>> snInfos = (List<Map<String, Object>>) itemMap.get(SERIALNOTABLE);
                            List<WrSerialNoVO> snVOs = this.getWrSerialNos(snInfos);
                            item.setSerialnovos(snVOs.toArray(new WrSerialNoVO[0]));
                        } else if (PICKNOTABLE.equals(key)) {
                            continue;
                        } else if (this.isGNumFilds(key)) {
                            hasGNumFlag = true;
                        } else {
                            item.setAttributeValue(key, itemMap.get(key));
                        }
                    }
                    if (hasGNumFlag) {
                        List<WrQualityVO> qualitys = this.getWrQualitysByGnum(itemMap, item);
                        item.setQualityvos(qualitys.toArray(new WrQualityVO[0]));
                    }
                    items.add(item);
                }
                vo.setChildren(WrItemVO.class, items.toArray(new WrItemVO[0]));
                voList.add(vo);
                IAPIWrMaintain server = NCLocator.getInstance().lookup(IAPIWrMaintain.class);
                List<AggWrVO> aggWrVOS = TransferCodeToPKTool.transferAggVO(voList);
                //翻译报告类型
                BaseDAO baseDAO = new BaseDAO();
                for (AggWrVO aggWrVO : aggWrVOS) {
                    List<BilltypeVO> collection = (List<BilltypeVO>) baseDAO.retrieveByClause(BilltypeVO.class, " pk_billtypecode='" + aggWrVO.getParentVO().getVtrantypecode() + "'");
                    if(collection==null||collection.size()==0){
                        throw new BusinessException("翻译报告类型失败，检查报告类型编码【"+aggWrVO.getParentVO().getVtrantypecode()+"】");
                    }
                    aggWrVO.getParentVO().setVtrantypeid(collection.get(0).getPk_billtypeid());
                    aggWrVO.getParentVO().setDbilldate(new UFDate());
                }
                AggWrVO[] aggvos = server.saveAndApprove(voList.toArray(new AggWrVO[0]));
                boolean successFlag = true;
                StringBuilder errMsg = new StringBuilder();
                if (MMArrayUtil.isNotEmpty(aggvos)) {
                    for (AggWrVO aggvo : aggvos) {
                        List<ValidationFailure> validateList = aggvo.getParentVO().getExcpMsgList();
                        if (MMCollectionUtil.isNotEmpty(validateList)) {
                            successFlag = false;
                            errMsg.append(aggvo.getParentVO().getVbillcode());
                            errMsg.append(":");
                            for (ValidationFailure validate : validateList) {
                                errMsg.append(validate.getMessage());
                                errMsg.append(";");
                            }
                        }
                    }
                }
                if (successFlag) {
                    return ResultMessageUtil.toJSON(aggvos, "生产报告保存成功");
                } else {
                    ExceptionUtils.wrappBusinessException(errMsg.toString());
                }
            }
        } catch (Exception e) {
            return ResultMessageUtil.exceptionToJSON(e);
        }
        return null;
    }

    private List<WrQualityVO> getWrQualitysByGnum(Map<String, Object> itemMap, WrItemVO item) {
        List<WrQualityVO> qualityVOs = new ArrayList<WrQualityVO>();
        // 合格数量1
        if (itemMap.containsKey(WrResource.GNUM_QUALITY) || itemMap.containsKey(WrResource.GASTNUM_QUALITY)) {
            WrQualityVO qVO = new WrQualityVO();
            qVO.setFgprocessmethod(1);
            if (itemMap.containsKey(WrResource.GNUM_QUALITY)) {
                qVO.setAttributeValue(WrQualityVO.NGNUM, itemMap.get(WrResource.GNUM_QUALITY));
            }
            if (itemMap.containsKey(WrResource.GASTNUM_QUALITY)) {
                qVO.setAttributeValue(WrQualityVO.NGASTNUM, itemMap.get(WrResource.GASTNUM_QUALITY));
            }
            if (MMNumberUtil.isGtZero(qVO.getNgnum()) || MMNumberUtil.isGtZero(qVO.getNgastnum())) {
                qualityVOs.add(qVO);
            }
        }
        // 报废数量2
        if (itemMap.containsKey(WrResource.GNUM_REJECT) || itemMap.containsKey(WrResource.GASTNUM_REJECT)) {
            WrQualityVO qVO = new WrQualityVO();
            qVO.setFgprocessmethod(2);
            if (itemMap.containsKey(WrResource.GNUM_REJECT)) {
                qVO.setAttributeValue(WrQualityVO.NGNUM, itemMap.get(WrResource.GNUM_REJECT));
            }
            if (itemMap.containsKey(WrResource.GASTNUM_REJECT)) {
                qVO.setAttributeValue(WrQualityVO.NGASTNUM, itemMap.get(WrResource.GASTNUM_REJECT));
            }
            if (MMNumberUtil.isGtZero(qVO.getNgnum()) || MMNumberUtil.isGtZero(qVO.getNgastnum())) {
                qualityVOs.add(qVO);
            }
        }
        // 返工数量3
        if (itemMap.containsKey(WrResource.GNUM_REWORK) || itemMap.containsKey(WrResource.GASTNUM_REWORK)) {
            WrQualityVO qVO = new WrQualityVO();
            qVO.setFgprocessmethod(3);
            if (itemMap.containsKey(WrResource.GNUM_REWORK)) {
                qVO.setAttributeValue(WrQualityVO.NGNUM, itemMap.get(WrResource.GNUM_REWORK));
            }
            if (itemMap.containsKey(WrResource.GASTNUM_REWORK)) {
                qVO.setAttributeValue(WrQualityVO.NGASTNUM, itemMap.get(WrResource.GASTNUM_REWORK));
            }
            if (MMNumberUtil.isGtZero(qVO.getNgnum()) || MMNumberUtil.isGtZero(qVO.getNgastnum())) {
                qualityVOs.add(qVO);
            }
        }
        return qualityVOs;
    }

    private boolean isGNumFilds(String key) {
        if (WrResource.GNUM_QUALITY.equals(key)) {
            return true;
        } else if (WrResource.GASTNUM_QUALITY.equals(key)) {
            return true;
        } else if (WrResource.GNUM_REJECT.equals(key)) {
            return true;
        } else if (WrResource.GASTNUM_REJECT.equals(key)) {
            return true;
        } else if (WrResource.GNUM_REWORK.equals(key)) {
            return true;
        } else if (WrResource.GASTNUM_REWORK.equals(key)) {
            return true;
        }
        return false;
    }

    private List<WrSerialNoVO> getWrSerialNos(List<Map<String, Object>> snInfos) {
        List<WrSerialNoVO> snVOs = new ArrayList<WrSerialNoVO>();
        for (Map<String, Object> snInfo : snInfos) {
            WrSerialNoVO snVO = new WrSerialNoVO();
            for (String key : snInfo.keySet()) {
                snVO.setAttributeValue(key, snInfo.get(key));
            }
            snVOs.add(snVO);
        }
        return snVOs;
    }

    private List<WrQualityVO> getWrQualitys(List<Map<String, Object>> qualityInfos) {
        List<WrQualityVO> qualityVOs = new ArrayList<WrQualityVO>();
        for (Map<String, Object> qualityInfo : qualityInfos) {
            WrQualityVO qualityVO = new WrQualityVO();
            for (String key : qualityInfo.keySet()) {
                qualityVO.setAttributeValue(key, qualityInfo.get(key));
            }
            qualityVOs.add(qualityVO);
        }
        return qualityVOs;
    }

    @Override
    public String getModule() {
        // TODO Auto-generated method stub
        return null;
    }

    @POST
    @Path("deleteByMesIDs")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString deleteByMesIDs(String[] mesIDs) {
        if (MMValueCheck.isEmpty(mesIDs)) {
            return ResultMessageUtil.exceptionToJSON("传入数据异常", "1");
        }
        try {
            IAPIWrMaintain server = NCLocator.getInstance().lookup(IAPIWrMaintain.class);
            server.deleteWrByMesID(mesIDs);
            return ResultMessageUtil.toJSON(null, "生产报告删除成功");

        } catch (Exception e) {
            return ResultMessageUtil.exceptionToJSON(e);
        }
    }

    @POST
    @Path("newsave")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString newsave(Map<String, Object> paramsMap) {
        List<Map<String, Object>> paramList = (List<Map<String, Object>>) paramsMap.get("data");
        if (MMValueCheck.isEmpty(paramList)) {
            return ResultMessageUtil.exceptionToJSON("传入数据异常，参数要包含表头信息和表体信息", "1");
        }
        List<AggWrVO> voList = new ArrayList<AggWrVO>();
        BaseDAO baseDAO = new BaseDAO();
        try {
            for (Map<String, Object> paramMap : paramList) {
                if (!paramMap.containsKey(HEADTABLE) || !paramMap.containsKey(BODYTABLE)) {
                    return ResultMessageUtil.exceptionToJSON("传入数据异常，参数要包含表头信息和表体信息", "1");
                }
                Map<String, Object> headInfo = (Map<String, Object>) paramMap.get(HEADTABLE);
                List<Map<String, Object>> itemInfos = new ArrayList<Map<String, Object>>();
                if (paramMap.get(BODYTABLE) instanceof List) {
                    itemInfos = (List<Map<String, Object>>) paramMap.get(BODYTABLE);
                } else {
                    Map<String, Object> bodyInfo = (Map<String, Object>) paramMap.get(BODYTABLE);
                    itemInfos.add(bodyInfo);
                }

                // 预处理数据：处理仓库转换和MES相关字段
                preProcessMesData(headInfo, itemInfos, baseDAO);
                AggWrVO vo = new AggWrVO();
                WrVO head = new WrVO();
                head.setPk_group(AppContext.getInstance().getPkGroup());
                for (String key : headInfo.keySet()) {
                    if (MMValueCheck.isEmpty(headInfo.get(key))) {
                        continue;
                    }
                    head.setAttributeValue(key, headInfo.get(key));
                }
                vo.setParentVO(head);
                List<WrItemVO> items = new ArrayList<WrItemVO>();
                String paramdata = NCCRestUtils.toJSONString(itemInfos).toJSONString();
                Log.getInstance("mm-mes").info("mes到生产报告参数：" + paramdata);
                for (Map<String, Object> itemMap : itemInfos) {
                    WrItemVO item = new WrItemVO();
                    boolean hasGNumFlag = false;
                    for (String key : itemMap.keySet()) {

                        if (QUALITYTABLE.equals(key)) {
                            List<Map<String, Object>> qualityInfos = (List<Map<String, Object>>) itemMap
                                    .get(QUALITYTABLE);
                            List<WrQualityVO> qualitys = this.getWrQualitys(qualityInfos);
                            item.setQualityvos(qualitys.toArray(new WrQualityVO[0]));
                        } else if (SERIALNOTABLE.equals(key)) {
                            List<Map<String, Object>> snInfos = (List<Map<String, Object>>) itemMap.get(SERIALNOTABLE);
                            List<WrSerialNoVO> snVOs = this.getWrSerialNos(snInfos);
                            item.setSerialnovos(snVOs.toArray(new WrSerialNoVO[0]));
                        } else if (PICKNOTABLE.equals(key)) {
                            continue;
                        } else if (this.isGNumFilds(key)) {
                            hasGNumFlag = true;
                        } else {
                            if (MMValueCheck.isEmpty(itemMap.get(key))) {
                                continue;
                            }
                            item.setAttributeValue(key, itemMap.get(key));
                        }
                    }
                    if (hasGNumFlag) {
                        List<WrQualityVO> qualitys = this.getWrQualitysByGnum(itemMap, item);
                        item.setQualityvos(qualitys.toArray(new WrQualityVO[0]));
                    }
                    items.add(item);
                }
                vo.setChildren(WrItemVO.class, items.toArray(new WrItemVO[0]));
                voList.add(vo);
                IAPIWrMaintain server = NCLocator.getInstance().lookup(IAPIWrMaintain.class);
                List<AggWrVO> aggWrVOS = TransferCodeToPKTool.transferAggVO(voList);
                //翻译报告类型
                for (AggWrVO aggWrVO : aggWrVOS) {
                    List<BilltypeVO> collection = (List<BilltypeVO>) baseDAO.retrieveByClause(BilltypeVO.class, " pk_billtypecode='" + aggWrVO.getParentVO().getVtrantypecode() + "'");
                    if(collection==null||collection.size()==0){
                        throw new BusinessException("翻译报告类型失败，检查报告类型编码【"+aggWrVO.getParentVO().getVtrantypecode()+"】");
                    }
                    aggWrVO.getParentVO().setVtrantypeid(collection.get(0).getPk_billtypeid());
                    aggWrVO.getParentVO().setDbilldate(new UFDate());
                }
                AggWrVO[] aggvos = server.newsave(voList.toArray(new AggWrVO[0]));
                boolean successFlag = true;
                StringBuilder errMsg = new StringBuilder();
                if (MMArrayUtil.isNotEmpty(aggvos)) {
                    for (AggWrVO aggvo : aggvos) {
                        List<ValidationFailure> validateList = aggvo.getParentVO().getExcpMsgList();
                        if (MMCollectionUtil.isNotEmpty(validateList)) {
                            successFlag = false;
                            errMsg.append(aggvo.getParentVO().getVbillcode());
                            errMsg.append(":");
                            for (ValidationFailure validate : validateList) {
                                errMsg.append(validate.getMessage());
                                errMsg.append(";");
                            }
                        }
                    }
                }
                if (successFlag) {
                    return ResultMessageUtil.toJSON(aggvos, "生产报告保存成功");
                } else {
                    ExceptionUtils.wrappBusinessException(errMsg.toString());
                }
            }
        } catch (Exception e) {
            return ResultMessageUtil.exceptionToJSON(e);
        }
        return null;
    }

    @POST
    @Path("update")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString update(Map<String, Object> paramsMap) throws BusinessException {
        List<Map<String, Object>> paramList = (List<Map<String, Object>>) paramsMap.get("data");
        if (MMValueCheck.isEmpty(paramList)) {
            return ResultMessageUtil.exceptionToJSON("传入数据异常，参数要包含表头信息和表体信息", "1");
        }
        List<AggWrVO> voList = new ArrayList<AggWrVO>();
        IAPIWrMaintain server = NCLocator.getInstance().lookup(IAPIWrMaintain.class);

        List<String> aggIds = new ArrayList<>();
        for (Map<String, Object> paramMap : paramList) {
            if (!paramMap.containsKey(HEADTABLE) || !paramMap.containsKey(BODYTABLE)) {
                return ResultMessageUtil.exceptionToJSON("传入数据异常，参数要包含表头信息和表体信息", "1");
            }
            Map<String, Object> headInfo = (Map<String, Object>) paramMap.get(HEADTABLE);
            if (MMValueCheck.isNotEmpty(headInfo.get("pk_wr"))) {
                aggIds.add(headInfo.get("pk_wr").toString());
            }
        }
        if (MMValueCheck.isEmpty(aggIds)) {
            return ResultMessageUtil.exceptionToJSON("传入数据异常，参数要包含生产报告表头主键", "1");
        }
        AggWrVO[] aggWrVOSByIds = server.findAggWrVOSByIds(aggIds.toArray(new String[0]));
        Map<String, AggWrVO> voMap = new HashMap<>();
        for (AggWrVO aggWrVO : aggWrVOSByIds) {
            voMap.put(aggWrVO.getParentVO().getPk_wr(), aggWrVO);
        }

        try {
            // 根据传递阐参数修改生产报告数据
            for (Map<String, Object> paramMap : paramList) {

                Map<String, Object> headInfo = (Map<String, Object>) paramMap.get(HEADTABLE);
                List<Map<String, Object>> itemInfos = new ArrayList<Map<String, Object>>();
                if (paramMap.get(BODYTABLE) instanceof List) {
                    itemInfos = (List<Map<String, Object>>) paramMap.get(BODYTABLE);
                } else {
                    Map<String, Object> bodyInfo = (Map<String, Object>) paramMap.get(BODYTABLE);
                    itemInfos.add(bodyInfo);
                }
                AggWrVO vo = voMap.get(headInfo.get("pk_wr").toString());
                if (MMValueCheck.isEmpty(vo)) {
                    return ResultMessageUtil
                            .exceptionToJSON("单据号：" + headInfo.get("vbillcode") + "生产报告在数据库中不存在或者已经被删除！", "1");
                }
                WrVO head = vo.getParentVO();
                if (!(WrBillStatusEnum.I_FREEDOM.intValue() == head.getFbillstatus())) {
                    return ResultMessageUtil.exceptionToJSON("非自由态的生产报告不允许修改！", "1");
                }

                // 处理表头数据
                head.setStatus(VOStatus.UPDATED);
                for (String key : headInfo.keySet()) {
                    if (MMValueCheck.isEmpty(headInfo.get(key))) {
                        continue;
                    }
                    if (HeadUnUpdateFiled.contains(key)
                            && !head.getAttributeValue(key).toString().equals(headInfo.get(key))) {
                        return ResultMessageUtil.exceptionToJSON("表头属性：" + key + "不允许修改", "1");
                    }
                    head.setAttributeValue(key, headInfo.get(key));
                }
                vo.setParentVO(head);

                // 处理表体数据和孙表数据
                Map<String, WrItemVO> wrItemVOMap = new HashMap<>();
                if (MMValueCheck.isNotEmpty(vo.getChildrenVO())) {
                    for (WrItemVO wrItemVO : vo.getChildrenVO()) {
                        wrItemVOMap.put(wrItemVO.getPk_wr_product(), wrItemVO);
                    }
                }
                List<WrItemVO> items = new ArrayList<WrItemVO>();
                String paramdata = NCCRestUtils.toJSONString(itemInfos).toJSONString();
                Log.getInstance("mm-mes").info("mes到生产报告参数：" + paramdata);
                for (Map<String, Object> itemMap : itemInfos) {
                    WrItemVO item = wrItemVOMap.get(itemMap.get("pk_wr_product"));
                    if (MMValueCheck.isEmpty(item)) {
                        continue;
                    }
                    item.setStatus(VOStatus.UPDATED);
                    boolean hasGNumFlag = false;
                    for (String key : itemMap.keySet()) {

                        if (QUALITYTABLE.equals(key)) {
                            List<Map<String, Object>> qualityInfos = (List<Map<String, Object>>) itemMap
                                    .get(QUALITYTABLE);
                            List<WrQualityVO> qualitys = this.getWrQualitys(qualityInfos);
                            item.setQualityvos(qualitys.toArray(new WrQualityVO[0]));
                        } else if (SERIALNOTABLE.equals(key)) {
                            List<Map<String, Object>> snInfos = (List<Map<String, Object>>) itemMap.get(SERIALNOTABLE);
                            List<WrSerialNoVO> snVOs = this.getWrSerialNos(snInfos);
                            item.setSerialnovos(snVOs.toArray(new WrSerialNoVO[0]));
                        } else if (PICKNOTABLE.equals(key)) {
                            continue;
                        } else if (this.isGNumFilds(key)) {
                            hasGNumFlag = true;
                        } else {
                            if (MMValueCheck.isEmpty(itemMap.get(key))) {
                                continue;
                            }
                            if (BodyUnUpdateFiled.contains(key) && MMValueCheck.isNotEmpty(item.getAttributeValue(key))
                                    && !item.getAttributeValue(key).toString().equals(itemMap.get(key).toString())) {
                                return ResultMessageUtil.exceptionToJSON("表体属性：" + key + "不允许修改", "1");
                            }
                            item.setAttributeValue(key, itemMap.get(key));
                        }
                    }
                    if (hasGNumFlag) {
                        List<WrQualityVO> qualitys = this.getWrQualitysByGnum(itemMap, item);
                        item.setQualityvos(qualitys.toArray(new WrQualityVO[0]));
                    }
                    items.add(item);
                }
                vo.setChildren(WrItemVO.class, items.toArray(new WrItemVO[0]));
                voList.add(vo);
            }

            AggWrVO[] aggvos = server.update(voList.toArray(new AggWrVO[0]));
            boolean successFlag = true;
            StringBuilder errMsg = new StringBuilder();
            if (MMArrayUtil.isNotEmpty(aggvos)) {
                for (AggWrVO aggvo : aggvos) {
                    List<ValidationFailure> validateList = aggvo.getParentVO().getExcpMsgList();
                    if (MMCollectionUtil.isNotEmpty(validateList)) {
                        successFlag = false;
                        errMsg.append(aggvo.getParentVO().getVbillcode());
                        errMsg.append(":");
                        for (ValidationFailure validate : validateList) {
                            errMsg.append(validate.getMessage());
                            errMsg.append(";");
                        }
                    }
                }
            }
            if (successFlag) {
                return ResultMessageUtil.toJSON(aggvos, "生产报告修改成功");
            } else {
                ExceptionUtils.wrappBusinessException(errMsg.toString());
            }
        } catch (Exception e) {
            return ResultMessageUtil.exceptionToJSON(e);
        }
        return null;
    }

    @POST
    @Path("delete")
    @Consumes({"application/json"})
    @Produces({"application/json"})
    public JSONString delete(Map<String, Object> paramMap) throws BusinessException {
        if (MMValueCheck.isEmpty(paramMap)) {
            return ResultMessageUtil.exceptionToJSON("传入数据异常", "1");
        }
        Set<String> aggwrIds = new HashSet<>();
        Map<String, String> idTsMap = new HashMap<>();
        if (!paramMap.containsKey("aggWrPk")) {
            return ResultMessageUtil.exceptionToJSON("传入数据异常，参数要包含生产报告主键", "10000");
        }
        aggwrIds.addAll((Collection<? extends String>) paramMap.get("aggWrPk"));

        try {
            IAPIWrMaintain server = NCLocator.getInstance().lookup(IAPIWrMaintain.class);
            AggWrVO[] aggWrVOSByIds = server.findAggWrVOSByIds(aggwrIds.toArray(new String[0]));

            List<AggWrVO> deleteVos = new ArrayList<>();
            for (AggWrVO aggWrVOSById : aggWrVOSByIds) {
                if (!(WrBillStatusEnum.I_FREEDOM.intValue() == aggWrVOSById.getParentVO().getFbillstatus())) {
                    continue;
                }
                deleteVos.add(aggWrVOSById);
            }
            if (MMValueCheck.isEmpty(deleteVos)) {
                return ResultMessageUtil.exceptionToJSON("生产报告状态为审批通过，不允许删除！", "1");
            }
            server.delete(deleteVos.toArray(new AggWrVO[0]));
            return ResultMessageUtil.toJSON(new String[0], "生产报告删除成功");
        } catch (Exception e) {        return ResultMessageUtil.exceptionToJSON(e);
        }
    }

    /**
     * 预处理数据：包含仓库转换和MES相关字段处理
     * @param headInfo 表头信息
     * @param itemInfos 表体信息列表
     * @param baseDAO 数据库操作对象
     * @throws BusinessException 处理失败时抛出异常
     */
    private void preProcessMesData(Map<String, Object> headInfo, List<Map<String, Object>> itemInfos, BaseDAO baseDAO)
            throws BusinessException {
        // 处理表体信息中的数据转换
        for (Map<String, Object> itemMap : itemInfos) {
            // 处理MES相关字段自动赋值
            processMESFields(itemMap, baseDAO);
            
            // 处理质量信息中的仓库转换
            if (itemMap.containsKey(QUALITYTABLE)) {
                List<Map<String, Object>> qualityInfos = (List<Map<String, Object>>) itemMap.get(QUALITYTABLE);
                processWarehouseConversion(qualityInfos, baseDAO);
            }
        }
    }
    
    /**
     * 处理MES相关字段自动赋值
     * 如果用户code是MES，那么将cbmoid保持和vbsrcid一致，cbmobid保持和vbsrcrowid一致
     * 增加vbmobillcode单据号，通过cbmoid查询流程生产订单表的vbillcode
     * @param itemMap 表体信息
     * @param baseDAO 数据库操作对象
     * @throws BusinessException 查询失败时抛出异常
     */

    private void processMESFields(Map<String, Object> itemMap, BaseDAO baseDAO) throws BusinessException {
        // 检查是否需要处理MES字段
        // 这里可以通过上下文、用户信息或其他标识来判断
        // 暂时通过检查是否存在特定字段来判断是MES用户
        boolean isMESUser = isMESUser(itemMap);
        
        if (!isMESUser) {
            return;
        }
        
        try {
            // 设置cbmoid保持和vbsrcid一致
            if (itemMap.containsKey("vbsrcid") && MMValueCheck.isNotEmpty(itemMap.get("vbsrcid"))) {
                itemMap.put("cbmoid", itemMap.get("vbsrcid"));
            }
            
            // 设置cbmobid保持和vbsrcrowid一致
            if (itemMap.containsKey("vbsrcrowid") && MMValueCheck.isNotEmpty(itemMap.get("vbsrcrowid"))) {
                itemMap.put("cbmobid", itemMap.get("vbsrcrowid"));
            }
              // 通过cbmoid查询流程生产订单表的vbillcode
            if (itemMap.containsKey("cbmoid") && MMValueCheck.isNotEmpty(itemMap.get("cbmoid"))) {
                String cbmoid = String.valueOf(itemMap.get("cbmoid"));
                String sql = "SELECT vbillcode FROM mm_pmo WHERE cpmohid = ? AND dr = 0";
                SQLParameter param = new SQLParameter();
                param.addParam(cbmoid);
                String vbillcode = (String) baseDAO.executeQuery(sql, param, new ColumnProcessor());
                
                if (MMValueCheck.isEmpty(vbillcode)) {
                    throw new BusinessException("通过流程生产订单主键【" + cbmoid + "】查询不到对应的单据号，请检查数据");
                }
                
                itemMap.put("vbmobillcode", vbillcode);
            }
            
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                throw e;
            }
            throw new BusinessException("处理MES字段失败：" + e.getMessage());
        }
    }
      /**
     * 判断是否为MES用户
     * 通过获取线程上下文中的用户编码来判断是否为MES用户
     * @param itemMap 表体信息（保留参数以保持方法签名一致性）
     * @return 是否为MES用户
     */

    private boolean isMESUser(Map<String, Object> itemMap) {
        try {
            // 获取当前线程上下文中的用户编码
            String userCode = InvocationInfoProxy.getInstance().getUserCode();
            
            // 判断用户编码是否为MES
            return "MES".equals(userCode);
            
        } catch (Exception e) {
            // 如果获取用户编码失败，记录日志并返回false
            Log.getInstance("mm-mes").error("获取用户编码失败：" + e.getMessage(), e);
            return false;
        }
    }
    
    /**
     * 处理仓库转换（将原有的仓库转换逻辑包装成独立函数）
     * @param qualityInfos 质量信息列表
     * @param baseDAO 数据库操作对象
     * @throws BusinessException 转换失败时抛出异常
     */
    private void processWarehouseConversion(List<Map<String, Object>> qualityInfos, BaseDAO baseDAO) 
            throws BusinessException {
        if (qualityInfos == null || qualityInfos.isEmpty()) {
            return;
        }
        
        for (Map<String, Object> qualityInfo : qualityInfos) {
            if (qualityInfo.containsKey("cgwarehouseid") && MMValueCheck.isNotEmpty(qualityInfo.get("cgwarehouseid"))) {
                String warehouseValue = String.valueOf(qualityInfo.get("cgwarehouseid"));
                String warehousePk = convertWarehouseCodeToPk(warehouseValue, baseDAO);
                qualityInfo.put("cgwarehouseid", warehousePk);
            }
        }
    }

    /**
     * 转换仓库编码为主键
     * 首先假设传入值是主键，如果查询不到，再假设是编码进行查询
     * @param warehouseValue 仓库值（可能是主键或编码）
     * @param baseDAO 数据库操作对象
     * @return 仓库主键
     * @throws BusinessException 如果仓库不存在
     */
    private String convertWarehouseCodeToPk(String warehouseValue, BaseDAO baseDAO) throws BusinessException {
        if (MMValueCheck.isEmpty(warehouseValue)) {
            return warehouseValue;
        }
        try {
            // 首先假设是主键，直接查询
            String sql = "SELECT pk_stordoc FROM bd_stordoc WHERE pk_stordoc = ? AND dr = 0";
            SQLParameter param = new SQLParameter();
            param.addParam(warehouseValue);
            String result = (String) baseDAO.executeQuery(sql, param, new ColumnProcessor());

            if (MMValueCheck.isNotEmpty(result)) {
                // 主键查询成功，直接返回
                return warehouseValue;
            }

            // 主键查询失败，假设是编码查询
            sql = "SELECT pk_stordoc FROM bd_stordoc WHERE code = ? AND dr = 0";
            param = new SQLParameter();
            param.addParam(warehouseValue);
            result = (String) baseDAO.executeQuery(sql, param, new ColumnProcessor());

            if (MMValueCheck.isNotEmpty(result)) {
                // 编码查询成功，返回主键
                return result;
            }

            // 都查询不到，抛出异常
            throw new BusinessException("仓库【" + warehouseValue + "】不存在，请检查仓库编码或主键");

        } catch (Exception e) {
            if (e instanceof BusinessException) {
                throw e;
            }
            throw new BusinessException("查询仓库信息失败：" + e.getMessage());
        }
    }
}
