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

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

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

/**
 * 外销合同 -》 内审预算单
 */
public class SalesOrderToIntAuditBusaConvert extends AbstractConvertPlugIn {
    @Override
    public void afterConvert(AfterConvertEventArgs e) {
        super.afterConvert(e);
        String targetName = this.getTgtMainType().getName();
        ExtendedDataEntity[] entities = e.getTargetExtDataEntitySet().FindByEntityKey(targetName);
        for (ExtendedDataEntity entity : entities) {
            DynamicObject dataEntity = entity.getDataEntity();
            long sourceentryid = dataEntity.getLong("yem_sourceentryid");
            String sourcebilltype = dataEntity.getString("yem_sourcebilltype");
            if (YEM.isEmpty(sourcebilltype)) continue;
            QFilter qFilter = new QFilter("yem_es_materialinfo.id", QCP.equals, sourceentryid);
            DynamicObject salesorder = BusinessDataServiceHelper.loadSingle(sourcebilltype, qFilter.toArray());
            if (salesorder == null) continue;
            fillWithCreditRate(salesorder, dataEntity);

            DynamicObjectCollection collection = salesorder.getDynamicObjectCollection("yem_es_materialinfo");
            for (DynamicObject dynamicObject : collection) {
                long id = dynamicObject.getLong("id");
                if (id == sourceentryid) {
                    // 销售FOB金额
                    BigDecimal amt = dynamicObject.getBigDecimal("yem_safobamount");
                    List<BigDecimal> rateList = getReceiveRate(salesorder);
                    // 销售单价（价格条款）
                    BigDecimal sapricepriceclause = dynamicObject.getBigDecimal("yem_sapricepriceclause");
                    fillWithInsuredAmount(rateList, sapricepriceclause, dataEntity);

                    BigDecimal rateSum = BigDecimal.ZERO;
                    for (BigDecimal rate : rateList) {
                        rateSum = rateSum.add(rate);
                    }

                    dataEntity.set("yem_rapratesum", rateSum);
//                    fillWithCreditAmount(amt, salesorder, dataEntity);
                }
            }
        }
    }

    /**
     * 计算信保费
     * 3、信保费：等于（当前行的销售金额*收款计划中的是否信保为是的收汇百分比%*信保费率）的累计值；
     *
     * 2024-07-03 修改为在合同完成计算，下推携带 zzs
     *
     * @param amt
     * @param salesorder
     * @param entity
     */
    private void fillWithCreditAmount(BigDecimal amt, DynamicObject salesorder, DynamicObject entity) {
        BigDecimal calcRes = BigDecimal.ZERO;
        DynamicObjectCollection collection = salesorder.getDynamicObjectCollection("yem_es_salescontrac_s");
        for (DynamicObject dynamicObject : collection) {
            // 信保费率
            BigDecimal sinosurerate = dynamicObject.getBigDecimal("yem_sinosurerate");
            // 收汇百分比%
            BigDecimal raprate = dynamicObject.getBigDecimal("yem_raprate");
            // 是否信保
            String issinosure = dynamicObject.getString("yem_issinosure");
            if ("A".equals(issinosure)) {
                BigDecimal raprateR = BigDecimalUtils.div(raprate, new BigDecimal("100"), 12);
                BigDecimal sinosurerateR = BigDecimalUtils.div(sinosurerate, new BigDecimal("100"), 12);
                BigDecimal res = amt.multiply(sinosurerateR).multiply(raprateR);
                calcRes = calcRes.add(res);
            }
        }
        entity.set("yem_creditamt", calcRes);
        BigDecimal exrate = entity.getBigDecimal("yem_exrate");
        entity.set("yem_creditamtba", calcRes.multiply(exrate));
    }

    /**
     * 计算投保金额
     * // 2、投保金额：计算逻辑：等于当前行的销售金额*收款计划中的是否信保为是的收汇百分比%合计；
     *
     * 销售单价（价格条款）*收款计划中的是否信保为是的收汇百分比%合计
     *
     * @param rateList
     * @param amt
     * @param entity
     */
    private void fillWithInsuredAmount(List<BigDecimal> rateList, BigDecimal amt, DynamicObject entity) {
        BigDecimal calcRes = BigDecimal.ZERO;
        for (BigDecimal rate : rateList) {
            calcRes = calcRes.add(amt.multiply(rate));
        }
        entity.set("yem_suminsured", calcRes);
    }

    /**
     * 获取合同中否信保为是的收汇百分比%
     * @param salesorder
     * @return
     */
    private List<BigDecimal> getReceiveRate(DynamicObject salesorder) {
        DynamicObjectCollection collection = salesorder.getDynamicObjectCollection("yem_es_salescontrac_s");
        List<BigDecimal> res = new ArrayList<>();
        for (DynamicObject dynamicObject : collection) {
            // 是否信保
            String issinosure = dynamicObject.getString("yem_issinosure");
            if ("A".equals(issinosure)) {
                BigDecimal raprate = dynamicObject.getBigDecimal("yem_raprate");
                BigDecimal decimal = BigDecimalUtils.div(raprate, new BigDecimal("100"), 12);
                res.add(decimal);
            }
        }
        return res;
    }

    /**
     * 拼接信保费率
     * @param salesorder
     * @param dataEntity
     */
    private void fillWithCreditRate(DynamicObject salesorder, DynamicObject dataEntity) {
        DynamicObjectCollection collection = salesorder.getDynamicObjectCollection("yem_es_salescontrac_s");
        StringBuilder sb = new StringBuilder();
        for (DynamicObject dynamicObject : collection) {
            // 是否信保
            String issinosure = dynamicObject.getString("yem_issinosure");
            if ("A".equals(issinosure)) {
                BigDecimal sinosurerate = dynamicObject.getBigDecimal("yem_sinosurerate");
                sb.append(sinosurerate).append("；");
            }
        }

        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        dataEntity.set("yem_creditratetext", sb.toString());
    }
}
