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

import com.yem.wm.utils.DynamicObjectUtil;
import com.yem.wm.utils.YEM;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
import kd.bos.entity.validate.ValidateResultCollection;
import kd.bos.exception.KDBizException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.sdk.plugin.Plugin;

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

/**
 * @author xwudd
 * @date 14:30
 * @Description
 **/
public class UnCreateCreditNoteBillOp extends AbstractOperationServicePlugIn implements Plugin {
    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {
        super.endOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
        for(DynamicObject dataEntitie : dataEntities){
            String selectfields = DynamicObjectUtil.getSelectfields("yem_debcrednote", false);
            selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields,"yem_debcrednote","yem_creditnotesource",false);
            selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields,"yem_debcrednote","yem_creditnotedes",false);
            DynamicObject[] debCreditNotes = BusinessDataServiceHelper.load("yem_debcrednote", selectfields,
                    new QFilter[]{new QFilter("yem_sourcebillid", QCP.equals, dataEntitie.getPkValue()),
                            new QFilter("yem_sourcebilltype",QCP.equals,dataEntitie.getDynamicObjectType().getName())});
            OperationResult unAuditResult = OperationServiceHelper.executeOperate("unaudit", "yem_debcrednote", debCreditNotes, OperateOption.create());
            if(unAuditResult.isSuccess()){
                OperationResult delResult = OperationServiceHelper.executeOperate("delete", "yem_debcrednote", debCreditNotes, OperateOption.create());
                if(delResult.isSuccess()){

                }else{
                    ValidateResultCollection validateResult = delResult.getValidateResult();
                    String message = delResult.getMessage();
                    throw new KDBizException("删除失败，" + message + "，" + validateResult.getValidateErrors().toString());
                }
            }else{
                ValidateResultCollection validateResult = unAuditResult.getValidateResult();
                String message = unAuditResult.getMessage();
                throw new KDBizException("反审核失败，" + message + "，" + validateResult.getValidateErrors().toString());
            }
        }
    }

}
