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

import com.yem.wm.es.shippingdetails.util.PaymentControlUtil;
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 static com.yem.wm.es.contractamtlist.util.FunUtil.getPayBills;
import static com.yem.wm.es.contractamtlist.util.FunUtil.getShipBills;

/**
 * @author xwudd
 * @Description 寄单放单申请收汇信息分录构建
 * @date 9:52
 **/
public class StorgeTransToExportPresentConvert 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> storageTrans = (List<DynamicObject>) findByEntityKey.getValue("ConvertSource");
            Set<Long> shipIds = new HashSet();
            Set<Long> saleIds = new HashSet();
            for (DynamicObject storageTran : storageTrans) {
                long id = storageTran.getLong("id");
                storageTran = BusinessDataServiceHelper.loadSingle(id, name);
                DynamicObjectCollection materialInfos = storageTran.getDynamicObjectCollection("yem_es_materialinfo");
                for (DynamicObject materialInfo : materialInfos) {
                    shipIds.add(materialInfo.getLong("yem_sourcebillid_d"));
                    saleIds.add(materialInfo.getLong("yem_corebillid_d"));
                }
            }
            Map<Long, DynamicObject> saleMap = new HashMap();
            String selectFields = DynamicObjectUtil.getSelectfields("yem_shippingdetails", false);
            DynamicObject[] shippingDetails = BusinessDataServiceHelper.load("yem_shippingdetails", selectFields,
                    new QFilter[]{new QFilter("id", QCP.in, shipIds)});
            selectFields = DynamicObjectUtil.getSelectfields("yem_es_salesorder", false);
            selectFields = DynamicObjectUtil.getEntrySelectfields(selectFields, "yem_es_salesorder", "yem_es_salescontrac_s", false);
            DynamicObject[] salesOrders = BusinessDataServiceHelper.load("yem_es_salesorder", selectFields,
                    new QFilter[]{new QFilter("id", QCP.in, saleIds)});
            for (DynamicObject salesOrder : salesOrders) {
                saleMap.put(salesOrder.getLong("id"), salesOrder);
            }
            DynamicObjectCollection collectionInfos = dataEntity.getDynamicObjectCollection("yem_es_exportpre_erf");
            for (DynamicObject shippingDetail : shippingDetails) {
                long sourceBillId = shippingDetail.getLong("yem_sourcebillid");
                DynamicObject saleOrder = saleMap.get(sourceBillId);
                if (YEM.isNotEmpty(saleOrder)) {
                    DynamicObject addNew = collectionInfos.addNew();
                    BigDecimal offerAmount = saleOrder.getBigDecimal("yem_offeramount");
                    BigDecimal collectionAmt = PaymentControlUtil.getCollection(sourceBillId);
                    BigDecimal allShipPayment = PaymentControlUtil.getAllBalancePayment("yem_es_salesorder", sourceBillId);
                    BigDecimal allDeliverPayment = PaymentControlUtil.getAllDeliverPayment("yem_es_salesorder", sourceBillId);
//                    BigDecimal rapRate = PaymentControlUtil.getRapRate(saleOrder);
//                    BigDecimal offerAmountBalance = PaymentControlUtil.getAdvancePayment(offerAmount, rapRate);
//                    BigDecimal allDeliverPaymentBalance = PaymentControlUtil.getBalancePayment(allDeliverPayment, rapRate);
                    addNew.set("yem_shipbill", shippingDetail);//出运明细单号
                    addNew.set("yem_saleorder", saleOrder);//外销合同号
                    addNew.set("yem_payment_erf", saleOrder.getDynamicObject("yem_reccondition"));//收款条件
                    addNew.set("yem_receiptcurr", shippingDetail.getDynamicObject("yem_currency"));//出运明细币别
                    addNew.set("yem_contractamt", offerAmount.setScale(2, RoundingMode.HALF_UP));//合同金额
                    addNew.set("yem_contractpayamt", collectionAmt.setScale(2, RoundingMode.HALF_UP));//合同总收款金额
                    addNew.set("yem_contractshipamt", allShipPayment.setScale(2, RoundingMode.HALF_UP));//合同已发运金额
                    addNew.set("yem_shipmentamt_d", allDeliverPayment.setScale(2, RoundingMode.HALF_UP));//合同已发货金额
                    // 欠款金额
                    DynamicObject[] shipBills = getShipBills(saleOrder, dataEntity, "A");//出运
                    DynamicObject[] payBills = getPayBills(saleOrder, dataEntity, "B");//收款单
                    DynamicObject thisShipDetail = null;
                    for (DynamicObject shippingDetailObj : shippingDetails) {
                        long pkValue = (long) shippingDetailObj.getPkValue();
                        long sourcebillid = dataEntity.getLong("yem_sourcebillid");
                        DynamicObject single = BusinessDataServiceHelper.loadSingle(sourcebillid, "yem_es_storagetrans" ,"id, billno, yem_sourcebillid");
                        if (single == null) continue;
                        long shipDetailId = single.getLong("yem_sourcebillid");
                        if (shipDetailId == pkValue) {
                            thisShipDetail = shippingDetailObj;
                            break;
                        }
                    }
                    if (thisShipDetail == null) continue;
                    BigDecimal thisRealityAmt = PaymentControlUtil.getThisRealityAmt(saleOrder, shipBills, payBills, thisShipDetail);
                    addNew.set("yem_debtamt", thisRealityAmt.setScale(2, RoundingMode.HALF_UP));//欠款金额
                }
            }
        }
    }
}
