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

import com.yem.wm.es.contractamtlist.util.FunUtil;
import com.yem.wm.es.shippingdetails.util.PaymentControlUtil;
import com.yem.wm.utils.YEM;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.operate.FormOperate;
import kd.bos.list.plugin.AbstractListPlugin;
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.util.HashSet;
import java.util.Set;

import static com.yem.wm.es.contractamtlist.util.FunUtil.getPayBills;
import static com.yem.wm.es.contractamtlist.util.FunUtil.getShipBills;
import static com.yem.wm.es.shippingdetails.util.PaymentControlUtil.calcIOUAmount;

/**
 * @Description TODO
 * @Date 2024/1/24 21:09
 * @Created by ZZSLL
 */

public class ShippingDetailsListPlugin extends AbstractListPlugin
{
    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args)
    {
        super.beforeDoOperation(args);
        FormOperate operation = (FormOperate) args.getSource();
        String operateKey = operation.getOperateKey();
        if ("push".equals(operateKey)) {
            ListSelectedRowCollection rows = this.getSelectedRows();
            Object[] keyValues = rows.getPrimaryKeyValues();
            Set<Long> set = new HashSet<>();
            for (Object keyValue : keyValues) {
                set.add((Long) keyValue);
            }
            for (Long keyValue : set) {
                DynamicObject dataEntity = BusinessDataServiceHelper.loadSingle(keyValue, "yem_shippingdetails");
                String saleorderno = dataEntity.getString("yem_saleorderno");
                if (YEM.isEmpty(saleorderno)) return;
                DynamicObject saleOrder = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", new QFilter[]{new QFilter("billno", QCP.equals, saleorderno)});
                if (saleOrder == null) return;
                DynamicObject[] shipBills = getShipBills(saleOrder, dataEntity, "A");//出运
                DynamicObject[] payBills = getPayBills(saleOrder, dataEntity, "B");//收款单
                BigDecimal thisRealityAmt = PaymentControlUtil.getThisRealityAmt(saleOrder, shipBills, payBills, dataEntity);
                dataEntity.set("yem_arrearsamt", thisRealityAmt);//本次发运欠款金额
                dataEntity.set("yem_arrearsamtapply", FunUtil.getAbs(thisRealityAmt));//本次发运应申请欠条金额

                BigDecimal decimal = calcIOUAmount(dataEntity);
                dataEntity.set("yem_iouamount", decimal);

                SaveServiceHelper.save(new DynamicObject[]{dataEntity});
            }
        }
    }
}
