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

import com.yem.wm.fm.gathering.validator.GatheringAuditValidator;
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.AddValidatorsEventArgs;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
import kd.bos.entity.validate.AbstractValidator;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import org.omg.DynamicAny.DynAnyFactoryOperations;


/**
 * @Description: TODO
 * @Date: 2024/6/12 18:24
 * @Created: by ZZSLL
 */

public class GatheringAuditOp extends AbstractOperationServicePlugIn {
    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        super.onAddValidators(e);
        e.addValidator(new GatheringAuditValidator());
    }

    @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","B");
            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", curr.getBigDecimal("yem_receivableamt").abs());
                        }
                    }
                }
                SaveServiceHelper.save(new DynamicObject[]{sourceBill});
            }
        }
    }
}
