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

import java.util.Date;
import java.util.List;

import com.yem.wm.bc.change.business.ChangeModelHelper;
import com.yem.wm.bc.change.business.ChangeResumeLogHelper;
import com.yem.wm.bc.change.common.consts.BizChangeStatusEnum;
import com.yem.wm.bc.change.common.consts.ChangeResumeFormConst;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.dataentity.resource.ResManager;
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.BeginOperationTransactionArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
import kd.bos.exception.KDBizException;
import kd.bos.metadata.entity.validation.ConditionValidation;
import kd.bos.orm.query.QFilter;
import kd.bos.service.operation.validate.ConditionValidator;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.MetadataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.DeleteServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;

/**
 * @author 夜子
 * @ClassName XBillSubmitOp
 * @description: 变更单提交
 * @date 2023年08月03日
 * @version: 1.0
 */
public class XBillSubmitOp extends AbstractOperationServicePlugIn {
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        e.getFieldKeys().add("sourcebillid");
        e.getFieldKeys().add("changebillno");
        e.getFieldKeys().add("changebizdate");
        e.getFieldKeys().add("changereason");
        e.getFieldKeys().add("billno");
        e.getFieldKeys().add("version");
        e.getFieldKeys().add("subversion");
        e.getFieldKeys().add("validstatus");
    }

    public void onAddValidators(AddValidatorsEventArgs e) {
        super.onAddValidators(e);
        if (this.billEntityType != null) {
            String opkey = (String) this.operateMeta.get("key");
            List<ConditionValidation> vallist = ChangeModelHelper.getValidConditionList(this.billEntityType.getName(),
                    opkey);
            if (vallist != null && vallist.size() > 0) {
                for (ConditionValidation conditionValidation : vallist) {
                    ConditionValidator XBillCV = new ConditionValidator();
                    XBillCV.setValidation(conditionValidation.createValidate());
                    e.addValidator(XBillCV);
                }
            }
        }
    }

    public void beginOperationTransaction(BeginOperationTransactionArgs e) {
        if (e.getDataEntities() != null && e.getDataEntities().length != 0) {
            DynamicObject[] bills = e.getDataEntities();
            DynamicObject changeModel = ChangeModelHelper
                    .getChangeModel4XBill(bills[0].getDataEntityType().getName());
            if (changeModel == null) {
                return;
            }
            for (DynamicObject bill : bills) {
                ChangeModelHelper.excutePluginMethod(changeModel, "beforeXBillSubmit",
                        bill);
            }
        }
    }

    public void endOperationTransaction(EndOperationTransactionArgs e) {
        if (e.getDataEntities() != null && e.getDataEntities().length != 0) {
            DynamicObject[] bills = e.getDataEntities();
            DynamicObject changeModel = ChangeModelHelper
                    .getChangeModel4XBill((String) bills[0].getDataEntityType().getName());
            if (changeModel == null) {
                return;
            }
            for (DynamicObject bill : bills) {
                DynamicObject srcBill = BusinessDataServiceHelper.loadSingleFromCache((Object) bill.get("sourcebillid"),
                        (String) ((String) changeModel.getDynamicObject("srcbill").getPkValue()));
                if (!BizChangeStatusEnum.CHANGING.getValue().equals(srcBill.get("changestatus"))) {
                    srcBill.set("changestatus", (Object) BizChangeStatusEnum.CHANGING.getValue());
                    SaveServiceHelper.update((DynamicObject[]) new DynamicObject[]{srcBill});
                } else if (bill.getPkValue() != null) {
                    QFilter qFilter = new QFilter("changebillno", "=", bill.get("changebillno"));
                    DynamicObject temp = BusinessDataServiceHelper.loadSingle(
                            (String) bill.getDataEntityType().getName(), (String) "id",
                            (QFilter[]) new QFilter[]{qFilter});
                    if (temp != null && !temp.getPkValue().equals(bill.getPkValue())) {
                        throw new KDBizException(
                                ResManager.loadKDString((String) "不能选择正在变更的数据进行变更操作。", (String) "XBillSubmitOp_0",
                                        (String) "yem-yc-changemodel", (Object[]) new Object[0]));
                    }
                }
                DynamicObject xBill = BusinessDataServiceHelper.loadSingleFromCache((Object) bill.getPkValue(),
                        (String) ((String) changeModel.getDynamicObject("xbill").getPkValue()));
                long srcbillid = (Long) srcBill.getPkValue();
                String srcBillEntity = srcBill.getDataEntityType().getName();
                String srcBillNo = srcBill.getString("billno");
                String srcBillVersion = srcBill.getString("version");
                long xbillid = (Long) bill.getPkValue();
                String xbillno = bill.getString("changebillno");
                String xbillentity = bill.getDataEntityType().getName();
                DynamicObject creator = BusinessDataServiceHelper
                        .loadSingleFromCache((Object) UserServiceHelper.getCurrentUserId(), (String) "bos_user");
                Date biztime = bill.getDate("changebizdate");
                String xreason = bill.getString("changereason");
                String srcBillSubVersion = srcBill.getString("subversion");
                QFilter qFilter1 = new QFilter("srcbillid", "=", (Object) srcbillid);
                QFilter qFilter2 = new QFilter("xbillid", "=", (Object) xbillid);
                String enableChangeResume = this.getOption().getVariableValue(ChangeResumeFormConst.ENABLE_CHANGERESUME,
                        "true");
                if ("true".equals(enableChangeResume)) {
                    MainEntityType changeResumeDetailET = MetadataServiceHelper
                            .getDataEntityType((String) "yem_changeresumedetail");
                    DeleteServiceHelper.delete((String) "yem_changeresumedetail",
                            (QFilter[]) new QFilter[]{qFilter1, qFilter2});
                    DynamicObject resumeDetailDO = new DynamicObject((DynamicObjectType) changeResumeDetailET);
                    resumeDetailDO.set("srcbillid", (Object) srcbillid);
                    resumeDetailDO.set("srcbillno", (Object) srcBillNo);
                    resumeDetailDO.set("srcbillentity", (Object) srcBillEntity);
                    resumeDetailDO.set("srcbillversion", (Object) srcBillVersion);
                    resumeDetailDO.set("xbillid", (Object) xbillid);
                    resumeDetailDO.set("xbillentity", (Object) xbillentity);
                    resumeDetailDO.set("xbillno", (Object) xbillno);
                    resumeDetailDO.set("xbiztime", (Object) biztime);
                    resumeDetailDO.set("xcreator", (Object) creator);
                    resumeDetailDO.set("xreason", (Object) xreason);
                    resumeDetailDO.set("crdheadjson_tag",
                            (Object) ChangeResumeLogHelper.getBilljson((DynamicObject) srcBill, (DynamicObject) xBill));
                    resumeDetailDO.set("crdentryjson_tag",
                            (Object) ChangeResumeLogHelper.getBillEntryjson((DynamicObject) srcBill,
                                    (DynamicObject) xBill,
                                     ChangeModelHelper.getXBillEntryAndOp((DynamicObject) changeModel)));
                    SaveServiceHelper.save((DynamicObject[]) new DynamicObject[]{resumeDetailDO});
                    QFilter qFilter3 = new QFilter("srcbillid", "=", (Object) srcbillid);
                    QFilter qFilter4 = new QFilter("xbillid", "=", (Object) xbillid);
                    QFilter qFilter5 = new QFilter("currentchangenumber", "!=", (Object) 0);
                    DeleteServiceHelper.delete((String) "yem_changeresume",
                            (QFilter[]) new QFilter[]{qFilter3, qFilter4, qFilter5});
                    MainEntityType changeResumeET = MetadataServiceHelper
                            .getDataEntityType((String) "yem_changeresume");
                    QFilter qFilterZero1 = new QFilter("srcbillid", "=", (Object) srcbillid);
                    QFilter qFilterZero2 = new QFilter("currentchangenumber", "=", (Object) 0);
                    boolean isExistsZero = QueryServiceHelper.exists((String) "yem_changeresume",
                            (QFilter[]) new QFilter[]{qFilterZero1, qFilterZero2});
                    if (!isExistsZero && "1".equals(srcBillVersion) && "1".equals(srcBillSubVersion)) {
                        DynamicObject zeroXBill = ChangeModelHelper.generateXBilll((String) srcBillEntity,
                                (long) srcbillid);
                        if (zeroXBill != null) {
                            zeroXBill.set("changestatus", (Object) "D");
                            zeroXBill.set("changebillno", (Object) (srcBillNo + "_0"));
                        }
                        Object[] inDBZeroXBill = SaveServiceHelper
                                .save((DynamicObject[]) new DynamicObject[]{zeroXBill});
                        if (inDBZeroXBill != null && inDBZeroXBill.length > 0 && inDBZeroXBill[0] != null) {
                            MainEntityType changeReCordlist = MetadataServiceHelper
                                    .getDataEntityType((String) "yem_changeresume");
                            DynamicObject zeroChangeResumeDO = new DynamicObject((DynamicObjectType) changeReCordlist);
                            zeroChangeResumeDO.set("xbillid", ((DynamicObject) inDBZeroXBill[0]).getPkValue());
                            zeroChangeResumeDO.set("xbillno",
                                    (Object) ((DynamicObject) inDBZeroXBill[0]).getString("changebillno"));
                            zeroChangeResumeDO.set("xvalidstatus", (Object) bill.getString("validstatus"));
                            zeroChangeResumeDO.set("xbillentity", (Object) xbillentity);
                            zeroChangeResumeDO.set("xbiztime", (Object) biztime);
                            zeroChangeResumeDO.set("xcreator", (Object) creator);
                            zeroChangeResumeDO.set("srcbillid", (Object) srcbillid);
                            zeroChangeResumeDO.set("srcbillentity", (Object) srcBillEntity);
                            zeroChangeResumeDO.set("srcbillno", (Object) srcBillNo);
                            zeroChangeResumeDO.set("srcbillversion", (Object) srcBillVersion);
                            zeroChangeResumeDO.set("srcbillsubversion", (Object) srcBillSubVersion);
                            zeroChangeResumeDO.set("changemodel", changeModel.getPkValue());
                            zeroChangeResumeDO.set("currentchangenumber", (Object) 0);
                            SaveServiceHelper.save((DynamicObject[]) new DynamicObject[]{zeroChangeResumeDO});
                        }
                    }
                    DynamicObject currentChangeResumeDO = new DynamicObject(changeResumeET);
                    DynamicObjectCollection num = QueryServiceHelper.query((String) "yem_changeresume",
                            "currentchangenumber", new QFilter[]{qFilter3, qFilter5},
                            "currentchangenumber");
                    int currentChangeNumber = 0;
                    currentChangeNumber = num != null && num.size() > 0 ? num.size() + 1 : 1;
                    currentChangeResumeDO.set("srcbillid", srcbillid);
                    currentChangeResumeDO.set("srcbillentity", srcBillEntity);
                    currentChangeResumeDO.set("srcbillno", srcBillNo);
                    currentChangeResumeDO.set("srcbillversion", srcBillVersion);
                    currentChangeResumeDO.set("srcbillsubversion", srcBillSubVersion);
                    currentChangeResumeDO.set("currentchangenumber", currentChangeNumber);
                    currentChangeResumeDO.set("xvalidstatus", bill.getString("validstatus"));
                    currentChangeResumeDO.set("xbillid", xbillid);
                    currentChangeResumeDO.set("xbillentity", xbillentity);
                    currentChangeResumeDO.set("xbillno", xbillno);
                    currentChangeResumeDO.set("xbiztime", biztime);
                    currentChangeResumeDO.set("xreason", xreason);
                    currentChangeResumeDO.set("xcreator", creator);
                    currentChangeResumeDO.set("changemodel", changeModel.getPkValue());
                    SaveServiceHelper.save(new DynamicObject[]{currentChangeResumeDO});
                }
                ChangeModelHelper.excutePluginMethod(changeModel, "afterXBillSubmit",
                        bill);
            }
        }
    }
}
