package com.yem.wm.es.salesorder.op;

import com.yem.wm.es.salesorder.validator.SaleOrdeExportisVoidValidator;
import com.yem.wm.utils.GiftAmount;
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.AfterOperationArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.exception.KDBizException;
import kd.bos.exception.KDException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhouc
 * @date 2024/4/24 10:01
 * @className SaleOrdeExportisVoid
 * @description 外销合同【外销作废】服务插件
 */
public class SaleOrdeExportisVoid extends AbstractOperationServicePlugIn {
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("billstatus");
    }

    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        super.onAddValidators(e);
        e.addValidator(new SaleOrdeExportisVoidValidator());
    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
        for (DynamicObject dataEntity : dataEntities) {
            dataEntity = BusinessDataServiceHelper.loadSingle(dataEntity.getPkValue(), dataEntity.getDynamicObjectType().getName());
            String billstatus = dataEntity.getString("billstatus");
            if (!billstatus.equals("C")) {
//                e.setCancel(true);
//                throw new KDBizException("当前单据未审核，禁止作废！");
            }
        }
    }

    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        super.afterExecuteOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
        for (DynamicObject dataEntity : dataEntities) {
            dataEntity = BusinessDataServiceHelper.loadSingle(dataEntity.getPkValue(), dataEntity.getDynamicObjectType().getName());
            dataEntity.set("yem_cancelstatus","C");//作废中
            SaveServiceHelper.update(new DynamicObject[]{dataEntity});
        }
    }
}
