package com.yem.wm.es.storagetrans.form;

import com.yem.wm.es.Util.TotalUtil;
import com.yem.wm.es.Util.ZJUtils;
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.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.AfterDeleteRowEventArgs;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
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.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.sdk.plugin.Plugin;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;

/**
 * @author xwudd
 * @date 11:22
 * @Description
 **/
public class StorageTransZJEdit extends AbstractBillPlugIn implements BeforeF7SelectListener, Plugin {

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        BasedataEdit declarationEle = this.getControl("yem_declarationele");
        if (declarationEle != null) {
            declarationEle.addBeforeF7SelectListener(this);
        }
        BasedataEdit hsCode = this.getControl("yem_hscode");
        if (hsCode != null) {
            hsCode.addBeforeF7SelectListener(this);
        }
        BasedataEdit customClass = this.getControl("yem_customclass");
        if (customClass != null) {
            customClass.addBeforeF7SelectListener(this);
        }
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        IDataModel model = this.getModel();
        FormShowParameter fsp = this.getView().getFormShowParameter();
        OperationStatus status = fsp.getStatus();
        if (OperationStatus.ADDNEW == status) {
            ZJUtils.totalContractNo(model);
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        ChangeData changeData = e.getChangeSet()[0];
        String name = e.getProperty().getName();
        int rowIndex = changeData.getRowIndex();
        switch (name) {
//            case "yem_ticketprice":
//            case "yem_bigcabinetprice":
//            case "yem_mincabinetprice":
//            case "yem_bigcabinetnumber":
//            case "yem_mincabinetnumber":
//            case "yem_singlenumber":
//                ZJUtils.countCostSumAmountZJ(model);
//                break;
            case "yem_piece"://件数
                ZJUtils.countSumQtyTypeField(model, "yem_sumpiece", "yem_es_materialinfo", "yem_piece");//汇总件数
                break;
            case "yem_grossweightsum":
                ZJUtils.countSumQtyTypeField(model, "yem_boxgwsum", "yem_es_materialinfo", "yem_grossweightsum");//汇总总毛重
                break;
            case "yem_netweightsum":
                ZJUtils.countSumQtyTypeField(model, "yem_boxnwsum", "yem_es_materialinfo", "yem_netweightsum");//汇总总净重
                break;
            case "yem_volm3sum":
                ZJUtils.countSumQtyTypeField(model, "yem_boxvolsum", "yem_es_materialinfo", "yem_volm3sum");//汇总体积
                break;
            case "yem_saamtpriceclause":
                countRapRateOrAmt(rowIndex);
                countStorageTransAmt(rowIndex);
                break;
            case "yem_lenghtunit"://长度单位
            case "yem_vol"://体积
                TotalUtil.countVolM3(model, rowIndex, "yem_lenghtunit", "yem_vol", "yem_volm3");
                ;
                break;
            case "yem_clientcountry"://贸易国别
                setCreditRate();
                break;
            case "yem_contractnumbers_m"://合同号
                ZJUtils.totalContractNo(model);
                break;
        }
    }


    @Override
    public void afterDeleteRow(AfterDeleteRowEventArgs e) {
        super.afterDeleteRow(e);
        IDataModel model = this.getModel();
        String name = e.getEntryProp().getName();
        switch (name) {
            case "yem_es_materialinfo"://商品分录
                ZJUtils.totalContractNo(model);
                break;
        }
    }

    /**
     * @description 计算收汇比例或金额
     * @author xwudd
     * @param[1] rowIndex
     * return
     * @time 2023/8/18 15:41
     */

    public void countRapRateOrAmt(int rowIndex) {
        IDataModel model = this.getModel();
        BigDecimal total = BigDecimal.ZERO;
        int materialInfoRows = model.getEntryRowCount("yem_es_materialinfo");
        String contractNumbers = (String) model.getValue("yem_contractnumbers_m", rowIndex);
        for (int i = 0; i < materialInfoRows; i++) {
            String contractNumbersFor = (String) model.getValue("yem_contractnumbers_m", i);
            if (contractNumbers.equals(contractNumbersFor)) {
                total.add((BigDecimal) model.getValue("yem_saamtpriceclause", i));
            }
        }

        int salesContrac_Rows = model.getEntryRowCount("yem_es_salescontrac_s");
        for (int i = 0; i < salesContrac_Rows; i++) {
            DynamicObject payment = (DynamicObject) model.getValue("yem_payment", i);
            if (YEM.isNotEmpty(payment)) {
                String basis = payment.getString("basis");
                if ("A".equals(basis)) {
                    BigDecimal rapRate = (BigDecimal) model.getValue("yem_raprate", i);
                    model.setValue("yem_rapamt", total.multiply(rapRate.divide(new BigDecimal(100)).setScale(4)), i);
                }
                if ("B".equals(basis)) {
                    BigDecimal rapAmt = (BigDecimal) model.getValue("yem_rapamt", i);
                    if (total.compareTo(BigDecimal.ZERO) > 0) {
                        model.setValue("yem_raprate", rapAmt.divide(total, RoundingMode.HALF_UP).setScale(4).multiply(new BigDecimal(100)), i);
                    } else {
                        model.setValue("yem_raprate", BigDecimal.ZERO, i);
                    }

                }
            }
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        IFormView view = this.getView();
        String operateKey = e.getOperateKey();
        OperationResult operationResult = e.getOperationResult();
        switch (operateKey) {
            case "creditbackfill":
                DynamicObject dataEntity = this.getModel().getDataEntity();
                DynamicObject customer = dataEntity.getDynamicObject("yem_customer");
                DynamicObject method = TotalUtil.getSettlementMethod(dataEntity);
                DynamicObject company = dataEntity.getDynamicObject("yem_company.yem_erporg");
                String swiftCode = TotalUtil.getSwiftCode(dataEntity);
                DynamicObject csrCreditLine = TotalUtil.getCsrCreditLine(customer, method, company, swiftCode);
                if (csrCreditLine != null) {
                    boolean yem_changing = csrCreditLine.getBoolean("yem_changing");
                    boolean yem_effective = csrCreditLine.getBoolean("yem_effective");
                    String billno = csrCreditLine.getString("billno");
                    if (!yem_changing) {
                        creditBackFill();
                    } else {
                        view.showErrorNotification("获取到客户信保额度申请【" + billno + "】正在变更中，请稍后重试！");
                    }
                } else {
                    view.showErrorNotification("未找到客户信保额度申请");
                }

                break;
        }
    }

    public void creditBackFill() {
        IFormView view = this.getView();
        FormShowParameter fsp = new FormShowParameter();
        fsp.setFormId("yem_creditbackfill");
        fsp.getOpenStyle().setShowType(ShowType.Modal);
        view.showForm(fsp);
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        String name = e.getProperty().getName();
        int row = e.getRow();
        switch (name) {
            case "yem_declarationele":
                selectF7DeclarationEle(e);
                break;
            case "yem_hscode":
                selectF7HsCode(e);
                break;
            case "yem_customclass":
                selectF7CustomClass(e);
                break;
        }
    }

    public void selectF7DeclarationEle(BeforeF7SelectEvent e) {
        //商品明细：手动维护申报要素字段，根据物料编码+报关分类到基础资料-【申报要素】库中过滤对应的申报要素，按照【申报要素】中的字段：年份，做降序排序展示。
        int row = e.getRow();
        IDataModel model = this.getModel();
        DynamicObject yem_hscode = (DynamicObject) model.getValue("yem_hscode", row);
        if (YEM.isNotEmpty(yem_hscode)) {
            e.addCustomQFilter(new QFilter("yem_hscodebase", QCP.equals, yem_hscode.getPkValue()));
        }
        DynamicObject yem_customclass = (DynamicObject) model.getValue("yem_customclass", row);
        if (YEM.isNotEmpty(yem_customclass)) {
            e.addCustomQFilter(new QFilter("yem_customclass", QCP.equals, yem_customclass.getPkValue()));
        }
    }

    public void selectF7HsCode(BeforeF7SelectEvent e) {
        int row = e.getRow();
        List<Long> ids = new ArrayList();
        IDataModel model = this.getModel();
        DynamicObject yem_customclass = (DynamicObject) model.getValue("yem_customclass", row);
        if (YEM.isNotEmpty(yem_customclass)) {
            DynamicObject[] declarationEles = BusinessDataServiceHelper.load("yem_bd_declarationele", "id,yem_hscodebase",
                    new QFilter[]{new QFilter("yem_customclass", QCP.equals, yem_customclass.getPkValue())});
            for (DynamicObject declarationEle : declarationEles) {
                DynamicObject hsCodebase = declarationEle.getDynamicObject("yem_hscodebase");
                if (YEM.isNotEmpty(hsCodebase)) {
                    ids.add(hsCodebase.getLong("id"));
                }
            }
        }
        e.addCustomQFilter(new QFilter("id", QCP.in, ids));
    }

    public void selectF7CustomClass(BeforeF7SelectEvent e) {
        //1、过滤报关分类时，整机行只能过滤业务分类为整机的报关分类；配件行只能过滤业务分类为配件的报关分类
        int row = e.getRow();
        List<Long> ids = new ArrayList();
        IDataModel model = this.getModel();
        DynamicObject materiel = (DynamicObject) model.getValue("yem_materiel", row);
        if (YEM.isNotEmpty(materiel)) {
            DynamicObject[] declarationEles = BusinessDataServiceHelper.load("yem_bd_declarationele", "id,yem_customclass",
                    new QFilter[]{new QFilter("yem_material", QCP.equals, materiel.getPkValue())});
            for (DynamicObject declarationEle : declarationEles) {
                DynamicObject hsCodebase = declarationEle.getDynamicObject("yem_customclass");
                if (YEM.isNotEmpty(hsCodebase)) {
                    ids.add(hsCodebase.getLong("id"));
                }
            }
        }
        e.addCustomQFilter(new QFilter("id", QCP.in, ids));

        String businesssort = (String) this.getModel().getValue("yem_businesssort", row);
        if (businesssort == null) {
            e.addCustomQFilter(new QFilter("yem_businessclassify", QCP.equals, null));
        }
        if ("Z".equals(businesssort)) {
            e.addCustomQFilter(new QFilter("yem_businessclassify", QCP.equals, "Z"));
        }
        if ("P".equals(businesssort)) {
            e.addCustomQFilter(new QFilter("yem_businessclassify", QCP.equals, "P"));
        }

    }

    /**
     * @description 销售金额（价格条款）改变 同步改变信保明细中相同外销合同号的储运合同金额
     * @author xwudd
     * @param[1] rowIndex
     * return
     * @time 2023/8/31 14:48
     */

    public void countStorageTransAmt(int rowIndex) {
        IDataModel model = this.getModel();
        BigDecimal totalAmt = BigDecimal.ZERO;
        int materialInfoRowCount = model.getEntryRowCount("yem_es_materialinfo");
        String contractNumberRowIndex = (String) model.getValue("yem_contractnumbers_m", rowIndex);
        for (int i = 0; i < materialInfoRowCount; i++) {
            String contractNumbersI = (String) model.getValue("yem_contractnumbers_m", i);
            if (contractNumberRowIndex.equals(contractNumbersI)) {
                totalAmt = totalAmt.add((BigDecimal) model.getValue("yem_saamtpriceclause", i));
            }
        }
        int creditDetailRowCount = model.getEntryRowCount("yem_creditdetail");
        for (int i = 0; i < creditDetailRowCount; i++) {
            String saleContractNoText = (String) model.getValue("yem_salecontractnotext", i);
            if (contractNumberRowIndex.equals(saleContractNoText)) {
                model.setValue("yem_storagetransamt", totalAmt, i);
                break;
            }
        }
    }


    public void setCreditRate() {
        IDataModel model = this.getModel();
        DynamicObject clientCountry = (DynamicObject) model.getValue("yem_clientcountry");
        DynamicObject countrySignals = TotalUtil.getCountrySignals(clientCountry);
        int creditDetailRowCount = model.getEntryRowCount("yem_creditdetail");
        for (int i = 0; i < creditDetailRowCount; i++) {
            DynamicObject quotation = (DynamicObject) model.getValue("yem_quotation_cd", i);
            DynamicObject term = (DynamicObject) model.getValue("yem_term_cd", i);
            BigDecimal signals = TotalUtil.getSignals(countrySignals, quotation, term);
            model.setValue("yem_sinosurerate_cd", signals, i);
        }
    }


}
