package com.yem.wm.es.encasement.from;

import com.google.common.collect.Sets;
import com.yem.em.utils.BigDecimalUtils;
import com.yem.wm.es.Util.TotalUtil;
import com.yem.wm.es.encasement.util.AttachmentUtil;
import com.yem.wm.es.encasement.util.EncaseMentUtil;
import com.yem.wm.es.encasement.util.FileUtil;
import com.yem.wm.utils.DynamicObjectUtil;
import com.yem.wm.utils.FunctionalCommon;
import com.yem.wm.utils.YEM;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.RowDataEntity;
import kd.bos.entity.datamodel.events.*;
import kd.bos.exception.KDBizException;
import kd.bos.form.*;
import kd.bos.form.control.Control;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.TextEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.operate.AbstractOperate;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.url.UrlService;
import kd.sdk.plugin.Plugin;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;


/**
 * @author GX
 * 装箱单-表单插件
 */
public class EncaseMentEdit extends AbstractBillPlugIn implements Plugin, BeforeF7SelectListener {

    /**
     * 携带装箱方案赋值商品明细可拆卸信息中 存储当前行，与当前行的uuid
     */
    private static Map<Integer, String> map = new HashMap();

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        String key = e.getProperty().getName();
        int row = e.getRow();
        switch (key) {
            case "yem_boxscheme":
                String businesssort = (String) this.getModel().getValue("yem_businesssort", row);
                if (YEM.isEmpty(businesssort) || "P".equals(businesssort)) {
                    throw new KDBizException("只有【业务分类】为整机的行可以选择【装箱方案】!");
                }
                break;

        }
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        FormShowParameter fsp = this.getView().getFormShowParameter();
        OperationStatus status = fsp.getStatus();
        if (OperationStatus.ADDNEW == status) {
            setDefaultBoxScheme();
        }
    }

    /**
     * @description 明细信息装箱方案默认赋值
     * @author xwudd
     * return
     * @time 2023/10/12 10:52
     */

    private void setDefaultBoxScheme() {
        IDataModel model = this.getModel();
        Set<Long> ids = new HashSet<>();
        int materialInfoRows = model.getEntryRowCount("yem_im_materialinfo_mi");
        for (int i = 0; i < materialInfoRows; i++) {
            DynamicObject resourceId = (DynamicObject) model.getValue("yem_resourceid", i);
            if (YEM.isNotEmpty(resourceId)) {
                ids.add(resourceId.getLong("id"));
            }
        }
        Map<Long, DynamicObject> objs = new HashMap();
        DynamicObject[] packPlans = BusinessDataServiceHelper.load("yem_packplan", "id,yem_appresourcenos",
                new QFilter[]{new QFilter("yem_appresourcenos", QCP.in, ids),
                        new QFilter("yem_ifbasemodel", QCP.equals, "Y")});
        for (DynamicObject packPlan : packPlans) {
            DynamicObject appResourceNos = packPlan.getDynamicObject("yem_appresourcenos");
            objs.put(appResourceNos.getLong("id"), packPlan);
        }
        for (int i = 0; i < materialInfoRows; i++) {
            DynamicObject resourceId = (DynamicObject) model.getValue("yem_resourceid", i);
            if (YEM.isNotEmpty(resourceId)) {
                model.setValue("yem_boxscheme", objs.get(resourceId.getLong("id")), i);
            }
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String operateKey = e.getOperateKey();
        switch (operateKey) {
            case "accpackingback":
                accPackingBack();
                break;
            case "exportentrydata":
//                beforeExportCalc();
                exportEntityData();
                break;
            case "importdata1":
                DynamicObjectCollection stuffingpiece = this.getModel().getEntryEntity("yem_sumpartspack");
                for (DynamicObject dynamicObject : stuffingpiece) {
                    BigDecimal decimal = dynamicObject.getBigDecimal("yem_stuffingpiece");
                    if (decimal.compareTo(BigDecimal.ZERO) > 0) {
                        this.getView().showErrorNotification("已有已装柜数据，配件引入功能不可用");
                        return;
                    }
                }
                importEntityData();
                break;
            case "deleteentry3":
                deleteEntryRow();
                break;
            case "statusconvertpjqr":
                lockAccessoriesPackaging(false);
                break;
            case "statusconvertpjfqr":
                lockAccessoriesPackaging(true);
                break;
            case "statusconvertqrzj":
                lockRemovable(false);
                break;
            case "statusconvertfqrzj":
                lockRemovable(true);
                break;
            case "mergedata":
                calcSumData();
                break;
        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        AbstractOperate operate = (AbstractOperate) args.getSource();
        String operateKey = operate.getOperateKey();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        if ("statusconvertpjqr".equals(operateKey) || "statusconvertqrzj".equals(operateKey)) {

            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_im_packinginfor_pi");
            StringBuilder sb = new StringBuilder();
            for (DynamicObject dynamicObject : collection) {
                int index = collection.indexOf(dynamicObject);
                // 整柜重量
                BigDecimal wholew = dynamicObject.getBigDecimal("yem_wholew");
                if (YEM.isNotEmpty(wholew) && wholew.compareTo(new BigDecimal(25000)) > 0) {
                    sb.append(String.format("装柜信息第 [ %S ] 行的整柜重量超出25吨!", index + 1)).append("\r\n");
                }
            }

            if ("statusconvertqrzj".equals(operateKey)) {
                auditValidator(dataEntity);

                BigDecimal qty = BigDecimal.ZERO;
                BigDecimal weight = BigDecimal.ZERO;
                DynamicObjectCollection imMaterialinfoMi = dataEntity.getDynamicObjectCollection("yem_im_materialinfo_mi");
                BigDecimal sumwholenum = dataEntity.getBigDecimal("yem_sumwholenum");
                BigDecimal sumwholew = dataEntity.getBigDecimal("yem_sumwholew");
                StringBuilder sbStr = new StringBuilder();
                HashSet<Long> sourceIds = Sets.newHashSet();

                for (DynamicObject dynamicObject : imMaterialinfoMi) {
                    int index = imMaterialinfoMi.indexOf(dynamicObject);
                    sourceIds.add(dynamicObject.getLong("yem_sourceentryid"));
                    BigDecimal totalqty = dynamicObject.getBigDecimal("yem_totalqty");
                    BigDecimal netweightsum = dynamicObject.getBigDecimal("yem_netweightsum");
                    qty = qty.add(totalqty);
                    weight = weight.add(netweightsum);
                    String businesssort = dynamicObject.getString("yem_businesssort");
                    BigDecimal singlestandardqty = dynamicObject.getBigDecimal("yem_singlestandardqty");
                    if ("Z".equals(businesssort) && singlestandardqty.compareTo(BigDecimal.ZERO) <= 0) {
                        sbStr.append(String.format("明细信息第 %s 行，单台标准件数必录，请检查！！", index + 1)).append("\r\n");
                    }
                }
                if (qty.compareTo(sumwholenum) > 0) {
                    sbStr.append("明细信息总件数合计值不允许超过整机总件数，请检查！！\r\n");
//                    throw new KDBizException("明细信息总件数合计值不允许超过整机总件数，请检查！！");
                }
                if (weight.compareTo(sumwholew) > 0) {
                    sbStr.append("明细信息总净重合计值不允许超过整机总重量，请检查！！");
//                    throw new KDBizException("明细信息总净重合计值不允许超过整机总重量，请检查！！");
                }

                if (sbStr.length() > 0) {
                    throw new KDBizException(sbStr.toString());
                }

                String selectfields = DynamicObjectUtil.getSelectfields("yem_es_storagetrans");
                String storagetransSelectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_es_storagetrans", "yem_es_materialinfo");
                DynamicObject[] load = BusinessDataServiceHelper.load("yem_es_storagetrans", storagetransSelectfields, new QFilter[]{new QFilter("yem_es_materialinfo.id", "in", sourceIds)});
                for (DynamicObject dynamicObject : load) {
                    DynamicObjectCollection sourceCollection = dynamicObject.getDynamicObjectCollection("yem_es_materialinfo");
                    for (DynamicObject source : sourceCollection) {
                        long existId = source.getLong("id");
                        for (DynamicObject target : imMaterialinfoMi) {
                            long sourceentryid = target.getLong("yem_sourceentryid");
                            if (existId == sourceentryid) {
                                BigDecimal totalqty = target.getBigDecimal("yem_totalqty");//总件数
                                BigDecimal netweightsum = target.getBigDecimal("yem_netweightsum");//总净重
                                BigDecimal grossweightsum = target.getBigDecimal("yem_grossweightsum");//总毛重

                                if (totalqty.compareTo(BigDecimal.ZERO) > 0) {
                                    source.set("yem_piece", totalqty);
                                }
                                if (netweightsum.compareTo(BigDecimal.ZERO) > 0) {
                                    source.set("yem_netweightsum", netweightsum);
                                }
                                if (grossweightsum.compareTo(BigDecimal.ZERO) > 0) {
                                    source.set("yem_grossweightsum", grossweightsum);
                                }
                                BigDecimal piece = source.getBigDecimal("yem_piece");
                                netweightsum = source.getBigDecimal("yem_netweightsum");
                                grossweightsum = source.getBigDecimal("yem_grossweightsum");
                                source.set("yem_netweight", BigDecimalUtils.div(netweightsum, piece, 2));
                                source.set("yem_grossweight", BigDecimalUtils.div(grossweightsum, piece, 2));
                            }
                        }
                    }
                }
                if (load.length > 0) {
                    SaveServiceHelper.save(load);
                }
            }

            if (sb.length() > 0) {
                sb.append("请确认是否继续？");
                ConfirmCallBackListener confirmCallBackListener = new ConfirmCallBackListener(operateKey, this);
                this.getView().showConfirm(sb.toString(), MessageBoxOptions.YesNo, confirmCallBackListener);
            } else {
                doConfirm(operateKey);
            }
        }

        IFormView view = this.getView();
        if ("fillback_finish".equals(operateKey)) {
            dataEntity.set("yem_equipmentstate", "B");
            SaveServiceHelper.save(new DynamicObject[]{dataEntity});
            view.showSuccessNotification("操作成功");
            view.invokeOperation("refresh");
        }

        if ("fillbaaack_cancel".equals(operateKey)) {
            dataEntity.set("yem_equipmentstate", "A");
            SaveServiceHelper.save(new DynamicObject[]{dataEntity});
            view.showSuccessNotification("操作成功");
            view.invokeOperation("refresh");
        }
    }

    private void auditValidator(DynamicObject dataEntity) {

        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_backentry");
        Map<Long, BigDecimal> map = new LinkedHashMap<>();
        for (DynamicObject dynamicObject : collection) {
            long resourceid = dynamicObject.getLong("yem_resourceid_bac.id");
            if (!map.containsKey(resourceid)) {
                map.put(resourceid, dynamicObject.getBigDecimal("yem_totalweight"));
            } else {
                BigDecimal totalweight = dynamicObject.getBigDecimal("yem_totalweight");
                if (map.get(resourceid).compareTo(totalweight) > 0) {
                    map.put(resourceid, totalweight);
                }
            }
        }

        for (Map.Entry<Long, BigDecimal> entry : map.entrySet()) {
            Long k = entry.getKey();
            BigDecimal v = entry.getValue();

            DynamicObjectCollection backentry = dataEntity.getDynamicObjectCollection("yem_backentry");

            BigDecimal totalweight = BigDecimal.ZERO;
            for (DynamicObject dynamicObject : backentry) {
                long resourceid = dynamicObject.getLong("yem_resourceid_bac.id");
                if (k == resourceid) {
                    BigDecimal weight = dynamicObject.getBigDecimal("yem_weight");
                    BigDecimal staqty = dynamicObject.getBigDecimal("yem_staqty");
                    totalweight = totalweight.add(weight.multiply(staqty));
                }
            }

            if (v.compareTo(totalweight) != 0) {
                throw new KDBizException("商品明细可拆卸信息中【标准数量】*【重量】需等于【整机重量】");
            }
        }
    }

    private void doConfirm(String operateKey) {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        long sourcebillid = dataEntity.getLong("yem_sourcebillid");
        String sourcebilltype = dataEntity.getString("yem_sourcebilltype");
        if (YEM.isEmpty(sourcebillid) || YEM.isEmpty(sourcebilltype)) return;
        DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(sourcebillid, sourcebilltype);
        if (YEM.isEmpty(dynamicObject)) return;
        dynamicObject.set("yem_sumwholenum", dataEntity.getBigDecimal("yem_sumwholenum"));
        dynamicObject.set("yem_sumwholew", dataEntity.getBigDecimal("yem_sumwholew"));
        dynamicObject.set("yem_sumwholecube", dataEntity.getBigDecimal("yem_sumwholecube"));
        dynamicObject.set("yem_sumparts", dataEntity.getBigDecimal("yem_sumparts"));
        dynamicObject.set("yem_summountingweight", dataEntity.getBigDecimal("yem_summountingweight"));
        dynamicObject.set("yem_summountingcube", dataEntity.getBigDecimal("yem_summountingcube"));
        dynamicObject.set("yem_sumunits", dataEntity.getBigDecimal("yem_sumunits"));
        dynamicObject.set("yem_sumweight", dataEntity.getBigDecimal("yem_sumweight"));
        dynamicObject.set("yem_sumcube", dataEntity.getBigDecimal("yem_sumcube"));
        SaveServiceHelper.save(new DynamicObject[]{dynamicObject});
        long currentUserId = YEM.getCurrentUserId();
        DynamicObject user = BusinessDataServiceHelper.loadSingle(currentUserId, "bos_user");
        if ("statusconvertpjqr".equals(operateKey)) {

            dataEntity.set("yem_completionstatuspj", "B");
            dataEntity.set("yem_affirmmanpj", user);
            dataEntity.set("yem_affirmdatepj", new Date());
        }

        if ("statusconvertqrzj".equals(operateKey)) {

            dataEntity.set("yem_completionstatuszj", "B");
            dataEntity.set("yem_affirmmanzj", user);
            dataEntity.set("yem_affirmdatezj", new Date());
        }
        SaveServiceHelper.save(new DynamicObject[]{dataEntity});
        this.getView().invokeOperation("refresh");
        this.getView().showSuccessNotification("确认完成");
    }

    /**
     * 3、点击整机装箱确认按钮：
     * 商品明细可拆卸信息页签锁定；操作锁定
     * 装柜信息：回填整机装柜按钮锁定，不可操作
     * 4、点击整机装箱反确认按钮：放开3的所有锁定
     *
     * @param op true:解锁 false:锁定
     */
    private void lockRemovable(boolean op) {
        IDataModel model = this.getModel();
        DynamicObjectCollection materialinfoMi = model.getEntryEntity("yem_backentry");
        for (int i = 0; i < materialinfoMi.size(); i++) {
            this.getView().setEnable(op, i, "yem_totalweight", "yem_picno", "yem_picnoz", "yem_staqty", "yem_weight");
        }

        this.getView().setEnable(op, "yem_backmessagezj");
    }

    /**
     * 配件包装明细这个页签字段锁定
     * 配件包装汇总信息这个页签字段锁定
     * 装柜信息：回填配件装柜按钮锁定
     *
     * @param op true:解锁 false:锁定
     */
    private void lockAccessoriesPackaging(boolean op) {
        IDataModel model = this.getModel();
        // 锁定配件包装信息
        DynamicObjectCollection pjpackageinfo = model.getEntryEntity("yem_pjpackageinfo");
        for (int i = 0; i < pjpackageinfo.size(); i++) {

            this.getView().setEnable(op, i, "yem_sernumber", "yem_businesssort1", "yem_customclass1", "yem_hscode1", "yem_outnumberno1");
        }

        // 锁定配件包装汇总信息
        DynamicObjectCollection sumpartspack = model.getEntryEntity("yem_sumpartspack");
        for (int i = 0; i < sumpartspack.size(); i++) {
            this.getView().setEnable(op, i, "yem_long1", "yem_wide1", "yem_high1", "yem_sumvolume", "yem_sumroughweight");
        }

        this.getView().setEnable(op, "yem_backmessagepj");
    }

    @Override
    public void confirmCallBack(MessageBoxClosedEvent e) {
        super.confirmCallBack(e);
        String callBackId = e.getCallBackId();
        MessageBoxResult result = e.getResult();
        if (MessageBoxResult.Yes.equals(result)) {

            if ("statusconvertpjqr".equals(callBackId) || "statusconvertqrzj".equals(callBackId)) {
                doConfirm(callBackId);
            }
        }
    }

    @Override
    public void registerListener(EventObject e) {
        TextEdit textEdit = this.getControl("yem_containernumber");
        textEdit.addClickListener(this);
        TextEdit machinenumber = this.getControl("yem_machinenumber");
        machinenumber.addClickListener(this);
        BasedataEdit basedataEdit = this.getControl("yem_boxscheme");
        basedataEdit.addBeforeF7SelectListener(this);
        super.registerListener(e);
        this.addItemClickListeners("yem_advcontoolbarap1");
    }

    @Override
    public void afterDeleteRow(AfterDeleteRowEventArgs e) {
        String name = e.getEntryProp().getName();
        //装柜明细删除行 更新装柜信息
        if ("yem_im_detaweight_dw".equals(name)) {
            goodDescribe();
            setZCounts();
            setZWeight();
            setPCounts();
            setPWeight();
            setPCube();
        }
    }

    /**
     * @param evt 监听集装箱号/车号按钮回填，监听保存按钮，显示集装箱号/车号按钮
     */
    @Override
    public void itemClick(ItemClickEvent evt) {
        // TODO Auto-generated method stub
        super.itemClick(evt);
        String key = evt.getItemKey();
        if (StringUtils.equals("yem_backcarcomp", key)) {
            showInfoForm(this.getView());
        }
        if (StringUtils.equals("bar_save", key)) {
            this.getView().setVisible(true, "yem_backcarcomp");
            setGoodsDesc();
        }
    }

    /**
     * 计算序列号
     */
    private void beforeExportCalc() {
        DynamicObjectCollection collection = this.getModel().getEntryEntity("yem_im_materialinfo_mi");
        for (int i = 0; i < collection.size(); i++) {
            collection.get(i).set("yem_serialnumber", i + 1);
            collection.get(i).set("yem_entryid", collection.get(i).getPkValue());
        }
    }

    /**
     * @param view 设置打开装柜信息动态表单
     */
    private void showInfoForm(IFormView view) {
        // 获取单据体
        FormShowParameter showParameter = new FormShowParameter();
        showParameter.setStatus(OperationStatus.ADDNEW);
        showParameter.getOpenStyle().setShowType(ShowType.Modal);
        showParameter.setFormId("yem_im_packinginfor_tc");
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        DynamicObjectCollection entity = this.getModel().getEntryEntity("yem_im_packinginfor_pi");
        showParameter.setCustomParam("yem_im_packinginfor_pi", entity);
        DynamicObjectCollection entitys = this.getModel().getEntryEntity("yem_im_encasement_ci");
        showParameter.setCustomParam("yem_im_encasement_ci", entitys);
        long sourcebillid = this.getModel().getDataEntity().getLong("yem_sourcebillid");
        showParameter.setCustomParam("sourcebillid", sourcebillid);// 来源单据id
        showParameter.setCustomParam("sourcebilltype", this.getModel().getDataEntityType().getName());
        showParameter.setCloseCallBack(new CloseCallBack(this, "yem_backcarcomp"));
        view.showForm(showParameter);
    }

    /**
     * @param e 回调，接收子页面传来的值。
     */
    @Override
    public void closedCallBack(ClosedCallBackEvent e) {
        String actionId = e.getActionId();
        Object returnData = e.getReturnData();
        switch (actionId) {
            case "yem_backcarcomp":
                DynamicObject data = (DynamicObject) returnData;
                setValue(data);
                break;
            case "yem_inputdata":
                if (returnData != null) {
                    JSONObject re = JSONObject.fromObject(e.getReturnData());
                    if (null != re && !re.getJSONArray("values").isEmpty()) {
                        JSONArray jsonArray = re.getJSONArray("values");
                        setEntityValue(jsonArray);
                    }
                }
                break;
            default:
                break;
        }
    }

    private void setValue(DynamicObject data) {
        if (data != null) {
            DynamicObjectCollection tpv_personinfor = data.getDynamicObjectCollection("yem_entryentity");
            //   this.getModel().deleteEntryData("yem_im_packinginfor_pi");
            int index = 0;
            IDataModel model = this.getModel();
            DynamicObject dataEntity = model.getDataEntity(true);
            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_im_packinginfor_pi");
            DynamicObjectCollection sumpartspack = dataEntity.getDynamicObjectCollection("yem_sumpartspack");

            for (DynamicObject dynamicObject : collection) {
                DynamicObject personinfor = tpv_personinfor.get(index);
                dynamicObject.set("yem_cabinettype", personinfor.getDynamicObject("yem_cabinettype"));
                dynamicObject.set("yem_goodescription", personinfor.getString("yem_goodescription"));
                dynamicObject.set("yem_contnum", personinfor.getString("yem_contnum"));
                dynamicObject.set("yem_containernumber", personinfor.getString("yem_containernumber"));
                dynamicObject.set("yem_carnum", personinfor.getString("yem_carnum"));
                dynamicObject.set("yem_machinenumber", personinfor.getString("yem_machinenumber"));
                index++;
            }
//            for (DynamicObject personinfor : tpv_personinfor) {
//                //   int index = this.getModel().createNewEntryRow("yem_im_packinginfor_pi");
//                //this.getModel().setValue("yem_boxgoodsid", personinfor.getDynamicObject("yem_boxgoodsid"), index);
//                //  this.getModel().setValue("yem_resourceidps", personinfor.getDynamicObject("yem_resourceidps"), index);
//                dataEntity.set("yem_cabinettype", personinfor.getDynamicObject("yem_cabinettype"), index);
//                dataEntity.set("yem_goodescription", personinfor.getString("yem_goodescription"), index);
//                dataEntity.set("yem_contnum", personinfor.getString("yem_contnum"), index);
//                dataEntity.set("yem_containernumber", personinfor.getString("yem_containernumber"), index);
//                dataEntity.set("yem_carnum", personinfor.getString("yem_carnum"), index);
//                dataEntity.set("yem_machinenumber", personinfor.getString("yem_machinenumber"), index);
////                this.getModel().setValue("yem_numberunits", personinfor.getBigDecimal("yem_numberunits"), index);
////                this.getModel().setValue("yem_weightsum", personinfor.getBigDecimal("yem_weightsum"), index);
////                this.getModel().setValue("yem_cube", personinfor.getBigDecimal("yem_cube"), index);
////                this.getModel().setValue("yem_numberparts", personinfor.getBigDecimal("yem_numberparts"), index);
////                this.getModel().setValue("yem_mountingweight", personinfor.getBigDecimal("yem_mountingweight"), index);
////                this.getModel().setValue("yem_mountingcube", personinfor.getBigDecimal("yem_mountingcube"), index);
////                this.getModel().setValue("yem_wholenum", personinfor.getBigDecimal("yem_wholenum"), index);
////                this.getModel().setValue("yem_wholew", personinfor.getBigDecimal("yem_wholew"), index);
////                this.getModel().setValue("yem_wholecube", personinfor.getBigDecimal("yem_wholecube"), index);
////                this.getModel().setValue("yem_comment", personinfor.getString("yem_comment"), index);
//                index++;
//            }
//            this.getView().invokeOperation("save");

            SaveServiceHelper.save(new DynamicObject[]{dataEntity});
            this.getView().invokeOperation("refresh");
        }
    }

    /**
     * @param e 值改变事件
     */
    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        IDataModel model = this.getModel();
        String name = e.getProperty().getName();
        ChangeData changeData = e.getChangeSet()[0];
        int rowIndex = changeData.getRowIndex();
        switch (name) {
//            case "yem_numberunits"://件数
//            case "yem_weightsum"://总重量
//            case "yem_cube"://立方（cmb）
//            case "yem_numberparts"://配件件数
//            case "yem_mountingweight"://配件重量
//            case "yem_mountingcube"://配件立方
//            case "yem_wholenum"://整柜件数
//            case "yem_wholew"://整柜重量
//            case "yem_wholecube"://整柜立方
//                ZJHZ();//汇总至表头
//                break;
            case "yem_lenghtunit":
            case "yem_vol":
                TotalUtil.countVolM3(model, rowIndex, "yem_lenghtunit", "yem_vol", "yem_volm3");
                break;
            case "yem_boxscheme"://明细信息整机 携带 装箱方案 赋值 商品明细可拆卸信息
                setValuesByMS(e);
//                carryWeight(e);
                break;
            case "yem_picnoz_det":
                goodDescribe();
                setGoodsDesc();
                break;
            case "yem_businesssort_dw":
                setZCounts();
                setZWeight();
                setPCounts();
                setPWeight();
                setPCube();
                setGoodsDesc();
                break;
            case "yem_grossweightsumd":
                setZWeight();
                setPWeight();
                break;
            case "yem_pieces_det":
                setZCounts();
                setPCounts();
                goodDescribe();
                setGoodsDesc();
                break;
            case "yem_volsum_det":
                setPCube();
                break;
            case "yem_shipmentqty":
            case "yem_packingqty":
                calcResidueqty();
                break;
            case "yem_long1":
            case "yem_wide1":
            case "yem_high1":
                calcVolM3(rowIndex);
                break;
            case "yem_numberunits":
            case "yem_weightsum":
            case "yem_cube":
            case "yem_numberparts":
            case "yem_mountingweight":
            case "yem_mountingcube":
            case "yem_wholenum":
            case "yem_wholew":
            case "yem_wholecube":
                ZJHZ();
                break;
            case "yem_cabinettype":
                bringVolumeInfo(rowIndex);
                break;
        }
    }

    /**
     * 选择柜型时，携带柜型体积到整柜立方数字段
     *
     * @param rowIndex
     */
    private void bringVolumeInfo(int rowIndex) {
        IDataModel model = this.getModel();
        DynamicObject cabinettype = (DynamicObject) model.getValue("yem_cabinettype", rowIndex);
        if (YEM.isNotEmpty(cabinettype)) {
            DynamicObject single = BusinessDataServiceHelper.loadSingle(cabinettype.getPkValue(), cabinettype.getDynamicObjectType().getName());
            BigDecimal volume = single.getBigDecimal("yem_volume");
            model.setValue("yem_wholecube", volume, rowIndex);
        } else {
            model.setValue("yem_wholecube", null, rowIndex);
        }
    }

    /**
     * 装柜明细业务分类为配件时，将每行按照件数*包装名称+件数*包装名称的格式拼接生成到配件货物描述字段；
     * 装柜明细业务分类为整机时，将每行按照件数*包装名称+件数*包装名称的格式拼接生成到整机货物描述字段；
     */
    private void setGoodsDesc() {
        IDataModel model = this.getModel();

        String name = this.getModel().getDataEntityType().getName();
        if (!"yem_im_encasement".equals(name)) {
            return;
        }

        // 装柜信息
        DynamicObjectCollection entryEntity = model.getEntryEntity("yem_im_packinginfor_pi");
        for (DynamicObject dynamicObject : entryEntity) {
            int index = entryEntity.indexOf(dynamicObject);
            // 装柜明细
            DynamicObjectCollection collection = dynamicObject.getDynamicObjectCollection("yem_im_detaweight_dw");
            StringBuilder sbP = new StringBuilder();
            StringBuilder sbZ = new StringBuilder();
            for (DynamicObject object : collection) {
                // 包装名称
                String picnozDet = object.getString("yem_picnoz_det");
                // 件数
                String piecesDet = object.getBigDecimal("yem_pieces_det").setScale(0, RoundingMode.HALF_UP).toString();

                if ("P".equals(object.getString("yem_businesssort_dw"))) {
                    sbP.append(piecesDet).append("*").append(picnozDet).append("+");
                }

                if ("Z".equals(object.getString("yem_businesssort_dw"))) {
                    sbZ.append(piecesDet).append("*").append(picnozDet).append("+");
                }
            }
            if (sbP.length() > 0) {
                sbP.deleteCharAt(sbP.length() - 1);
            }
            if (sbZ.length() > 0) {
                sbZ.deleteCharAt(sbZ.length() - 1);
            }
            model.setValue("yem_pjgooddesc1", sbP, index);
            model.setValue("yem_zjgooddesc", sbZ, index);
        }
    }

    /**
     * 装箱单--明细信息  选装箱方案，需要根据装箱方案（基础资料）的整机重量给装箱单-商品可拆卸信息的整机重量赋值
     *
     * @param e
     */
    private void carryWeight(PropertyChangedArgs e) {
        int rowIndex = e.getChangeSet()[0].getRowIndex();
        IDataModel model = this.getModel();
        DynamicObjectCollection entryEntity = model.getEntryEntity("yem_im_materialinfo_mi");
        DynamicObject dynamicObject = entryEntity.get(rowIndex);
        DynamicObject boxscheme = dynamicObject.getDynamicObject("yem_boxscheme");

        if (boxscheme != null) {
            long appresourcenos = boxscheme.getLong("yem_appresourcenos.id");
            BigDecimal weight = boxscheme.getBigDecimal("yem_weight");
            // 商品明细可拆卸信息
            DynamicObjectCollection collection = model.getEntryEntity("yem_backentry");

            for (int i = 0; i < collection.size(); i++) {
                DynamicObject object = collection.get(i);
                long resourceid = object.getLong("yem_resourceid_bac.id");
                if (resourceid == appresourcenos) {
                    model.setValue("yem_totalweight", weight, i);
                }
            }
        }

    }

    /**
     * 计算总体积
     *
     * @param rowIndex
     */
    private void calcVolM3(int rowIndex) {
        IDataModel model = this.getModel();
        DynamicObjectCollection entryEntity = model.getEntryEntity("yem_sumpartspack");
        DynamicObject dynamicObject = entryEntity.get(rowIndex);
        BigDecimal volLong = dynamicObject.getBigDecimal("yem_long1");
        BigDecimal volWide = dynamicObject.getBigDecimal("yem_wide1");
        BigDecimal volHigh = dynamicObject.getBigDecimal("yem_high1");
        if (volHigh.compareTo(BigDecimal.ZERO) > 0 && volLong.compareTo(BigDecimal.ZERO) > 0 && volWide.compareTo(BigDecimal.ZERO) > 0) {
            BigDecimal volM3 = volHigh.multiply(volLong).multiply(volWide);
            model.setValue("yem_sumvolume", volM3, rowIndex);
        }
    }

    private void calcResidueqty() {
        IDataModel model = this.getModel();
        DynamicObjectCollection materialinfoMi = model.getEntryEntity("yem_im_materialinfo_mi");
        for (int i = 0; i < materialinfoMi.size(); i++) {
            // 装箱数量
            BigDecimal shipmentqty = materialinfoMi.get(i).getBigDecimal("yem_shipmentqty");
            // 已包装数量
            BigDecimal packingqty = materialinfoMi.get(i).getBigDecimal("yem_packingqty");
            // 计算剩余数量
            this.getModel().setValue("yem_residueqty", shipmentqty.subtract(packingqty), i);
        }
    }

    @Override
    public void click(EventObject evt) {
        Control control = (Control) evt.getSource();
        if (StringUtils.equals("yem_containernumber", control.getKey())) {
            FormShowParameter parameter = new FormShowParameter();
            parameter.setFormId("yem_containernr");
            parameter.getOpenStyle().setShowType(ShowType.Modal);
            DynamicObjectCollection entryEntity = this.getModel().getEntryEntity("yem_im_encasement_ci");
            List<String[]> list = new ArrayList<>();
            for (DynamicObject temp : entryEntity) {
                list.add(new String[]{temp.getString("yem_encasenum"), temp.getString("yem_carnums")});
            }
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("key", list);
            parameter.setCustomParams(dataMap);
            this.getView().showForm(parameter);
        }
        if (StringUtils.equals("yem_machinenumber", control.getKey())) {
            List<String> zNo = new ArrayList();
            String sourcebillno = (String) this.getModel().getValue("yem_sourcebillno");
            if (YEM.isNotEmpty(sourcebillno)) {
                DynamicObject datas = BusinessDataServiceHelper.loadSingle("yem_es_storagetrans", "", new QFilter[]{
                        new QFilter("billno", QCP.equals, sourcebillno), new QFilter("billstatus", QCP.equals, "C")
                });
                if (datas != null) {
                    DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(datas.getPkValue(), datas.getDynamicObjectType().getName());
                    DynamicObjectCollection dynamicObjectCollection = dynamicObject.getDynamicObjectCollection("yem_es_materialinfo");
                    for (DynamicObject temp : dynamicObjectCollection) {
                        if (temp != null) {
                            DynamicObjectCollection dynamicObjectCollection1 = temp.getDynamicObjectCollection("yem_es_salesorder_z");
                            for (DynamicObject dy : dynamicObjectCollection1) {
                                zNo.add(dy.getString("yem_vehicleno"));
                            }
                        }
                    }
                }
            }
            FormShowParameter parameter = new FormShowParameter();
            parameter.setFormId("yem_znumber");
            parameter.getOpenStyle().setShowType(ShowType.Modal);
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("key", zNo);
            parameter.setCustomParams(dataMap);
            this.getView().showForm(parameter);
        }
    }

    @Override
    public void beforeDeleteRow(BeforeDeleteRowEventArgs e) {
        super.beforeDeleteRow(e);
        String name = e.getEntryProp().getName();
        int[] rowIndexs = e.getRowIndexs();
//        switch (name) {
//            case "yem_pjpackageinfo"://件数
//                deletePjPackageInfo(e, rowIndexs);
//                break;
//            case "yem_im_materialinfo_mi"://件数
//                deleteMaterialInfo(e, rowIndexs);
//                break;
//        }
    }


    /**
     * 表头汇总
     */
    private void ZJHZ() {
        DynamicObjectCollection entrys = this.getModel().getEntryEntity("yem_im_packinginfor_pi");//获取到装柜信息分录
        BigDecimal sumunits = BigDecimal.ZERO;//表头总件数
        BigDecimal sumweight = BigDecimal.ZERO;//表头总重量
        BigDecimal sumcube = BigDecimal.ZERO;//表头总立方
        BigDecimal sumparts = BigDecimal.ZERO;//表头配件总件数
        BigDecimal summountingweight = BigDecimal.ZERO;//表头配件总重量
        BigDecimal summountingcube = BigDecimal.ZERO;//表头配件总立方
        BigDecimal sumwholenum = BigDecimal.ZERO;//表头整柜总件数
        BigDecimal sumwholew = BigDecimal.ZERO;//表头整柜总重量
        BigDecimal sumwholecube = BigDecimal.ZERO;//表头整柜总立方
        for (DynamicObject enty : entrys) {
            sumunits = sumunits.add(enty.getBigDecimal("yem_numberunits"));//计算总件数
            sumweight = sumweight.add(enty.getBigDecimal("yem_weightsum"));//计算总重量
            sumcube = sumcube.add(enty.getBigDecimal("yem_cube"));//计算总立方
            sumparts = sumparts.add(enty.getBigDecimal("yem_numberparts"));//计算配件总件数
            summountingweight = summountingweight.add(enty.getBigDecimal("yem_mountingweight"));//计算配件总重量
            summountingcube = summountingcube.add(enty.getBigDecimal("yem_mountingcube"));//计算配件总立方
            sumwholenum = sumwholenum.add(enty.getBigDecimal("yem_wholenum"));//表头整柜总件数
            sumwholew = sumwholew.add(enty.getBigDecimal("yem_wholew"));//表头整柜总重量
            sumwholecube = sumwholecube.add(enty.getBigDecimal("yem_wholecube"));//表头整柜总立方
        }
        this.getModel().setValue("yem_sumunits", sumwholenum);//汇总至总件数
        this.getModel().setValue("yem_sumweight", sumwholew);//汇总至总重量
        this.getModel().setValue("yem_sumcube", sumwholecube);//汇总至总立方
        this.getModel().setValue("yem_sumparts", sumparts);//汇总至配件总件数
        this.getModel().setValue("yem_summountingweight", summountingweight);//汇总至配件总重量
        this.getModel().setValue("yem_summountingcube", summountingcube);//汇总至配件总立方
        this.getModel().setValue("yem_sumwholenum", sumunits);//汇总至整柜总件数
        this.getModel().setValue("yem_sumwholew", sumweight);//汇总至整柜总重量
        this.getModel().setValue("yem_sumwholecube", sumcube);//汇总至整柜总立方
    }


    /**
     * @description 配件装箱按钮点击
     * @author xwudd
     * return
     * @time 2023/8/29 18:40
     */

    public void accPackingBack() {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        Boolean flag = true;
        DynamicObjectCollection materialInfos = model.getEntryEntity("yem_im_materialinfo_mi");
        for (DynamicObject materialInfo : materialInfos) {
            long pkValue = (long) materialInfo.getPkValue();
            if (pkValue == 0L) {
                flag = false;
            }
        }
        if (flag) {
            FunctionalCommon.viewForm("yem_accpackingback", null, view);
        } else {
            view.showErrorNotification("请先保存单据，再进行配件装箱操作！");
        }

    }

    /**
     * @description 删除配件包装信息分录后触发
     * 1.删除配件包装汇总信息相关数据
     * @author xwudd
     * @param[1] rowIndexs
     * return
     * @time 2023/8/30 9:42
     */

    public void deletePjPackageInfo(BeforeDeleteRowEventArgs e, int[] rowIndexs) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        for (int rowIndex : rowIndexs) {
            String info = isDelAccSumInfo(view, model, "yem_pjpackageinfo", -1, rowIndex);
            if (YEM.isNotEmpty(info)) {
                view.showErrorNotification(info);
                e.setCancel(true);
            }

//            String trayNumbers = (String)model.getValue("yem_traynumbers",rowIndex);
//            String boxNumber = (String)model.getValue("yem_boxnumber",rowIndex);
//            BigDecimal pieces = (BigDecimal)model.getValue("yem_pieces",rowIndex);
//            BigDecimal qty = (BigDecimal)model.getValue("yem_qtys",rowIndex);
//            BigDecimal grossWeightSums = (BigDecimal)model.getValue("yem_grossweightsums",rowIndex);
//            BigDecimal volM3sums = (BigDecimal)model.getValue("yem_volm3sums",rowIndex);
//            int sumPartSpaRows = model.getEntryRowCount("yem_sumpartspack");
//            for (int i = 0; i < sumPartSpaRows; i++) {
//                String trayNo = (String)model.getValue("yem_trayno",i);
//                String boxNo = (String)model.getValue("yem_boxno",i);
//                if(trayNo.equals(trayNumbers) && boxNo.equals(boxNumber)){
//                    BigDecimal pieceNum = (BigDecimal)model.getValue("yem_piecenum",i);
//                    BigDecimal quantity = (BigDecimal)model.getValue("yem_quantity",i);
//                    BigDecimal sumRoughWeight = (BigDecimal)model.getValue("yem_sumroughweight",i);
//                    BigDecimal sumVolumeM3 = (BigDecimal)model.getValue("yem_sumvolumem3",i);
//                    BigDecimal stuffingPiece = (BigDecimal)model.getValue("yem_stuffingpiece",i);
//                    if(pieceNum.subtract(pieces).compareTo(stuffingPiece) < 0){
//                        view.showErrorNotification(String.format("配件包装信息分录第%s行不允许删除，删除后托盘号为%s，箱号为%s的配件包装汇总信息中的已装柜件数大于件数，不允许删除！！！",rowIndex,trayNo,boxNo));
//                    }else{
//                        model.setValue("yem_piecenum",pieceNum.subtract(pieces),i);
//                        model.setValue("yem_quantity",quantity.subtract(qty),i);
//                        model.setValue("yem_sumroughweight",sumRoughWeight.subtract(grossWeightSums),i);
//                        model.setValue("yem_sumvolumem3",sumVolumeM3.subtract(volM3sums),i);
//                        model.setValue("yem_residuepiece",pieceNum.subtract(pieces).subtract(stuffingPiece),i);
//                    }
//
//                }
//            }
        }
    }

    public void deleteMaterialInfo(BeforeDeleteRowEventArgs e, int[] rowIndexs) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        for (int rowIndex : rowIndexs) {
            DynamicObject materialInfoRowObj = model.getEntryRowEntity("yem_im_materialinfo_mi", rowIndex);
            if (YEM.isNotEmpty(materialInfoRowObj)) {
                long deleteRowId = materialInfoRowObj.getLong("id");
                int pjPackageInfoRows = model.getEntryRowCount("yem_pjpackageinfo");
                for (int i = 0; i < pjPackageInfoRows; i++) {
                    long materialInfoId = (long) model.getValue("yem_materialinfoid", i);
                    if (deleteRowId == materialInfoId) {
                        String info = isDelAccSumInfo(view, model, "yem_im_materialinfo_mi", rowIndex, i);
                        if (YEM.isNotEmpty(info)) {
                            view.showErrorNotification(info);
                            e.setCancel(true);
                        } else {
                            model.deleteEntryRow("yem_pjpackageinfo", i);
                        }

                    }
                }
            }
        }
    }

    private String isDelAccSumInfo(IFormView view, IDataModel model, String entryKey, int rowIndex, int i) {
        String info = "";
        Map<Long, BigDecimal> map = new HashMap<>();
        BigDecimal pieces = (BigDecimal) model.getValue("yem_pieces", i);
        Long materialInfoId = (Long) model.getValue("yem_materialinfoid", i);
        String trayNumbers = (String) model.getValue("yem_traynumbers", i);
        String boxNumber = (String) model.getValue("yem_boxnumber", i);
        int sumPartSpaRows = model.getEntryRowCount("yem_sumpartspack");
        BigDecimal qty = (BigDecimal) model.getValue("yem_qtys", i);
        BigDecimal grossWeightSums = (BigDecimal) model.getValue("yem_grossweightsums", i);
        BigDecimal volM3sums = (BigDecimal) model.getValue("yem_volm3sums", i);
        map.put(materialInfoId, qty);
        for (int j = 0; j < sumPartSpaRows; j++) {
            String trayNo = (String) model.getValue("yem_trayno", j);
            String boxNo = (String) model.getValue("yem_boxno", j);
            if (trayNumbers.equals(trayNo) && boxNumber.equals(boxNo)) {
                BigDecimal residuePiece = (BigDecimal) model.getValue("yem_residuepiece", j);
                if ("yem_pjpackageinfo".equals(entryKey)) {
                    if (pieces.compareTo(residuePiece) > 0) {
                        info = String.format("配件包装信息分录第%s行不允许删除，删除后托盘号为%s，箱号为%s的配件包装汇总信息中的剩余装柜数量小于件数，不允许删除！！！", i, trayNo, boxNo);
                    } else {
                        EncaseMentUtil.backFillResidueQtyFor(model, map, false);
                        BigDecimal pieceNum = (BigDecimal) model.getValue("yem_piecenum", j);
                        BigDecimal quantity = (BigDecimal) model.getValue("yem_quantity", j);
                        BigDecimal sumRoughWeight = (BigDecimal) model.getValue("yem_sumroughweight", j);
                        BigDecimal sumVolumeM3 = (BigDecimal) model.getValue("yem_sumvolume", j);
                        BigDecimal stuffingPiece = (BigDecimal) model.getValue("yem_stuffingpiece", j);
                        pieceNum = pieceNum.subtract(pieces);
                        quantity = quantity.subtract(qty);
                        sumRoughWeight = sumRoughWeight.subtract(grossWeightSums);
                        sumVolumeM3 = sumVolumeM3.subtract(volM3sums);
                        stuffingPiece = pieceNum.subtract(stuffingPiece);
                        if (pieceNum.compareTo(BigDecimal.ZERO) == 0 && quantity.compareTo(BigDecimal.ZERO) == 0
                                && sumRoughWeight.compareTo(BigDecimal.ZERO) == 0 && sumVolumeM3.compareTo(BigDecimal.ZERO) == 0) {
                            model.deleteEntryRow("yem_sumpartspack", j);
                        } else {
                            model.setValue("yem_piecenum", pieceNum, j);
                            model.setValue("yem_quantity", quantity, j);
                            model.setValue("yem_sumroughweight", sumRoughWeight, j);
                            model.setValue("yem_sumvolume", sumVolumeM3, j);
                            model.setValue("yem_residuepiece", stuffingPiece, j);
                        }
                    }
                }
                if ("yem_im_materialinfo_mi".equals(entryKey)) {
                    if (pieces.compareTo(residuePiece) > 0) {
                        info = String.format("明细信息分录第%s行不允许删除，删除后会同步删除配件包装信息分录中第%s行数据，该行数据托盘号为%s，箱号为%s的配件包装汇总信息中的剩余装柜数量小于件数，不允许删除！！！", rowIndex, i, trayNo, boxNo);
                    }
                }
            }
        }
        return info;
    }

    /**
     * 装柜信息 子分录汇总 整机总重量
     */

    private void setZWeight() {
        int parentRowIndex = this.getModel().getEntryCurrentRowIndex("yem_im_packinginfor_pi");
        DynamicObjectCollection entryEntity = this.getModel().getEntryEntity("yem_im_detaweight_dw");
        BigDecimal count = BigDecimal.ZERO;
        for (DynamicObject temp : entryEntity) {
            BigDecimal piecesTemp = temp.getBigDecimal("yem_grossweightsumd");
            String businesssortTemp = temp.getString("yem_businesssort_dw");
            if (YEM.isNotEmpty(piecesTemp) && "Z".equals(businesssortTemp)) {
                count = piecesTemp.add(count);
            }
        }
        this.getModel().setValue("yem_weightsum", count, parentRowIndex);

    }

    /**
     * 装柜信息 子分录汇总 配件总重量
     */

    private void setPWeight() {
        int parentRowIndex = this.getModel().getEntryCurrentRowIndex("yem_im_packinginfor_pi");
        DynamicObjectCollection entryEntity = this.getModel().getEntryEntity("yem_im_detaweight_dw");
        BigDecimal count = BigDecimal.ZERO;
        for (DynamicObject temp : entryEntity) {
            BigDecimal piecesTemp = temp.getBigDecimal("yem_grossweightsumd");
            String businesssortTemp = temp.getString("yem_businesssort_dw");
            if (YEM.isNotEmpty(piecesTemp) && "P".equals(businesssortTemp)) {
                count = piecesTemp.add(count);
            }
        }
        this.getModel().setValue("yem_mountingweight", count, parentRowIndex);
    }

    /**
     * 装柜信息 子分录汇总 配件立方
     */

    private void setPCube() {
        int parentRowIndex = this.getModel().getEntryCurrentRowIndex("yem_im_packinginfor_pi");
        DynamicObjectCollection entryEntity = this.getModel().getEntryEntity("yem_im_detaweight_dw");
        BigDecimal count = BigDecimal.ZERO;
        for (DynamicObject temp : entryEntity) {
            BigDecimal piecesTemp = temp.getBigDecimal("yem_volsum_det");
            String businesssortTemp = temp.getString("yem_businesssort_dw");
            if (YEM.isNotEmpty(piecesTemp) && "P".equals(businesssortTemp)) {
                count = piecesTemp.add(count);
            }
        }
        this.getModel().setValue("yem_mountingcube", count, parentRowIndex);
    }


    /**
     * 装柜信息  子分录汇总 整机件数
     */

    private void setZCounts() {
        int parentRowIndex = this.getModel().getEntryCurrentRowIndex("yem_im_packinginfor_pi");
        DynamicObjectCollection entryEntity = this.getModel().getEntryEntity("yem_im_detaweight_dw");
        BigDecimal count = BigDecimal.ZERO;
        for (DynamicObject temp : entryEntity) {
            BigDecimal piecesTemp = temp.getBigDecimal("yem_pieces_det");
            String businesssortTemp = temp.getString("yem_businesssort_dw");
            if (YEM.isNotEmpty(piecesTemp) && "Z".equals(businesssortTemp)) {
                count = piecesTemp.add(count);
            }
        }
        this.getModel().setValue("yem_numberunits", count, parentRowIndex);
    }

    /**
     * 装柜信息  子分录汇总 配件件数
     */

    private void setPCounts() {
        int parentRowIndex = this.getModel().getEntryCurrentRowIndex("yem_im_packinginfor_pi");
        DynamicObjectCollection entryEntity = this.getModel().getEntryEntity("yem_im_detaweight_dw");
        BigDecimal count = BigDecimal.ZERO;
        for (DynamicObject temp : entryEntity) {
            BigDecimal piecesTemp = temp.getBigDecimal("yem_pieces_det");
            String businesssortTemp = temp.getString("yem_businesssort_dw");
            if (YEM.isNotEmpty(piecesTemp) && "P".equals(businesssortTemp)) {
                count = piecesTemp.add(count);
            }
        }
        this.getModel().setValue("yem_numberparts", count, parentRowIndex);
    }

    /**
     * 装柜信息 子单据体 赋值给货物描述
     */
    private void goodDescribe() {
        int parentRowIndex = this.getModel().getEntryCurrentRowIndex("yem_im_packinginfor_pi");
        StringBuffer info = new StringBuffer();
        DynamicObjectCollection entryEntity = this.getModel().getEntryEntity("yem_im_detaweight_dw");
        int row = 0;
        for (DynamicObject temp : entryEntity) {
            String picnozTemp = temp.getString("yem_picnoz_det");
            BigDecimal piecesTemp = temp.getBigDecimal("yem_pieces_det");

            if (YEM.isNotEmpty(picnozTemp) && YEM.isNotEmpty(piecesTemp)) {
                piecesTemp = piecesTemp.stripTrailingZeros();
                if (row == 0) {
                    info.append(piecesTemp);
                    info.append("*");
                    info.append(picnozTemp);
                } else {
                    info.append("+");
                    info.append(piecesTemp);
                    info.append("*");
                    info.append(picnozTemp);
                }
                row++;
            }

        }
        this.getModel().setValue("yem_goodescription", info.toString(), parentRowIndex);
    }

    /**
     * 明细信息整机 携带 装箱方案 赋值 商品明细可拆卸信息
     */
    private void setValuesByMS(PropertyChangedArgs e) {
        //携带当前行【装箱方案】到【商品明细可拆卸信息】当前行
        ChangeData changeData = e.getChangeSet()[0];
        int row = changeData.getRowIndex();
        Object old = changeData.getOldValue();
        if (YEM.isNotEmpty(old)) {
            String ids = map.get(row);
            DynamicObjectCollection yemBackentry = this.getModel().getEntryEntity("yem_backentry");
            List<Integer> indexList = new ArrayList();
            int rowIndexs = 0;
            for (DynamicObject dt : yemBackentry) {
                String bigintfield = dt.getString("yem_infoid");
                if (bigintfield.equals(ids)) {
                    indexList.add(rowIndexs);
                }
                rowIndexs++;
            }
            this.getModel().deleteEntryRows("yem_backentry", indexList.stream().mapToInt(i -> i).toArray());
        }
        DynamicObject entry = this.getModel().getDataEntity(true);
        DynamicObject boxscheme = (DynamicObject) this.getModel().getValue("yem_boxscheme", row);
        DynamicObject resourceid = (DynamicObject) this.getModel().getValue("yem_resourceid", row);
        DynamicObject productmodel = null;
        BigDecimal shipmentqty = (BigDecimal) this.getModel().getValue("yem_shipmentqty", row);
        List<DynamicObject> listRow = new ArrayList<>();
        DynamicObject datas = null;
        if (boxscheme != null) {
            datas = BusinessDataServiceHelper.loadSingle(boxscheme.getPkValue(), boxscheme.getDynamicObjectType().getName());
            if (datas != null) {
                productmodel = datas.getDynamicObject("yem_productmodel");
                DynamicObjectCollection packplan = datas.getDynamicObjectCollection("yem_packplan_e");
                for (DynamicObject dy : packplan) {
                    listRow.add(dy);
                }
            }
        }
        DynamicObjectCollection materialinfo_mi = entry.getDynamicObjectCollection("yem_backentry");
        int rowIndex = materialinfo_mi.size();
        String id = get16UUID();
        map.put(row, id);
        //获取当前明细行 主键
        for (DynamicObject dc : listRow) {
            this.getModel().createNewEntryRow("yem_backentry");
            this.getModel().setValue("yem_infoid", id, rowIndex);
            if (resourceid != null) {
                this.getModel().setValue("yem_resourceid_bac", resourceid.getPkValue(), rowIndex);
            }
            if (productmodel != null) {
                this.getModel().setValue("yem_productmodel_bac", productmodel.getPkValue(), rowIndex);
            }
            this.getModel().setValue("yem_picno", dc.getDynamicObject("yem_picno"), rowIndex);
//            DynamicObject picno = dc.getDynamicObject("yem_picno");
//            if(picno != null) {
//                this.getModel().setValue("yem_picnoz", picno.getString("name"), rowIndex);
//            }
            this.getModel().setValue("yem_picnoz", dc.getString("yem_splitname"), rowIndex);
            this.getModel().setValue("yem_weight", dc.getBigDecimal("yem_weight_e"), rowIndex);
            this.getModel().setValue("yem_staqty", dc.getBigDecimal("yem_staqty"), rowIndex);
            this.getModel().setValue("yem_qty", shipmentqty, rowIndex);
            this.getModel().setValue("yem_totalweight", datas.getBigDecimal("yem_weight"), rowIndex);
            rowIndex++;
        }
    }

    /*
     * 获得16个长度的十六进制的UUID
     * */
    public static String get16UUID() {

        UUID id = UUID.randomUUID();
        String[] idd = id.toString().split("-");
        return idd[0] + idd[1] + idd[2];
    }

    /**
     * excel导出
     */
    private void exportEntityData() {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity();
        String name = model.getDataEntityType().getName();
        FileUtil fileUtil = new FileUtil(name);

        String fileName = "明细信息.xlsx";

        File file = null;

        Map<Integer, List<String>> map = new LinkedHashMap<>();

        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_im_materialinfo_mi");
        for (int i = 0; i < collection.size(); i++) {
            String businesssort = collection.get(i).getString("yem_businesssort");
            if ("P".equals(businesssort)) {

                DynamicObject object = collection.get(i);

                List<String> items = new ArrayList<>();
                // 对应装箱单分录ID
                items.add(String.valueOf(object.getPkValue()));
                // 业务分类
                items.add("配件");
                // 外销合同号
                items.add(object.getString("yem_salenumberno"));
                // 出运明细单号
                items.add(object.getString("yem_outnumberno"));
                // 配件分类
                DynamicObject customclass = object.getDynamicObject("yem_customclass");
                if (customclass != null) {
                    items.add(customclass.getString("name"));
                } else {
                    items.add("");
                }
                // HS编码
                DynamicObject hscode = object.getDynamicObject("yem_hscode");
                if (hscode != null) {
                    items.add(hscode.getString("number"));
                } else {
                    items.add("");
                }
                // 物料名称
                DynamicObject material = object.getDynamicObject("yem_material");
                if (material != null) {
                    items.add(material.getString("name"));
                } else {
                    items.add("");
                }
                // Part Number
                DynamicObject material1 = object.getDynamicObject("yem_material");
                if (material1 != null) {
                    items.add(material1.getString("number"));
                } else {
                    items.add("");
                }
                // Part Name
                items.add(object.getString("yem_productennames"));
                // 装箱数量
                items.add(String.valueOf(object.getBigDecimal("yem_shipmentqty").setScale(2, RoundingMode.HALF_EVEN)));
                // 包装数量
                BigDecimal packingqty = object.getBigDecimal("yem_packingqty");
                if (packingqty.compareTo(BigDecimal.ZERO) == 0) {
                    items.add("0");
                } else {
                    items.add(String.valueOf(packingqty));
                }
                // 包装方式
                DynamicObject packstyle = object.getDynamicObject("yem_packstyle");
                if (YEM.isNotEmpty(packstyle)) {
                    items.add(packstyle.getString("number"));
                } else {
                    items.add("");
                }
                // 箱号
                items.add("");
                // 托盘号
                items.add("");
                map.put(i + 1, items);
            }
        }

        try {
            file = fileUtil.createNewFile(fileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("Data");

            // 写入第一行数据
            Row headerRow = sheet.createRow(0);
            String[] headers = {"引入序号", "对应装箱单分录ID", "业务分类", "外销合同号", "出运明细单号", "配件分类", "HS编码", "物料名称", "Part Number", "Part Name", "装箱数量", "包装数量", "包装方式", "箱号", "托盘号"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            int rowIdx = 1;
            for (Map.Entry<Integer, List<String>> entry : map.entrySet()) {
                Row row = sheet.createRow(rowIdx++);
                row.createCell(0).setCellValue(entry.getKey()); // 写入第一列的序号
                List<String> rowData = entry.getValue();
                for (int colIdx = 0; colIdx < rowData.size(); colIdx++) {
                    row.createCell(colIdx + 1).setCellValue(rowData.get(colIdx)); // 写入第二列及以后的数据
                }
            }

            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i); // 调整每一列的列宽以适应内容
            }

            // 写入到文件
            try (FileOutputStream fileOut = new FileOutputStream(file.getPath())) {
                workbook.write(fileOut);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        Object formId = this.getModel().getDataEntity().getPkValue();
        String uploaded;
        try {
            uploaded = AttachmentUtil.uploadFileItem("yem", name, String.valueOf(formId), fileName, file.getPath());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (uploaded != null) {
            String fileUrl = UrlService.getAttachmentFullUrl(uploaded);
            this.getView().openUrl(fileUrl);
        }
    }

    private void importEntityData() {
        FormShowParameter showParameter = new FormShowParameter();
        showParameter.setFormId("yem_im_dataimport");
        // 状态
        showParameter.setStatus(OperationStatus.ADDNEW);
        // 设置弹出页面打开方式
        showParameter.getOpenStyle().setShowType(ShowType.Modal);
        showParameter.setCloseCallBack(new CloseCallBack(this, "yem_inputdata"));
        this.getView().showForm(showParameter);
    }

    /**
     * 导入的数据设置值
     *
     * @param json
     */
    private void setEntityValue(JSONArray json) {
        // 配件包装信息
        IDataModel model = this.getModel();
        // 明细信息
        DynamicObjectCollection collection = model.getEntryEntity("yem_im_materialinfo_mi");
        int number = 1;
        for (Object object : json) {
            JSONArray jsonArray = (JSONArray) object;
            int serNum = new BigDecimal((String) jsonArray.get(0)).intValue() - 1;
            long pkValue = (long) collection.get(serNum).getPkValue();
            int entryRow = model.createNewEntryRow("yem_pjpackageinfo");
            // 序号
            model.setValue("yem_sernumber", number, entryRow);
            // 业务分类
            model.setValue("yem_businesssort1", "P", entryRow);
            // 配件分类
            model.setValue("yem_customclass1", collection.get(serNum).getLong("yem_customclass.id"), entryRow);
            // 物料编码
            model.setValue("yem_materiels", collection.get(serNum).getLong("yem_material.id"), entryRow);
            // 箱号
            String boxNum = (String) jsonArray.get(13);
            if (boxNum.contains(".")) {
                boxNum = boxNum.substring(0, boxNum.indexOf("."));
            }
            model.setValue("yem_boxnumber", boxNum, entryRow);
            // 托盘号
            String panNum = (String) jsonArray.get(14);
            if (panNum.contains(".")) {
                panNum = panNum.substring(0, panNum.indexOf("."));
            }
            model.setValue("yem_traynumbers", panNum, entryRow);
            // 包装数量
            model.setValue("yem_qtys", new BigDecimal((String) jsonArray.get(11)), entryRow);
            // 包装方式
            String packstylesnNumber = (String) jsonArray.get(12);
            if (YEM.isNotEmpty(packstylesnNumber)) {
                DynamicObject single = BusinessDataServiceHelper.loadSingle("yem_bd_packing", new QFilter[]{new QFilter("number", QCP.equals, packstylesnNumber)});
                if (single != null) {
                    model.setValue("yem_packstyles", single.getPkValue(), entryRow);
                }
            } else {
                model.setValue("yem_packstyles", null, entryRow);
            }
            // 包装名称
            model.setValue("yem_bzmc", boxNum, entryRow);
            // 海关编码
            model.setValue("yem_hscode1", collection.get(serNum).getLong("yem_hscode.id"), entryRow);
            // 对应装箱单分录ID
            model.setValue("yem_packingentriesid", pkValue, entryRow);
            // 外销合同号
            model.setValue("yem_salenumberno1", collection.get(serNum).getString("yem_salenumberno"), entryRow);
            // 出运明细单号
            model.setValue("yem_outnumberno1", collection.get(serNum).getString("yem_outnumberno"), entryRow);
            model.setValue("yem_materialinfoid", jsonArray.get(1), entryRow);
            number++;
        }

        calcSumData();
    }

    private void calcSumData() {
        IDataModel model = this.getModel();

        validatorAbleDelete(model);

        model.deleteEntryData("yem_sumpartspack");

        // 合并
        DynamicObjectCollection pjpackageinfo = model.getEntryEntity("yem_pjpackageinfo");

        // 托盘号 - 托盘号相同的行
        Map<String, List<Integer>> palletsMap = new LinkedHashMap<>();
        for (DynamicObject dynamicObject : pjpackageinfo) {
            // 托盘号
            Integer pkValue = dynamicObject.getInt("yem_sernumber");
            String traynumbers = dynamicObject.getString("yem_traynumbers");
            if (palletsMap.containsKey(traynumbers)) {
                palletsMap.get(traynumbers).add(pkValue);
            } else {
                List<Integer> list = new ArrayList<>();
                list.add(pkValue);
                palletsMap.put(traynumbers, list);
            }
        }

        for (Map.Entry<String, List<Integer>> pallet : palletsMap.entrySet()) {
            String k = pallet.getKey();
            // 相同托盘号的id list
            List<Integer> v = pallet.getValue();

            Map<String, List<Integer>> boxMap = new LinkedHashMap<>();

            for (Integer id : v) {
                DynamicObject object = getPjpackageinfoBySerNum(pjpackageinfo, id);
                if (object != null) {
                    // 箱号
                    String boxnumber = object.getString("yem_boxnumber");
                    Integer pkValue = object.getInt("yem_sernumber");
                    if (boxMap.containsKey(boxnumber)) {
                        boxMap.get(boxnumber).add(pkValue);
                    } else {
                        List<Integer> list = new ArrayList<>();
                        list.add(pkValue);
                        boxMap.put(boxnumber, list);
                    }
                }
            }

            for (Map.Entry<String, List<Integer>> box : boxMap.entrySet()) {
                String boxKey = box.getKey();
                List<Integer> boxValue = box.getValue();
                sumAndInsert(boxValue);
            }
        }

        // 包装数量反写到明细信息中的以包装数量
        Map<Long, BigDecimal> map = new LinkedHashMap<>();

        for (DynamicObject dynamicObject : pjpackageinfo) {
            long materialinfoid = dynamicObject.getLong("yem_materialinfoid");
            if (YEM.isEmpty(materialinfoid)) continue;
            // 包装数量
            BigDecimal decimal = dynamicObject.getBigDecimal("yem_qtys");
            if (map.containsKey(materialinfoid)) {
                map.put(materialinfoid, map.get(materialinfoid).add(decimal));
            } else {
                map.put(materialinfoid, decimal);
            }
        }

        for (Map.Entry<Long, BigDecimal> entry : map.entrySet()) {
            Long k = entry.getKey();
            BigDecimal v = entry.getValue();
            DynamicObjectCollection materialinfoMi = model.getEntryEntity("yem_im_materialinfo_mi");
            for (int i = 0; i < materialinfoMi.size(); i++) {
                Long pkValue = (Long) materialinfoMi.get(i).getPkValue();
                if (Objects.equals(k, pkValue)) {
                    model.setValue("yem_packingqty", v, i);
                }
            }
        }

        calcResidueqty();
    }

    /**
     * 校验已装柜数量是否大于0，否则不能进行合并
     *
     * @param model
     */
    private void validatorAbleDelete(IDataModel model) {

        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_sumpartspack");
        StringBuilder sb = new StringBuilder();
        for (DynamicObject object : collection) {
            int index = collection.indexOf(object);
            // 已装柜件数
            BigDecimal stuffingpiece = object.getBigDecimal("yem_stuffingpiece");
            if (stuffingpiece.compareTo(BigDecimal.ZERO) != 0) {
                sb.append(String.format("汇总信息中第 [ %s ] 行已经装柜，无法进行合并，请删除对应装柜明细数据之后重试！", index + 1)).append("\r\n");
            }
        }
        if (sb.length() > 0) {
            throw new KDBizException(sb.toString());
        }
    }

    private void sumAndInsert(List<Integer> boxValue) {
        IDataModel model = this.getModel();
        DynamicObject dynamicObject = getPjpackageinfoBySerNum(model.getEntryEntity("yem_pjpackageinfo"), boxValue.get(0));
        // 包装数量
        int qtys = 0;
        // 总毛重
        BigDecimal grossweightsum = BigDecimal.ZERO;

        BigDecimal volm3sum = BigDecimal.ZERO;
        for (Integer id : boxValue) {
            DynamicObject object = getPjpackageinfoBySerNum(model.getEntryEntity("yem_pjpackageinfo"), id);
            if (object != null) {
                qtys = qtys + object.getInt("yem_qtys");
            }
        }
        int entryRow = model.createNewEntryRow("yem_sumpartspack");
        if (dynamicObject != null) {

            // 明细信息分录id
            long packingentriesid = dynamicObject.getLong("yem_packingentriesid");

            DynamicObject materialinfo = getMaterialinfoByPk(packingentriesid);

//            if (materialinfo != null) {
//                grossweightsum = grossweightsum.add(materialinfo.getBigDecimal("yem_grossweightsum"));
//
//                volm3sum = volm3sum.add(materialinfo.getBigDecimal("yem_volm3sum"));
//                // 总毛重（隐藏）
//                model.setValue("yem_sumroughweight", grossweightsum, entryRow);
//                // 总体积M3（隐藏）
//                model.setValue("yem_sumvolume", volm3sum, entryRow);
//            }
            model.setValue("yem_packtype", dynamicObject.getLong("yem_packstyles.id"), entryRow);
            // 序号
            model.setValue("yem_sernumber1", dynamicObject.getInt("yem_sernumber"), entryRow);
            // 托盘号
            model.setValue("yem_trayno", dynamicObject.getString("yem_traynumbers"), entryRow);
            // 箱号
            model.setValue("yem_boxno", dynamicObject.getString("yem_boxnumber"), entryRow);
            // 件数
            model.setValue("yem_piecenum", BigDecimal.ONE, entryRow);
            // 剩余件数
            model.setValue("yem_residuepiece", BigDecimal.ONE, entryRow);
            // 包装名称
            model.setValue("yem_packname", dynamicObject.getString("yem_boxnumber"), entryRow);
            // 数量
            model.setValue("yem_quantity", qtys, entryRow);
        }
    }

    private DynamicObject getMaterialinfoByPk(long packingentriesid) {
        DynamicObjectCollection materialinfoMi = this.getModel().getEntryEntity("yem_im_materialinfo_mi");
        for (DynamicObject dynamicObject : materialinfoMi) {
            if (packingentriesid == (Long) dynamicObject.getPkValue()) {
                return dynamicObject;
            }
        }
        return null;
    }

    /**
     * 获取 配件包装信息
     *
     * @param pjpackageinfo 配件包装信息分录
     * @param id            序号
     * @return
     */
    private DynamicObject getPjpackageinfoBySerNum(DynamicObjectCollection pjpackageinfo, Integer id) {
        for (DynamicObject dynamicObject : pjpackageinfo) {
            if (dynamicObject.getInt("yem_sernumber") == id) {
                return dynamicObject;
            }
        }
        return null;
    }


    private void deleteEntryRow() {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        EntryGrid pjpackageinfo = view.getControl("yem_pjpackageinfo");
        int[] selectRows = pjpackageinfo.getSelectRows();
        DynamicObjectCollection collection = model.getEntryEntity("yem_pjpackageinfo");


        for (int rowIdx : selectRows) {
            // 托盘号
            String traynumbers = collection.get(rowIdx).getString("yem_traynumbers");
            // 箱号
            String boxnumber = collection.get(rowIdx).getString("yem_boxnumber");

            // 汇总信息
            DynamicObject dynamicObject = getSumpartspackByTraynAndBoxnum(traynumbers, boxnumber);
            Integer index = getSumpartspackIndexByTraynAndBoxnum(traynumbers, boxnumber);
            if (dynamicObject == null || index == null) {
                continue;
            }
            // 已装柜数量
            BigDecimal decimal = dynamicObject.getBigDecimal("yem_stuffingpiece");

            if (decimal.compareTo(BigDecimal.ZERO) > 0) {
                view.showErrorNotification("配件包装信息分录序号为：" + (index + 1) + "的行已装柜数量大于0，不允许删除");
                return;
            }

            // 包装数量
            BigDecimal quantity = dynamicObject.getBigDecimal("yem_quantity");
            BigDecimal qtys = collection.get(rowIdx).getBigDecimal("yem_qtys");
            model.setValue("yem_quantity", quantity.subtract(qtys), index);
        }

        DynamicObjectCollection sumpartspack = model.getEntryEntity("yem_sumpartspack");

        List<Integer> deleteList = new ArrayList<>();

        for (int i = 0; i < sumpartspack.size(); i++) {
            BigDecimal quantity = sumpartspack.get(i).getBigDecimal("yem_quantity");
            if (quantity.compareTo(BigDecimal.ZERO) <= 0) {
                deleteList.add(i);
            }
        }
        model.deleteEntryRows("yem_sumpartspack", deleteList.stream().mapToInt(Integer::intValue).toArray());

        for (int selectRow : selectRows) {
            DynamicObject dynamicObject = collection.get(selectRow);
            // 包装数量
            BigDecimal qtys = dynamicObject.getBigDecimal("yem_qtys");
            // 明细信息中对应的id
            long materialinfoid = dynamicObject.getLong("yem_materialinfoid");

            DynamicObjectCollection materialinfoMi = model.getEntryEntity("yem_im_materialinfo_mi");
            for (int i = 0; i < materialinfoMi.size(); i++) {
                Long pkValue = (Long) materialinfoMi.get(i).getPkValue();
                if (materialinfoid == pkValue) {
                    // 已包装数量
                    BigDecimal decimal = materialinfoMi.get(i).getBigDecimal("yem_packingqty");
                    decimal = decimal.subtract(qtys);
                    model.setValue("yem_packingqty", decimal, i);
                }
            }
        }

        // 删除配件包装信息中选中的行
        model.deleteEntryRows("yem_pjpackageinfo", selectRows);

        calcResidueqty();
    }

    private DynamicObject getSumpartspackByTraynAndBoxnum(String traynumbers, String boxnumber) {
        IDataModel model = this.getModel();
        DynamicObjectCollection sumpartspack = model.getEntryEntity("yem_sumpartspack");
        for (DynamicObject dynamicObject : sumpartspack) {
            // 箱号
            String boxno = dynamicObject.getString("yem_boxno");
            // 托盘号
            String trayno = dynamicObject.getString("yem_trayno");

            if (Objects.equals(boxno, boxnumber) && Objects.equals(trayno, traynumbers)) {
                return dynamicObject;
            }
        }
        return null;
    }

    private Integer getSumpartspackIndexByTraynAndBoxnum(String traynumbers, String boxnumber) {
        IDataModel model = this.getModel();
        DynamicObjectCollection sumpartspack = model.getEntryEntity("yem_sumpartspack");
        for (int i = 0; i < sumpartspack.size(); i++) {
            // 箱号
            String boxno = sumpartspack.get(i).getString("yem_boxno");
            // 托盘号
            String trayno = sumpartspack.get(i).getString("yem_trayno");

            if (Objects.equals(boxno, boxnumber) && Objects.equals(trayno, traynumbers)) {
                return i;
            }
        }
        return null;
    }

    private DynamicObject getSumpartspackSerNum(DynamicObjectCollection sumpartspack, Integer rowIdx) {
        for (DynamicObject dynamicObject : sumpartspack) {
            if (dynamicObject.getInt("yem_sernumber1") == rowIdx) {
                return dynamicObject;
            }
        }
        return null;
    }

    @Override
    public void afterAddRow(AfterAddRowEventArgs e) {
        super.afterAddRow(e);
        String name = e.getEntryProp().getName();
        IDataModel model = this.getModel();
        RowDataEntity[] rowDataEntities = e.getRowDataEntities();
        for (RowDataEntity dataEntity : rowDataEntities) {
            int rowIndex = dataEntity.getRowIndex();
            if ("yem_im_packinginfor_pi".equals(name)) {
                model.setValue("yem_contnum", rowIndex + 1, rowIndex);
            }
        }
    }
}