package com.yem.wm.es.shippingdetails.convert;

import com.yem.wm.es.contractamtlist.util.FunUtil;
import com.yem.wm.es.shippingdetails.util.PaymentControlUtil;
import com.yem.wm.utils.YEM;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.botp.plugin.AbstractConvertPlugIn;
import kd.bos.entity.botp.plugin.args.AfterConvertEventArgs;
import kd.bos.servicehelper.BusinessDataServiceHelper;

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

import static com.yem.wm.es.contractamtlist.util.FunUtil.getPayBills;
import static com.yem.wm.es.contractamtlist.util.FunUtil.getShipBills;

/**
 * @author xwudd
 * @Description 出运明细下推国贸贷款欠条申请
 * @date 17:26
 **/
public class ShippingDetailToTradeAppConvert extends AbstractConvertPlugIn
{

    @Override
    public void afterConvert(AfterConvertEventArgs e)
    {
        super.afterConvert(e);
        String targetName = this.getTgtMainType().getName();
        String name = this.getSrcMainType().getName();
        ExtendedDataEntity[] findByEntityKeys = e.getTargetExtDataEntitySet().FindByEntityKey(targetName);
        for (ExtendedDataEntity findByEntityKey : findByEntityKeys) {
            DynamicObject dataEntity = findByEntityKey.getDataEntity();
            List<DynamicObject> shippingDetails = (List<DynamicObject>) findByEntityKey.getValue("ConvertSource");
            for (DynamicObject shippingDetail : shippingDetails) {
                long id = shippingDetail.getLong("id");
                shippingDetail = BusinessDataServiceHelper.loadSingle(id, name);
                String sourceBillType = shippingDetail.getString("yem_sourcebilltype");
                long sourceBillId = shippingDetail.getLong("yem_sourcebillid");
                DynamicObject saleOrder = BusinessDataServiceHelper.loadSingle(sourceBillId, sourceBillType);
//                BigDecimal rapRate = PaymentControlUtil.getRapRate(saleOrder);
                BigDecimal collection = PaymentControlUtil.getCollection(sourceBillId);//A 合同的所有收款
//                BigDecimal contractPayment = PaymentControlUtil.getAdvancePayment(PaymentControlUtil.getContractPayment(saleOrder), rapRate);//B 合同的预收款
//                BigDecimal balancePayment = PaymentControlUtil.getBalancePayment(PaymentControlUtil.getBalancePayment(id, sourceBillType, sourceBillId), rapRate);//C 提交、审核的历史发运尾款
//                BigDecimal translateBalancePayment = PaymentControlUtil.getBalancePayment(PaymentControlUtil.getTranslateBalancePayment(shippingDetail), rapRate);//D 本次发运尾款
//                BigDecimal arrearsAmt = collection.subtract(contractPayment).subtract(balancePayment).subtract(translateBalancePayment);
//                BigDecimal fAbs = arrearsAmt.abs();
//                BigDecimal eAmt = PaymentControlUtil.getBalancePayment(collection.subtract(contractPayment).subtract(balancePayment), rapRate);
//                BigDecimal gAmt = fAbs.add(eAmt);
                dataEntity.set("yem_contractallamt", collection.setScale(2, RoundingMode.HALF_UP));//合同所有收款

                // changed by zzs, 2023/1/23
                BigDecimal contractadvanceamt = PaymentControlUtil.getTotalClaimedAmount(saleOrder);
                dataEntity.set("yem_contractadvanceamt", contractadvanceamt.setScale(2, RoundingMode.HALF_UP));//合同下单已认额金额

                // changed by zzs, 2023/1/23
                BigDecimal shipamt = PaymentControlUtil.getShipAmt(saleOrder, shippingDetail);
                dataEntity.set("yem_shipamt", shipamt.setScale(2, RoundingMode.HALF_UP));//已发运金额

                DynamicObject[] shipBills = getShipBills(saleOrder, shippingDetail, "A");//出运
                DynamicObject[] payBills = getPayBills(saleOrder, shippingDetail, "B");//收款单

                BigDecimal thisRealityAmt = PaymentControlUtil.getThisRealityAmt(saleOrder, shipBills, payBills, shippingDetail);
                dataEntity.set("yem_thisrealityamt", thisRealityAmt);//本次发运欠款金额
                dataEntity.set("yem_thisshipiouamt", FunUtil.getAbs(thisRealityAmt));

                // 合同的发运预收款
//                BigDecimal shipadvancepay = PaymentControlUtil.getBalancePayment(PaymentControlUtil.getContractPayment(saleOrder), rapRate);
//                dataEntity.set("yem_shipadvancepay", shipadvancepay.setScale(2, RoundingMode.HALF_UP));

                BigDecimal shippedamtSum = BigDecimal.ZERO;
                DynamicObjectCollection tradeapps = dataEntity.getDynamicObjectCollection("yem_im_tradeapp_em");
                for (DynamicObject tradeapp : tradeapps) {
                    shippedamtSum = shippedamtSum.add(tradeapp.getBigDecimal("yem_sellamt"));
                }
                BigDecimal shipPreRapRate = PaymentControlUtil.getShipPreRapRate(saleOrder);//发货预收汇比例
                BigDecimal procPreRapRate = PaymentControlUtil.getProcPreRapRate(saleOrder);//生产预收
                dataEntity.set("yem_thisshipamt", PaymentControlUtil.getAdvancePayment(shippedamtSum, shipPreRapRate));//本次发运尾款

                // yem_remainunwamount = yem_thisshipiouamt - yem_writtenoffamount
                // 剩余未核销金额计算
                dataEntity.set("yem_remainunwamount", dataEntity.getBigDecimal("yem_thisshipiouamt").subtract(dataEntity.getBigDecimal("yem_writtenoffamount")));


                /**
                 * yem_thishipcollected 本次发运已收款
                 * 计算逻辑：
                 * 1、发运单号对应的合同的在收款单的认领明细的款项性质是下单预收款的合同认领金额-历史发运（非本单）的金额*合同收款计划中下单预收比例； 0-0*0.3
                 * 2、如果公式1大于0，则公式1计算的结果-本次发运金额*合同收款计划中下单预收比例；
                 * 3、如果公式2大于等于0，则输出结果本次发运金额*合同收款计划中下单预收比例；如果小于0，则输出结果公式1
                 * 4、公式3+发运单号对应的收款的认领明细的-款项性质：发货预收款的合同认领金额 0 + 427
                 * 发运账期款：发运金额*合同收款计划中的账期比例；
                 */
                // 合同的在收款单的认领明细的款项性质是下单预收款的合同认领金额
                BigDecimal contractClimeAmt = PaymentControlUtil.getContractClimeAmt(saleOrder, "D");
                // 历史发运（非本单）的金额 shipamt
                // 下单预收比例 procPreRapRate
                // 本次发运金额 yem_offeramount
                BigDecimal formulaOne = contractClimeAmt.subtract(PaymentControlUtil.getAdvancePayment(shipamt, procPreRapRate));
                BigDecimal formulaTwo = BigDecimal.ZERO;
                BigDecimal calcRes;
                BigDecimal thisShipAmt = shippingDetail.getBigDecimal("yem_offeramount");
                if (formulaOne.compareTo(BigDecimal.ZERO) > 0) {
                    formulaTwo = formulaOne.subtract(PaymentControlUtil.getAdvancePayment(thisShipAmt, procPreRapRate));
                    if (formulaTwo.compareTo(BigDecimal.ZERO) >= 0) {
                        formulaTwo = PaymentControlUtil.getAdvancePayment(thisShipAmt, procPreRapRate);
                    } else {
                        formulaTwo = formulaOne;
                    }
                }

                calcRes = formulaTwo.add(PaymentControlUtil.getShipClaimContractClimeAmt(shippingDetail, "E"));
                dataEntity.set("yem_thishipcollected", calcRes.setScale(4, RoundingMode.HALF_UP));
                // 账期
                BigDecimal accountingPeriod = BigDecimal.ONE.subtract(procPreRapRate.multiply(BigDecimal.valueOf(0.01))).subtract(shipPreRapRate.multiply(BigDecimal.valueOf(0.01)));
                dataEntity.set("yem_shipaccperiod", thisShipAmt.multiply(accountingPeriod).setScale(4, RoundingMode.HALF_UP));

                DynamicObject bdProducts = dataEntity.getDynamicObject("yem_bd_products");
                if (YEM.isNotEmpty(bdProducts)) {
                    bdProducts = BusinessDataServiceHelper.loadSingle(bdProducts.getLong("id"), "yem_bd_productsgroup","yem_businesssort");
                    String businesssort = bdProducts.getString("yem_businesssort");
                    if ("Z".equals(businesssort)) {
                        dataEntity.set("yem_paymenttype", "Z");
                    } else {
                        dataEntity.set("yem_paymenttype", "P");
                    }
                }
            }
        }
    }
}
