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

import com.alibaba.druid.util.StringUtils;
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.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.BeforeDeleteEntryEventArgs;
import kd.bos.entity.datamodel.events.BeforeDeleteRowEventArgs;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.property.EntryProp;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.events.CustomEventArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;

import java.math.BigDecimal;
import java.util.EventObject;

/**
 * @author power
 * @ClassName
 * @description: 回填装柜信息 装箱单
 * @date 2023/8/29
 */
public class EncaseMentStuffingEdit extends AbstractBillPlugIn
{
    @Override
    public void registerListener(EventObject e)
    {
        // TODO Auto-generated method stub
        //监听点击的行数
        super.registerListener(e);
        this.addItemClickListeners("yem_advcontoolbarap1");
    }


    @Override
    public void afterDoOperation(AfterDoOperationEventArgs afterDoOperationEventArgs)
    {
        super.afterDoOperation(afterDoOperationEventArgs);
    }

    @Override
    public void itemClick(ItemClickEvent evt)
    {
        // TODO Auto-generated method stub
        String key = evt.getItemKey();
        // 判断是否为回填按钮
//        if (StringUtils.equals("yem_backfistuffingmessage", key)) {
//            this.showInfoForm(this.getView());
//        }
        IFormView view = this.getView();
        if (StringUtils.equals("yem_backmessagepj", key)) {
            view.invokeOperation("save");
            this.showInfoForm(view, "yem_stuffingmessage_pj");
        }
        if (StringUtils.equals("yem_backmessagezj", key)) {
            view.invokeOperation("save");
            this.showInfoForm(view, "yem_stuffingmessage_zj");
        }
    }

    @Override
    public void customEvent(CustomEventArgs e)
    {
        // TODO Auto-generated method stub
        super.customEvent(e);
    }

    private void showInfoForm(IFormView view, String classname)
    {
        FormShowParameter showParameter = new FormShowParameter();
        showParameter.setStatus(OperationStatus.ADDNEW);
        showParameter.getOpenStyle().setShowType(ShowType.Modal);
        showParameter.setFormId(classname);


        DynamicObjectCollection entity = this.getModel().getEntryEntity("yem_sumpartspack");
        showParameter.setCustomParam("yem_sumpartspack", entity);

        DynamicObjectCollection entitys = this.getModel().getEntryEntity("yem_backentry");
        showParameter.setCustomParam("yem_backentry", entitys);

        showParameter.setCloseCallBack(new CloseCallBack(this, "yem_im_encasement"));
        view.showForm(showParameter);
    }

    /**
     * 动态表单回填单据字段
     */
    private void setInwardInfo(DynamicObjectCollection[] values)
    {
        DynamicObjectCollection yem_backentrys = values[0];
        DynamicObjectCollection yem_sumpartspack = values[1];


//        DynamicObjectCollection tpv_personinforss = yem_backentrys.getDynamicObjectCollection("yem_backentry");
//        this.getModel().deleteEntryData("yem_im_detaweight_dw");
        for (DynamicObject tpv_personinfor : yem_backentrys) {
            int index = this.getModel().createNewEntryRow("yem_im_detaweight_dw");
            if (index != -1) {
                this.getModel().setValue("yem_businesssort_dw", "Z", index);
                this.getModel().setValue("yem_resourceids", tpv_personinfor.getDynamicObject("yem_resourceid_bac"), index);
                this.getModel().setValue("yem_milltype", tpv_personinfor.getDynamicObject("yem_productmodel_bac"), index);
                this.getModel().setValue("yem_picno_det", tpv_personinfor.getDynamicObject("yem_picno"), index);
                this.getModel().setValue("yem_picnoz_det", tpv_personinfor.getString("yem_picnoz"), index);
                this.getModel().setValue("yem_pieces_det", tpv_personinfor.getBigDecimal("yem_cabinetpiece"), index);
                this.getModel().setValue("yem_grossweightsumd", tpv_personinfor.getBigDecimal("yem_qtyamt"), index);
                this.getModel().setValue("yem_pillarsid", tpv_personinfor.getString("yem_pillarsid"), index);

                BigDecimal qtypacked = (BigDecimal) this.getModel().getValue("yem_qtypacked", tpv_personinfor.getInt("seq") - 1);
                this.getModel().setValue("yem_qtypacked", qtypacked.add(tpv_personinfor.getBigDecimal("yem_cabinetpiece"))
                        , tpv_personinfor.getInt("seq") - 1);

                BigDecimal qtyamt = (BigDecimal) this.getModel().getValue("yem_qtyamt", tpv_personinfor.getInt("seq") - 1);
                this.getModel().setValue("yem_qtyremain",
                        qtyamt.subtract(qtypacked.add(tpv_personinfor.getBigDecimal("yem_cabinetpiece")))
                        , tpv_personinfor.getInt("seq") - 1);

            }
            if (index == -1) {
                this.getView().showMessage("请先录入装柜信息");
            }
        }
//        DynamicObjectCollection yem_sumpartspackss = yem_sumpartspack.getDynamicObjectCollection("yem_sumpartspack");
        for (DynamicObject yem_sumpartspacks : yem_sumpartspack) {
            int index = this.getModel().createNewEntryRow("yem_im_detaweight_dw");
            if (index != -1) {
                this.getModel().setValue("yem_businesssort_dw", "P", index);
                this.getModel().setValue("yem_picnoz_det", yem_sumpartspacks.getString("yem_packname"), index);
                this.getModel().setValue("yem_traynumber_det", yem_sumpartspacks.getString("yem_trayno"), index);
                this.getModel().setValue("yem_boxnumber_det", yem_sumpartspacks.getString("yem_boxno"), index);
                this.getModel().setValue("yem_packstyle_det", yem_sumpartspacks.getDynamicObject("yem_packtype"), index);
                this.getModel().setValue("yem_pieces_det", yem_sumpartspacks.getBigDecimal("yem_piecenum"), index);
                this.getModel().setValue("yem_grossweightsumd", yem_sumpartspacks.getBigDecimal("yem_sumroughweight"), index);
                this.getModel().setValue("yem_volsum_det", yem_sumpartspacks.getBigDecimal("yem_sumvolume"), index);
                this.getModel().setValue("yem_partsid", yem_sumpartspacks.getString("yem_partsid"), index);
                this.getModel().setValue("yem_grossweightsumd", yem_sumpartspacks.getBigDecimal("yem_sumroughweight"), index);
                this.getModel().setValue("yem_volsum_det", yem_sumpartspacks.getString("yem_sumvolume"), index);

                BigDecimal stuffingpiece = (BigDecimal) this.getModel().getValue("yem_stuffingpiece", yem_sumpartspacks.getInt("seq") - 1);
                this.getModel().setValue("yem_stuffingpiece", stuffingpiece.add(yem_sumpartspacks.getBigDecimal("yem_piecenum"))
                        , yem_sumpartspacks.getInt("seq") - 1);

                BigDecimal quantity = (BigDecimal) this.getModel().getValue("yem_piecenum", yem_sumpartspacks.getInt("seq") - 1);
                this.getModel().setValue("yem_residuepiece",
                        quantity.subtract(stuffingpiece.add(yem_sumpartspacks.getBigDecimal("yem_piecenum")))
                        , yem_sumpartspacks.getInt("seq") - 1);
            }
            if (index == -1) {
                this.getView().showMessage("请先录入装柜信息");
            }
        }
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent closedCallBackEvent)
    {
        Object returnData = closedCallBackEvent.getReturnData();
        //判断标识是否匹配，并验证返回值不为空，不验证返回值可能会报空指针
        if (StringUtils.equals(closedCallBackEvent.getActionId(), "yem_im_encasement") && null != closedCallBackEvent.getReturnData()) {
            //这里返回对象为Object，可强转成相应的其他类型，
            // 单条数据可用String类型传输，返回多条数据可放入map中，也可使用json等方式传输
            DynamicObjectCollection[] data = (DynamicObjectCollection[]) returnData;
            this.setInwardInfo(data);
        }
    }

    @Override
    public void beforeDeleteRow(BeforeDeleteRowEventArgs e)
    {
        super.beforeDeleteRow(e);
        int[] index = e.getRowIndexs();
        EntryProp entryProp = e.getEntryProp();
        if ("yem_im_detaweight_dw".equals(entryProp.getName())) {
            for (int row : index) {
                String businesssort_dw = (String) this.getModel().getValue("yem_businesssort_dw", row);
                if ("Z".equals(businesssort_dw)) {
                    BigDecimal pieces_det = (BigDecimal) this.getModel().getValue("yem_pieces_det", row);
                    Long pillarsid = Long.valueOf((String) this.getModel().getValue("yem_pillarsid", row));
                    DynamicObject encasement = BusinessDataServiceHelper.loadSingle("yem_im_encasement",
                            "yem_backentry.seq",
                            new QFilter[]{new QFilter("yem_backentry.id", QCP.equals, pillarsid),});
                    if(encasement != null){
                        DynamicObjectCollection encasements = encasement.getDynamicObjectCollection("yem_backentry");
                        DynamicObjectCollection backentrys = this.getView().getModel().getEntryEntity("yem_backentry");
                        for (DynamicObject encasementss : encasements) {
                            Long id = encasementss.getLong("id");
                            if (id.equals(pillarsid)) {
                                int seq = encasementss.getInt("seq");
                                DynamicObject backentry = backentrys.get(seq - 1);
                                BigDecimal qtypacked = backentry.getBigDecimal("yem_qtypacked");
                                BigDecimal qtyremain = backentry.getBigDecimal("yem_qtyremain");
                                BigDecimal cheqtypacked = qtypacked.subtract(pieces_det);
                                BigDecimal cheqtyremain = qtyremain.add(pieces_det);
                                this.getModel().setValue("yem_qtypacked", cheqtypacked, seq - 1);
                                this.getModel().setValue("yem_qtyremain", cheqtyremain, seq - 1);
                            }
                        }
                    }

                }
                if ("P".equals(businesssort_dw)) {
                    BigDecimal pieces_det = (BigDecimal) this.getModel().getValue("yem_pieces_det", row);
                    Long partsid = Long.valueOf((String) this.getModel().getValue("yem_partsid", row));
                    DynamicObject encasement = BusinessDataServiceHelper.loadSingle("yem_im_encasement",
                            "yem_sumpartspack.seq",
                            new QFilter[]{new QFilter("yem_sumpartspack.id", QCP.equals, partsid)});
                    if (encasement!=null){
                        DynamicObjectCollection encasements = encasement.getDynamicObjectCollection("yem_sumpartspack");
                        DynamicObjectCollection sumpartspacks = this.getView().getModel().getEntryEntity("yem_sumpartspack");
                        for (DynamicObject encasementss : encasements) {
                            Long id = encasementss.getLong("id");
                            if (id.equals(partsid)) {
                                int seq = encasementss.getInt("seq");
                                DynamicObject sumpartspack = sumpartspacks.get(seq - 1);
                                BigDecimal stuffingpiece = sumpartspack.getBigDecimal("yem_stuffingpiece");
                                BigDecimal residuepiece = sumpartspack.getBigDecimal("yem_residuepiece");
                                BigDecimal cheqstuffingpiece = stuffingpiece.subtract(pieces_det);
                                BigDecimal cheffingpiece = residuepiece.add(pieces_det);
                                this.getModel().setValue("yem_stuffingpiece", cheqstuffingpiece, seq - 1);
                                this.getModel().setValue("yem_residuepiece", cheffingpiece, seq - 1);
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        int rowIndex = e.getChangeSet()[0].getRowIndex();
        String name = e.getProperty().getName();
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        DynamicObject dataEntity = model.getDataEntity(true);
        if ("yem_pieces_det".equals(name)) {
            int packinginfo = model.getEntryCurrentRowIndex("yem_im_packinginfor_pi");
            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_im_packinginfor_pi");
            DynamicObject object = collection.get(packinginfo);
            DynamicObjectCollection subCollection = object.getDynamicObjectCollection("yem_im_detaweight_dw");
            for (DynamicObject subObject : subCollection) {
                // 商品明细可拆卸信息id
                String pillars = subObject.getString("yem_pillarsid");
                if (YEM.isNotEmpty(pillars)) {
                    DynamicObjectCollection pi = dataEntity.getDynamicObjectCollection("yem_im_packinginfor_pi");
                    BigDecimal currentTotal = BigDecimal.ZERO;
                    for (DynamicObject subObj : pi) {
                        DynamicObjectCollection subList = subObj.getDynamicObjectCollection("yem_im_detaweight_dw");
                        for (DynamicObject sub : subList) {
                            String pillarsid = sub.getString("yem_pillarsid");
                            if (YEM.isNotEmpty(pillarsid) && pillarsid.equals(pillars)) {
                                // 件数
                                BigDecimal det = sub.getBigDecimal("yem_pieces_det");
                                currentTotal = currentTotal.add(det);
                            }
                        }
                    }
                    DynamicObjectCollection backentry = dataEntity.getDynamicObjectCollection("yem_backentry");
                    for (DynamicObject dynamicObject : backentry) {
                        String id = String.valueOf(dynamicObject.getLong("id"));
                        if (pillars.equals(id)) {
                            BigDecimal qtyamt = dynamicObject.getBigDecimal("yem_qtyamt");
                            dynamicObject.set("yem_qtypacked", currentTotal);
                            dynamicObject.set("yem_qtyremain", qtyamt.subtract(currentTotal));
                        }
                    }
                }
                view.updateView("yem_backentry");
            }
        }
    }
}
