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

import com.yem.wm.utils.FunctionalCommon;
import com.yem.wm.utils.OrgFilterUtils;
import com.yem.wm.utils.YEM;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.IFormView;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.field.BasedataEdit;
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 java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.EventObject;
import java.util.List;

/**
 * @author power
 * @ClassName InquirylistEdit
 * @description: 询价单表单插件
 * @date 2023年07月25日
 * @version: 1.0
 */
public class InquirylistEdit extends AbstractBillPlugIn implements BeforeF7SelectListener {
    public static final String YEM_BD_PRODUCTS = "yem_bd_products";

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        String operateKey = e.getOperateKey();
        OperationResult operationResult = e.getOperationResult();
        switch (operateKey) {
            case "optionaloperation":
                FunctionalCommon.optionalOperation(model, view, "yem_optional", "optionaloperation");
                break;
            case "replaceoperation":
                FunctionalCommon.optionalOperation(model, view, "yem_replace", "replaceoperation");
                break;
            case "retrofittingoperation":
                FunctionalCommon.optionalOperation(model, view, "yem_retrofitting", "retrofittingoperation");
                break;
//           case "submit":
////                if (YEM.isNotEmpty(operationResult)) {
////                    view.invokeOperation("refresh");
////                }
//                break;
//            case "unsubmit":
//                if (YEM.isNotEmpty(operationResult)) {
//                    view.invokeOperation("refresh");
//                }
//                break;
        }
    }

    /**
     * @param isDisable
     * @Description 禁用操作
     */
    private void disableOperation(boolean isDisable) {
        IDataModel model = this.getModel();
        EntryGrid multiconfig = this.getControl("yem_multiconfig");

        int detailedinforSelectRow = model.getEntryCurrentRowIndex("yem_im_detailedinfor");

        int[] multiconfigSelectRows = multiconfig.getSelectRows();

        DynamicObject dataEntity = model.getDataEntity();

        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_im_detailedinfor");
        DynamicObjectCollection subCollection = collection.get(detailedinforSelectRow).getDynamicObjectCollection("yem_multiconfig");
        for (int subRow : multiconfigSelectRows) {
            DynamicObject dynamicObject = subCollection.get(subRow);
            if (isDisable) {
                // 禁用
                dynamicObject.set("yem_disabledstate", "B");
                dynamicObject.set("yem_prohibitedperson", BusinessDataServiceHelper.loadSingle(YEM.getCurrentUserId(), "bos_user"));
                dynamicObject.set("yem_disabletime", new Date());
            } else {
                // 启用
                dynamicObject.set("yem_disabledstate", "A");
                dynamicObject.set("yem_prohibitedperson", null);
                dynamicObject.set("yem_disabletime", null);
            }
            subCollection.set(subRow, dynamicObject);
        }
        this.getView().updateView("yem_multiconfig");
    }

    @Override
    public void afterCreateNewData(EventObject e) {

        setBillType();
    }


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

        BasedataEdit yem_companyorg = this.getControl("yem_companyorg");
        yem_companyorg.addBeforeF7SelectListener(this);
    }

    /**
     * @Description 过滤产品类型配件 整机
     */

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        DynamicObject datas = this.getModel().getDataEntity(true);
        String key = e.getProperty().getName();
        QFilter qFilter = null;
        DynamicObject products = datas.getDynamicObject(YEM_BD_PRODUCTS);
        switch (key) {
            //过滤产品分类
            case "yem_bd_products":
                DynamicObject types = datas.getDynamicObject("yem_billtype");
                if (types == null) {
                    this.getView().showMessage("请选择单据类型");
                    e.setCancel(true);
                } else {
                    qFilter = new QFilter("yem_businesssort", QCP.equals,
                            types.getString("number").equals("yem_im_inquirylist_ZJ") ? "Z" : "P");
                    e.addCustomQFilter(qFilter);
                }
                break;
            case "yem_productmodel":
                selectF7ProductModel(e);//
                break;
            case "yem_companyorg"://财务组织
                DynamicObject value = (DynamicObject) this.getModel().getValue("org");
                e.addCustomQFilter(OrgFilterUtils.getOrgFilter(value));
                break;
            default:
                break;
        }

    }

    /**
     * @description 选择基础机型根据表头产品分类过滤
     * @author xwudd
     * * @param[1] e
     * @time 2023/7/28 18:09
     */

    public void selectF7ProductModel(BeforeF7SelectEvent e) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        DynamicObject products = (DynamicObject) model.getValue("yem_bd_products");
        if (products != null) {
            e.addCustomQFilter(new QFilter("yem_productsgroup", QCP.equals, products.getPkValue()));
        } else {
            view.showErrorNotification("请先维护基本信息-产品分类字段!");
            e.setCancel(true);

        }
    }

    /**
     * @Description 根据布局给
     */
    public void setBillType() {

        IFormView view = this.getView();
        IDataModel model = this.getModel();
        String key = ((BillView) this.getView()).getRootControl().getKey();
        QFilter qFilter = null;
        if (key.equals("yem_im_inquirylist_pj")) {
            qFilter = new QFilter("number", QCP.equals, "yem_im_inquirylist_PJ");
        } else if (key.equals("yem_im_inquirylist_zj")) {
            qFilter = new QFilter("number", QCP.equals, "yem_im_inquirylist_ZJ");
        }
        if (qFilter != null) {
            DynamicObject billType = BusinessDataServiceHelper.loadSingle("bos_billtype", "id", qFilter.toArray());
            model.setValue("yem_billtype", billType);
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        IDataModel model = this.getModel();
        String name = e.getProperty().getName();
        switch (name) {
            case "yem_productmodel":
                model.deleteEntryData("yem_multiconfig");
                break;
            case "yem_material":
                int rowIndex = e.getChangeSet()[0].getRowIndex();
                DynamicObjectCollection entryEntity = model.getEntryEntity("yem_im_detailedinfor");
                DynamicObject dynamicObject = entryEntity.get(rowIndex);
                long materialId = dynamicObject.getLong("yem_material.id");
                if (materialId > 0) {
                    String number = dynamicObject.getString("yem_material.number");
                    if (number != null && !number.isEmpty()) {
                        DynamicObject materialsort = BusinessDataServiceHelper.loadSingle("yem_bd_materialsort",
                                new QFilter[]{new QFilter("yem_material.number", QCP.equals, number)});
                        if (materialsort != null) {
                            model.setValue("yem_classification", materialsort.getLong("yem_markup.id"), rowIndex);
                        }
                    }
                }
                Object newValue = e.getChangeSet()[0].getNewValue();
                if (newValue == null) {
                    model.setValue("yem_classification", null, rowIndex);
                }
                break;
        }
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        DynamicObjectCollection yemImDetailedinfor = (DynamicObjectCollection) this.getModel().getValue("yem_im_detailedinfor");
        if (yemImDetailedinfor.size()>0){
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < yemImDetailedinfor.size(); i++) {
                DynamicObject dynamicObject = yemImDetailedinfor.get(i);
                BigDecimal yemFobprice = dynamicObject.getBigDecimal("yem_fobprice");
                if (yemFobprice.compareTo(BigDecimal.ZERO)!=0){
                    list.add(i);
                }
            }
            for (int i = list.size();  i!=0; i--) {
                Integer integer = list.get(i-1);
                this.getModel().deleteEntryRow("yem_im_detailedinfor",integer);
            }
        }
    }
}
