package com.yem.wm.bc.change.op;

import java.util.Date;

import com.yem.wm.bc.change.business.ChangeModelHelper;
import com.yem.wm.bc.change.common.consts.BizChangeStatusEnum;
import com.yem.wm.bc.change.common.consts.ChangeResumeFormConst;
import com.yem.wm.bc.common.CommonUtils;
import kd.bos.dataentity.entity.CloneUtils;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
import kd.bos.entity.validate.AbstractValidator;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.MetadataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;

/**
 * @author 夜子
 * @ClassName SrcBillBizChangeOp
 * @description: 源单变更操作
 * @date 2023年08月03日
 * @version: 1.0
 */
public class SrcBillBizChangeOp extends AbstractOperationServicePlugIn {
    public static Log logger = LogFactory.getLog(SrcBillBizChangeOp.class);

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

    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        e.getFieldKeys().add("billstatus");
        e.getFieldKeys().add("changestatus");
        e.getFieldKeys().add("version");
        e.getFieldKeys().add("billno");
        e.getFieldKeys().add("subversion");
    }

    public void endOperationTransaction(EndOperationTransactionArgs e) {
        super.endOperationTransaction(e);
        if ("bizchange".equals(e.getOperationKey()) && e.getDataEntities() != null && e.getDataEntities().length != 0) {
            DynamicObject[] bills = e.getDataEntities();
            logger.info("bills.length : " + bills.length);
            long beginTime = System.currentTimeMillis();
            logger.info("bizchange begin :" + new Date(beginTime));
            DynamicObject changeModel = ChangeModelHelper
                    .getChangeModel4SrcBill((String) bills[0].getDataEntityType().getName());
            for (DynamicObject bill : bills) {
                ChangeModelHelper.excutePluginMethod((DynamicObject) changeModel, (String) "beforeSrcBillChange",
                        (DynamicObject) bill);
            }
            DynamicObject[] xBills = ChangeModelHelper.generateXBilll((DynamicObject[]) bills);
            String xBillEntityID = "";
            if (!CommonUtils.isNull((Object) xBills)) {
                xBillEntityID = xBills[0].getDataEntityType().getName();
                for (DynamicObject bill : bills) {
                    bill.set("changestatus", (Object) BizChangeStatusEnum.CHANGING.getValue());
                }
                SaveServiceHelper.save((DynamicObject[]) xBills);
                SaveServiceHelper.update((DynamicObject[]) bills);
                for (DynamicObject xBill : xBills) {
                    long sourceBillId;
                    QFilter qFilter2;
                    QFilter qFilter1;
                    DynamicObject srcBill;
                    String enableChangeResume;
                    boolean isExistsZero;
                    ChangeModelHelper.excutePluginMethod((DynamicObject) changeModel, (String) "afterSrcBillChange",
                            (DynamicObject) xBill);
                    if (changeModel == null
                            || !"true".equalsIgnoreCase(enableChangeResume = this.getOption()
                            .getVariableValue(ChangeResumeFormConst.ENABLE_CHANGERESUME, "true"))
                            || (srcBill = BusinessDataServiceHelper.loadSingleFromCache(
                            (Object) (sourceBillId = ((Long) xBill.get("sourcebillid")).longValue()),
                            (String) bills[0].getDataEntityType().getName())) == null
                            || (isExistsZero = QueryServiceHelper.exists((String) "yem_changeresume",
                            (QFilter[]) new QFilter[]{
                                    qFilter1 = new QFilter("srcbillid", "=", (Object) sourceBillId),
                                    qFilter2 = new QFilter("currentchangenumber", "=", (Object) 0)}))
                            || !"1".equals(srcBill.getString("version"))
                            || !"1".equals(srcBill.getString("subversion")))
                        continue;
                    DynamicObject zeroXBill = (DynamicObject) new CloneUtils(false, true)
                            .clone(xBill.getDataEntityType(), (Object) xBill);
                    zeroXBill.set("changestatus", (Object) "D");
                    zeroXBill.set("changebillno", (Object) (srcBill.getString("billno") + "_0"));
                    Object[] inDBZeroXBill = SaveServiceHelper.save((DynamicObject[]) new DynamicObject[]{zeroXBill});
                    if (inDBZeroXBill == null || inDBZeroXBill.length <= 0 || inDBZeroXBill[0] == null)
                        continue;
                    DynamicObject zeroXBillDO = (DynamicObject) inDBZeroXBill[0];
                    MainEntityType changeResumeET = MetadataServiceHelper
                            .getDataEntityType((String) "yem_changeresume");
                    DynamicObject changeResumeDO = new DynamicObject((DynamicObjectType) changeResumeET);
                    changeResumeDO.set("xbillid", zeroXBillDO.getPkValue());
                    changeResumeDO.set("xbillno", (Object) zeroXBillDO.getString("changebillno"));
                    changeResumeDO.set("xvalidstatus", (Object) zeroXBillDO.getString("validstatus"));
                    changeResumeDO.set("xbillentity", (Object) xBill.getDataEntityType().getName());
                    changeResumeDO.set("xbiztime", (Object) xBill.getDate("changebizdate"));
                    DynamicObject creator = BusinessDataServiceHelper
                            .loadSingleFromCache((Object) UserServiceHelper.getCurrentUserId(), (String) "bos_user");
                    changeResumeDO.set("xcreator", (Object) creator);
                    changeResumeDO.set("srcbillid", (Object) sourceBillId);
                    changeResumeDO.set("srcbillentity", (Object) srcBill.getDataEntityType().getName());
                    changeResumeDO.set("srcbillno", (Object) srcBill.getString("billno"));
                    changeResumeDO.set("srcbillversion", (Object) srcBill.getString("version"));
                    changeResumeDO.set("srcbillsubversion", (Object) srcBill.getString("subversion"));
                    changeResumeDO.set("changemodel", changeModel.getPkValue());
                    changeResumeDO.set("currentchangenumber", (Object) 0);
                    SaveServiceHelper.save((DynamicObject[]) new DynamicObject[]{changeResumeDO});
                }
                this.getOperationResult().setSuccess(true);
                long endTime = System.currentTimeMillis();
                logger.info("bizchange end :" + new Date(endTime));
                logger.info("bizchange usetime(ms): " + (endTime - beginTime));
                this.getOption().setVariableValue("changemodel",
                        changeModel != null ? changeModel.getPkValue().toString() : "");
                this.getOption().setVariableValue("xBillEntityID", xBillEntityID);
            }
        }
    }
}