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

import com.yem.wm.es.Util.CreditBackFillUtils;
import com.yem.wm.es.Util.TotalUtil;
import com.yem.wm.utils.CalendarUtils;
import com.yem.wm.utils.YEM;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.IFormView;
import kd.bos.form.control.Control;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xwudd
 * @date 18:40
 * @Description
 **/
public class CreditBackFillEdit extends AbstractFormPlugin {

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);

        IFormView view = this.getView();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        IFormView parentView = view.getParentView();
        IDataModel parentModel = parentView.getModel();
        DynamicObject parentDataEntity = parentModel.getDataEntity(true);

        model.setValue("yem_storagetransno", parentModel.getValue("billno"));//储运托单号
        model.setValue("yem_currency", parentModel.getValue("yem_creditcurr"));//信保币别
        model.setValue("yem_currencybase", parentModel.getValue("yem_currencybase"));//本位币
        model.setValue("yem_actulpreamount", parentModel.getValue("yem_actualsinkamount"));//实际收汇金额汇总
        model.setValue("yem_actulpreamountbase", parentModel.getValue("yem_actualsinkamountba"));//实际收汇本位币金额汇总
        model.setValue("yem_clientcountry", parentModel.getValue("yem_clientcountry"));//贸易国别
        model.setValue("yem_creditreportcfm", parentModel.getValue("yem_creditreportcfm"));//是否信保申报确认
        model.setValue("yem_creditbackstatus", parentModel.getValue("yem_creditbackstatus"));//信保回填确认状态

        DynamicObjectCollection parentCreditDetail = parentDataEntity.getDynamicObjectCollection("yem_creditdetail");

        for (DynamicObject dynamicObject : parentCreditDetail) {
            int currentEntryIdx = parentCreditDetail.indexOf(dynamicObject);
            int addNewRowIdx = model.createNewEntryRow("yem_creditentry");
            DynamicObject saleContract = (DynamicObject) dynamicObject.get("yem_salecontractno");
            model.setValue("yem_salecontractno", saleContract.getString("billno"), addNewRowIdx);
            model.setValue("yem_usacreditamt_cd", dynamicObject.get("yem_usacreditamt_cd"), addNewRowIdx);
            model.setValue("yem_creditdate1_cd", dynamicObject.get("yem_creditdate1_cd"), addNewRowIdx);//信保天数1
            model.setValue("yem_paymentamt1_cd", dynamicObject.get("yem_paymentamt1_cd"), addNewRowIdx);//收款金额1
            model.setValue("yem_paymentamt1_cdbase", dynamicObject.get("yem_paymentamt1_cdbase"), addNewRowIdx);//收款金额1（本位币）
            model.setValue("yem_creditdate2_cd", dynamicObject.get("yem_creditdate2_cd"), addNewRowIdx);//信保天数2
            model.setValue("yem_paymentamt2_cd", dynamicObject.get("yem_paymentamt2_cd"), addNewRowIdx);//收款金额2
            model.setValue("yem_paymentamt2_cdbase", dynamicObject.get("yem_paymentamt2_cdbase"), addNewRowIdx);//收款金额2（本位币）
            model.setValue("yem_actulpreamt", dynamicObject.get("yem_actualsinkamt_cd"), addNewRowIdx);//实际收汇金额
            model.setValue("yem_actulpreamtbase", dynamicObject.get("yem_actualsinkamtba_cd"), addNewRowIdx);//实际收汇本位币金额
            model.setValue("yem_creditremark", dynamicObject.get("yem_creditremark"), addNewRowIdx);//信保备注

            model.setValue("yem_creditquotation", dynamicObject.get("yem_creditquotation"), addNewRowIdx);//信保结算方式
            model.setValue("yem_sinosurerate_cd", dynamicObject.get("yem_sinosurerate_cd"), addNewRowIdx);//信保费率
            model.setValue("yem_term_cd", dynamicObject.get("yem_term_cd"), addNewRowIdx);//信用期限

            model.setValue("yem_year_e", dynamicObject.get("yem_year_e"), addNewRowIdx);//年份
            model.setValue("yem_creditstatus_e", dynamicObject.get("yem_creditstatus_e"), addNewRowIdx);//信保状态

            Long pkValue = (Long) dynamicObject.getPkValue();
            model.setValue("yem_parententryid", pkValue, addNewRowIdx);

            model.setValue("yem_premium", dynamicObject.get("yem_insuranceamt_cd"), addNewRowIdx);//保险费

            DynamicObjectCollection parentSubCollection = dynamicObject.getDynamicObjectCollection("yem_crecollection");

            DynamicObjectCollection subCollection = dataEntity.getDynamicObjectCollection("yem_creditentry").get(currentEntryIdx).getDynamicObjectCollection("yem_crecollection");

            for (DynamicObject subObject : parentSubCollection) {

                DynamicObject subAddNew = subCollection.addNew();

                subAddNew.set("yem_credate", subObject.getDate("yem_credate"));//业务日期
                subAddNew.set("yem_crecurrency", subObject.getDynamicObject("yem_crecurrency"));//信保币别
                subAddNew.set("yem_crerate", subObject.getBigDecimal("yem_crerate"));//信保汇率
                subAddNew.set("yem_crecollecdate", subObject.getDate("yem_crecollecdate"));//收款日期
                subAddNew.set("yem_creactualamt", subObject.getBigDecimal("yem_creactualamt"));//实际收汇金额
                subAddNew.set("yem_creactuallocamt", subObject.getBigDecimal("yem_creactuallocamt"));//实际收汇金额本位币
                subAddNew.set("yem_crenote", subObject.getString("yem_crenote"));//收款备注
                subAddNew.set("yem_crecollecurrency", subObject.getDynamicObject("yem_crecollecurrency"));//收款币别
                subAddNew.set("yem_crecollecamt", subObject.getBigDecimal("yem_crecollecamt"));//收款金额
            }
        }
    }

    @Override
    public void registerListener(EventObject e) {
        this.addClickListeners("btnok");
    }

    @Override
    public void click(EventObject e) {
        super.click(e);
        Control control = (Control) e.getSource();
        String key = control.getKey();
        if ("btnok".equals(key)) {

            IFormView view = this.getView();
            IDataModel model = this.getModel();
            DynamicObject dataEntity = model.getDataEntity(true);
            IFormView parentView = view.getParentView();
            IDataModel parentModel = parentView.getModel();
            DynamicObject parentDataEntity = parentModel.getDataEntity(true);

            BigDecimal actualPreAmount = (BigDecimal) model.getValue("yem_actulpreamount");//实际收汇金额汇总
            BigDecimal actualPreAmountBase = (BigDecimal) model.getValue("yem_actulpreamountbase");//实际收汇本位币金额汇总
            DynamicObject clientcountry = (DynamicObject) model.getValue("yem_clientcountry");

            parentModel.setValue("yem_actualsinkamount", actualPreAmount);
            parentModel.setValue("yem_actualsinkamountba", actualPreAmountBase);
            parentModel.setValue("yem_clientcountry", clientcountry);



            Map<Long, Map<String, Object>> parentMap = cacheEntryData();

            DynamicObjectCollection parentCreditDetail = parentDataEntity.getDynamicObjectCollection("yem_creditdetail");
            for (DynamicObject dynamicObject : parentCreditDetail) {
                int i = parentCreditDetail.indexOf(dynamicObject);
                Long pkValue = (Long) dynamicObject.getPkValue();
                if (parentMap.containsKey(pkValue)) {
                    Map<String, Object> subMap = parentMap.get(pkValue);
                    parentModel.setValue("yem_usacreditamt_cd", subMap.get("usaCreditAmt"), i);//信报金额美元
                    parentModel.setValue("yem_creditdate1_cd", subMap.get("creditDate1"), i);//信保天数1
                    parentModel.setValue("yem_paymentamt1_cd", subMap.get("paymentAmt1"), i);//收款金额1
                    parentModel.setValue("yem_paymentamt1_cdbase", subMap.get("paymentAmtBase1"), i);//收款金额1（本位币）
                    parentModel.setValue("yem_creditdate2_cd", subMap.get("creditDate2"), i);//信保天数2
                    parentModel.setValue("yem_paymentamt2_cd", subMap.get("paymentAmt2"), i);//收款金额2
                    parentModel.setValue("yem_paymentamt2_cdbase", subMap.get("paymentAmtBase2"), i);//收款金额2（本位币）
                    parentModel.setValue("yem_actualsinkamt_cd", subMap.get("actulPreAmt"), i);//实际收汇金额
                    parentModel.setValue("yem_actualsinkamtba_cd", subMap.get("actulPreAmtBase"), i);//实际收汇本位币金额
                    parentModel.setValue("yem_creditremark", subMap.get("creditRemark"), i);//信保备注

                    parentModel.setValue("yem_creditquotation", subMap.get("yem_creditquotation"), i);
                    parentModel.setValue("yem_sinosurerate_cd", subMap.get("yem_sinosurerate_cd"));
                    parentModel.setValue("yem_term_cd", subMap.get("yem_term_cd"));

                    parentModel.setValue("yem_year_e", subMap.get("year"));
                    parentModel.setValue("yem_creditstatus_e", subMap.get("creditstatus"));

                    parentModel.setValue("yem_insuranceamt_cd", subMap.get("yem_premium"));//保险费
                }
            }
            subEntryBackFill();
//            parentMap = cacheEntryData();
            backFillCsrCreditLine(parentModel, parentMap);
            calcAmountOwed(parentModel);
            SaveServiceHelper.save(new DynamicObject[]{parentDataEntity});
            parentView.invokeOperation("refresh");
            view.sendFormAction(parentView);
            view.close();
        }
    }

    /**
     * 缓存分录数据
     * @return
     */
    private Map<Long, Map<String, Object>> cacheEntryData()
    {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        IFormView parentView = view.getParentView();
        IDataModel parentModel = parentView.getModel();
        DynamicObject parentDataEntity = parentModel.getDataEntity(true);
        Map<Long, Map<String, Object>> collectionMap = new HashMap<>();

        DynamicObjectCollection creditEntryCollection = dataEntity.getDynamicObjectCollection("yem_creditentry");
        for (DynamicObject dynamicObject : creditEntryCollection) {
            int i = creditEntryCollection.indexOf(dynamicObject);

            Map<String, Object> map = new HashMap<>();

            String saleContractNo = (String) model.getValue("yem_salecontractno", i);
            Integer creditDate1 = (Integer) model.getValue("yem_creditdate1_cd", i);
            BigDecimal paymentAmt1 = (BigDecimal) model.getValue("yem_paymentamt1_cd", i);
            BigDecimal paymentAmtBase1 = (BigDecimal) model.getValue("yem_paymentamt1_cdbase", i);
            Integer creditDate2 = (Integer) model.getValue("yem_creditdate2_cd", i);
            BigDecimal paymentAmt2 = (BigDecimal) model.getValue("yem_paymentamt2_cd", i);
            BigDecimal paymentAmtBase2 = (BigDecimal) model.getValue("yem_paymentamt2_cdbase", i);
            BigDecimal actualPreAmt = (BigDecimal) model.getValue("yem_actulpreamt", i);
            BigDecimal actualPreAmtBase = (BigDecimal) model.getValue("yem_actulpreamtbase", i);
            String creditRemark = (String) model.getValue("yem_creditremark", i);
            BigDecimal usaCreditAmt = (BigDecimal) model.getValue("yem_usacreditamt_cd", i);

            Date year = (Date) model.getValue("yem_year_e", i);
            String creditstatus = (String) model.getValue("yem_creditstatus_e", i);

            Object creditquotation = model.getValue("yem_creditquotation", i);//信保结算方式
            Object sinosurerateCd = model.getValue("yem_sinosurerate_cd", i);//信保费率
            Object termCd = model.getValue("yem_term_cd", i);//信用期限

            map.put("salesOrderNo", saleContractNo);
            map.put("creditDate1", creditDate1);
            map.put("paymentAmt1", paymentAmt1);
            map.put("paymentAmtBase1", paymentAmtBase1);
            map.put("creditDate2", creditDate2);
            map.put("paymentAmt2", paymentAmt2);
            map.put("paymentAmtBase2", paymentAmtBase2);
            map.put("actulPreAmt", actualPreAmt);
            map.put("actulPreAmtBase", actualPreAmtBase);
            map.put("creditRemark", creditRemark);
            map.put("usaCreditAmt", usaCreditAmt);

            map.put("yem_stclaiamt_cd", parentModel.getValue("yem_stclaiamt_cd", i));//储运认领金额
            map.put("yem_preamt_cd", parentModel.getValue("yem_preamt_cd", i));//预收金额
            map.put("yem_countpayback", parentModel.getValue("yem_countpayback", i));//应回款倒计时
            map.put("yem_amountowed", parentModel.getValue("yem_amountowed", i));//欠款金额

            map.put("yem_creditquotation", creditquotation);//信保结算方式
            map.put("yem_sinosurerate_cd", sinosurerateCd);//信保费率
            map.put("yem_term_cd", termCd);//信用期限

            map.put("year", year);
            map.put("creditstatus", creditstatus);

            map.put("yem_premium", model.getValue("yem_premium", i));//保险费

            Long pkValue = dynamicObject.getLong("yem_parententryid");
            collectionMap.put(pkValue, map);
        }
        return collectionMap;
    }

    /**
     * 计算欠款金额
     * @param parentmodel
     */
    private void calcAmountOwed(IDataModel parentmodel)
    {
        DynamicObject dataEntity = parentmodel.getDataEntity(true);
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_creditdetail");
        for (DynamicObject dynamicObject : collection) {
            Date receivableDate = dynamicObject.getDate("yem_paydate1");
            if (receivableDate != null) {
                dynamicObject.set("yem_countpayback", CalendarUtils.calcPayBackCount(receivableDate));
            }
            // 投保回款金额美元（实际收汇金额）
            BigDecimal actualsinkamt_cd = dynamicObject.getBigDecimal("yem_actualsinkamt_cd");
            // 应收款金额1
            BigDecimal paymentamt1Cd = dynamicObject.getBigDecimal("yem_paymentamt1_cd");
            BigDecimal amountowed = actualsinkamt_cd.subtract(paymentamt1Cd);
            dynamicObject.set("yem_amountowed", amountowed);
        }
    }

    public void backFillCsrCreditLine(IDataModel parentModel, Map<Long, Map<String, Object>> allMap) {
        DynamicObject parentModelDataEntity = parentModel.getDataEntity(true);
        DynamicObject customer = (DynamicObject) parentModel.getValue("yem_customer");
        DynamicObject method = TotalUtil.getSettlementMethod(parentModelDataEntity);
        DynamicObject company = parentModelDataEntity.getDynamicObject("yem_company.yem_erporg");
        String swiftCode = TotalUtil.getSwiftCode(parentModelDataEntity);
        DynamicObject csrCreditLine = TotalUtil.getCsrCreditLine(customer, method, company, swiftCode);
        if (YEM.isNotEmpty(csrCreditLine)) {

            csrCreditLine.set("yem_swiftcode", swiftCode);
            //信保额度明细信息
            DynamicObjectCollection collection = csrCreditLine.getDynamicObjectCollection("yem_im_info");
            for (DynamicObject dynamicObject : collection) {

                long sourceEntryId = dynamicObject.getLong("yem_storagetranentryid");

                if (YEM.isEmpty(sourceEntryId)) return;

                if (allMap.containsKey(sourceEntryId)) {
                    Map<String, Object> map = allMap.get(sourceEntryId);
                    dynamicObject.set("yem_creditamtuse", map.get("usaCreditAmt"));
                    dynamicObject.set("yem_creditdate1_cd", map.get("creditDate1"));
                    dynamicObject.set("yem_paymentamt1_cd", map.get("paymentAmt1"));
                    dynamicObject.set("yem_paymentamt1_cdbase", map.get("paymentAmtBase1"));
                    dynamicObject.set("yem_creditdate2_cd", map.get("creditDate2"));
                    dynamicObject.set("yem_paymentamt2_cd", map.get("paymentAmt2"));
                    dynamicObject.set("yem_paymentamt2_cdbase", map.get("paymentAmtBase2"));
                    dynamicObject.set("yem_actualsinkamt", map.get("actulPreAmt"));
                    dynamicObject.set("yem_actualsinkamtbase", map.get("actulPreAmtBase"));
                    dynamicObject.set("yem_creditremark", map.get("creditRemark"));
                    dynamicObject.set("yem_creditamtuse", map.get("usaCreditAmt"));
                    dynamicObject.set("yem_stclaiamt_cd", map.get("yem_stclaiamt_cd"));
                    dynamicObject.set("yem_preamt_cd", map.get("yem_preamt_cd"));
                    dynamicObject.set("yem_countpayback", map.get("yem_countpayback"));

                    BigDecimal paymentamt1Cd = (BigDecimal) map.get("paymentAmt1");
                    BigDecimal actualsinkamt = (BigDecimal) map.get("actulPreAmt");
                    dynamicObject.set("yem_amountowed", paymentamt1Cd.subtract(actualsinkamt).abs());

                    dynamicObject.set("yem_year_e", map.get("year"));
                    dynamicObject.set("yem_creditstatus_e", map.get("creditstatus"));

                    dynamicObject.set("yem_premium", map.get("yem_premium"));
                }
            }
            SaveServiceHelper.save(new DynamicObject[]{csrCreditLine});
            //反写子单据体
            setcrecollection(csrCreditLine);
        }
    }

    /**
     * 处理信保额度申请
     *
     * @param csrCreditLine
     */
    public void setcrecollection(DynamicObject csrCreditLine)
    {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        IFormView parentView = view.getParentView();
        IDataModel parentModel = parentView.getModel();

        csrCreditLine = BusinessDataServiceHelper.loadSingle(csrCreditLine.getPkValue(), csrCreditLine.getDataEntityType().getName());

        DynamicObjectCollection formEntry = dataEntity.getDynamicObjectCollection("yem_creditentry");//动态表单

        DynamicObjectCollection yem_im_info = csrCreditLine.getDynamicObjectCollection("yem_im_info");//保额度明细信息

        //获取信保额度明细信息id
        for (DynamicObject dynamicObject : formEntry) {
            long parentEntryId = dynamicObject.getLong("yem_parententryid");

            for (DynamicObject im_info : yem_im_info) {

                long storagetranentryid = im_info.getLong("yem_storagetranentryid");

                if (parentEntryId == storagetranentryid) {

                    DynamicObjectCollection formCreCollection = dynamicObject.getDynamicObjectCollection("yem_crecollection");

                    if (!formCreCollection.isEmpty()) {

                        DynamicObjectCollection im_infocrecollection = im_info.getDynamicObjectCollection("yem_crecollection");

                        im_infocrecollection.clear();

                        for (DynamicObject crecollection : formCreCollection) {
                            DynamicObject addNew = im_infocrecollection.addNew();
                            addNew.set("yem_credate", crecollection.getDate("yem_credate"));//业务日期
                            addNew.set("yem_crecurrency", crecollection.getDynamicObject("yem_crecurrency"));//信保币别
                            addNew.set("yem_crerate", crecollection.getBigDecimal("yem_crerate"));//信保汇率
                            addNew.set("yem_crecollecdate", crecollection.getDate("yem_crecollecdate"));//收款日期
                            addNew.set("yem_creactualamt", crecollection.getBigDecimal("yem_creactualamt"));//实际收汇金额
                            addNew.set("yem_creactuallocamt", crecollection.getBigDecimal("yem_creactuallocamt"));//实际收汇金额本位币
                            addNew.set("yem_crenote", crecollection.getString("yem_crenote"));//收款备注
                            addNew.set("yem_crecollecurrency", crecollection.getDynamicObject("yem_crecollecurrency"));//收款币别
                            addNew.set("yem_crecollecamt", crecollection.getBigDecimal("yem_crecollecamt"));//收款金额
                        }
                    } else {
                        DynamicObjectCollection im_infocrecollection = im_info.getDynamicObjectCollection("yem_crecollection");
                        im_infocrecollection.clear();
                    }
                }
            }
        }
        BigDecimal yem_totaloccupancy = BigDecimal.ZERO;
        DynamicObjectCollection collection = csrCreditLine.getDynamicObjectCollection("yem_im_info");
        for (DynamicObject object : collection) {
            yem_totaloccupancy = yem_totaloccupancy.add(object.getBigDecimal("yem_creditamtuse"));
        }
        csrCreditLine.set("yem_totaloccupancy", yem_totaloccupancy);
        BigDecimal decimal = CreditBackFillUtils.calcRemainingAmount(csrCreditLine);
        csrCreditLine.set("yem_balance", decimal);
        SaveServiceHelper.save(new DynamicObject[]{csrCreditLine});
    }

    /**
     * 子分录回填
     */
    public void subEntryBackFill() {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        DynamicObjectCollection thisCreditEntry = dataEntity.getDynamicObjectCollection("yem_creditentry");

        IFormView parentView = view.getParentView();
        IDataModel parentmodel = parentView.getModel();
        DynamicObject parentdataEntity = parentmodel.getDataEntity(true);
        DynamicObjectCollection parentCreditEntry = parentdataEntity.getDynamicObjectCollection("yem_creditdetail");

        for (DynamicObject dynamicObject : thisCreditEntry) {
            int index = thisCreditEntry.indexOf(dynamicObject);
            DynamicObjectCollection subCollection = dynamicObject.getDynamicObjectCollection("yem_crecollection");
            DynamicObjectCollection parentSubCollection = parentCreditEntry.get(index).getDynamicObjectCollection("yem_crecollection");
            parentSubCollection.clear();
            for (DynamicObject crecollection : subCollection) {
                DynamicObject parentAddNer = parentSubCollection.addNew();
                parentAddNer.set("yem_credate", crecollection.getDate("yem_credate"));//业务日期
                parentAddNer.set("yem_crecurrency", crecollection.getDynamicObject("yem_crecurrency"));//信保币别
                parentAddNer.set("yem_crerate", crecollection.getBigDecimal("yem_crerate"));//信保汇率
                parentAddNer.set("yem_crecollecdate", crecollection.getDate("yem_crecollecdate"));//收款日期
                parentAddNer.set("yem_creactualamt", crecollection.getBigDecimal("yem_creactualamt"));//实际收汇金额
                parentAddNer.set("yem_creactuallocamt", crecollection.getBigDecimal("yem_creactuallocamt"));//实际收汇金额本位币
                parentAddNer.set("yem_crenote", crecollection.getString("yem_crenote"));//收款备注
                parentAddNer.set("yem_crecollecurrency", crecollection.getDynamicObject("yem_crecollecurrency"));//收款币别
                parentAddNer.set("yem_crecollecamt", crecollection.getBigDecimal("yem_crecollecamt"));//收款金额
            }

            BigDecimal creactualamt = BigDecimal.ZERO;// 实际收汇金额
            BigDecimal creactuallocamt = BigDecimal.ZERO;// 实际收汇金额本位币
            for (DynamicObject parentSubObject : parentSubCollection) {
                creactualamt = creactualamt.add(parentSubObject.getBigDecimal("yem_creactualamt"));
                creactuallocamt = creactuallocamt.add(parentSubObject.getBigDecimal("yem_creactuallocamt"));
            }
            parentmodel.setValue("yem_actualsinkamt_cd", creactualamt, index);
            parentmodel.setValue("yem_actualsinkamtba_cd", creactuallocamt, index);
        }
    }


    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String operateKey = e.getOperateKey();
        if ("deleteentry_cre".equals(operateKey)) {
            computecreactualamt();
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        ChangeData[] changeData = e.getChangeSet();
        Object newValue = changeData[0].getNewValue();
        int row = changeData[0].getRowIndex();
        String key = e.getProperty().getName();
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        int enrow = this.getModel().getEntryCurrentRowIndex("yem_crecollection");
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        if ("yem_creactualamt".equals(key) || "yem_crerate".equals(key)) {
            computecreactualamt();
        }
        if ("yem_crerate".equals(key)) {
            BigDecimal yem_crerate = (BigDecimal) model.getValue("yem_crerate", enrow);
            if (yem_crerate.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal yem_creactualamt = (BigDecimal) model.getValue("yem_creactualamt", enrow);
                model.setValue("yem_creactuallocamt", yem_creactualamt.multiply(yem_crerate), enrow);
            }
        }

        if ("yem_creditquotation".equals(key) || "yem_term_cd".equals(key) || "yem_clientcountry".equals(key)) {
            carryCreditInsuranceRate(row);
        }

        if ("yem_crecollecamt".equals(key)) {
            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_creditentry");
            int rowIndex = model.getEntryCurrentRowIndex("yem_creditentry");
            DynamicObject object = collection.get(rowIndex);
            DynamicObjectCollection subCollection = object.getDynamicObjectCollection("yem_crecollection");
            DynamicObject dynamicObject = subCollection.get(row);
            BigDecimal crerate = dynamicObject.getBigDecimal("yem_crerate");//信保汇率1
            BigDecimal creactualamt = dynamicObject.getBigDecimal("yem_creactualamt");//实际收汇金额（美元）3
            BigDecimal crecollecamt = dynamicObject.getBigDecimal("yem_crecollecamt");//收款币别金额2
            if (YEM.isNotEmpty(crerate)) {
                creactualamt = crecollecamt.divide(crerate,4 ,RoundingMode.HALF_UP);
                // disable 2024-04-22 by zzs
//                dynamicObject.set("yem_creactualamt", creactualamt);//3 = 2 / 1
                this.getView().updateView();
            }

            if (YEM.isNotEmpty(creactualamt) && YEM.isNotEmpty(crecollecamt)) {
                crerate = crecollecamt.divide(creactualamt,4 ,RoundingMode.HALF_UP);
//                dynamicObject.set("yem_crerate", crerate);
            }

            this.getView().updateView();
        }

        if ("yem_creactualamt".equals(key) || "yem_crerate".equals(key) || "yem_crecollecamt".equals(key)) {
            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_creditentry");
            int rowIndex = model.getEntryCurrentRowIndex("yem_creditentry");
            DynamicObject object = collection.get(rowIndex);
            DynamicObjectCollection subCollection = object.getDynamicObjectCollection("yem_crecollection");
            DynamicObject dynamicObject = subCollection.get(row);
            BigDecimal creactualamt = dynamicObject.getBigDecimal("yem_creactualamt");//实际收汇金额（美元）3
            BigDecimal crerate = dynamicObject.getBigDecimal("yem_crerate");//信保汇率1
            dynamicObject.set("yem_creactuallocamt", creactualamt.multiply(crerate));
            this.getView().updateView();
        }
    }

    private void carryCreditInsuranceRate(int rowIndex)
    {
        IDataModel model = this.getModel();
        // 信报结算方式
        DynamicObject rapstyle = (DynamicObject) model.getValue("yem_creditquotation", rowIndex);
        // 贸易国别
        DynamicObject clientcountry = (DynamicObject) model.getValue("yem_clientcountry");
        // 信用期限
        DynamicObject term = (DynamicObject) model.getValue("yem_term_cd", rowIndex);

        if (rapstyle == null || clientcountry == null || term == null) return;

        Long pkValue = (Long) clientcountry.getPkValue();
        QFilter qFilter = new QFilter("yem_countryinfo.yem_nation.id", QCP.equals, pkValue);
        DynamicObject[] load = BusinessDataServiceHelper.load("yem_bd_signals", "id, billno, yem_countryinfo.yem_nation", qFilter.toArray());
        if (YEM.isEmpty(load)) return;

        for (DynamicObject dynamicObject : load) {
            dynamicObject = BusinessDataServiceHelper.loadSingle(dynamicObject.getLong("id"), "yem_bd_signals");
            DynamicObjectCollection collection = dynamicObject.getDynamicObjectCollection("yem_bd_signals_em");
            for (DynamicObject object : collection) {
                DynamicObject payment = object.getDynamicObject("yem_payment");
                DynamicObject yem_term = object.getDynamicObject("yem_term");
                if (YEM.isEmpty(payment) || YEM.isEmpty(yem_term)) continue;
                if (rapstyle.getLong("id") == payment.getLong("id") && term.getLong("id") == yem_term.getLong("id")) {
                    model.setValue("yem_sinosurerate_cd", object.getBigDecimal("yem_rate"), rowIndex);
                    return;
                }
            }
        }
        model.setValue("yem_sinosurerate_cd", null, rowIndex);
    }


    /**
     * 计算实际收汇金额汇总
     */
    public void computecreactualamt() {
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        DynamicObjectCollection yem_creditentry = dataEntity.getDynamicObjectCollection("yem_creditentry");
        for (int i = 0; i < yem_creditentry.size(); i++) {
            BigDecimal yem_actulpreamt = BigDecimal.ZERO;
            BigDecimal yem_actulpreamtbase = BigDecimal.ZERO;
            DynamicObject dynamicObject = yem_creditentry.get(i);
            DynamicObjectCollection yem_crecollection = dynamicObject.getDynamicObjectCollection("yem_crecollection");
            for (int j = 0; j < yem_crecollection.size(); j++) {
                DynamicObject crecollection = yem_crecollection.get(j);
                BigDecimal yem_creactualamt = crecollection.getBigDecimal("yem_creactualamt");
                BigDecimal yem_crerate = crecollection.getBigDecimal("yem_crerate");
                BigDecimal yem_creactuallocamt = yem_creactualamt.multiply(yem_crerate);
                model.setValue("yem_creactuallocamt", yem_creactuallocamt, j, i);
                yem_actulpreamt = yem_actulpreamt.add(crecollection.getBigDecimal("yem_creactualamt"));
                yem_actulpreamtbase = yem_actulpreamtbase.add(yem_creactuallocamt);
            }
            model.setValue("yem_actulpreamt", yem_actulpreamt, i);
            model.setValue("yem_actulpreamtbase", yem_actulpreamtbase, i);
        }
    }
}
