package com.yem.wm.im.delivernotice.op;

import com.yem.wm.es.shippingdetails.util.PaymentControlUtil;
import com.yem.wm.im.delivernotice.validator.DeliverNoticeEASValidator;
import com.yem.wm.im.delivernotice.validator.DeliverNoticeSubmitValidator;
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.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.yem.wm.es.storagetrans.form.StorageTransEdit.calculateExportAmount;

/**
 * @author xwudd
 * @Description
 * @date 15:35
 **/
public class DeliverNoticeSubmitOp extends AbstractOperationServicePlugIn {


    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_corebilltype");
        fieldKeys.add("yem_corebillid");
        fieldKeys.add("yem_totalallamount");
        fieldKeys.add("yem_sourcebillid");
        fieldKeys.add("billno");
        fieldKeys.add("yem_es_materialinfo");
        fieldKeys.add("yem_sourceentryid");
        fieldKeys.add("yem_isaccgift");
        fieldKeys.add("yem_acccurrency");
        fieldKeys.add("yem_accrate");
        fieldKeys.add("yem_saleorder");
        fieldKeys.add("yem_products");
        fieldKeys.add("yem_productstree");
        fieldKeys.add("yem_num");
        fieldKeys.add("yem_singleaccamt");
        fieldKeys.add("yem_singleaccamtbase");
        fieldKeys.add("yem_accamt");
        fieldKeys.add("yem_accamtbase");
        fieldKeys.add("yem_remarke");
        fieldKeys.add("yem_contractallamt");
        fieldKeys.add("yem_contractadvanceamt");
        fieldKeys.add("yem_deliveramt");
        fieldKeys.add("yem_thisdeliveramt");
        fieldKeys.add("yem_thisrealityamt");
        fieldKeys.add("yem_amt");
        fieldKeys.add("yem_qty");
        fieldKeys.add("yem_contractnum");
        fieldKeys.add("yem_customer");
        fieldKeys.add("yem_es_materialinfo");
        fieldKeys.add("yem_es_materialinfo.yem_materiel");
        fieldKeys.add("yem_es_materialinfo.seq");
        fieldKeys.add("yem_company");
    }

    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        super.onAddValidators(e);
        e.addValidator(new DeliverNoticeSubmitValidator());
        e.addValidator(new DeliverNoticeEASValidator());
//        e.addValidator(new DeliverNoticeValidator());
    }


    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {
        super.endOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
        for (DynamicObject dataEntitie : dataEntities) {
            dataEntitie = BusinessDataServiceHelper.loadSingle(dataEntitie.getPkValue(), dataEntitie.getDynamicObjectType().getName());
            setAccGiftInfo(dataEntitie);
            setArrearsAmt(dataEntitie);
            SaveServiceHelper.save(new DynamicObject[]{dataEntitie});
            //反写储运托单中的 关联发货数量
            setValueToStorage(dataEntitie);
        }

    }


    /**
     * @description 赋值赠送配件分录
     * @author xwudd
     * @param[1] dataEntitie
     * return
     * @time 2023/11/15 10:12
     */

    public void setAccGiftInfo(DynamicObject dataEntitie) {
        String coreBillType = dataEntitie.getString("yem_corebilltype");
        long coreBillId = dataEntitie.getLong("yem_corebillid");
        if (coreBillType.length() > 0 && coreBillId > 0) {
            DynamicObject saleOrder = BusinessDataServiceHelper.loadSingle(coreBillId, coreBillType);
            if (YEM.isNotEmpty(saleOrder)) {
                String isGiftGiveParts = saleOrder.getString("yem_isgiftgiveparts");
                if ("A".equals(isGiftGiveParts)) {
                    Map<Long, BigDecimal> map = new HashMap();
                    DynamicObjectCollection materialInfos = dataEntitie.getDynamicObjectCollection("yem_es_materialinfo");
                    for (DynamicObject materialInfo : materialInfos) {
                        DynamicObject productModel = materialInfo.getDynamicObject("yem_productmodel");
                        BigDecimal qty = materialInfo.getBigDecimal("yem_qty");
                        if (YEM.isNotEmpty(productModel)) {
                            DynamicObject products = productModel.getDynamicObject("yem_products");
                            if (YEM.isNotEmpty(products)) {
                                long id = products.getLong("id");
                                if (map.containsKey(id)) {
                                    map.put(id, qty.add(map.get(id)));
                                } else {
                                    map.put(id, qty);
                                }
                            }
                        }
                    }
                    dataEntitie.set("yem_isaccgift", true);//是否配件赠送
                    dataEntitie.set("yem_acccurrency", saleOrder.get("yem_givecurrency"));//配件币别
                    dataEntitie.set("yem_accrate", saleOrder.get("yem_givedecimal"));//配件汇率
                    DynamicObjectCollection deliverGiftAccInfos = dataEntitie.getDynamicObjectCollection("yem_giftaccentry");
                    DynamicObjectCollection saleAccGiftInfos = saleOrder.getDynamicObjectCollection("yem_es_salesorder_zp");
                    deliverGiftAccInfos.clear();
                    for (DynamicObject saleAccGiftInfo : saleAccGiftInfos) {
                        DynamicObject giveProAcType = saleAccGiftInfo.getDynamicObject("yem_giveproactype");
                        if (YEM.isNotEmpty(giveProAcType)) {
                            long id = giveProAcType.getLong("id");
                            BigDecimal qty = map.get(id);
                            if (YEM.isNotEmpty(qty) && qty.compareTo(BigDecimal.ZERO) > 0) {
                                DynamicObject addNew = deliverGiftAccInfos.addNew();
                                BigDecimal singleAmt = saleAccGiftInfo.getBigDecimal("yem_singleamt");
                                BigDecimal singleAmtLocal = saleAccGiftInfo.getBigDecimal("yem_singleamtlocal");
                                addNew.set("yem_num", qty);//台数
                                addNew.set("yem_products", giveProAcType.get("group"));//产品类型
                                addNew.set("yem_productstree", giveProAcType);//产品机型
                                addNew.set("yem_saleorder", saleOrder);//外销合同号
                                addNew.set("yem_singleaccamt", singleAmt);//单台配件金额
                                addNew.set("yem_singleaccamtbase", singleAmtLocal);//单台配件金（本位币）
                                addNew.set("yem_accamt", qty.multiply(singleAmt));//配件金额
                                addNew.set("yem_accamtbase", qty.multiply(singleAmtLocal));//配件金额（本位币）
                                addNew.set("yem_remarke", saleAccGiftInfo.get("yem_giveremark"));//备注
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * @description 反写储运托单 关联发货数量  发货通知单单号
     * @author zlp
     * @param[1] dataEntitie
     * return
     * @time 2023/11/10
     */
    public void setValueToStorage(DynamicObject dataEntitie) {
        //key 发货通知单分录行Id  value 出运明细分录行id
        HashMap<Long, BigDecimal> map = new HashMap();
        HashMap<Long, BigDecimal> mapAmount = new HashMap();
        DynamicObjectCollection entryDeliver = dataEntitie.getDynamicObjectCollection("yem_es_materialinfo");
        for (DynamicObject entry : entryDeliver) {
            map.put(entry.getLong("yem_sourceentryid"), entry.getBigDecimal("yem_qty"));
            mapAmount.put(entry.getLong("yem_sourceentryid"), entry.getBigDecimal("yem_amountandtax"));
        }
        Set<Long> longs = map.keySet();
        String selectfields = DynamicObjectUtil.getSelectfields("yem_es_storagetrans");
        String entrySelectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_es_storagetrans", "yem_es_materialinfo");
        DynamicObject[] storagetrans = BusinessDataServiceHelper.load("yem_es_storagetrans", entrySelectfields, new QFilter[]{
                new QFilter("yem_es_materialinfo.yem_sourceentryid", QCP.in, longs)
        });
        if (storagetrans != null && storagetrans.length > 0) {
            for (DynamicObject dt : storagetrans) {
                DynamicObjectCollection materialinfo = dt.getDynamicObjectCollection("yem_es_materialinfo");
                for (DynamicObject entry : materialinfo) {
                    long sourceentryid = entry.getLong("yem_sourceentryid");
                    if (map.containsKey(sourceentryid)) {
                        BigDecimal yemAdstqty = entry.getBigDecimal("yem_adstqty");
                        BigDecimal yemAdstamount = entry.getBigDecimal("yem_adstamount");
                        BigDecimal decimal = map.get(sourceentryid);
                        BigDecimal amt = mapAmount.get(sourceentryid);
                        if (decimal != null) {
                            entry.set("yem_adstqty", decimal.add(yemAdstqty));
                        }
                        if (amt != null) {
                            entry.set("yem_adstamount", amt.add(yemAdstamount));
                        }
                        String sgnenumber = entry.getString("yem_sgnenumber");
                        if (YEM.isNotEmpty(sgnenumber) && !sgnenumber.contains(dataEntitie.getString("billno"))) {
                            entry.set("yem_sgnenumber", sgnenumber + ";" + dataEntitie.getString("billno"));

                        } else {
                            entry.set("yem_sgnenumber", dataEntitie.getString("billno"));
                        }

                    }
                }
                calculateExportAmount(dt);
            }
            SaveServiceHelper.save(storagetrans);
        }
    }

    /**
     * @description 欠款字段赋值
     * @author xwudd
     * @param[1] dataEntitie
     * return
     * @time 2023/11/14 16:44
     */

    public void setArrearsAmt(DynamicObject dataEntitie) {
        String coreBillType = dataEntitie.getString("yem_corebilltype");
        long coreBillId = dataEntitie.getLong("yem_corebillid");
        if (coreBillType.length() > 0 && coreBillId > 0) {
            DynamicObject saleOrder = BusinessDataServiceHelper.loadSingle(coreBillId, coreBillType);
            BigDecimal rapRate = PaymentControlUtil.getRapRate(saleOrder);
            BigDecimal collection = PaymentControlUtil.getCollection(coreBillId);//A 合同的所有收款
            BigDecimal contractPayment = PaymentControlUtil.getAdvancePayment(PaymentControlUtil.getContractPayment(saleOrder), rapRate);//B 合同的预收款
            BigDecimal deliverPayment = PaymentControlUtil.getAllDeliverPayment(coreBillType, coreBillId);//C 外销合同号向下所有提交+已审核的发货通知单-财务信息-价税合计的合计值
            BigDecimal translateDeliverPayment = PaymentControlUtil.getBalancePayment(PaymentControlUtil.getTranslateDeliverPayment(dataEntitie), rapRate);//D 本次发货尾款
            BigDecimal arrearsAmt = collection.subtract(contractPayment).subtract(deliverPayment).subtract(translateDeliverPayment);
            if (arrearsAmt.compareTo(BigDecimal.ZERO) < 0) {
                BigDecimal fAbs = arrearsAmt.abs();
                dataEntitie.set("yem_thisrealityamt", fAbs.setScale(2, RoundingMode.HALF_UP));
            } else {
                dataEntitie.set("yem_thisrealityamt", BigDecimal.ZERO);
            }
            dataEntitie.set("yem_contractallamt", collection.setScale(2, RoundingMode.HALF_UP));
            dataEntitie.set("yem_contractadvanceamt", contractPayment.setScale(2, RoundingMode.HALF_UP));
            dataEntitie.set("yem_deliveramt", deliverPayment.setScale(2, RoundingMode.HALF_UP));
            dataEntitie.set("yem_thisdeliveramt", translateDeliverPayment.setScale(2, RoundingMode.HALF_UP));
        }
    }
}
