package com.yem.wm.im.priceLibrary.form;

import com.yem.wm.utils.DynamicObjectUtil;
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.entity.LocaleString;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.RowDataEntity;
import kd.bos.entity.datamodel.events.AfterAddRowEventArgs;
import kd.bos.entity.datamodel.events.BeforeDeleteRowEventArgs;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.property.EntryProp;
import kd.bos.entity.report.CellStyle;
import kd.bos.form.*;
import kd.bos.form.control.Control;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.FieldEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.mvc.bill.BillView;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.sdk.plugin.Plugin;

import javax.json.JsonObject;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Description 价格库表单插件
 */
public class PriceLibraryFormPlugIn extends AbstractBillPlugIn implements BeforeF7SelectListener {


    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        String name = model.getDataEntity().getDataEntityType().getName();
        if ("yem_pricelibrary".equals(name)) {
            setBillType();
            batchSetColor("yem_optional", "yem_salesmarkup_o");
            batchSetColor("yem_replaceable", "yem_salesmarkup_re");
            batchSetColor("yem_retrofitting", "yem_salesmarkup_rt");
        }

    }

    /**
     * @Description 根据布局给
     */
    public void setBillType() {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        FormShowParameter fsp = view.getFormShowParameter();
        OperationStatus status = fsp.getStatus();
        if (status.equals(OperationStatus.ADDNEW)) {
            String name = model.getDataEntity().getDataEntityType().getName();
            String key = ((BillView) this.getView()).getRootControl().getKey();
//        String formId = view.getFormShowParameter().getFormId();
            QFilter qFilter = null;
            if (key.equals("yem_pricelibrary_zj")) {
                qFilter = new QFilter("number", QCP.equals, "yem_pricelibrary_ZJ");
            } else if (key.equals("yem_pricelibrary_pj")) {
                qFilter = new QFilter("number", QCP.equals, "yem_pricelibrary_PJ");
            } else {
                qFilter = new QFilter("number", QCP.equals, "yem_pricelibrary_ZJ");
            }
            if (qFilter != null) {
                DynamicObject billType = BusinessDataServiceHelper.loadSingle("bos_billtype", "id", qFilter.toArray());
                model.setValue("yem_billtype", billType);
            }
        }
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        BasedataEdit products = this.getControl("yem_bd_products");
        if (products != null) {
            products.addBeforeF7SelectListener(this);
        }
        BasedataEdit model = this.getControl("yem_model");
        model.addBeforeF7SelectListener(this);
    }


    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        String name = e.getProperty().getName();
        switch (name) {
            case "yem_bd_products":
                productF7Select(e);
                break;
            case "yem_model":
                modelF7Select(e);
                break;
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        String operateKey = e.getOperateKey();
        switch (operateKey) {
            case "optionalbutton":
                isProductType("yem_optional", "A");
                break;
            case "replaceablebutton":
                isProductType("yem_replace", "B");
                break;
            case "retrofittingbutton":
                isProductType("yem_retrofitting", "C");
                break;
            case "yem_b_optionaldisable":
                disableOperation(true, "yem_optional");
                break;
            case "yem_b_optionalenable":
                disableOperation(false, "yem_optional");
                break;
            case "yem_b_replacedisable":
                disableOperation(true, "yem_replaceable");
                break;
            case "yem_b_replaceenable":
                disableOperation(false, "yem_replaceable");
                break;
            case "yem_b_retrofittingdisable":
                disableOperation(true, "yem_retrofitting");
                break;
            case "yem_b_retrofittingenable":
                disableOperation(false, "yem_retrofitting");
                break;
        }
    }

    private void disableOperation(boolean isDisable, String optional) {
        IDataModel model = this.getModel();
        EntryGrid entryGrid = this.getControl(optional);
        int[] selectRows = entryGrid.getSelectRows();
        for (int selectRow : selectRows) {
            if (isDisable) {
                if ("yem_optional".equals(optional)) {
                    model.setValue("yem_disabledstate", "B", selectRow);
                    model.setValue("yem_prohibitedperson", BusinessDataServiceHelper.loadSingle(YEM.getCurrentUserId(), "bos_user"), selectRow);
                    model.setValue("yem_disabletime", new Date(), selectRow);
                }
                if ("yem_replaceable".equals(optional)) {
                    model.setValue("yem_disabledstate1", "B", selectRow);
                    model.setValue("yem_prohibitedperson1", BusinessDataServiceHelper.loadSingle(YEM.getCurrentUserId(), "bos_user"), selectRow);
                    model.setValue("yem_disabletime1", new Date(), selectRow);
                }
                if ("yem_retrofitting".equals(optional)) {
                    model.setValue("yem_disabledstate2", "B", selectRow);
                    model.setValue("yem_prohibitedperson2", BusinessDataServiceHelper.loadSingle(YEM.getCurrentUserId(), "bos_user"), selectRow);
                    model.setValue("yem_disabletime2", new Date(), selectRow);
                }
            } else {
                if ("yem_optional".equals(optional)) {
                    model.setValue("yem_disabledstate", "A", selectRow);
                    model.setValue("yem_prohibitedperson", null, selectRow);
                    model.setValue("yem_disabletime", null, selectRow);
                }
                if ("yem_replaceable".equals(optional)) {
                    model.setValue("yem_disabledstate1", "A", selectRow);
                    model.setValue("yem_prohibitedperson1", null, selectRow);
                    model.setValue("yem_disabletime1", null, selectRow);
                }
                if ("yem_retrofitting".equals(optional)) {
                    model.setValue("yem_disabledstate2", "A", selectRow);
                    model.setValue("yem_prohibitedperson2", null, selectRow);
                    model.setValue("yem_disabletime2", null, selectRow);
                }
            }
        }
    }

    @Override
    public void beforePropertyChanged(PropertyChangedArgs e) {
        IFormView view = this.getView();
        String name = e.getProperty().getName();
        ChangeData changeData = e.getChangeSet()[0];
        IPageCache pageCache = this.getPageCache();
        switch (name) {
            case "yem_bd_products":
                DynamicObject oldValue = (DynamicObject) changeData.getOldValue();
                pageCache.put("productsOldValue", oldValue != null ? oldValue.getPkValue() + "" : "");
                view.showConfirm("产品机型切换，将清除单据信息，是否确认切换？", MessageBoxOptions.YesNo,
                        new ConfirmCallBackListener(name, this));
                break;
        }
    }

    @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_bd_products".equals(callBackId)) {
                model.deleteEntryData("yem_basicmodel");
                model.deleteEntryData("yem_accessory");
                model.deleteEntryData("yem_optional");
                model.deleteEntryData("yem_replaceable");
                model.deleteEntryData("yem_retrofitting");
            }
        }
        if (result == MessageBoxResult.No) {
            if ("yem_bd_products".equals(callBackId)) {
                model.beginInit();
                String productsOldValue = pageCache.get("productsOldValue");
                if (YEM.isEmpty(productsOldValue)) {
                    model.setValue("yem_bd_products", null);
                } else {
                    model.setValue("yem_bd_products", Long.parseLong(productsOldValue));
                }
                model.endInit();
                view.updateView("yem_bd_products");
            }
        }
    }

    /**
     * @param e
     * @Description 产品类型过滤
     */
    private void productF7Select(BeforeF7SelectEvent e) {
        IDataModel model = this.getModel();
        DynamicObject billType = (DynamicObject) model.getValue("yem_billtype");
        if (billType != null) {
            String number = billType.getString("number");
            if ("yem_pricelibrary_acc".equals(number)) {
                e.addCustomQFilter(new QFilter("yem_classification", QCP.equals, "B"));
            }
            if ("yem_pricelibrary_basic".equals(number)) {
                e.addCustomQFilter(new QFilter("yem_classification", QCP.equals, "A"));
            }
        }
    }

    /**
     * @param e
     * @Description 产品型号过滤
     */
    private void modelF7Select(BeforeF7SelectEvent e) {
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        DynamicObject products = (DynamicObject) model.getValue("yem_bd_products");
        if (products != null) {
            e.addCustomQFilter(new QFilter("yem_products", QCP.equals, products.getPkValue()));
        } else {
            view.showErrorNotification("请先选择产品机型！");
            e.setCancel(true);
        }
    }


    /**
     * @param fromId
     * @param type
     * @Description 选装、替换、加装 按钮操作
     */
    private void isProductType(String fromId, String type) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        int currentRowIndex = model.getEntryCurrentRowIndex("yem_basicmodel");
        DynamicObject modelObj = (DynamicObject) model.getValue("yem_model", currentRowIndex);
        DynamicObject yem_bd_products = (DynamicObject) model.getValue("yem_bd_products");
        if (yem_bd_products == null) {
            view.showErrorNotification("请先选择【产品机型】！");
        } else {
            List<Long> ids = new ArrayList<>();
            if ("A".equals(type)) {
                int optionalRows = model.getEntryRowCount("yem_optional");
                for (int i = 0; i < optionalRows; i++) {
                    Long entryId_o = (Long) model.getValue("yem_entryid_o", i);
                    ids.add(entryId_o);
                }
            }
            if ("B".equals(type)) {
                int optionalRows = model.getEntryRowCount("yem_replaceable");
                for (int i = 0; i < optionalRows; i++) {
                    Long entryId_re = (Long) model.getValue("yem_entryid_re", i);
                    ids.add(entryId_re);
                }
            }
            if ("C".equals(type)) {
                int optionalRows = model.getEntryRowCount("yem_retrofitting");
                for (int i = 0; i < optionalRows; i++) {
                    Long entryId_rt = (Long) model.getValue("yem_entryid_rt", i);
                    ids.add(entryId_rt);
                }
            }
            Map<String, Object> map = new HashMap<>();
//            map.put("modelObj", modelObj);
            map.put("modelObj", yem_bd_products);
            map.put("ids", ids);
            map.put("type", "A");
            FormShowParameter formShowParameter = new FormShowParameter();
            formShowParameter.setFormId(fromId);
            formShowParameter.getOpenStyle().setShowType(ShowType.Modal);
            formShowParameter.setCustomParams(map);
            view.showForm(formShowParameter);
        }
    }


    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        ChangeData changeData = e.getChangeSet()[0];
        int rowIndex = changeData.getRowIndex();
        String name = e.getProperty().getName();
        switch (name) {
            case "yem_salesmarkup_o":
                setColor(rowIndex, "yem_optional", "yem_salesmarkup_o");
                break;
            case "yem_salesmarkup_re":
                setColor(rowIndex, "yem_replaceable", "yem_salesmarkup_re");
                break;
            case "yem_salesmarkup_rt":
                setColor(rowIndex, "yem_retrofitting", "yem_salesmarkup_rt");
                break;

        }
    }


    @Override
    public void afterAddRow(AfterAddRowEventArgs e) {
        super.afterAddRow(e);
        EntryProp entryProp = e.getEntryProp();
        String name = entryProp.getName();
        RowDataEntity[] rowDataEntities = e.getRowDataEntities();
        for (RowDataEntity rowDataEntitie : rowDataEntities) {
            int rowIndex = rowDataEntitie.getRowIndex();
            switch (name) {
                case "yem_salesmarkup_o":
                    setColor(rowIndex, "yem_optional", "yem_salesmarkup_o");
                    break;
                case "yem_salesmarkup_re":
                    setColor(rowIndex, "yem_replaceable", "yem_salesmarkup_re");
                    break;
                case "yem_salesmarkup_rt":
                    setColor(rowIndex, "yem_retrofitting", "yem_salesmarkup_rt");
                    break;
            }
        }
    }

    /**
     * @description 根据销售加价批量设置单据体行颜色
     * @author xwudd
     * @param[1] entryKey
     * @param[2] amtKey
     * return
     * @time 2023/10/30 14:39
     */

    public void batchSetColor(String entryKey, String amtKey) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        int entryRowCount = model.getEntryRowCount(entryKey);
        for (int i = 0; i < entryRowCount; i++) {
            setColor(i, entryKey, amtKey);
        }
    }


    /**
     * @description 根据销售加价设置单据体行颜色
     * @author xwudd
     * @param[1] row 行数
     * @param[2] entryKey 单据体标识
     * @param[3] amtKey 销售加价字段标识
     * return
     * @time 2023/10/30 14:40
     */

    public void setColor(int row, String entryKey, String amtKey) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        EntryGrid optional = view.getControl(entryKey);
        List<CellStyle> cellStyles = new ArrayList<>();
        BigDecimal value = (BigDecimal) model.getValue(amtKey, row);
        List<Control> optionalControls = optional.getControls();
        for (Control optionalControl : optionalControls) {
            CellStyle cellStyle = new CellStyle();
            // 设置字段
            cellStyle.setFieldKey(optionalControl.getKey());
            // 行号
            cellStyle.setRow(row);
            // 字体颜色
            if (value.compareTo(BigDecimal.ZERO) > 0) {
                cellStyle.setBackColor("#ffffff");
            } else {
                cellStyle.setBackColor("#f90d58");
            }
            cellStyles.add(cellStyle);
        }
        optional.setCellStyle(cellStyles);
    }

    @Override
    public void beforeDeleteRow(BeforeDeleteRowEventArgs e) {
        super.beforeDeleteRow(e);
        EntryProp entryProp = e.getEntryProp();
        String keyFieldId = entryProp.getName();
        Boolean bool = false;
        int[] rowIndexs = e.getRowIndexs();
        if ("yem_optional".equals(keyFieldId)) {
            for (int dynamicObject : rowIndexs) {
                if (extracted(dynamicObject, "yem_optional.id", "yem_es_salesorder", "yem_es_materialinfo", "yem_es_materialinfo.yem_multiconfig.yem_configentryid", e)) {
                    bool = true;
                }
                if (!bool&&extracted(dynamicObject, "yem_optional.id", "yem_im_clientdemand", "yem_im_detailedinfor", "yem_im_detailedinfor.yem_multiconfig.yem_configentryid", e)) {
                    bool = true;
                }
            }
            if (bool) {
                this.getView().showTipNotification("当前行已被引用，禁止删除！！！");
                e.setCancel(true);
            }
        }
        if ("yem_replaceable".equals(keyFieldId)) {
            for (int dynamicObject : rowIndexs) {
                if (extracted(dynamicObject, "yem_replaceable.id", "yem_es_salesorder", "yem_es_materialinfo", "yem_es_materialinfo.yem_multiconfig.yem_configentryid", e)) {
                    bool = true;
                }
                if (!bool&&extracted(dynamicObject, "yem_replaceable.id", "yem_im_clientdemand", "yem_im_detailedinfor", "yem_im_detailedinfor.yem_multiconfig.yem_configentryid", e)) {
                    bool = true;
                }
            }
            if (bool) {
                this.getView().showTipNotification("当前行已被引用，禁止删除！！！");
                e.setCancel(true);
            }
        }
        if ("yem_retrofitting".equals(keyFieldId)) {
            for (int dynamicObject : rowIndexs) {
                if (extracted(dynamicObject, "yem_retrofitting.id", "yem_es_salesorder", "yem_es_materialinfo", "yem_es_materialinfo.yem_multiconfig.yem_configentryid", e)) {
                    bool = true;
                }
                if (!bool&&extracted(dynamicObject, "yem_retrofitting.id", "yem_im_clientdemand", "yem_im_detailedinfor", "yem_im_detailedinfor.yem_multiconfig.yem_configentryid", e)) {
                    bool = true;
                }
            }
            if (bool) {
                this.getView().showTipNotification("当前行已被引用，禁止删除！！！");
                e.setCancel(true);
            }
        }
    }

    private Boolean extracted(int rowIndexs, String s, String string, String multiconfig, String property, BeforeDeleteRowEventArgs e) {
        String selectfield = DynamicObjectUtil.getSelectfields(string, false);
        String selectfields = DynamicObjectUtil.getEntrySelectfields(selectfield, string, multiconfig + ".yem_multiconfig", false);
        long aLong = (long) this.getModel().getValue(s, rowIndexs);
        DynamicObject[] load = BusinessDataServiceHelper.load(string, selectfields, new QFilter[]{new QFilter(property, QCP.equals, aLong)});
        if (load.length > 0) {
            return true;
        }
        return false;
    }
}