package com.yem.wm.fm.gathering.op;

import com.yem.wm.utils.DynamicObjectUtil;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
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;

/**
 * @Description: TODO
 * @Date: 2024/6/29 16:08
 * @Created: by ZZSLL
 */

public class GatheringUnAuditOp extends AbstractOperationServicePlugIn {
    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {
        super.endOperationTransaction(e);

        DynamicObject[] entities = e.getDataEntities();
        for (DynamicObject dynamicObject : entities) {
            dynamicObject = BusinessDataServiceHelper.loadSingle(dynamicObject.getPkValue(), dynamicObject.getDynamicObjectType().getName());
            dynamicObject.set("yem_financeaffirm","A");
            String billtype = dynamicObject.getString("yem_billtype.number");
            if ("yem_gathering_TZF".equals(billtype)) {//负向收款调整单
                long sourcebillid = dynamicObject.getLong("yem_sourcebillid");
                String selectfields = DynamicObjectUtil.getSelectfields("yem_gathering");
                String entrySelectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_gathering", "yem_receiptdetail");
                DynamicObject sourceBill = BusinessDataServiceHelper.loadSingle("yem_gathering", entrySelectfields, new QFilter[]{new QFilter("id", QCP.equals, sourcebillid)});
                if (sourceBill == null) {return;}
                DynamicObjectCollection currentColl = dynamicObject.getDynamicObjectCollection("yem_receiptdetail");
                DynamicObjectCollection sourceEntry = sourceBill.getDynamicObjectCollection("yem_receiptdetail");
                for (DynamicObject curr : currentColl) {
                    long sourceentryid = curr.getLong("yem_sourceentryid");
                    for (DynamicObject source : sourceEntry) {
                        long id = source.getLong("id");
                        if (id == sourceentryid) {
                            source.set("yem_adjustamt", BigDecimal.ZERO);
                        }
                    }
                }
                SaveServiceHelper.save(new DynamicObject[]{sourceBill});
            }
        }
    }
}
