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

import com.yem.tws.common1.BigDecimalUtils;
import com.yem.wm.utils.DynamicObjectUtil;
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.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lipan
 * @date 2023/11/9 11:03
 * @className DeclareDocxToExportinvoiceBotp
 * @description 出口报关下推出口发票Botp
 */
public class DeclareDocxToExportinvoiceConvert 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) {
            //携带合同中的佣金率
            setRate(findByEntityKey);

            DynamicObject dataEntity = findByEntityKey.getDataEntity();//单据主实体
            bringLatestExRate(dataEntity);
            DynamicObjectCollection yemExportinvoiceC = dataEntity.getDynamicObjectCollection("yem_exportinvoice_c");//报关商品
            DynamicObjectCollection yemExportinvoiceCd = dataEntity.getDynamicObjectCollection("yem_exportinvoice_cd");//报关商品对照表
            DynamicObjectCollection yemEsMaterialinfo = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");///商品明细
            List<String> idList = yemEsMaterialinfo.stream().map(x -> x.getString("yem_fseq")).collect(Collectors.toList());//获取源单序号
            List<String> yem_fgseq = new ArrayList<>();
            for (DynamicObject yemExportinvoiceCds : yemExportinvoiceCd) {
                if (idList.contains(yemExportinvoiceCds.getString("yem_fgseq")))//源单序相等
                {
                    yem_fgseq.add(yemExportinvoiceCds.getString("yem_decgoodsseq"));//报关序号
                }
            }
            BigDecimal yem_sumamt = BigDecimal.ZERO;//金额合计
            for (Iterator<DynamicObject> iterator = yemExportinvoiceC.iterator(); iterator.hasNext(); ) {
                DynamicObject str = iterator.next();
                if (!yem_fgseq.contains(str.getString("yem_fseqexport")))//源单序相等
                {
                    iterator.remove();
                } else {
                    yem_sumamt = yem_sumamt.add(str.getBigDecimal("yem_cusamount"));
                }
            }
            /**
             * 1、出口报关单下推出口发票时，出口发票-报关商品页签分摊金额，计算逻辑：
             * （1）分摊金额=金额/金额合计*（（海运费结算币别+保费结算币别+佣金结算币别）
             * （2）开票金额=金额-分摊金额；
             * （3）开票单价=开票金额/数量；
             * 2、分摊金额的合计值 与   海运费结算币别+保费结算币别+佣金结算币别   需一致，如果分摊产生的尾差，统一调整在报关商品分录的最后一行；
             */
            BigDecimal yem_seabase = dataEntity.getBigDecimal("yem_seabase");//海运费（结算币别）
            BigDecimal yem_insurefeecurrba = dataEntity.getBigDecimal("yem_insurefeecurrba");//保费（结算币别）
            BigDecimal yem_commission = dataEntity.getBigDecimal("yem_commission");//佣金（结算币别）
            BigDecimal sum = yem_seabase.add(yem_insurefeecurrba).add(yem_commission);
            BigDecimal sumyem_shareamt = BigDecimal.ZERO;
//            for (Iterator<DynamicObject> iterator = yemExportinvoiceC.iterator(); iterator.hasNext(); ) {
//                DynamicObject yemExportinvoiceCs = iterator.next();
//                BigDecimal yem_shareamt=yemExportinvoiceCs.getBigDecimal("yem_cusamount").divide(yem_sumamt,4).multiply(sum);
//                yemExportinvoiceCs.set("yem_shareamt",yem_shareamt);//分摊金额
//                sumyem_shareamt=sumyem_shareamt.add(yem_shareamt);
//
//                BigDecimal yem_invoiceamt=yemExportinvoiceCs.getBigDecimal("yem_cusamount").subtract(yem_shareamt);
//                yemExportinvoiceCs.set("yem_invoiceamt",yem_invoiceamt);//开票金额
//
//                BigDecimal yem_invoiceprice=yem_invoiceamt.divide(yemExportinvoiceCs.getBigDecimal("yem_cusqty"));
//                yemExportinvoiceCs.set("yem_invoiceprice",yem_invoiceprice);//开票单价
//
//                if (!iterator.hasNext())
//                {
//                    yemExportinvoiceCs.set("yem_shareamt",  sum.subtract(sumyem_shareamt).add(yem_shareamt));//分摊金额
//                }
//
//            }

            calculatePremium(dataEntity);
        }
    }

    /**
     * 获取出口日期的海运费汇率 保费汇率
     *
     * @param dataEntity
     */
    private void bringLatestExRate(DynamicObject dataEntity) {
        // 本位币
        long currencybase = dataEntity.getLong("yem_currencybase.id");
        // 海运费币别
        long seacurryId = dataEntity.getLong("yem_seatransfeecurr.id");
        // 保费币别
        long insurecurry = dataEntity.getLong("yem_insurefeecurr.id");
        // 出口日期
        Date date = dataEntity.getDate("yem_exportationdate");
        // 汇率表
        DynamicObject exratetable = dataEntity.getDynamicObject("yem_exratetable");

        if (YEM.isNotEmpty(exratetable) && YEM.isNotEmpty(currencybase) && YEM.isNotEmpty(seacurryId) && YEM.isNotEmpty(date)) {
            BigDecimal rate = YEM.getExchangeRate(exratetable, seacurryId, currencybase, date);
            dataEntity.set("yem_seatransfeerate", rate);
        }

        if (YEM.isNotEmpty(exratetable) && YEM.isNotEmpty(currencybase) && YEM.isNotEmpty(insurecurry) && YEM.isNotEmpty(date)) {
            BigDecimal rate = YEM.getExchangeRate(exratetable, insurecurry, currencybase, date);
            dataEntity.set("yem_insurefeesexrate", rate);
        }
    }

    /**
     * 计算保费
     *
     * @param dataEntity 出口发票
     */
    private void calculatePremium(DynamicObject dataEntity) {
        long sourcebillid = dataEntity.getLong("yem_sourcebillid");
        // 出口报关单
        DynamicObject single = BusinessDataServiceHelper.loadSingle(sourcebillid, "yem_es_declaredocx");
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        BigDecimal sourceAmt = BigDecimal.ZERO;
        for (DynamicObject dynamicObject : collection) {
            BigDecimal sellamt = dynamicObject.getBigDecimal("yem_sellamt");
            sourceAmt = sourceAmt.add(sellamt);
        }
        BigDecimal amt = BigDecimal.ZERO;
        DynamicObjectCollection sourceEntry = single.getDynamicObjectCollection("yem_es_materialinfo");
        for (DynamicObject dynamicObject : sourceEntry) {
            BigDecimal sellamt = dynamicObject.getBigDecimal("yem_sellamt");
            amt = amt.add(sellamt);
        }

        BigDecimal reightamt = single.getBigDecimal("yem_premiumamt");
        BigDecimal multiply = BigDecimalUtils.div(sourceAmt, amt, 12).multiply(reightamt).setScale(2, RoundingMode.HALF_UP);
        dataEntity.set("yem_insurefee", multiply);

        //保费（本位币）
        BigDecimal yem_insurefeebase = dataEntity.getBigDecimal("yem_insurefee").multiply(dataEntity.getBigDecimal("yem_insurefeesexrate"));
        dataEntity.set("yem_insurefeebase", yem_insurefeebase);

        //报关单（海运费/金额）
        BigDecimal yem_count = dataEntity.getBigDecimal("yem_count");
        //销售金额合计值 1,295,997.50
        BigDecimal yem_localamountsum = BigDecimal.ZERO;
        DynamicObjectCollection yem_exportinvoice_c = dataEntity.getDynamicObjectCollection("yem_exportinvoice_c");
        for (DynamicObject yem_exportinvoice : yem_exportinvoice_c) {
            BigDecimal yem_localamount = yem_exportinvoice.getBigDecimal("yem_localamount");
            yem_localamountsum = yem_localamountsum.add(yem_localamount);
        }
        //汇率
        BigDecimal yem_seatransfeerate = dataEntity.getBigDecimal("yem_seatransfeerate");
        //海运费原币
        BigDecimal multiply1 = yem_count.multiply(yem_localamountsum).setScale(2,BigDecimal.ROUND_HALF_UP);
        //海运费（本位币）
        BigDecimal yem_seatransfeebase = yem_seatransfeerate.multiply(multiply1).setScale(2,BigDecimal.ROUND_HALF_UP);
        //佣金
        BigDecimal yem_commissionba = dataEntity.getBigDecimal("yem_commissionba");
        BigDecimal ybz = yem_seatransfeebase.add(yem_insurefeebase).add(yem_commissionba);
        for (DynamicObject exportinvoice : yem_exportinvoice_c) {
            BigDecimal yem_localamount = exportinvoice.getBigDecimal("yem_localamount");
            if (yem_localamount.compareTo(BigDecimal.ZERO) == 1) {
                BigDecimal yem_localassessedamo = ybz.multiply(yem_localamount).divide(yem_localamountsum, 10, BigDecimal.ROUND_HALF_UP);
                exportinvoice.set("yem_localassessedamo", yem_localassessedamo);
                // 开票金额（本位币） = 金额（本位币） - 分摊金额（本位币）
                BigDecimal localamount = exportinvoice.getBigDecimal("yem_localamount"); // 金额（本位币）\
                BigDecimal localinvoicedamo = localamount.subtract(yem_localassessedamo);
                exportinvoice.set("yem_localinvoicedamo", localinvoicedamo);
                // yem_localinvoicingunit = yem_localinvoicedamo / yem_cusqty
                // 开票单价（本位币） = 开票金额（本位币） / 数量
                BigDecimal cusqty = exportinvoice.getBigDecimal("yem_cusqty");
                exportinvoice.set("yem_localinvoicingunit", BigDecimalUtils.div(localinvoicedamo, cusqty, 2));
            }
        }

    }

    /**
     * 根据分录合同、获取佣金汇率 zlp
     */

    private static void setRate(ExtendedDataEntity entity) {
        // 出口发票
        DynamicObject dataEntity = entity.getDataEntity();
        DynamicObjectCollection materialinfo = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        Set<String> set = new LinkedHashSet<>();
        for (DynamicObject dt : materialinfo) {
            String string = dt.getString("yem_contractnumbers_m");
            set.add(string);
        }
        List<String> list = new ArrayList<>(set);

        DynamicObject[] load = BusinessDataServiceHelper.load("yem_es_salesorder", DynamicObjectUtil.getSelectfields("yem_es_salesorder", false) + ", yem_es_materialinfo.yem_onecarcom",
                new QFilter[]{new QFilter("billstatus", QCP.equals, "C"),
                        new QFilter("yem_incommission", QCP.equals, "A"),
                        new QFilter("billno", QCP.in, list)});
        if (load != null && load.length > 0) {
            // 外销合同
            DynamicObject dynamicObject = load[0];
            BigDecimal yemCnexrate = dynamicObject.getBigDecimal("yem_cnexrate");
            entity.setValue("yem_amountrate", yemCnexrate);

//            // 佣金方式
//            String commissionmethod = dynamicObject.getString("yem_commissionmethod");
//            DynamicObjectCollection collection = dynamicObject.getDynamicObjectCollection("yem_es_materialinfo");
//            for (DynamicObject salesorder : materialinfo) {
//                for (DynamicObject object : collection) {
//                    Long pkValue = (Long) object.getPkValue();
//                    // 单台佣金
//                    BigDecimal onecarcom = object.getBigDecimal("yem_onecarcom");
//                    if (pkValue == salesorder.getLong("yem_coreentryid")) {
//                        // 明佣 A | 暗佣 B
//                        if ("A".equals(commissionmethod)) {
//                            // 如果关联的外销合同-付佣方式为暗佣，则不需要取值
//                            salesorder.set("yem_onecarcom", onecarcom);
//                        } else {
//                            salesorder.set("yem_onecarcom", BigDecimal.ZERO);
//                        }
//                    }
//                }
//            }
        }
    }
}
