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

import com.yem.wm.utils.FunctionalCommon;
import com.yem.wm.utils.RequestCmmp;
import com.yem.wm.utils.YEM;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.entity.datamodel.events.*;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.*;
import kd.bos.form.builder.ListRowStyleBuilder;
import kd.bos.form.control.Control;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.list.ListFilterParameter;
import kd.bos.list.ListShowParameter;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;

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

import static com.yem.wm.es.salesorder.utils.SalesOrderUtils.*;

/**
 * @author 张立攀
 * @version 1.0
 * @description 客户需求单
 * @date 2023-07-22 14:56
 */
public class ClientDemandFormPlugin extends AbstractBillPlugIn implements BeforeF7SelectListener {

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

    @Override
    public void click(EventObject e) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        super.click(e);
        Control source = (Control) e.getSource();
        String key = source.getKey();
        if ("yem_colour".equals(key)) {
            ListShowParameter parameter = new ListShowParameter();
            parameter.setMultiSelect(true);
            parameter.setParentPageId(view.getPageId());
            parameter.setStatus(OperationStatus.VIEW);
            parameter.getOpenStyle().setShowType(ShowType.Modal);
            parameter.getOpenStyle().setCacheId(parameter.getPageId());
            parameter.setLookUp(true);
            parameter.setMultiSelect(false);
            StyleCss css = new StyleCss();
            css.setHeight("580");
            css.setWidth("960");
            ListFilterParameter listFilterParameter = new ListFilterParameter();
            int yemImDetailedinfor = model.getEntryCurrentRowIndex("yem_im_detailedinfor");
            DynamicObject yemMateriel = (DynamicObject) model.getValue("yem_materiel", yemImDetailedinfor);
            if (yemMateriel != null) {
                String sql = "select  COLOR_CODE  from   VIEW_SELECT_COLOR_WM   where ITEM_CODE='" + yemMateriel.getString("number") + "'";
                List<String> listNEW = new ArrayList<>();
                DynamicObject value = (DynamicObject) this.getModel().getValue("yem_bd_products");
                if (null != value) {
                    long aLong = value.getLong("id");
                    List<Map> fromCmmp = RequestCmmp.getFromCmmp(0l, sql, aLong);
                    for (Map map : fromCmmp) {
                        for (Object o : map.entrySet()) {
                            Map.Entry<String, Object> o1 = (Map.Entry<String, Object>) o;
                            String value1 = (String) o1.getValue();
                            listNEW.add(value1);
                        }
                    }
                    listFilterParameter.setFilter(new QFilter("number", QCP.in, listNEW));
                }
            }
            parameter.setListFilterParameter(listFilterParameter);
            parameter.getOpenStyle().setInlineStyleCss(css);
            parameter.setBillFormId("yem_em_color");
            parameter.setCloseCallBack(new CloseCallBack(this, "yem_em_color"));
            view.showForm(parameter);
        }
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent e) {
        IDataModel model = this.getModel();
        super.closedCallBack(e);
        String actionId = e.getActionId();
        if ("yem_em_color".equals(actionId)) {
            ListSelectedRowCollection returnData = (ListSelectedRowCollection) e.getReturnData();
            if (returnData != null && !returnData.isEmpty()) {
                ListSelectedRow row = returnData.get(0);
                Long colorId = (Long) row.getPrimaryKeyValue();
                DynamicObject color = BusinessDataServiceHelper.loadSingle(colorId, "yem_em_color");
                int detailedinfor = model.getEntryCurrentRowIndex("yem_im_detailedinfor");
                model.setValue("yem_colour", color.getString("number"), detailedinfor);
                model.setValue("yem_colorname", color.getString("name"), detailedinfor);
                model.setValue("yem_colorenname", color.getString("yem_enname"), detailedinfor);
            }
        }
    }

    @Override
    public void afterAddRow(AfterAddRowEventArgs e) {


    }

    @Override
    public void afterDeleteRow(AfterDeleteRowEventArgs e) {

    }

    @Override
    public void beforeDeleteRow(BeforeDeleteRowEventArgs e) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        int[] rowIndexs = e.getRowIndexs();
        String name = e.getEntryProp().getName();
        if ("yem_im_detailedinfor".equals(name)) {
            FunctionalCommon.deleteMaterialEntry(e, view, model, rowIndexs);
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        IFormView view = this.getView();
        String operateKey = e.getOperateKey();
        OperationResult operationResult = e.getOperationResult();
        switch (operateKey) {
            case "batchcreate":
                if (operationResult.isSuccess()) {
                    this.getModel().batchCreateNewEntryRow("yem_im_detailedinfor", 10);
                }
                break;

        }

    }

    @Override
    public void afterCreateNewData(EventObject e) {

        // 计算折扣率
        calcFrontrate(this.getModel().getDataEntity());
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        DynamicObject datas = this.getModel().getDataEntity(true);
        String key = e.getProperty().getName();
        QFilter qFilter = null;
        switch (key) {
            //过滤产品销售类型
            case "yem_salesmethod":
                DynamicObject types = datas.getDynamicObject("yem_billtype");
                if (types == null) {
                    this.getView().showMessage("请选择单据类型");
                    e.setCancel(true);
                } else {
                    qFilter = new QFilter("yem_businessclassify", QCP.equals,
                            types.getString("number").equals("yem_im_clientdeman_zj") ||
                                    types.getString("number").equals("yem_im_inclientdeman_zj") ? "zj" : "pj");
                    e.addCustomQFilter(qFilter);
                }
                break;
            case "yem_bd_products":
                DynamicObject billtype = datas.getDynamicObject("yem_billtype");
                if (billtype == null) return;
                String billtypeString = billtype.getString("number");
                if ("yem_im_clientdeman_zj".equals(billtypeString) || "yem_im_inclientdeman_zj".equals(billtypeString)) {
                    e.addCustomQFilter(new QFilter("yem_businesssort", QCP.equals, "Z"));
                }
                if ("yem_im_inclientdema_pj".equals(billtypeString) || "yem_im_clientdema_pj".equals(billtypeString)) {
                    e.addCustomQFilter(new QFilter("yem_businesssort", QCP.equals, "P"));
                }
                break;
            case "yem_internationalrate":
                DynamicObject yem_currency = datas.getDynamicObject("yem_currency");
                if (yem_currency != null) {
                    qFilter = new QFilter("yem_currency.number", QCP.equals, yem_currency.getString("number"));
                    qFilter.and(new QFilter("enable", QCP.equals, "1"));
                    e.addCustomQFilter(qFilter);
                }
                break;
            default:
                break;
        }


    }

    @Override
    public void beforePropertyChanged(PropertyChangedArgs e) {
        ChangeData changeData = e.getChangeSet()[0];
        int rowIndex = changeData.getRowIndex();
        String name = e.getProperty().getName();
        switch (name) {
            case "yem_productmodel":
                //基础机型改变 清除fob青岛价  fob单价 多功能配置分录
                Object yem_intauditbusaid = this.getModel().getValue("yem_intauditbusaid", rowIndex);
                if (yem_intauditbusaid instanceof Long && YEM.isNotEmpty(yem_intauditbusaid)) {
                    DynamicObject intauditbusa = BusinessDataServiceHelper.loadSingle(yem_intauditbusaid, "yem_im_intauditbusa");
                    if (intauditbusa != null) {
                        OperationResult unaudit = OperationServiceHelper.executeOperate("unaudit", intauditbusa.getDataEntityType().getName(), new Object[]{intauditbusa.getPkValue()}, OperateOption.create());
                        if (unaudit.isSuccess()) {
                            this.getView().updateView("attachmentpanel");
                        }

                    }
                }
                break;
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        String name = e.getProperty().getName();
        // 资金使用类型字段切换时，清空 配件客商/借记额度
        ChangeData changeData = e.getChangeSet()[0];
        int rowIndex = changeData.getRowIndex();
        if ("yem_fundusetype".equals(name)) {
            this.getModel().setValue("yem_debitamount", null);
        }

        // 配件资金使用类型时：使用配件资金池，使用方式：金额；  财务信息的折扣率计算公式：  （分录非赠品行的销售EXW金额  合计-基本信息-使用额度）/分录非赠品行的销售EXW金额  合计
        // 使用额度                          销售FOB金额
        if ("yem_fundpoolamt".equals(name) || "yem_safobamount".equals(name)) {

            calcFrontrate(this.getModel().getDataEntity());
        }

        switch (name) {
            case "yem_priceitem":
            case "yem_clientcountry":
            case "yem_transportstyle":
                carryPriceItem(this.getModel(), this.getView());
                genTradeTermsDestports(this.getModel(), this.getView());
                genTradeTermsShipports(this.getModel(), this.getView());
                break;
            case "yem_shipports":
                genShipPortEnName(this.getModel());
                genTradeTermsShipports(this.getModel(), this.getView());
                break;
            case "yem_destports":
                genDescPortEnName(this.getModel());
                genTradeTermsDestports(this.getModel(), this.getView());
                break;
            case "yem_urgentornot":
                extracted();
        }
    }

    /**
     * 改变颜色
     */
    private void extracted() {
        DynamicObjectCollection yemImDetailedinfor = this.getModel().getEntryEntity("yem_im_detailedinfor");
        if (!yemImDetailedinfor.isEmpty()) {
            for (int i = 0; i < yemImDetailedinfor.size(); i++) {
                DynamicObject dynamicObject = yemImDetailedinfor.get(i);
                String yemUrgentornot = dynamicObject.getString("yem_urgentornot");
                if ("A".equals(yemUrgentornot)) {
                    IClientViewProxy proxy = this.getView().getService(IClientViewProxy.class);
                    ListRowStyleBuilder rowStyleBuilder = ClientActions.createRowStyleBuilder();
                    //行索引
                    rowStyleBuilder.setRows(new int[]{i});
                    rowStyleBuilder.setBackColor("#FF6A6A");//FFFFFF
                    rowStyleBuilder.buildStyle();
                    rowStyleBuilder.build();
                    rowStyleBuilder.invokeControlMethod(proxy, "yem_im_detailedinfor");
                } else if ("B".equals(yemUrgentornot)) {
                    IClientViewProxy proxy = this.getView().getService(IClientViewProxy.class);
                    ListRowStyleBuilder rowStyleBuilder = ClientActions.createRowStyleBuilder();
                    //行索引
                    rowStyleBuilder.setRows(new int[]{i});
                    rowStyleBuilder.setBackColor("#FFFFFF");//FFFFFF
                    rowStyleBuilder.buildStyle();
                    rowStyleBuilder.build();
                    rowStyleBuilder.invokeControlMethod(proxy, "yem_im_detailedinfor");
                }
            }
        }
    }

    /**
     * 计算折扣率
     *
     * @param dataEntity
     */
    private void calcFrontrate(DynamicObject dataEntity) {
        // 资金使用类型
        String fundusetype = dataEntity.getString("yem_fundusetype");
        // 配件资金使用方式
        String accamtusetype = dataEntity.getString("yem_accamtusetype");
        // 分录中 销售FOB金额 合计
        BigDecimal amount = BigDecimal.ZERO;
        // 使用额度
        BigDecimal fundpoolamt = dataEntity.getBigDecimal("yem_fundpoolamt");
        // 客户配件资金池 && 是金额
        if ("B".equals(fundusetype) && "A".equals(accamtusetype)) {
            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_im_detailedinfor");
            for (DynamicObject object : collection) {
                BigDecimal safobamount = object.getBigDecimal("yem_safobamount");
                boolean ifgift = object.getBoolean("yem_ifgift");
                if (safobamount != null && !ifgift) {
                    amount = amount.add(safobamount);
                }
            }
            // 折扣率
            BigDecimal frontrate = amount.subtract(fundpoolamt).divide(amount, 4, RoundingMode.HALF_UP);
            this.getModel().setValue("yem_frontrate", frontrate);
            this.getView().updateView();
        }
    }

    @Override
    public void afterBindData(EventObject e) {
        extracted();
        OperationStatus status = this.getView().getFormShowParameter().getStatus();
        //复制时 给未储运数量赋值
        if (OperationStatus.ADDNEW == status) {
            DynamicObject dataEntity = this.getModel().getDataEntity(true);
            DynamicObjectCollection dynamicObjectCollection1 = dataEntity.getDynamicObjectCollection("yem_im_detailedinfor");
            int row = 0;
            for (DynamicObject temp : dynamicObjectCollection1) {
                int yemQty = temp.getInt("yem_qty");
                this.getModel().setValue("yem_unasscontractqty", yemQty, row);
                row++;
            }
        }
//        genShipPortEnName(this.getModel(), this.getView());
//        genTradeTermsDestports(this.getModel(), this.getView());
//        genTradeTermsShipports(this.getModel(), this.getView());
    }
}
