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

import com.yem.ensign.common.CommonUtils;
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.AfterBuildDrawFilterEventArgs;
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.*;

/**
 * @author xwudd
 * @date 15:17
 * @Description
 **/
public class ShippingDetialToStoraConvert extends AbstractConvertPlugIn
{

    @Override
    public void afterBuildDrawFilter(AfterBuildDrawFilterEventArgs e)
    {
        super.afterBuildDrawFilter(e);
        Long org = Long.valueOf(getOption().getVariableValue("org"));
        Long customer = Long.valueOf(getOption().getVariableValue("customer"));
        //过滤单据类型是：外贸出运配件的  已审核的    发运明细单
        Set<String> strArray = new HashSet<>();
        strArray.add("yem_shippingdetails_pj");
        strArray.add("yem_shippingdetails_zj");
        QFilter qFilter = new QFilter("org.id", QCP.equals, org).and(new QFilter("yem_customer.id", QCP.equals, customer)).and(new QFilter("yem_billtype.number", QCP.in, strArray)).and(new QFilter("billstatus", QCP.equals, "C"));
        e.setPlugFilter(qFilter);
    }

    @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);
        ExtendedDataEntity[] entities = e.getTargetExtDataEntitySet().FindByEntityKey(name);
        for (ExtendedDataEntity findByEntityKey : findByEntityKeys) {
            DynamicObject dataEntity = findByEntityKey.getDataEntity();

            DynamicObjectCollection materialinfo = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
            Set<String> set = new HashSet<>();
            for (DynamicObject dynamicObject : materialinfo) {
                set.add(dynamicObject.getString("yem_contractnumbers_m"));
            }

            Map<String, List<DynamicObject>> map = new HashMap<>();
            for (String billno : set) {
                DynamicObject saleOrder = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", new QFilter[]{new QFilter("billno", QCP.equals, billno)});
                if (saleOrder == null) continue;
                // 外销合同 收款计划
                DynamicObjectCollection salescontracs = saleOrder.getDynamicObjectCollection("yem_es_salescontrac_s");
                List<DynamicObject> list = new ArrayList<>();
                for (DynamicObject salescontrac : salescontracs) {
                    // 是否信保
                    String issinosure = salescontrac.getString("yem_issinosure");
                    if ("A".equals(issinosure)) {
                        list.add(salescontrac);
                    }
                }
                map.put(billno, list);
            }
            DynamicObjectCollection creditdetail = dataEntity.getDynamicObjectCollection("yem_creditdetail");
            creditdetail.clear();
            // 订舱收款计划
            DynamicObjectCollection current = dataEntity.getDynamicObjectCollection("yem_es_salescontrac_s");
            current.clear();

            Set<Map.Entry<String, List<DynamicObject>>> entries = map.entrySet();
            for (Map.Entry<String, List<DynamicObject>> entry : entries) {
                String billno = entry.getKey();
                List<DynamicObject> list = entry.getValue();
                DynamicObject single = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", new QFilter[]{new QFilter("billno", QCP.equals, billno)});
                // 订舱通知单 信保明细

                String currency = dataEntity.getString("yem_currency.number");
                BigDecimal exrate = dataEntity.getBigDecimal("yem_exrate");
                for (DynamicObject dynamicObject : list) {
                    DynamicObject addNew = creditdetail.addNew();
                    // 外销合同号
                    Long pkValue = (Long) single.getPkValue();
                    addNew.set("yem_salecontractno", single);
                    // 储运合同金额
                    BigDecimal storageAmount = getStorageAmountSum(billno, dataEntity);
                    addNew.set("yem_storagetransamt", storageAmount);
                    // 结算方式
                    DynamicObject rapstyle = (DynamicObject) dynamicObject.get("yem_rapstyle");
                    addNew.set("yem_quotation_cd", rapstyle);
                    // 信保结算方式
                    addNew.set("yem_creditquotation", rapstyle);
                    // 收款条件
                    addNew.set("yem_reccondition_cd", dynamicObject.get("yem_payment"));
                    // 预收比例%
                    BigDecimal raprate = getRaprate(single);
                    addNew.set("yem_preradio_cd", raprate);
                    // 预收金额
                    addNew.set("yem_preamt_cd", raprate.multiply(storageAmount).divide(new BigDecimal(100), 4, RoundingMode.HALF_UP));
                    // 合同认领金额
                    Map<String, Object> amount = getContractClaimAmount(dataEntity, billno);
                    addNew.set("yem_contractclaiamt_cd", amount.get("claimAmt"));
                    // 储运认领金额
                    addNew.set("yem_stclaiamt_cd", amount.get("shipClaimAmt"));
                    // 投保金额（原币）
                    addNew.set("yem_creditamt_cd", storageAmount);

                    // 信保本位币金额
                    addNew.set("yem_creditamtbase", storageAmount.multiply(exrate));

                    if ("USD".equals(currency)) {
                        // 投保金额（美元）
                        addNew.set("yem_usacreditamt_cd", storageAmount);

                    } else {
                        storageAmount = BigDecimal.ZERO;
                        addNew.set("yem_usacreditamt_cd", BigDecimal.ZERO);
                    }

                    // 信保费率（合同取）
//                    DynamicObject term = (DynamicObject) dynamicObject.get("yem_term");
//                    DynamicObject clientCountry = dataEntity.getDynamicObject("yem_clientcountry");
//                    DynamicObject countrySignals = TotalUtil.getCountrySignals(clientCountry);
//                    if (YEM.isNotEmpty(countrySignals)) {
//                        BigDecimal signals = TotalUtil.getSignals(countrySignals, rapstyle, term);
//                    }
                    BigDecimal sinosurerate = (BigDecimal) dynamicObject.get("yem_sinosurerate");
                    addNew.set("yem_sinosurerate_cd", sinosurerate);
                    // yem_insuranceamt_cd = yem_usacreditamt_cd * yem_sinosurerate_cd / 100
                    BigDecimal insuranceamt = storageAmount.multiply(sinosurerate).divide(new BigDecimal("100"), 10, RoundingMode.HALF_UP);
                    // 保险费
                    addNew.set("yem_insuranceamt_cd", insuranceamt);
                    // 信用期限
                    addNew.set("yem_term_cd", dynamicObject.get("yem_term"));

                    // 保险费本位币金额
                    addNew.set("yem_insuranceamtbas_cd", insuranceamt.multiply(exrate));
//                    //SWIFT CODE
//                    addNew.set("yem_swiftcode", dynamicObject.get("yem_swiftcode"));
                }

                // 合同收款计划
                DynamicObjectCollection collection = single.getDynamicObjectCollection("yem_es_salescontrac_s");

                for (DynamicObject dynamicObject : collection) {
                    DynamicObject addNew = current.addNew();

                    addNew.set("yem_contractnumbers_p", billno);
//                    addNew.set("yem_shipmentnumbers_p", dynamicObject.get("yem_shipmentnumbers_p"));
                    addNew.set("yem_rapstyle", dynamicObject.get("yem_rapstyle"));
                    addNew.set("yem_issinosure", dynamicObject.get("yem_issinosure"));
                    addNew.set("yem_sinosurerate", dynamicObject.get("yem_sinosurerate"));
                    addNew.set("yem_term", dynamicObject.get("yem_term"));
                    addNew.set("yem_payment", dynamicObject.get("yem_payment"));
                    addNew.set("yem_raprate", dynamicObject.get("yem_raprate"));
                    addNew.set("yem_ispre", dynamicObject.get("yem_ispre"));
                    addNew.set("yem_rapamt", dynamicObject.get("yem_rapamt"));
                    addNew.set("yem_recadvancedate", dynamicObject.get("yem_recadvancedate"));
                    addNew.set("yem_swiftcode", dynamicObject.get("yem_swiftcode"));
                    addNew.set("yem_rapcontent", dynamicObject.get("yem_rapcontent"));
                    addNew.set("yem_lcnumber", dynamicObject.get("yem_lcnumber"));
                }
            }

            //下推后计算 海运费汇率
            DynamicObject yemCurrencybase = dataEntity.getDynamicObject("yem_currencybase");
            DynamicObject yemCurrencyfreight = dataEntity.getDynamicObject("yem_currencyfreight");
            DynamicObject yemExratetable = dataEntity.getDynamicObject("yem_exratetable");
            DynamicObject org = dataEntity.getDynamicObject("org");
            if (org != null && yemCurrencyfreight != null && yemCurrencybase != null && yemExratetable != null) {
                BigDecimal exchangeRate = CommonUtils.getExchangeRate(yemExratetable.getLong("id"), yemCurrencyfreight.getLong("id"), yemCurrencybase.getLong("id"), org.getLong("id"), new Date());
                dataEntity.set("yem_freightrate", exchangeRate);
            }
            //携带明细信息 物料中净重
            DynamicObjectCollection yem_es_materialinfo = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
            HashMap<Long, BigDecimal> datas = new HashMap();
            for (DynamicObject object : yem_es_materialinfo) {
                DynamicObject yemMateriel = object.getDynamicObject("yem_materiel");
                if (yemMateriel != null) {
                    datas.put(yemMateriel.getLong("id"), BigDecimal.ZERO);
                }
            }

            DynamicObject[] load = BusinessDataServiceHelper.load("bd_material", "id,netweight,grossweight", new QFilter[]{new QFilter("id", QCP.in, datas.keySet())});
            BigDecimal sumMweight = BigDecimal.ZERO;
            BigDecimal sumJweight = BigDecimal.ZERO;
            BigDecimal sumVm = BigDecimal.ZERO;
            for (DynamicObject object : yem_es_materialinfo) {
                DynamicObject yemMincabinet = object.getDynamicObject("yem_mincabinet");
                BigDecimal yemVolumeMin = BigDecimal.ZERO;
                BigDecimal yemVolumeBig = BigDecimal.ZERO;
                BigDecimal minQty = BigDecimal.ZERO;
                BigDecimal bigQty = BigDecimal.ZERO;
                if (yemMincabinet != null) {
                    yemVolumeMin = yemMincabinet.getBigDecimal("yem_volume");
                    object.set("yem_minvm", yemVolumeMin);
                }
                DynamicObject yemBigcabinet = object.getDynamicObject("yem_bigcabinet");
                if (yemBigcabinet != null) {
                    yemVolumeBig = yemBigcabinet.getBigDecimal("yem_volume");
                    object.set("yem_bigvm", yemVolumeBig);
                }
                bigQty = object.getBigDecimal("yem_bigcabinetnumbers");
                minQty = object.getBigDecimal("yem_mincabinetnumbers");
                object.set("yem_volm3sum", minQty.multiply(yemVolumeMin).add(bigQty.multiply(yemVolumeBig)));
                DynamicObject yemMateriel = object.getDynamicObject("yem_materiel");
                if (yemMateriel != null) {
                    long aLong = yemMateriel.getLong("id");
                    BigDecimal netweight = BigDecimal.ZERO;
                    BigDecimal grossweight = BigDecimal.ZERO;
                    for (DynamicObject loadSon : load) {
                        if (aLong != 0l && aLong == loadSon.getLong("id")) {
                            netweight = loadSon.getBigDecimal("netweight");
                            grossweight = loadSon.getBigDecimal("grossweight");
                        }
                    }
                    object.set("yem_netweight", netweight);
                    object.set("yem_netweightsum", netweight.multiply(object.getBigDecimal("yem_qty")));
                    object.set("yem_grossweight", netweight);
                    object.set("yem_grossweightsum", netweight.multiply(object.getBigDecimal("yem_qty")));
                }
                sumMweight = sumMweight.add(object.getBigDecimal("yem_grossweightsum"));
                sumJweight = sumJweight.add(object.getBigDecimal("yem_netweightsum"));
                sumVm = sumVm.add(object.getBigDecimal("yem_volm3sum"));
            }
            dataEntity.set("yem_boxgwsum", sumMweight);
            dataEntity.set("yem_boxnwsum", sumJweight);
            dataEntity.set("yem_boxvolsum", sumVm);



        }
    }

    private BigDecimal getRaprate(DynamicObject single)
    {
        BigDecimal raprate = BigDecimal.ZERO;
        DynamicObjectCollection collection = single.getDynamicObjectCollection("yem_es_salescontrac_s");
        for (DynamicObject object : collection) {
            if (object.getBoolean("yem_ispre")) {
                raprate = raprate.add(object.getBigDecimal("yem_raprate"));
            }
        }
        return raprate;
    }

    private BigDecimal getStorageAmountSum(String billno, DynamicObject dataEntity)
    {
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        BigDecimal totalAmt = BigDecimal.ZERO;
        for (DynamicObject object : collection) {
            if (billno.equals(object.getString("yem_contractnumbers_m"))) {
                totalAmt = totalAmt.add(object.getBigDecimal("yem_saamtpriceclause"));
            }
        }
        return totalAmt;
    }

    // 储运合同金额
    private BigDecimal getStorageAmount(DynamicObject dataEntity)
    {
        DynamicObject shippingDetail = getSourceBill(dataEntity);
        if (shippingDetail == null) return BigDecimal.ZERO;
        BigDecimal totalAmt = BigDecimal.ZERO;
        DynamicObjectCollection shippingMaterialEntrys = shippingDetail.getDynamicObjectCollection("yem_es_materialinfo");
        for (DynamicObject shippingMaterialEntry : shippingMaterialEntrys) {
            BigDecimal unStorageQty = shippingMaterialEntry.getBigDecimal("yem_unstorageqty");
            BigDecimal saPricePriceClause = shippingMaterialEntry.getBigDecimal("yem_sapricepriceclause");
            totalAmt = totalAmt.add(unStorageQty.multiply(saPricePriceClause));
        }
        return totalAmt;
    }

    // 获取来源单据
    private DynamicObject getSourceBill(DynamicObject dataEntity)
    {
        long sourcebillid = dataEntity.getLong("yem_sourcebillid");
        return BusinessDataServiceHelper.loadSingle(sourcebillid, "yem_shippingdetails");
    }

    // 合同认领金额
    private Map<String, Object> getContractClaimAmount(DynamicObject dataEntity, String billno)
    {
        DynamicObject bill = getSourceBill(dataEntity);
        String billNo = bill.getString("billno");
        Map<String, Object> map = new HashMap<>();
        String selectfields = DynamicObjectUtil.getSelectfields("yem_gathering", false);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_gathering", "yem_receiptdetail", false);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_gathering", "yem_receiptdetail", "yem_claimdetail", false);
        DynamicObject[] gatherings = BusinessDataServiceHelper.load("yem_gathering", selectfields, new QFilter[]{new QFilter("yem_claimdetail.yem_salcontractno", QCP.equals, billno), new QFilter("billstatus", QCP.equals, "C")});
        for (DynamicObject gathering : gatherings) {
            DynamicObjectCollection receiptDetails = gathering.getDynamicObjectCollection("yem_receiptdetail");
            for (DynamicObject receiptDetail : receiptDetails) {
                DynamicObjectCollection claimDetails = receiptDetail.getDynamicObjectCollection("yem_claimdetail");
                for (DynamicObject claimDetail : claimDetails) {
                    DynamicObject salContract = claimDetail.getDynamicObject("yem_salcontractno");
                    if (YEM.isNotEmpty(salContract)) {
                        String salContractNo = salContract.getString("billno");
                        BigDecimal claimAmt = claimDetail.getBigDecimal("yem_claimamt");
                        if (billno.equals(salContractNo)) {
                            if (map.containsKey("claimAmt")) {
                                map.put("claimAmt", claimAmt.add((BigDecimal) map.get("claimAmt")));
                            } else {
                                map.put("claimAmt", claimAmt);
                            }
                        }
                    }
                    DynamicObject shippingDetailsObj = claimDetail.getDynamicObject("yem_shippingdetailsno");
                    if (YEM.isNotEmpty(shippingDetailsObj)) {
                        String shippingDetailsNo = shippingDetailsObj.getString("billno");
                        BigDecimal shipClaimAmt = claimDetail.getBigDecimal("yem_shipclaimamt");
                        if (shippingDetailsNo.equals(billNo)) {
                            if (map.containsKey("shipClaimAmt")) {
                                map.put("shipClaimAmt", shipClaimAmt.add((BigDecimal) map.get("shipClaimAmt")));
                            } else {
                                map.put("shipClaimAmt", shipClaimAmt);
                            }
                        }
                    }
                }
            }
        }
        return map;
    }
}
