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

import com.alibaba.csp.sentinel.util.StringUtil;
import com.yem.tws.common1.BigDecimalUtils;
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.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.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;

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

/**
 * @author xwudd
 * @date 18:54
 * @Description 出口发票表单插件
 **/
public class ExportInVoiceEdit extends AbstractBillPlugIn {

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        String name = e.getProperty().getName();
        switch (name) {
            case "yem_seatransfee":
            case "yem_insurefee":
            case "yem_otherfee":
            case "yem_cusamount":
//                countShareAmt();
                break;
            case "yem_seabase":
            case "yem_commission":
            case "yem_insurefeecurrba":
                counttailAmt();
                break;
        }
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        OperationStatus status = this.getView().getFormShowParameter().getStatus();
        //给单车字段赋值
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        DynamicObjectCollection dynamicObjectCollection1 = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        int row = 0;
        for (DynamicObject temp : dynamicObjectCollection1) {
//            Long corebillid = temp.getLong("yem_corebillid_d");
            Long coreentryid = temp.getLong("yem_coreentryid");
            if (StringUtil.isNotEmpty(temp.getString("yem_contractnumbers_m"))) {
                DynamicObject salesorder = BusinessDataServiceHelper.loadSingle("yem_es_salesorder",
                        new QFilter[]{new QFilter("billno", QCP.equals, temp.getString("yem_contractnumbers_m"))});
                if (salesorder != null) {
                    if (salesorder.getDynamicObject("yem_cncurrency") != null) {
                        this.getModel().setValue("yem_cncurrency", salesorder.getLong("yem_cncurrency.id"));
                    }
                    DynamicObjectCollection materialinfos = salesorder.getDynamicObjectCollection("yem_es_materialinfo");
                    for (DynamicObject materialinfo : materialinfos) {
                        Long maid = materialinfo.getLong("id");
                        if (coreentryid.equals(maid)) {
                            BigDecimal onecarcom = materialinfo.getBigDecimal("yem_onecarcom");
                            // 佣金方式
                            String commissionmethod = salesorder.getString("yem_commissionmethod");
                            // 明佣 A | 暗佣 B
                            if ("A".equals(commissionmethod)) {
                                // 如果关联的外销合同-付佣方式为暗佣，则不需要取值
//                                salesorder.set("yem_onecarcom", onecarcom);
                                this.getModel().setValue("yem_onecarcom", onecarcom, row);
                            } else {
//                                salesorder.set("yem_onecarcom", BigDecimal.ZERO);
                                this.getModel().setValue("yem_onecarcom", BigDecimal.ZERO, row);
                            }
                        }
                    }
                }
            }
            row++;
        }
        counttailAmt();
        calculateApportionedAmountBase();
    }

    /**
     * 计算分摊金额本位币
     */
    private void calculateApportionedAmountBase() {
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_exportinvoice_c");
        BigDecimal seatransfeebase = dataEntity.getBigDecimal("yem_seatransfeebase"); // 海运费（本位币）
        BigDecimal insurefeebase = dataEntity.getBigDecimal("yem_insurefeebase"); //保费（本位币）
        BigDecimal commissionba = dataEntity.getBigDecimal("yem_commissionba"); // 佣金（本位币）
        BigDecimal localamountsum = dataEntity.getBigDecimal("yem_localamountsum"); // 金额本位币合计
        for (DynamicObject dynamicObject : collection) {
            // yem_localassessedamo = ( yem_seatransfeebase + yem_insurefeebase + yem_commissionba ) * yem_localamount / yem_localamountsum
            // 分摊金额（本位币） = ( 海运费（本位币） + 保费（本位币） + 佣金（本位币） ) * 金额（本位币） / 金额本位币合计
            BigDecimal localamount = dynamicObject.getBigDecimal("yem_localamount"); // 金额（本位币）\
            BigDecimal localassessedamo = BigDecimalUtils.div((seatransfeebase.add(insurefeebase).add(commissionba)).multiply(localamount), localamountsum, 2);
//            dynamicObject.set("yem_localassessedamo", localassessedamo);

            // yem_localinvoicedamo = yem_localamount - yem_localassessedamo
            // 开票金额（本位币） = 金额（本位币） - 分摊金额（本位币）
//            BigDecimal localinvoicedamo = localamount.subtract(localassessedamo);
//            dynamicObject.set("yem_localinvoicedamo", localinvoicedamo);
//            // yem_localinvoicingunit = yem_localinvoicedamo / yem_cusqty
//            // 开票单价（本位币） = 开票金额（本位币） / 数量
//            BigDecimal cusqty = dynamicObject.getBigDecimal("yem_cusqty");
//            dynamicObject.set("yem_localinvoicingunit", BigDecimalUtils.div(localinvoicedamo, cusqty, 2));
        }
        view.updateView("yem_exportinvoice_c");
    }

    /**
     * @description 计算分摊金额  尾差
     * @author power
     * return
     * @time 2023/9/4 9:26
     */
    public void counttailAmt() {
        IDataModel model = this.getModel();
        BigDecimal exrate = (BigDecimal) model.getValue("yem_exrate");//汇率
        if (exrate.compareTo(BigDecimal.ZERO) != 0) {
//            BigDecimal count= (BigDecimal) model.getValue("yem_count");//报关单（海运费/金额）
//            EntryGrid materialinfo = this.getControl("yem_es_materialinfo");
//            BigDecimal sellamt = materialinfo.getSum("yem_sellamt");//销售金额汇总值
//            BigDecimal yem_seabase =count.multiply(sellamt);//海运费（原币）
//            BigDecimal seatransfeerate= (BigDecimal) model.getValue("yem_seatransfeerate");//海运费（汇率）
//            yem_seabase = yem_seabase.multiply(seatransfeerate);
//            yem_seabase =yem_seabase.divide(exrate,2, BigDecimal.ROUND_HALF_UP);
            BigDecimal yem_seabae = (BigDecimal) model.getValue("yem_seabase");//海运费（结算币别）
//            BigDecimal yem_commission = materialinfo.getSum("yem_commissionamten");//佣金金额汇总
            BigDecimal yem_commission = (BigDecimal) model.getValue("yem_commission");//佣金（结算币别）

//            BigDecimal yem_iemkuprate= (BigDecimal) model.getValue("yem_iemkuprate");//保险加成率
//            BigDecimal yem_ftprmrate= (BigDecimal) model.getValue("yem_ftprmrate");//运保费率%
//            yem_ftprmrate=yem_ftprmrate.divide(BigDecimal.TEN.multiply(BigDecimal.TEN));
//            BigDecimal yem_insurefeecurrba =sellamt.multiply(yem_iemkuprate).multiply(yem_ftprmrate);//保费（结算币别）
            BigDecimal yem_insurefeecurrba = (BigDecimal) model.getValue("yem_insurefeecurrba");//保费（结算币别）

            BigDecimal sum = yem_seabae.add(yem_insurefeecurrba).add(yem_commission);
            DynamicObjectCollection exportinvoicecs = model.getEntryEntity("yem_exportinvoice_c");
//        BigDecimal cusamountsum= (BigDecimal) model.getValue("yem_cusamountsum");

            EntryGrid entry = this.getControl("yem_exportinvoice_c");
            //合计单据体的分摊金额字段
            BigDecimal discountamt = entry.getSum("yem_shareamtc");
            BigDecimal cusamountsum = entry.getSum("yem_cusamount");
            if (exportinvoicecs.size() != 0) {
                discountamt = discountamt.subtract(exportinvoicecs.get(exportinvoicecs.size() - 1).getBigDecimal("yem_shareamtc"));

            }
            for (int i = 0; i < exportinvoicecs.size(); i++) {
                BigDecimal shareamt = BigDecimal.ZERO;
                DynamicObject exportinvoicec = exportinvoicecs.get(i);
                BigDecimal cusamount = exportinvoicec.getBigDecimal("yem_cusamount");
                BigDecimal cusqty = exportinvoicec.getBigDecimal("yem_cusqty");
                if (i == exportinvoicecs.size() - 1) {
                    discountamt = entry.getSum("yem_shareamtc");
                    BigDecimal yem_shareamtc = exportinvoicec.getBigDecimal("yem_shareamtc");
                    discountamt = discountamt.subtract(yem_shareamtc);
                    shareamt = sum.subtract(discountamt);

//                    this.getModel().setValue("yem_shareamt",shareamt,i);
                    this.getModel().setValue("yem_shareamtc", shareamt, i);
                } else {
                    if (cusamountsum.compareTo(BigDecimal.ZERO) != 0) {
                        shareamt = cusamount.multiply(sum).divide(cusamountsum, 2, BigDecimal.ROUND_HALF_UP);
//                        this.getModel().setValue("yem_shareamt",shareamt,i);
                        this.getModel().setValue("yem_shareamtc", shareamt, i);
                    }
                }
                BigDecimal invoiceamt = cusamount.subtract(shareamt);
                if (invoiceamt.compareTo(BigDecimal.ZERO) != 0) {
                    BigDecimal invoiceprice = invoiceamt.divide(cusqty, 2, BigDecimal.ROUND_HALF_UP);
//                    this.getModel().setValue("yem_invoiceamt",invoiceamt,i);
//                    this.getModel().setValue("yem_invoiceprice",invoiceprice,i);
                    this.getModel().setValue("yem_invoiceamtc", invoiceamt, i);
                    this.getModel().setValue("yem_invoicepricecc", invoiceprice, i);
                }
            }
        }
        getView().updateView("yem_exportinvoice_c");
    }


    /**
     * @description 计算分摊金额
     * @author xwudd
     * return
     * @time 2023/9/4 9:26
     */

    public void countShareAmt() {
        IDataModel model = this.getModel();
        BigDecimal totalAmt = ((BigDecimal) model.getValue("yem_seatransfee")).
                add((BigDecimal) model.getValue("yem_insurefee")).
                add((BigDecimal) model.getValue("yem_otherfee"));
        int exportInvoiceRows = model.getEntryRowCount("yem_exportinvoice_c");
        BigDecimal totalAmtEntry = BigDecimal.ZERO;
        for (int i = 0; i < exportInvoiceRows; i++) {
            BigDecimal cusAmount = (BigDecimal) model.getValue("yem_cusamount", i);
            totalAmtEntry = totalAmtEntry.add(cusAmount);
        }
        for (int i = 0; i < exportInvoiceRows; i++) {
            BigDecimal cusAmount = (BigDecimal) model.getValue("yem_cusamount", i);
            if (totalAmt.compareTo(BigDecimal.ZERO) > 0 && totalAmtEntry.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal multiply = cusAmount.divide(totalAmtEntry, RoundingMode.HALF_UP).multiply(totalAmt);
                model.setValue("yem_shareamt", multiply, i);
            } else {
                model.setValue("yem_shareamt", null, i);
            }
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        String operateKey = e.getOperateKey();
        OperationResult operationResult = e.getOperationResult();
        boolean flag = false;
        if (operationResult != null) {
            flag = operationResult.isSuccess();
        }
        if (flag && "save".equals(operateKey)) {
            this.getView().updateView("yem_seatransfee");
        }
    }
}
