package com.yem.em.ass.assemtopart.form;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.*;
import kd.bos.form.control.Control;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.form.plugin.IFormPlugin;
import kd.bos.list.ListShowParameter;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author zhouc
 * @date 2024/1/3 0:04
 * @className AssemtoPart
 * @description 总成间零件替换关系表达插件
 */
public class AssemtoPart extends AbstractFormPlugin implements BeforeF7SelectListener {
    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addClickListeners("yem_onumber", "yem_repnumber");
        BasedataEdit yem_prao = this.getView().getControl("yem_prao");
        yem_prao.addBeforeF7SelectListener(this);
//        BasedataEdit yem_rep = this.getView().getControl("yem_rep");
//        yem_rep.addBeforeF7SelectListener(this);
    }

    @Override
    public void click(EventObject evt) {
        super.click(evt);
        Control c = (Control) evt.getSource();
        String key = c.getKey().toLowerCase();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        if (key.equals("yem_onumber")) {
            int row = this.getModel().getEntryCurrentRowIndex("yem_entryentity");
            Map<String, Object> entryInfo = new HashMap<String, Object>();
            DynamicObject yem_prao = (DynamicObject) model.getValue("yem_prao", row);
            if (yem_prao != null) {
                entryInfo.put("yem_parentass", yem_prao.getString("id"));
                showpartselection("yem_onumber", entryInfo);
            } else {
                this.getView().showErrorNotification("请选择对应的总成！");
            }
        }
        if (key.equals("yem_repnumber")) {
            int row = this.getModel().getEntryCurrentRowIndex("yem_entryentity");
            Map<String, Object> entryInfo = new HashMap<String, Object>();
            DynamicObject yem_rep = (DynamicObject) model.getValue("yem_rep", row);
            if (yem_rep != null) {
                entryInfo.put("yem_parentass", yem_rep.getString("id"));
                showpartselection("yem_repnumber", entryInfo);
            }
        }
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent e) {
        super.closedCallBack(e);
        String actionId = e.getActionId();
        IDataModel model = this.getModel();
        Object returnData = e.getReturnData();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        if (actionId.equals("yem_onumber")) {
            if (returnData != null) {
//                Map<String, Object> map = (Map) returnData;
//                int row = this.getModel().getEntryCurrentRowIndex("yem_entryentity");
//                model.setValue("yem_onumber", map.get("yem_number"), row);
//                model.setValue("yem_oname", map.get("yem_name"), row);
//                model.setValue("yem_oenname", map.get("yem_enname"), row);
//                model.setValue("yem_oqty", map.get("yem_qty"), row);
//                model.setValue("yem_repbeforeremark", map.get("yem_remark"), row);

                List<DynamicObject> list = (List) returnData;
                if (list.size() > 0) {
                    int creditDetailRowCount = this.getModel().getEntryRowCount("yem_entryentity");
                    int row = this.getModel().getEntryCurrentRowIndex("yem_entryentity");
                    for (int i = 0; i < list.size(); i++) {
                        if (i > 0) {
                            if (row >= creditDetailRowCount - 1) {
                                row = this.getModel().createNewEntryRow("yem_entryentity");
                            } else {
                                row = row + 1;
                            }
                        }
                        DynamicObject object = list.get(i);
                        model.setValue("yem_onumber", object.get("yem_number"), row);
                        model.setValue("yem_oname", object.get("yem_name"), row);
                        model.setValue("yem_oenname", object.get("yem_enname"), row);
                        model.setValue("yem_oqty", object.get("yem_qty"), row);
                        model.setValue("yem_prao", object.get("yem_prao"), row);
                        model.setValue("yem_praonumber", object.get("yem_praonumber"), row);
                        model.setValue("yem_praoname", object.get("yem_praoname"), row);
                    }
                }

            }
        }
        if (actionId.equals("yem_repnumber")) {
            if (returnData != null) {
                List<DynamicObject> list = (List) returnData;
                int row = this.getModel().getEntryCurrentRowIndex("yem_entryentity");
                int creditDetailRowCount = this.getModel().getEntryRowCount("yem_entryentity");
                for (int i = 0; i < list.size(); i++) {
                    if (i > 0) {
                        if (row >= creditDetailRowCount - 1) {
                            row = this.getModel().createNewEntryRow("yem_entryentity");
                        } else {
                            row = row + 1;
                        }
                    }
                    DynamicObject object = list.get(i);
                    model.setValue("yem_repnumber", object.get("yem_number"), row);
                    model.setValue("yem_repname", object.get("yem_name"), row);
                    model.setValue("yem_repenname", object.get("yem_enname"), row);
                    model.setValue("yem_repenqty", object.get("yem_qty"), row);
                    model.setValue("yem_rep", object.get("yem_prao"), row);
                    model.setValue("yem_repno", object.get("yem_praonumber"), row);
                    model.setValue("yem_repnoname", object.get("yem_praoname"), row);
                }
            }
        }
    }


    @Override
    public void beforePropertyChanged(PropertyChangedArgs e) {
        super.beforePropertyChanged(e);
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        String name = e.getProperty().getName();
        ChangeData changeData = e.getChangeSet()[0];
        int rowIndex = changeData.getRowIndex();
        Object newValue = changeData.getNewValue();
        Object oldValue = changeData.getOldValue();
        IPageCache pageCache = this.getPageCache();
        if (name.equals("yem_onumber")) {
            if (newValue != null && ((String) newValue).length() == 0) {
                model.setValue("yem_oname", null, rowIndex);
                model.setValue("yem_oenname", null, rowIndex);
                model.setValue("yem_oqty", new BigDecimal(0), rowIndex);
            }
        }
        if (name.equals("yem_repnumber")) {
            if (newValue != null && ((String) newValue).length() == 0) {
                model.setValue("yem_repname", null, rowIndex);
                model.setValue("yem_repenname", null, rowIndex);
                model.setValue("yem_repenqty", new BigDecimal(0), rowIndex);
            }
        }
        if (name.equals("yem_cmmptable") || name.equals("yem_parentass")) {
            long newlong = 0l;
            long oldlong = 0l;
            if (newValue instanceof Long) {
                newlong = (Long) newValue;
                String yem_parentass = pageCache.get("yem_parentass");
                if (yem_parentass != null) {
                    long l = Long.parseLong(yem_parentass);
                    if (newlong == l) {
                        return;
                    }
                }
            } else {
                DynamicObject yem_contract = (DynamicObject) newValue;
                if (yem_contract != null) {
                    newlong = yem_contract.getLong("id");
                }
            }
            if (oldValue instanceof Long) {
                oldlong = (Long) oldValue;
            } else {
                DynamicObject yem_contract = (DynamicObject) oldValue;
                if (yem_contract != null) {
                    oldlong = yem_contract.getLong("id");
                }
            }
            if (newlong > 0 && oldlong > 0) {
                pageCache.put("yem_parentass", String.valueOf(oldlong));
                pageCache.put("yem_newlong", String.valueOf(newlong));
                if (newlong != oldlong) {
                    view.showConfirm("选择部件后，将清除单据体信息，是否确认切换？", MessageBoxOptions.YesNo, ConfirmTypes.Wait,
                            new ConfirmCallBackListener(name, this));
                }
            }
        }
    }

    @Override
    public void confirmCallBack(MessageBoxClosedEvent e) {
        String callBackId = e.getCallBackId();
        MessageBoxResult result = e.getResult();
        IFormView view = (IFormView) e.getSource();
        IDataModel model = view.getModel();
        IPageCache pageCache = view.getPageCache();
        if (result == MessageBoxResult.Yes) {
            if ("yem_cmmptable".equals(callBackId)) {
                model.deleteEntryData("yem_entryentity");
                pageCache.put("yem_parentass", pageCache.get("yem_newlong"));
            }
        }
        if (result == MessageBoxResult.No) {
            if ("yem_cmmptable".equals(callBackId)) {
                String productsOldValue = pageCache.get("yem_parentass");
                model.setValue("yem_cmmptable", Long.parseLong(productsOldValue));
            }
        }
        if (result == MessageBoxResult.Yes) {
            if ("yem_parentass".equals(callBackId)) {
                model.deleteEntryData("yem_entryentity");
                pageCache.put("yem_parentass", pageCache.get("yem_newlong"));
            }
        }
        if (result == MessageBoxResult.No) {
            if ("yem_parentass".equals(callBackId)) {
                String productsOldValue = pageCache.get("yem_parentass");
                model.setValue("yem_parentass", Long.parseLong(productsOldValue));
            }
        }
    }

    public void showpartselection(String closeCallBack, Map<String, Object> entryInfo) {
        FormShowParameter showParameter = new FormShowParameter();
        showParameter.setFormId("yem_em_multpartselect");
        if (closeCallBack != null) {
            showParameter.setCloseCallBack(new CloseCallBack((IFormPlugin) this, closeCallBack));
        }
        if (entryInfo.size() > 0) {
            showParameter.setCustomParams(entryInfo);
        }
        showParameter.getOpenStyle().setShowType(ShowType.Modal);
        this.getView().showForm(showParameter);
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        String name = e.getProperty().getName();
        //|| name.equals("yem_rep")
        if (name.equals("yem_prao")) {
            List list = new ArrayList<>();
            String yem_replacement = dataEntity.getString("yem_replacement");
            if (yem_replacement.equals("Sub")) {
                DynamicObject yem_parentass = dataEntity.getDynamicObject("yem_parentass");
                if (yem_parentass != null) {
                    DynamicObject yem_em_assatlasdet = BusinessDataServiceHelper.loadSingle(yem_parentass.getLong("id"), "yem_em_assatlasdet");
                    if (yem_em_assatlasdet != null) {
                        DynamicObjectCollection yem_entryentity = yem_em_assatlasdet.getDynamicObjectCollection("yem_entryentity");
                        for (int i = 0; i < yem_entryentity.size(); i++) {
                            DynamicObject dynamicObject = yem_entryentity.get(i);
                            boolean yem_iscomp = dynamicObject.getBoolean("yem_iscomp");
                            if (yem_iscomp) {
                                list.add(dynamicObject.getString("yem_partnumber"));
                            }
                        }
                    }
                }

            } else {
                DynamicObject yem_cmmptable = dataEntity.getDynamicObject("yem_cmmptable");
                if (yem_cmmptable != null) {
                    DynamicObject yem_em_assatlasdet = BusinessDataServiceHelper.loadSingle(yem_cmmptable.getLong("id"), "yem_em_cmmptable");
                    if (yem_em_assatlasdet != null) {
                        DynamicObjectCollection yem_entryentity = yem_em_assatlasdet.getDynamicObjectCollection("yem_entryentity");
                        for (int i = 0; i < yem_entryentity.size(); i++) {
                            DynamicObject dynamicObject = yem_entryentity.get(i);
                            boolean yem_iscomp = dynamicObject.getBoolean("yem_isassatlasdet");
                            if (yem_iscomp) {
                                list.add(dynamicObject.getString("yem_asscomponent.number"));
                            }
                        }
                    }
                }
            }
            if (list.size() > 0) {
                ListShowParameter formShowParameter = (ListShowParameter) e.getFormShowParameter();
                QFilter qFilter = new QFilter("number", QFilter.in, list);
                formShowParameter.getListFilterParameter().setFilter(qFilter);
            } else {
                e.setCancel(true);
                this.getView().showErrorNotification("当前父项总成下未查询到部件！！！");
            }
        }
    }
}
