package nckd.jxccl.sit.hcsi.opplugin.web.coordination;

import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.operate.result.OperationResult;
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.BeginOperationTransactionArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
import kd.bos.exception.KDBizException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.sit.hcsi.business.coordination.SinsurCoordSplitService;
import nckd.jxccl.sit.hcsi.validate.web.SinsurEmpCoordConfirmEffectValidator;

import java.util.stream.Collectors;

/**
 * 单据操作插件
 */
public class SinsurEmpCoordSplitOp extends AbstractOperationServicePlugIn implements Plugin {

    private static final Log logger = LogFactory.getLog(SinsurEmpCoordSplitOp.class);

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        e.getFieldKeys().addAll(this.billEntityType.getAllFields().keySet());
    }

    public void onAddValidators(AddValidatorsEventArgs e) {
        super.onAddValidators(e);
        e.addValidator(new SinsurEmpCoordConfirmEffectValidator());
    }

    @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {
        super.beginOperationTransaction(e);
    }

    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {
        super.endOperationTransaction(e);
    }

    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        super.afterExecuteOperationTransaction(e);
        DynamicObject[] bills = e.getDataEntities();
        for(DynamicObject bill : bills) {
            SinsurCoordSplitService service = new SinsurCoordSplitService(bill.getLong("id"), bill);
            if(service.isNeedSplit()) {
                service.doSplit();
            }
            else {
                OperateOption option = OperateOption.create();
                OperationResult result = OperationServiceHelper.executeOperate("confirmeffect", "hpdi_empcoordverifbill3", new DynamicObject[]{bill}, option);
                logger.info("标品提交生效结果：" + result.isSuccess());
                if (!result.isSuccess()) {
                    String errorMessage = result.getAllErrorInfo().stream()
                            .map(dyx -> dyx.getMessage())
                            .collect(Collectors.joining(", "));
                    logger.info("标品提交生效错误：" + errorMessage);
                    throw new KDBizException(errorMessage);
                }
            }
        }
    }
}