import schema from 'async-validator';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
import { FormButtonModel, FormDruipartModel, FormGroupPanelModel, FormIFrameModel, FormItemModel, FormPageModel, FormPartModel, FormRawItemModel, FormTabPageModel, FormTabPanelModel, FormUserControlModel, ModelTool, Util, Verify, ViewTool, } from '@ibizstudio/runtime';
import { FormControlBase } from './form-control-base';
import { AppFormService } from '../ctrl-service';
import moment from 'moment';
import { AppCenterService, AppViewLogicService } from '../app-service';
import { notNilEmpty } from 'qx-util';
/**
 * 编辑表单部件基类
 *
 * @export
 * @class EditFormControlBase
 * @extends {FormControlBase}
 */
export class EditFormControlBase extends FormControlBase {
    constructor() {
        super(...arguments);
        /**
         * 主键表单项名称
         *
         * @protected
         * @type {string}
         * @memberof EditFormControlBase
         */
        this.majorKeyItemName = '';
        /**
         * 主信息属性映射表单项名称
         *
         * @type {string}
         * @memberof EditFormControlBase
         */
        this.majorMessageItemName = '';
        /**
         * 当前执行的行为逻辑
         *
         * @type {string}
         * @memberof EditFormControlBase
         */
        this.currentAction = '';
        /**
         * 工作流审批意见控件绑定值
         *
         * @memberof EditFormControlBase
         */
        this.srfwfmemo = '';
        /**
         * 关系界面数量
         *
         * @type {number}
         * @memberof EditFormControlBase
         */
        this.drCount = 0;
        /**
         * 关系界面计数器
         *
         * @type {number}
         * @memberof EditFormControlBase
         */
        this.drcounter = 0;
        /**
         * 需要等待关系界面保存时，第一次调用save参数的备份
         *
         * @type {number}
         * @memberof EditFormControlBase
         */
        this.drsaveopt = {};
        /**
         * 表单项校验错误提示信息
         *
         *  @memberof  EditFormControlBase
         */
        this.errorMessages = [];
        /**
         * 保存时的显示处理提示
         *
         * @memberof  EditFormControlBase
         */
        this.showResultInfo = true;
        /**
         * 表单分组锚点数据集合
         *
         * @memberof  EditFormControlBase
         */
        this.groupAnchorDatas = [];
        /**
         * 错误提示信息
         *
         * @type {string}
         * @memberof EditFormControlBase
         */
        this.errMessage = '';
    }
    // onDataChange(): void {
    //   console.log(`onDataChange`);
    // }
    /**
     * 监听静态参数变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof EditFormControlBase
     */
    onStaticPropsChange(newVal, oldVal) {
        this.isAutoLoad = this.staticProps.isautoload;
        this.isEditable = this.staticProps.iseditable;
        super.onStaticPropsChange(newVal, oldVal);
    }
    /**
     * 表单部件模型数据加载
     *
     * @memberof EditFormControlBase
     */
    async ctrlModelLoad() {
        await super.ctrlModelLoad();
        // 加载关系界面
        let allFormDetails = ModelTool.getAllFormDetails(this.controlInstance);
        for (let formDetail of allFormDetails) {
            if (formDetail.detailType == 'DRUIPART') {
                let refView = formDetail === null || formDetail === void 0 ? void 0 : formDetail.getPSAppView();
                if (refView) {
                    await refView.fill(true);
                }
            }
        }
    }
    /**
     * 部件模型数据初始化实例
     *
     * @memberof EditFormControlBase
     */
    async ctrlModelInit(args) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
        await super.ctrlModelInit();
        if (!(this.Environment && this.Environment.isPreviewMode)) {
            this.service = new AppFormService(this.controlInstance, this.context);
            await this.service.loaded();
        }
        this.showFormNavBar = this.controlInstance.showFormNavBar;
        this.isAutoSave = this.controlInstance.enableAutoSave;
        this.loaddraftAction = (_c = (_b = (_a = this.controlInstance).getGetDraftPSControlAction) === null || _b === void 0 ? void 0 : _b.call(_a)) === null || _c === void 0 ? void 0 : _c.actionName;
        this.updateAction = ((_f = (_e = (_d = this.controlInstance).getUpdatePSControlAction) === null || _e === void 0 ? void 0 : _e.call(_d)) === null || _f === void 0 ? void 0 : _f.actionName) || 'Update';
        this.removeAction = (_j = (_h = (_g = this.controlInstance).getRemovePSControlAction) === null || _h === void 0 ? void 0 : _h.call(_g)) === null || _j === void 0 ? void 0 : _j.actionName;
        this.loadAction = (_m = (_l = (_k = this.controlInstance).getGetPSControlAction) === null || _l === void 0 ? void 0 : _l.call(_k)) === null || _m === void 0 ? void 0 : _m.actionName;
        this.createAction = ((_q = (_p = (_o = this.controlInstance).getCreatePSControlAction) === null || _p === void 0 ? void 0 : _p.call(_o)) === null || _q === void 0 ? void 0 : _q.actionName) || 'Create';
        this.WFSubmitAction = (_t = (_s = (_r = this.controlInstance).getWFSubmitPSControlAction) === null || _s === void 0 ? void 0 : _s.call(_r)) === null || _t === void 0 ? void 0 : _t.actionName;
        this.WFStartAction = (_w = (_v = (_u = this.controlInstance).getWFStartPSControlAction) === null || _v === void 0 ? void 0 : _v.call(_u)) === null || _w === void 0 ? void 0 : _w.actionName;
        // 初始化data
        (_x = this.controlInstance.getPSDEFormItems()) === null || _x === void 0 ? void 0 : _x.forEach((formItem) => {
            this.$set(this.data, formItem.id, null);
        });
        // 初始化表单成员运行时模型
        this.initDetailsModel();
        // 初始化静态值规则
        this.initRules();
    }
    /**
     * 编辑表单初始化
     *
     * @memberof EditFormControlBase
     */
    ctrlInit(args) {
        super.ctrlInit(args);
        if (this.isAutoLoad) {
            this.autoLoad({ srfkey: this.context[this.appDeCodeName.toLowerCase()] });
        }
        if (this.dataChang) {
            this.dataChang.pipe(debounceTime(300), distinctUntilChanged()).subscribe((data) => {
                this.handleDataChange();
            });
        }
    }
    viewStateAction(tag, action, data) {
        if (!Object.is(tag, this.name)) {
            return;
        }
        super.viewStateAction(tag, action, data);
        if (Object.is('save', action)) {
            this.save(data, data.showResultInfo);
        }
        if (Object.is('remove', action)) {
            this.remove(data);
        }
        if (Object.is('saveandexit', action)) {
            this.saveAndExit(data);
        }
        if (Object.is('saveandnew', action)) {
            this.saveAndNew(data);
        }
        if (Object.is('removeandexit', action)) {
            this.removeAndExit(data);
        }
        if (Object.is('refresh', action)) {
            this.refresh(data);
        }
        if (Object.is('panelaction', action)) {
            this.panelAction(data.action, data.emitAction, data.data);
        }
    }
    /**
     * 处理dataChang下发的事件
     *
     * @memberof EditFormControlBase
     */
    handleDataChange() {
        const state = !Object.is(JSON.stringify(this.oldData), JSON.stringify(this.data)) ? true : false;
        if (state) {
            if (this.isAutoSave) {
                this.autoSave();
            }
            else {
                this.ctrlEvent({
                    controlname: this.controlInstance.name,
                    action: 'viewstatechange',
                    data: {
                        viewDataChange: true,
                    },
                });
            }
        }
    }
    /**
     * 表单值变化
     *
     * @public
     * @param {{ name: string}} { name}
     * @returns {void}
     * @memberof EditFormControlBase
     */
    formDataChange({ name }) {
        if (this.ignorefieldvaluechange) {
            return;
        }
        this.resetFormData({ name: name });
        this.formLogic({ name: name });
        this.dataChang.next(JSON.stringify(this.data));
    }
    /**
     * 加载草稿
     *
     * @param {*} opt 额外参数
     * @memberof EditFormControlBase
     */
    loadDraft(opt = {}) {
        let callBack;
        if (!this.loaddraftAction) {
            this.$throw(`${this.controlInstance.codeName}` + this.$t('app.formpage.notconfig.loaddraftaction'), 'loadDraft');
            return;
        }
        this.createDefault();
        if (opt.callBack) {
            callBack = opt.callBack;
            delete opt.callBack;
        }
        const arg = Object.assign({}, opt);
        let viewparamResult = Object.assign(arg, this.viewparams);
        let tempContext = JSON.parse(JSON.stringify(this.context));
        this.onControlRequset('loadDraft', tempContext, viewparamResult);
        let post = this.service.loadDraft(this.loaddraftAction, tempContext, { viewparams: viewparamResult }, this.showBusyIndicator);
        post
            .then((response) => {
            var _a;
            this.onControlResponse('loadDraft', response);
            if (!response.status || response.status !== 200) {
                this.$throw(response, 'loadDraft');
                return;
            }
            const data = response.data;
            this.resetDraftFormStates();
            this.onFormLoad(data, 'loadDraft');
            if (callBack && callBack instanceof Function)
                callBack();
            // 删除主键表单项的值
            (_a = this.controlInstance.getPSDEFormItems()) === null || _a === void 0 ? void 0 : _a.find((item) => {
                var _a;
                if (((_a = item.getPSAppDEField()) === null || _a === void 0 ? void 0 : _a.keyField) && !item.hidden) {
                    data[item.name] = null;
                }
            });
            this.ctrlEvent({
                controlname: this.controlInstance.name,
                action: 'load',
                data: data,
            });
            this.$nextTick(() => {
                this.formState.next({ type: 'load', data: data });
            });
            setTimeout(() => {
                const form = this.$refs.form;
                if (form) {
                    form.fields.forEach((field) => {
                        field.validateMessage = '';
                        field.validateState = '';
                        field.validateStatus = false;
                    });
                }
            });
        })
            .catch((response) => {
            this.onControlResponse('loadDraft', response);
            this.$throw(response, 'loadDraft');
        });
    }
    /**
     * 自动保存
     *
     * @param {*} opt 额外参数
     * @memberof EditFormControlBase
     */
    autoSave(opt = {}) {
        if (!this.formValidateStatus()) {
            return;
        }
        const arg = Object.assign({}, opt);
        const data = this.getData();
        Object.assign(arg, data);
        Object.assign(arg, { srfmajortext: data[this.majorMessageItemName] });
        const action = Object.is(data.srfuf, '1') ? this.updateAction : this.createAction;
        if (!action) {
            let actionName = Object.is(data.srfuf, '1') ? 'updateAction' : 'createAction';
            this.$throw(`${this.controlInstance.codeName}` + this.$t('app.formpage.notconfig.actionname'), 'autoSave');
            return;
        }
        Object.assign(arg, { viewparams: this.viewparams });
        let tempContext = JSON.parse(JSON.stringify(this.context));
        if (this.context.srfcallbacktype && this.context.srfcallbackid) {
            Object.assign(arg, { srfcallbacktype: this.context.srfcallbacktype, srfcallbackid: this.context.srfcallbackid });
        }
        // this.onControlRequset('autoSave', tempContext, arg);
        const post = this.service.add(action, tempContext, arg, this.showBusyIndicator);
        post
            .then((response) => {
            // this.onControlResponse('autoSave', response);
            if (!response.status || response.status !== 200) {
                this.$throw(response, 'autoSave');
                return;
            }
            const data = response.data;
            this.onFormLoad(data, 'autoSave');
            this.ctrlEvent({
                controlname: this.controlInstance.name,
                action: 'save',
                data: data,
            });
            this.$nextTick(() => {
                this.formState.next({ type: 'save', action: 'autoSave', data: data });
            });
        })
            .catch((response) => {
            this.onControlResponse('autoSave', response);
            if (response && response.status && response.data) {
                this.$throw(response, 'autoSave', { dangerouslyUseHTMLString: true });
            }
            else {
                this.$throw(this.$t('app.commonwords.sysexception'), 'autoSave');
            }
        });
    }
    /**
     * 验证必填表单项
     *
     * @memberof EditFormControlBase
     */
    validateRequiredItem() {
        const arr = [];
        const form = this.$refs[this.controlInstance.name];
        for (const key in this.detailsModel) {
            if (this.detailsModel[key].required) {
                arr.push(this.detailsModel[key]);
            }
        }
        arr.forEach((item) => {
            form.validateField(item.name, this.validateErr.bind(this));
        });
    }
    /**
     * 校验错误信息
     *
     * @param {*} err
     * @memberof EditFormControlBase
     */
    validateErr(err) {
        if (err) {
            this.errMessage += `${err}<br/>`;
        }
    }
    /**
     * 保存
     *
     * @param {*} opt 额外参数
     * @param {boolean} showResultInfo 是否显示提示信息
     * @param {boolean} isStateNext formState是否下发通知
     * @return {*}  {Promise<any>}
     * @memberof EditFormControlBase
     */
    async save(opt = {}, showResultInfo = true, isStateNext = true) {
        return new Promise((resolve, reject) => {
            if (!this.formValidateStatus()) {
                this.errMessage = '';
                this.validateRequiredItem();
                if (this.errMessage) {
                    this.$throw(this.errMessage, 'save', { dangerouslyUseHTMLString: true });
                }
                else {
                    this.$throw(this.$t('app.searchform.globalerrortip'), 'save', { dangerouslyUseHTMLString: true });
                }
                reject();
                return;
            }
            const arg = Object.assign({}, opt);
            const data = this.getData();
            if (this.viewparams && this.viewparams.copymode) {
                data.srfuf = '0';
                const entity = this.controlInstance.getPSAppDataEntity();
                const codeName = entity.codeName.toLowerCase();
                const key = codeName + 'id';
                delete data[key];
                delete data.srfkey;
                delete this.context[codeName];
            }
            Object.assign(arg, this.context);
            Object.assign(arg, data);
            Object.assign(arg, { srfmajortext: data[this.majorMessageItemName] });
            this.showResultInfo = showResultInfo;
            if (isStateNext && this.drCount > 0) {
                this.drcounter = this.drCount;
                this.drsaveopt = opt;
                this.formState.next({ type: 'beforesave', data: arg }); //先通知关系界面保存
                this.saveState = resolve;
                return;
            }
            const action = Object.is(data.srfuf, '1') ? this.updateAction : this.createAction;
            const actionName = Object.is(data.srfuf, '1') ? 'updateAction' : 'createAction';
            if (!action) {
                this.$throw(`${this.controlInstance.codeName}` + this.$t('app.formpage.notconfig.actionname'), 'save');
                return;
            }
            Object.assign(arg, { viewparams: this.viewparams });
            let tempContext = JSON.parse(JSON.stringify(this.context));
            if (this.context.srfcallbacktype && this.context.srfcallbackid) {
                Object.assign(arg, { srfcallbacktype: this.context.srfcallbacktype, srfcallbackid: this.context.srfcallbackid });
            }
            this.onControlRequset('save', tempContext, arg);
            const post = Object.is(data.srfuf, '1')
                ? this.service.update(action, tempContext, arg, this.showBusyIndicator)
                : this.service.add(action, tempContext, arg, this.showBusyIndicator);
            post
                .then((response) => {
                var _a, _b;
                this.onControlResponse('save', response);
                if (!response.status || response.status !== 200) {
                    this.$throw(response, 'save');
                    reject(response);
                    return;
                }
                this.viewparams.copymode = false;
                const data = response.data;
                this.onFormLoad(data, 'save');
                this.ctrlEvent({
                    controlname: this.controlInstance.name,
                    action: 'save',
                    data: data,
                });
                if (this.viewDefaultUsage) {
                    AppCenterService.notifyMessage({ name: ((_a = this.controlInstance.getPSAppDataEntity()) === null || _a === void 0 ? void 0 : _a.codeName) || '', action: 'appRefresh', data: data });
                }
                this.$nextTick(() => {
                    this.formState.next({ type: 'save', data: data });
                });
                if (((_b = this.controlInstance.formFuncMode) === null || _b === void 0 ? void 0 : _b.toLowerCase()) != 'wizardform' && showResultInfo) {
                    this.$success((data.srfmajortext ? data.srfmajortext : '') + this.$t(`app.formpage.${actionName}`) + this.$t('app.commonwords.success'), 'save');
                }
                resolve(response);
            })
                .catch((response) => {
                this.onControlResponse('save', response);
                if (response && response.status && response.data) {
                    this.$throw(response, 'save', { dangerouslyUseHTMLString: true });
                    reject(response);
                }
                else {
                    this.$throw(this.$t('app.commonwords.sysexception'), 'save');
                    reject(response);
                }
                reject(response);
            });
        });
    }
    /**
     * 删除
     *
     * @param {Array<any>} [opt=[]] 额外参数
     * @param {boolean} [showResultInfo] 是否显示提示信息
     * @return {*}  {Promise<any>}
     * @memberof EditFormControlBase
     */
    async remove(opt = [], showResultInfo) {
        return new Promise((resolve, reject) => {
            if (!this.removeAction) {
                this.$throw(`${this.controlInstance.codeName}` + this.$t('app.formpage.notconfig.removeaction'), 'remove');
                return;
            }
            const arg = opt[0];
            const _this = this;
            Object.assign(arg, { viewparams: this.viewparams });
            let tempContext = Util.deepCopy(this.context);
            this.onControlRequset('remove', tempContext, arg);
            this.service
                .delete(_this.removeAction, tempContext, arg, showResultInfo)
                .then((response) => {
                var _a;
                this.onControlResponse('remove', response);
                if (response) {
                    const data = response.data;
                    this.ctrlEvent({
                        controlname: this.controlInstance.name,
                        action: 'remove',
                        data: data,
                    });
                    this.formState.next({ type: 'remove', data: data });
                    this.data.ismodify = false;
                    this.$success((data.srfmajortext ? data.srfmajortext : '') + this.$t('app.commonwords.deletesuccess'), 'remove');
                    AppCenterService.notifyMessage({ name: ((_a = this.controlInstance.getPSAppDataEntity()) === null || _a === void 0 ? void 0 : _a.codeName) || '', action: 'appRefresh', data: data });
                    resolve(response);
                }
            })
                .catch((error) => {
                this.onControlResponse('remove', error);
                this.$throw(error, 'remove');
                reject(error);
            });
        });
    }
    /**
     * 工作流启动
     *
     * @param {*} data  表单数据
     * @param {*} [localdata] 补充逻辑完成参数
     * @return {*}  {Promise<any>}
     * @memberof EditFormControlBase
     */
    async wfstart(data, localdata) {
        if (!this.formValidateStatus()) {
            this.$throw(this.$t('app.searchform.globalerrortip'), 'wfstart', { dangerouslyUseHTMLString: true });
            return;
        }
        return new Promise((resolve, reject) => {
            const _this = this;
            const formData = this.getData();
            const copyData = Util.deepCopy(data[0]);
            Object.assign(formData, { viewparams: copyData });
            let tempContext = JSON.parse(JSON.stringify(this.context));
            this.onControlRequset('save', tempContext, formData);
            const post = Object.is(formData.srfuf, '1')
                ? this.service.update(this.updateAction, tempContext, formData, this.showBusyIndicator, true)
                : this.service.add(this.createAction, tempContext, formData, this.showBusyIndicator, true);
            post
                .then((response) => {
                this.onControlResponse('save', response);
                const arg = response.data;
                const responseData = Util.deepCopy(arg);
                // 保存完成UI处理
                this.onFormLoad(arg, 'save');
                this.ctrlEvent({
                    controlname: this.controlInstance.name,
                    action: 'save',
                    data: arg,
                });
                this.$nextTick(() => {
                    this.formState.next({ type: 'save', data: arg });
                });
                // 准备工作流数据,填充未存库数据
                let tempWFData = {};
                if (copyData && Object.keys(copyData).length > 0) {
                    Object.keys(copyData).forEach((key) => {
                        if (!arg.hasOwnProperty(key) || (!arg[key] && copyData[key])) {
                            tempWFData[key] = copyData[key];
                        }
                    });
                }
                // 准备提交参数
                if (this.viewparams) {
                    let copyViewParams = Util.deepCopy(this.viewparams);
                    if (copyViewParams.w) {
                        delete copyViewParams.w;
                    }
                    if (this.appDeKeyFieldName && copyViewParams[this.appDeKeyFieldName.toLocaleLowerCase()]) {
                        delete copyViewParams[this.appDeKeyFieldName.toLocaleLowerCase()];
                    }
                    if (this.appDeMajorFieldName && copyViewParams[this.appDeMajorFieldName.toLocaleLowerCase()]) {
                        delete copyViewParams[this.appDeMajorFieldName.toLocaleLowerCase()];
                    }
                    Object.assign(responseData, copyViewParams);
                }
                if (tempWFData && Object.keys(tempWFData).length > 0) {
                    Object.assign(responseData, tempWFData);
                }
                Object.assign(arg, { viewparams: responseData });
                // 强制补充srfwfmemo
                if (copyData.srfwfmemo) {
                    Object.assign(arg, { srfwfmemo: copyData.srfwfmemo });
                }
                let tempContext = JSON.parse(JSON.stringify(this.context));
                this.onControlRequset('wfstart', tempContext, arg);
                const result = this.service.wfstart(_this.WFStartAction, tempContext, arg, this.showBusyIndicator, localdata);
                result
                    .then((response) => {
                    var _a;
                    this.onControlResponse('wfstart', response);
                    if (!response || response.status !== 200) {
                        this.$throw(this.$t('app.formpage.workflow.starterror') + ', ' + response.data.message, 'wfstart');
                        return;
                    }
                    AppCenterService.notifyMessage({ name: ((_a = this.controlInstance.getPSAppDataEntity()) === null || _a === void 0 ? void 0 : _a.codeName) || '', action: 'appRefresh', data: data });
                    this.$success(this.$t('app.formpage.workflow.startsuccess'), 'wfstart');
                    resolve(response);
                })
                    .catch((response) => {
                    this.onControlResponse('wfstart', response);
                    this.$throw(response, 'wfstart');
                    reject(response);
                });
            })
                .catch((response) => {
                this.onControlResponse('wfstart', response);
                this.$throw(response, 'wfstart');
                reject(response);
            });
        });
    }
    /**
     * 工作流提交
     *
     * @param {*} data  表单数据
     * @param {*} [localdata] 补充逻辑完成参数
     * @return {*}  {Promise<any>}
     * @memberof EditFormControlBase
     */
    async wfsubmit(data, localdata) {
        if (!this.formValidateStatus()) {
            this.$throw(this.$t('app.searchform.globalerrortip'), 'wfsubmit', { dangerouslyUseHTMLString: true });
            return;
        }
        return new Promise((resolve, reject) => {
            const _this = this;
            const arg = data[0];
            const copyData = Util.deepCopy(arg);
            Object.assign(this.viewparams, copyData);
            Object.assign(arg, { viewparams: this.viewparams });
            if (!arg[this.appDeKeyFieldName.toLowerCase()]) {
                return;
            }
            const submitData = (arg, responseData) => {
                // 准备工作流数据,填充未存库数据
                let tempWFData = {};
                if (copyData && Object.keys(copyData).length > 0) {
                    Object.keys(copyData).forEach((key) => {
                        if (!arg.hasOwnProperty(key) || (!arg[key] && copyData[key])) {
                            tempWFData[key] = copyData[key];
                        }
                    });
                }
                // 准备提交参数
                if (this.viewparams) {
                    Object.assign(responseData, this.viewparams);
                }
                if (tempWFData && Object.keys(tempWFData).length > 0) {
                    Object.assign(responseData, tempWFData);
                }
                // 补充逻辑完成参数
                if (localdata && localdata.type && Object.is(localdata.type, 'finish')) {
                    Object.assign(responseData, { srfwfpredefaction: 'finish' });
                }
                Object.assign(arg, { viewparams: responseData });
                // 强制补充srfwfmemo
                if (copyData.srfwfmemo) {
                    Object.assign(arg, { srfwfmemo: copyData.srfwfmemo });
                }
                let tempContext = JSON.parse(JSON.stringify(this.context));
                this.onControlRequset('wfsubmit', tempContext, arg);
                const result = this.service.wfsubmit(_this.WFSubmitAction, tempContext, arg, this.showBusyIndicator, localdata);
                result
                    .then((response) => {
                    var _a;
                    this.onControlResponse('wfsubmit', response);
                    if (!response || response.status !== 200) {
                        this.$throw(this.$t('app.formpage.workflow.submiterror') + ', ' + response.data.message, 'wfsubmit');
                        return;
                    }
                    this.onFormLoad(arg, 'submit');
                    AppCenterService.notifyMessage({ name: ((_a = this.controlInstance.getPSAppDataEntity()) === null || _a === void 0 ? void 0 : _a.codeName) || '', action: 'appRefresh', data: data });
                    this.$success(this.$t('app.formpage.workflow.submitsuccess'), 'wfsubmit');
                    resolve(response);
                })
                    .catch((response) => {
                    this.onControlResponse('wfsubmit', response);
                    this.$throw(response, 'wfsubmit');
                    reject(response);
                });
            };
            if (this.isEditable) {
                let tempContext = JSON.parse(JSON.stringify(this.context));
                this.onControlRequset('save', tempContext, arg);
                const post = Object.is(arg.srfuf, '1')
                    ? this.service.update(this.updateAction, tempContext, arg, this.showBusyIndicator, true)
                    : this.service.add(this.createAction, tempContext, arg, this.showBusyIndicator, true);
                post
                    .then((response) => {
                    this.onControlResponse('save', response);
                    const responseData = response.data;
                    let tempResponseData = Util.deepCopy(response);
                    this.service.handleResponse('save', tempResponseData);
                    const arg = tempResponseData.data;
                    // 保存完成UI处理
                    this.onFormLoad(arg, 'save');
                    this.ctrlEvent({
                        controlname: this.controlInstance.name,
                        action: 'save',
                        data: arg,
                    });
                    this.$nextTick(() => {
                        this.formState.next({ type: 'save', data: arg });
                    });
                    submitData(arg, responseData);
                })
                    .catch((response) => {
                    this.onControlResponse('save', response);
                    this.$throw(response, 'wfsubmit');
                    reject(response);
                });
            }
            else {
                const responseData = this.getData();
                submitData(arg, responseData);
            }
        });
    }
    /**
     * 表单刷新数据
     *
     * @param {any} args 额外参数
     * @memberof EditFormControlBase
     */
    refresh(args = {}) {
        if (args instanceof Array) {
            args = {};
        }
        if (this.data.srfkey && !Object.is(this.data.srfkey, '')) {
            Object.assign(args, { srfkey: this.data.srfkey });
            this.load(args);
            return;
        }
        if (this.data.srfkeys && !Object.is(this.data.srfkeys, '')) {
            Object.assign(args, { srfkey: this.data.srfkeys });
            this.load(args);
            return;
        }
    }
    /**
     * 面板行为
     *
     * @param {string} [action] 调用的实体行为
     * @param {string} [emitAction] 抛出行为
     * @param {*} [data={}] 传入数据
     * @param {boolean} [showloading] 是否显示加载状态
     *
     * @memberof EditFormControlBase
     */
    panelAction(action, emitAction, data = {}, showloading) {
        if (!action || (action && Object.is(action, ''))) {
            return;
        }
        const arg = Object.assign({}, data);
        const formdata = this.getData();
        Object.assign(arg, this.viewparams);
        Object.assign(arg, formdata);
        let tempContext = JSON.parse(JSON.stringify(this.context));
        if (data[this.appDeCodeName.toLowerCase()]) {
            Object.assign(tempContext, { [this.appDeCodeName.toLowerCase()]: data[this.appDeCodeName.toLowerCase()] });
        }
        this.onControlRequset('panelAction', tempContext, arg);
        const post = this.service.frontLogic(action, tempContext, arg, showloading);
        post
            .then((response) => {
            this.onControlResponse('panelAction', response);
            if (!response.status || response.status !== 200) {
                this.$throw(response, 'panelAction');
                return;
            }
            const data = response.data;
            this.onFormLoad(data, emitAction);
            this.ctrlEvent({
                controlname: this.controlInstance.name,
                action: emitAction,
                data: data,
            });
            this.$nextTick(() => {
                this.formState.next({ type: emitAction, data: data });
            });
        })
            .catch((response) => {
            this.onControlResponse('panelAction', response);
            this.$throw(response, 'panelAction');
        });
    }
    /**
     * 表单项更新
     *
     * @param {string} mode 界面行为名称
     * @param {*} [data={}] 请求数据
     * @param {string[]} updateDetails 更新项
     * @param {boolean} [showloading] 是否显示加载状态
     * @returns {void}
     * @memberof EditFormControlBase
     */
    updateFormItems(mode, data = {}, updateDetails, showloading = false) {
        if (!mode || (mode && Object.is(mode, ''))) {
            return;
        }
        const arg = Object.assign(Util.deepCopy(this.viewparams), data);
        let tempContext = JSON.parse(JSON.stringify(this.context));
        this.onControlRequset('updateFormItems', tempContext, arg);
        const post = this.service.frontLogic(mode, tempContext, arg, showloading);
        post
            .then((response) => {
            this.onControlResponse('updateFormItems', response);
            if (!response || response.status !== 200) {
                const { statusText } = response;
                const updatEerror = statusText ? statusText : this.$t('app.formpage.updateerror');
                this.$throw(updatEerror, 'updateFormItems');
                return;
            }
            const data = response.data;
            const _data = {};
            if (data) {
                updateDetails.forEach((name) => {
                    if (!data.hasOwnProperty(name)) {
                        return;
                    }
                    Object.assign(_data, { [name]: data[name] });
                });
            }
            this.setFormEnableCond(_data);
            this.fillForm(_data, 'updateFormItem');
            this.formLogic({ name: '' });
            this.dataChang.next(JSON.stringify(this.data));
            this.$nextTick(() => {
                this.formState.next({ type: 'updateformitem', ufimode: arg.srfufimode, data: _data });
            });
        })
            .catch((response) => {
            this.onControlResponse('updateFormItems', response);
            this.$throw(response, 'updateFormItems');
        });
    }
    /**
     * 保存并退出
     *
     * @param {any[]} data 额外参数
     * @return {*}  {Promise<any>}
     * @memberof EditFormControlBase
     */
    saveAndExit(data) {
        let _this = this;
        return new Promise((resolve, reject) => {
            let arg = {};
            if (data && data.length > 0) {
                Object.assign(arg, data[0]);
            }
            _this.currentAction = 'saveAndExit';
            _this
                .save([arg])
                .then(res => {
                if (res) {
                    _this.closeView(res.data);
                }
                resolve(res);
            })
                .catch(error => {
                reject(error);
            });
        });
    }
    /**
     * 保存并新建
     *
     * @param {any[]} data 额外参数
     * @return {*}  {Promise<any>}
     * @memberof EditFormControlBase
     */
    saveAndNew(data) {
        let _this = this;
        return new Promise((resolve, reject) => {
            let arg = {};
            if (data && data.length > 0) {
                Object.assign(arg, data[0]);
            }
            _this.currentAction = 'saveAndNew';
            _this
                .save([arg])
                .then(res => {
                _this.ResetData(res);
                _this.loadDraft({});
            })
                .catch(error => {
                reject(error);
            });
        });
    }
    /**
     * 删除并退出
     *
     * @param {any[]} data 额外参数
     * @return {*}  {Promise<any>}
     * @memberof EditFormControlBase
     */
    removeAndExit(data) {
        let _this = this;
        return new Promise((resolve, reject) => {
            let arg = {};
            if (data && data.length > 0) {
                Object.assign(arg, data[0]);
            }
            _this
                .remove([arg])
                .then(res => {
                if (res) {
                    _this.closeView(res.data);
                }
                resolve(res);
            })
                .catch(error => {
                reject(error);
            });
        });
    }
    /**
     * 关系界面数据保存完成
     *
     * @param {any} $event
     * @memberof EditFormControlBase
     */
    drdatasaved($event) {
        let _this = this;
        this.drcounter--;
        if (this.drcounter === 0) {
            this.save(this.drsaveopt, this.showResultInfo, false).then(res => {
                this.saveState(res);
                this.drsaveopt = {};
                if (Object.is(_this.currentAction, 'saveAndNew')) {
                    _this.ResetData(res);
                    _this.loadDraft({});
                }
                else if (Object.is(_this.currentAction, 'saveAndExit')) {
                    if (res) {
                        _this.closeView(res.data);
                    }
                }
            });
        }
    }
    /**
     * 表单加载完成
     *
     * @public
     * @param {*} [data={}]
     * @param {string} [action]
     * @memberof EditFormControlBase
     */
    onFormLoad(data = {}, action) {
        if (this.appDeCodeName.toLowerCase()) {
            if (Object.is(action, 'save') || Object.is(action, 'autoSave') || Object.is(action, 'submit')) {
                // 更新context的实体主键
                if (data[this.appDeCodeName.toLowerCase()]) {
                    Object.assign(this.context, { [this.appDeCodeName.toLowerCase()]: data[this.appDeCodeName.toLowerCase()] });
                }
                this.ctrlEvent({
                    controlname: this.controlInstance.name,
                    action: 'viewstatechange',
                    data: {
                        viewDataChange: false,
                    },
                });
            }
        }
        this.setFormEnableCond(data);
        this.computeButtonState(data);
        this.fillForm(data, action);
        this.oldData = {};
        Object.assign(this.oldData, Util.deepCopy(this.data));
        // this.$store.commit('viewaction/setViewDataChange', { viewtag: this.viewtag, viewdatachange: false });
        this.formLogic({ name: '' });
    }
    /**
     * 值填充
     *
     * @param {*} [_datas={}]
     * @param {string} [action]
     * @memberof EditFormControlBase
     */
    fillForm(_datas = {}, action) {
        this.ignorefieldvaluechange = true;
        Object.keys(_datas).forEach((name) => {
            if (this.data.hasOwnProperty(name)) {
                this.data[name] = _datas[name];
            }
        });
        if (Object.is(action, 'loadDraft')) {
            this.createDefault();
        }
        if (Object.is(action, 'load')) {
            this.updateDefault();
        }
        this.$nextTick(function () {
            this.ignorefieldvaluechange = false;
        });
    }
    /**
     * 置空对象
     *
     * @param {*} _datas 置空对象
     * @memberof EditFormControlBase
     */
    ResetData(_datas) {
        if (Object.keys(_datas).length > 0) {
            Object.keys(_datas).forEach((name) => {
                if (this.data.hasOwnProperty(name)) {
                    this.data[name] = null;
                }
            });
        }
    }
    /**
     * 重置
     *
     * @memberof EditFormControlBase
     */
    onReset() {
        this.ResetData(this.data);
        this.$nextTick(() => {
            this.formState.next({ type: 'load', data: this.data });
        });
    }
    /**
     * 表单项检查逻辑
     *
     * @public
     * @param {string} name 属性名
     * @return {*}  {Promise<any>}
     * @memberof EditFormControlBase
     */
    checkItem(name) {
        return new Promise((resolve, reject) => {
            if (!this.rules[name]) {
                resolve(true);
            }
            const validator = new schema({ [name]: this.rules[name] });
            validator
                .validate({ [name]: this.data[name] })
                .then(() => {
                resolve(true);
            })
                .catch(() => {
                resolve(false);
            });
        });
    }
    /**
     * 获取锚点项数据
     *
     * @public
     * @param {*} data
     * @memberof EditFormControlBase
     */
    setAnchorItems(item, anchorArray) {
        if (Object.is(item.detailType, 'GROUPPANEL')) {
            const itemDetails = item.getPSDEFormDetails() || [];
            if (itemDetails.length > 0) {
                itemDetails.forEach((item1, index) => {
                    this.setAnchorItems(item1, anchorArray);
                });
            }
        }
        else {
            if (item.enableAnchor) {
                anchorArray.push({
                    name: item.name,
                    editor: item.getPSEditor() || {},
                });
            }
        }
    }
    /**
     * 设置表单项是否启用
     *
     * @public
     * @param {*} data
     * @memberof EditFormControlBase
     */
    setFormEnableCond(data) {
        Object.values(this.detailsModel).forEach((detail) => {
            if (!Object.is(detail.detailType, 'FORMITEM')) {
                return;
            }
            const formItem = detail;
            formItem.setEnableCond(data.srfuf);
        });
    }
    /**
     * 表单按钮行为触发
     *
     * @param {*} arg
     * @returns {void}
     * @memberof EditFormControlBase
     */
    async onFormItemActionClick({ formdetail, event }) {
        if (formdetail && formdetail.actionType && Object.is(formdetail.actionType, 'FIUPDATE')) {
            const itemUpdate = formdetail.getPSDEFormItemUpdate();
            const showBusyIndicator = itemUpdate === null || itemUpdate === void 0 ? void 0 : itemUpdate.showBusyIndicator;
            const getPSAppDEMethod = itemUpdate === null || itemUpdate === void 0 ? void 0 : itemUpdate.getPSAppDEMethod();
            const getPSDEFIUpdateDetails = itemUpdate === null || itemUpdate === void 0 ? void 0 : itemUpdate.getPSDEFIUpdateDetails();
            let details = [];
            getPSDEFIUpdateDetails === null || getPSDEFIUpdateDetails === void 0 ? void 0 : getPSDEFIUpdateDetails.forEach((item) => {
                details.push(item.name);
            });
            if (formdetail.getParamPickupPSAppView()) {
                const pickupview = formdetail.getParamPickupPSAppView();
                await pickupview.fill();
                if (!pickupview) {
                    this.updateFormItems(getPSAppDEMethod === null || getPSAppDEMethod === void 0 ? void 0 : getPSAppDEMethod.codeName, this.data, details, showBusyIndicator);
                }
                else {
                    const tempContext = Util.deepCopy(this.context);
                    const data = Util.deepCopy(this.viewparams);
                    if ((formdetail === null || formdetail === void 0 ? void 0 : formdetail.getPSNavigateContexts()) && formdetail.getPSNavigateContexts().length > 0) {
                        let _context = Util.computedNavData(this.data, tempContext, data, formdetail.getPSNavigateContexts());
                        Object.assign(tempContext, _context);
                    }
                    if ((formdetail === null || formdetail === void 0 ? void 0 : formdetail.getPSNavigateParams()) && formdetail.getPSNavigateParams().length > 0) {
                        let _param = Util.computedNavData(this.data, tempContext, data, formdetail.getPSNavigateParams());
                        Object.assign(data, _param);
                    }
                    if (pickupview.openMode.indexOf('DRAWER') !== -1) {
                        const view = {
                            viewname: 'app-view-shell',
                            height: pickupview.height,
                            width: pickupview.width,
                            title: pickupview.title,
                            placement: pickupview.openMode,
                        };
                        if (pickupview && pickupview.modelPath) {
                            Object.assign(tempContext, { viewpath: pickupview.modelPath });
                        }
                        const appdrawer = this.$appdrawer.openDrawer(view, Util.getViewProps(tempContext, data));
                        appdrawer.subscribe((result) => {
                            if (result && Object.is(result.ret, 'OK')) {
                                const arg = this.getData();
                                Object.assign(arg, { srfactionparam: result.datas });
                                this.updateFormItems(getPSAppDEMethod === null || getPSAppDEMethod === void 0 ? void 0 : getPSAppDEMethod.codeName, arg, details, showBusyIndicator);
                            }
                        });
                    }
                    else {
                        const view = {
                            viewname: 'app-view-shell',
                            height: pickupview.height,
                            width: pickupview.width,
                            title: pickupview.title,
                        };
                        if (pickupview && pickupview.modelPath) {
                            Object.assign(tempContext, { viewpath: pickupview.modelPath });
                        }
                        const appmodal = this.$appmodal.openModal(view, tempContext, data);
                        appmodal.subscribe((result) => {
                            if (result && Object.is(result.ret, 'OK')) {
                                const arg = this.getData();
                                Object.assign(arg, { srfactionparam: result.datas });
                                this.updateFormItems(getPSAppDEMethod === null || getPSAppDEMethod === void 0 ? void 0 : getPSAppDEMethod.codeName, arg, details, showBusyIndicator);
                            }
                        });
                    }
                }
            }
            else {
                this.updateFormItems(getPSAppDEMethod === null || getPSAppDEMethod === void 0 ? void 0 : getPSAppDEMethod.codeName, this.data, details, showBusyIndicator);
            }
        }
        else {
            AppViewLogicService.getInstance().executeViewLogic(`${this.controlInstance.name}_${formdetail.name}_click`, event, this, null, this.controlInstance.getPSAppViewLogics());
        }
    }
    /**
     * 计算表单按钮权限状态
     *
     * @param {*} [data] 传入数据
     * @memberof EditFormControlBase
     */
    computeButtonState(data) {
        let targetData = this.transformData(data);
        ViewTool.calcActionItemAuthState(targetData, this.actionModel, this.appUIService);
        if (this.detailsModel && Object.keys(this.detailsModel).length > 0) {
            Object.keys(this.detailsModel).forEach((name) => {
                var _a, _b, _c;
                const model = this.detailsModel[name];
                if ((model === null || model === void 0 ? void 0 : model.detailType) == 'BUTTON' && ((_a = model.uiaction) === null || _a === void 0 ? void 0 : _a.tag)) {
                    // 更新detailsModel里的按钮的权限状态值
                    if (Util.isEmpty(this.actionModel[model.uiaction.tag].dataActionResult)) {
                        this.detailsModel[name].isPower = true;
                        this.detailsModel[name].visible = true;
                        this.detailsModel[name].disabled = false;
                    }
                    else {
                        this.detailsModel[name].visible = this.actionModel[model.uiaction.tag].visabled;
                        this.detailsModel[name].disabled = this.actionModel[model.uiaction.tag].disabled;
                        this.detailsModel[name].isPower = this.actionModel[model.uiaction.tag].dataActionResult === 1 ? true : false;
                    }
                }
                else if ((model === null || model === void 0 ? void 0 : model.detailType) == 'GROUPPANEL' && ((_c = (_b = model.uiActionGroup) === null || _b === void 0 ? void 0 : _b.details) === null || _c === void 0 ? void 0 : _c.length) > 0) {
                    // 更新分组面板界面行为组的权限状态值
                    model.uiActionGroup.details.forEach((actionDetail) => {
                        actionDetail.visible = this.actionModel[actionDetail.tag].visabled;
                        actionDetail.disabled = this.actionModel[actionDetail.tag].disabled;
                    });
                }
            });
        }
    }
    /**
     * 初始化界面行为模型
     *
     * @type {*}
     * @memberof EditFormControlBase
     */
    initCtrlActionModel() {
        let allFormDetails = ModelTool.getAllFormDetails(this.controlInstance);
        if ((allFormDetails === null || allFormDetails === void 0 ? void 0 : allFormDetails.length) > 0) {
            allFormDetails.forEach((detail) => {
                var _a, _b, _c, _d;
                if ((detail === null || detail === void 0 ? void 0 : detail.detailType) == 'BUTTON' && detail.getPSUIAction()) {
                    // 添加表单按钮的actionModel
                    const appUIAction = detail.getPSUIAction();
                    const appUIAction_M = Util.deepCopy(appUIAction.M);
                    this.actionModel[appUIAction.uIActionTag] = Object.assign(appUIAction_M, {
                        disabled: false,
                        visabled: true,
                        getNoPrivDisplayMode: appUIAction.noPrivDisplayMode ? appUIAction.noPrivDisplayMode : 6,
                    });
                }
                else if ((detail === null || detail === void 0 ? void 0 : detail.detailType) == 'GROUPPANEL' && ((_b = (_a = detail.getPSUIActionGroup()) === null || _a === void 0 ? void 0 : _a.getPSUIActionGroupDetails()) === null || _b === void 0 ? void 0 : _b.length)) {
                    // 添加表单分组界面行为组的actionModel
                    (_d = (_c = detail
                        .getPSUIActionGroup()) === null || _c === void 0 ? void 0 : _c.getPSUIActionGroupDetails()) === null || _d === void 0 ? void 0 : _d.forEach((actionDetail) => {
                        if (actionDetail === null || actionDetail === void 0 ? void 0 : actionDetail.getPSUIAction()) {
                            const appUIAction = actionDetail.getPSUIAction();
                            const appUIAction_M = Util.deepCopy(appUIAction.M);
                            this.actionModel[appUIAction.uIActionTag] = Object.assign(appUIAction_M, {
                                disabled: false,
                                visabled: true,
                                getNoPrivDisplayMode: appUIAction.noPrivDisplayMode ? appUIAction.noPrivDisplayMode : 6,
                            });
                        }
                    });
                }
            });
        }
    }
    /**
     * 设置表单项错误提示信息
     *
     * @param {*} prop 表单项字段名
     * @param {*} status 校验状态
     * @param {*} error 错误信息
     * @memberof EditFormControlBase
     */
    formItemValidate(prop, status, error) {
        error = error ? error : '';
        const index = this.errorMessages.findIndex((errorMessage) => Object.is(errorMessage.prop, prop));
        if (status) {
            if (index != -1) {
                this.errorMessages.splice(index, 1);
            }
        }
        else {
            this.handleBottomLabelErrorMsgPosition(prop);
            if (index != -1) {
                this.errorMessages[index].error = error;
            }
            else {
                this.errorMessages.push({ prop: prop, error: error });
            }
        }
    }
    /**
     * 处理下方标签错误信息位置
     *
     * @param {*} prop 表单项字段名
     * @memberof EditFormControlBase
     */
    handleBottomLabelErrorMsgPosition(prop) {
        var _a;
        const element = document.querySelector(`.${this.appDeCodeName.toLowerCase()}-${(_a = this.controlInstance.codeName) === null || _a === void 0 ? void 0 : _a.toLowerCase()}-item-${prop}`);
        if (element && element.className.indexOf('label-bottom') != -1) {
            this.$nextTick(() => {
                var _a;
                const labelWidth = (_a = element.querySelector('.app-form-item-label')) === null || _a === void 0 ? void 0 : _a.offsetWidth;
                const errorDom = element.querySelector('.ivu-form-item-error-tip');
                if (labelWidth && errorDom) {
                    errorDom.style.left = labelWidth + 'px';
                }
            });
        }
    }
    /**
     * 显示更多模式切换操作
     *
     * @param {string} name 名称
     * @memberof EditFormControlBase
     */
    manageContainerClick(name) {
        let model = this.detailsModel[name];
        if (model.isManageContainer) {
            model.setManageContainerStatus(!model.manageContainerStatus);
            model.controlledItems.forEach((item) => {
                if (this.detailsModel[item].isControlledContent) {
                    this.detailsModel[item].setVisible(model.manageContainerStatus ? this.detailsModel[item].oldVisible : false);
                }
            });
            this.$forceUpdate();
        }
    }
    /**
     * 打印
     *
     * @memberof EditFormControlBase
     */
    print() {
        var _a;
        let _this = this;
        _this.$print({ id: `${this.appDeCodeName.toLowerCase()}_${this.controlInstance.codeName}`, popTitle: `${(_a = this.controlInstance.getPSAppDataEntity()) === null || _a === void 0 ? void 0 : _a.logicName}` });
    }
    /**
     * 新建默认值
     *
     * @memberof EditFormControlBase
     */
    createDefault() {
        var _a, _b, _c;
        const allFormDetails = ModelTool.getAllFormItems(this.controlInstance);
        if (allFormDetails.length > 0) {
            for (const detail of allFormDetails) {
                const property = (_a = detail === null || detail === void 0 ? void 0 : detail.codeName) === null || _a === void 0 ? void 0 : _a.toLowerCase();
                if (((detail === null || detail === void 0 ? void 0 : detail.createDV) || (detail === null || detail === void 0 ? void 0 : detail.createDVT)) && this.data.hasOwnProperty(property)) {
                    switch (detail.createDVT) {
                        case 'CONTEXT':
                            this.data[property] = this.viewparams[detail === null || detail === void 0 ? void 0 : detail.createDV];
                            break;
                        case 'SESSION':
                            this.data[property] = this.context[detail === null || detail === void 0 ? void 0 : detail.createDV];
                            break;
                        case 'APPDATA':
                            this.data[property] = this.context[detail === null || detail === void 0 ? void 0 : detail.createDV];
                            break;
                        case 'OPERATORNAME':
                            this.data[property] = this.context['srfusername'];
                            break;
                        case 'OPERATOR':
                            this.data[property] = this.context['srfuserid'];
                            break;
                        case 'CURTIME':
                            this.data[property] = Util.dateFormat(new Date(), (_b = detail.getPSAppDEField()) === null || _b === void 0 ? void 0 : _b.valueFormat);
                            break;
                        case 'PARAM':
                            this.data[property] = ((_c = this.service.getRemoteCopyData()) === null || _c === void 0 ? void 0 : _c[property]) || null;
                            break;
                        default:
                            this.data[property] = ModelTool.isNumberField(detail === null || detail === void 0 ? void 0 : detail.getPSAppDEField()) ? Number(detail === null || detail === void 0 ? void 0 : detail.createDV) : detail === null || detail === void 0 ? void 0 : detail.createDV;
                            break;
                    }
                }
            }
        }
    }
    /**
     * 更新默认值
     *
     * @memberof EditFormControlBase
     */
    updateDefault() {
        var _a, _b;
        const allFormDetails = ModelTool.getAllFormItems(this.controlInstance);
        if (allFormDetails.length > 0) {
            for (const detail of allFormDetails) {
                const property = detail.codeName.toLowerCase();
                if (notNilEmpty(this.data[property])) {
                    continue;
                }
                if ((detail.updateDV || detail.updateDVT) && this.data.hasOwnProperty(property)) {
                    switch (detail.updateDVT) {
                        case 'CONTEXT':
                            this.data[property] = this.viewparams[detail.updateDV];
                            break;
                        case 'SESSION':
                            this.data[property] = this.context[detail.updateDV];
                            break;
                        case 'APPDATA':
                            this.data[property] = this.context[detail.updateDV];
                            break;
                        case 'OPERATORNAME':
                            this.data[property] = this.context['srfusername'];
                            break;
                        case 'OPERATOR':
                            this.data[property] = this.context['srfuserid'];
                            break;
                        case 'CURTIME':
                            this.data[property] = Util.dateFormat(new Date(), (_a = detail.getPSAppDEField()) === null || _a === void 0 ? void 0 : _a.valueFormat);
                            break;
                        case 'PARAM':
                            this.data[property] = ((_b = this.service.getRemoteCopyData()) === null || _b === void 0 ? void 0 : _b[property]) || null;
                            break;
                        case 'RESET':
                            this.data[property] = null;
                        default:
                            this.data[property] = ModelTool.isNumberField(detail.getPSAppDEField()) ? Number(detail.updateDV) : detail.updateDV;
                            break;
                    }
                }
            }
        }
    }
    /**
     * 初始化值规则
     *
     * @memberof EditFormControlBase
     */
    initRules() {
        var _a, _b;
        // 先初始化系统值规则和属性值规则
        let staticRules = {};
        const allFormItemVRs = this.controlInstance.getPSDEFormItemVRs();
        allFormItemVRs === null || allFormItemVRs === void 0 ? void 0 : allFormItemVRs.forEach((item) => {
            const { checkMode, valueRuleType } = item;
            const formItemName = item.getPSDEFormItemName() || '';
            const sysRule = item.getPSSysValueRule();
            const deRule = item.getPSDEFValueRule();
            if (!staticRules[formItemName]) {
                staticRules[formItemName] = [];
            }
            // 排除后台检查的值规则
            if (checkMode == 2) {
                return;
            }
            // 系统值规则
            if (valueRuleType == 'SYSVALUERULE' && sysRule) {
                // 正则值规则
                if (sysRule.ruleType == 'REG') {
                    staticRules[formItemName].push({
                        pattern: new RegExp(sysRule.regExCode),
                        message: sysRule.ruleInfo,
                        trigger: ['change', 'blur'],
                    });
                    // 脚本值规则
                }
                else if (sysRule.ruleType == 'SCRIPT') {
                    staticRules[formItemName].push({
                        validator: (rule, value, callback) => {
                            // 空值时不校验
                            if (Util.isEmpty(this.data[formItemName])) {
                                return true;
                            }
                            let source = this.data;
                            try {
                                eval(sysRule.scriptCode);
                            }
                            catch (error) {
                                this.$throw(error, 'initRules');
                            }
                            return true;
                        },
                        trigger: ['change', 'blur'],
                    });
                }
                // 属性值规则
            }
            else if (valueRuleType == 'DEFVALUERULE' && deRule) {
                // 有值项的情况，校验值项的值
                let formItem = this.controlInstance.findPSDEFormItem(formItemName);
                let valueName = (formItem === null || formItem === void 0 ? void 0 : formItem.valueItemName) || formItemName;
                staticRules[formItemName].push({
                    validator: (rule, value, callback, source) => {
                        // 空值时不校验
                        if (Util.isEmpty(this.data[valueName])) {
                            return true;
                        }
                        const { isPast, infoMessage } = Verify.verifyDeRules(valueName, this.data, deRule.getPSDEFVRGroupCondition());
                        if (!isPast) {
                            callback(new Error(infoMessage || deRule.ruleInfo));
                        }
                        return true;
                    },
                    trigger: ['change', 'blur'],
                });
            }
        });
        // 初始化非空值规则和数据类型值规则
        this.rules = {};
        const allFormItems = ModelTool.getAllFormItems(this.controlInstance);
        if (allFormItems && allFormItems.length > 0) {
            for (const detail of allFormItems) {
                if (detail.detailType == 'FORMITEM' && ((_a = detail.getPSEditor()) === null || _a === void 0 ? void 0 : _a.editorType) != 'HIDDEN' && !detail.compositeItem) {
                    let type = ModelTool.isNumberField(detail === null || detail === void 0 ? void 0 : detail.getPSAppDEField()) ? 'number' : 'string';
                    let otherRules = staticRules[detail.name] || [];
                    let editorRules = Verify.buildVerConditions(detail.getPSEditor());
                    this.rules[detail.name] = [
                        // 非空值规则
                        {
                            validator: (rule, value, callback) => {
                                return !(this.detailsModel[detail.name].required && (value === null || value === undefined || value === ''));
                            },
                            message: `${this.$t('app.formpage.valueverif')}${detail.caption}`,
                        },
                        // 表单值规则
                        ...otherRules,
                        // 编辑器基础值规则
                        ...editorRules,
                    ];
                }
                else if (detail.detailType == 'FORMITEM' && ((_b = detail.getPSEditor()) === null || _b === void 0 ? void 0 : _b.editorType) != 'HIDDEN' && detail.compositeItem) {
                    let compositeItemRules = this.getCompositeItemRules(detail);
                    this.rules[detail.name] = [
                        // 复合表单项基础值规则
                        ...compositeItemRules,
                    ];
                }
            }
        }
    }
    /**
     * 复合表单项值规则
     *
     * @param detail 复合表单项
     */
    getCompositeItemRules(detail) {
        var _a;
        let rules = [];
        if (detail.compositeItem && ((_a = detail.getPSEditor()) === null || _a === void 0 ? void 0 : _a.editorType) == 'DATEPICKER') {
            const formItems = detail.getPSDEFormItems();
            if (formItems && formItems.length > 1) {
                rules.push({
                    validator: (rule, value, callback) => {
                        return this.data[formItems[0].name] && this.data[formItems[1].name] && moment(this.data[formItems[0].name]).isAfter(this.data[formItems[1].name]) ? false : true;
                    },
                    message: this.$t('app.formpage.compositeitem.datepicker'),
                });
            }
        }
        return rules;
    }
    /**
     * 初始化表单成员模型
     *
     * @memberof EditFormControlBase
     */
    initDetailsModel() {
        var _a, _b, _c, _d, _e, _f;
        this.detailsModel = {};
        const { noTabHeader, name } = this.controlInstance;
        const allFormDetails = ModelTool.getAllFormDetails(this.controlInstance);
        if (allFormDetails.length > 0) {
            for (const detail of allFormDetails) {
                let detailOpts = {
                    name: detail.name,
                    caption: detail.caption,
                    isShowCaption: detail.showCaption,
                    detailType: detail.detailType,
                    visible: !ModelTool.findGroupLogicByLogicCat('PANELVISIBLE', detail.getPSDEFDGroupLogics()),
                    form: this,
                    isControlledContent: detail.showMoreMode == 1,
                };
                let detailModel = null;
                switch (detail.detailType) {
                    case 'BUTTON':
                        Object.assign(detailOpts, {
                            disabled: false,
                        });
                        const uiAction = (_b = (_a = detail).getPSUIAction) === null || _b === void 0 ? void 0 : _b.call(_a);
                        if (uiAction) {
                            detailOpts.uiaction = {
                                type: uiAction.uIActionType,
                                tag: uiAction.uIActionTag,
                                visabled: true,
                                disabled: false,
                            };
                            if (uiAction.actionTarget) {
                                detailOpts.uiaction.actiontarget = uiAction.actionTarget;
                            }
                            if (uiAction.noPrivDisplayMode) {
                                detailOpts.uiaction.noprivdisplaymode = uiAction.noPrivDisplayMode;
                            }
                            if (uiAction.dataAccessAction) {
                                detailOpts.uiaction.dataaccaction = uiAction.dataAccessAction;
                                if (this.Environment.enablePermissionValid) {
                                    detailOpts.visible = false;
                                }
                            }
                        }
                        detailModel = new FormButtonModel(detailOpts);
                        break;
                    case 'FORMITEM':
                        Object.assign(detailOpts, {
                            disabled: false,
                            required: !detail.allowEmpty,
                            enableCond: detail.enableCond,
                            ignoreInput: detail.ignoreInput,
                        });
                        detailModel = new FormItemModel(detailOpts);
                        break;
                    case 'GROUPPANEL':
                        detailOpts.isManageContainer = detail.showMoreMode == 2;
                        const PSUIActionGroup = detail.getPSUIActionGroup();
                        // 界面行为组
                        let uiActionGroup = {
                            caption: PSUIActionGroup === null || PSUIActionGroup === void 0 ? void 0 : PSUIActionGroup.name,
                            langbase: '',
                            extractMode: detail.actionGroupExtractMode || 'ITEM',
                            details: [],
                        };
                        const PSUIActionGroupDetails = ((_c = PSUIActionGroup === null || PSUIActionGroup === void 0 ? void 0 : PSUIActionGroup.getPSUIActionGroupDetails) === null || _c === void 0 ? void 0 : _c.call(PSUIActionGroup)) || [];
                        if (PSUIActionGroupDetails.length > 0) {
                            PSUIActionGroupDetails.forEach((actionDetail) => {
                                var _a, _b, _c, _d, _e, _f, _g, _h;
                                let uiaction = (_a = actionDetail === null || actionDetail === void 0 ? void 0 : actionDetail.getPSUIAction) === null || _a === void 0 ? void 0 : _a.call(actionDetail);
                                let temp = {
                                    name: `${detail.name}_${actionDetail.name}`,
                                    tag: uiaction === null || uiaction === void 0 ? void 0 : uiaction.uIActionTag,
                                    caption: this.$tl((_b = uiaction === null || uiaction === void 0 ? void 0 : uiaction.getCapPSLanguageRes()) === null || _b === void 0 ? void 0 : _b.lanResTag, (uiaction === null || uiaction === void 0 ? void 0 : uiaction.caption) || ''),
                                    disabled: false,
                                    visabled: true,
                                    noprivdisplaymode: uiaction === null || uiaction === void 0 ? void 0 : uiaction.noPrivDisplayMode,
                                    actiontarget: (uiaction === null || uiaction === void 0 ? void 0 : uiaction.actionTarget) || '',
                                    dataaccaction: (uiaction === null || uiaction === void 0 ? void 0 : uiaction.dataAccessAction) || '',
                                    isShowCaption: actionDetail.showCaption,
                                    isShowIcon: actionDetail.showIcon,
                                };
                                if ((_c = uiaction === null || uiaction === void 0 ? void 0 : uiaction.getPSAppDataEntity) === null || _c === void 0 ? void 0 : _c.call(uiaction)) {
                                    temp.uiactiontag = `${(_f = (_e = (_d = uiaction === null || uiaction === void 0 ? void 0 : uiaction.getPSAppDataEntity) === null || _d === void 0 ? void 0 : _d.call(uiaction)) === null || _e === void 0 ? void 0 : _e.codeName) === null || _f === void 0 ? void 0 : _f.toLowerCase()}_${(_g = uiaction === null || uiaction === void 0 ? void 0 : uiaction.uIActionTag) === null || _g === void 0 ? void 0 : _g.toLowerCase()}`;
                                }
                                // 图标
                                if ((_h = uiaction === null || uiaction === void 0 ? void 0 : uiaction.getPSSysImage) === null || _h === void 0 ? void 0 : _h.call(uiaction)) {
                                    let image = uiaction.getPSSysImage();
                                    if (image === null || image === void 0 ? void 0 : image.cssClass) {
                                        temp.icon = image.cssClass;
                                    }
                                    else {
                                        temp.img = image === null || image === void 0 ? void 0 : image.imagePath;
                                    }
                                }
                                uiActionGroup.details.push(temp);
                            });
                        }
                        detailOpts.uiActionGroup = uiActionGroup;
                        // 受控容器的成员
                        let showMoreModeItems = [];
                        //  支持锚点的成员
                        let anchorPoints = [];
                        // 分组面板支持锚点
                        if (detail === null || detail === void 0 ? void 0 : detail.enableAnchor) {
                            this.groupAnchorDatas.push({
                                caption: detail.caption,
                                codeName: detail.codeName,
                            });
                        }
                        (_d = detail.getPSDEFormDetails()) === null || _d === void 0 ? void 0 : _d.forEach((item, index) => {
                            var _a;
                            if (!item)
                                return;
                            if (item.showMoreMode == 1) {
                                showMoreModeItems.push(item.name);
                            }
                            this.setAnchorItems(item, anchorPoints);
                            const showMore = (_a = item.getShowMoreMgrPSDEFormDetail) === null || _a === void 0 ? void 0 : _a.call(item);
                            if (showMore && showMore.id && Object.is(showMore.id, detail.name)) {
                                detailOpts.isManageContainer = true;
                            }
                        });
                        detailOpts.controlledItems = showMoreModeItems;
                        detailOpts.anchorPoints = anchorPoints;
                        detailModel = new FormGroupPanelModel(detailOpts);
                        break;
                    case 'TABPANEL':
                        // 添加tab分页
                        let tabPages = [];
                        (_e = detail.getPSDEFormTabPages()) === null || _e === void 0 ? void 0 : _e.forEach((item, index) => {
                            tabPages.push({
                                name: item.name,
                                index: index,
                                visible: !ModelTool.findGroupLogicByLogicCat('PANELVISIBLE', detail.getPSDEFDGroupLogics()),
                            });
                        });
                        Object.assign(detailOpts, {
                            tabPages: tabPages,
                        });
                        detailModel = new FormTabPanelModel(detailOpts);
                        break;
                    case 'TABPAGE':
                        detailModel = new FormTabPageModel(detailOpts);
                        break;
                    case 'FORMPAGE':
                        detailModel = new FormPageModel(detailOpts);
                        break;
                    case 'FORMPART':
                        detailModel = new FormPartModel(detailOpts);
                        break;
                    case 'DRUIPART':
                        this.drCount++;
                        detailModel = new FormDruipartModel(detailOpts);
                        break;
                    case 'IFRAME':
                        detailModel = new FormIFrameModel(detailOpts);
                        break;
                    case 'RAWITEM':
                        detailModel = new FormRawItemModel(detailOpts);
                        break;
                    case 'USERCONTROL':
                        detailModel = new FormUserControlModel(detailOpts);
                        break;
                }
                this.$set(this.detailsModel, detail.name, detailModel);
            }
        }
        // 有分页头表格时
        if (!noTabHeader) {
            let formPages = [];
            (_f = this.controlInstance.getPSDEFormPages()) === null || _f === void 0 ? void 0 : _f.forEach((item, index) => {
                formPages.push({
                    name: item.name,
                    index: index,
                    visible: !ModelTool.findGroupLogicByLogicCat('PANELVISIBLE', item.getPSDEFDGroupLogics()),
                });
            });
            this.$set(this.detailsModel, name, new FormTabPanelModel({
                caption: name,
                detailType: 'TABPANEL',
                name: name,
                visible: true,
                isShowCaption: true,
                form: this,
                tabPages: formPages,
            }));
        }
    }
    /**
     * 重置表单项值
     *
     * @public
     * @param {{ name: string }} { name } 名称
     * @memberof AppDefaultForm
     */
    resetFormData({ name }) {
        const formItems = ModelTool.getAllFormItems(this.controlInstance);
        if (formItems && formItems.length > 0) {
            for (const item of formItems) {
                if (item.resetItemName && item.resetItemName == name) {
                    this.onFormItemValueChange({ name: item.name, value: null });
                    if (item.valueItemName) {
                        this.onFormItemValueChange({ name: item.valueItemName, value: null });
                    }
                }
            }
        }
    }
    /**
     * 表单逻辑
     *
     * @public
     * @param {{ name: string }} { name } 名称
     * @memberof FormControlBase
     */
    async formLogic({ name }) {
        var _a;
        const allFormDetails = ModelTool.getAllFormDetails(this.controlInstance);
        // 表单动态逻辑
        allFormDetails === null || allFormDetails === void 0 ? void 0 : allFormDetails.forEach((detail) => {
            var _a;
            (_a = detail.getPSDEFDGroupLogics()) === null || _a === void 0 ? void 0 : _a.forEach((logic) => {
                // todo lxm 缺少getRelatedDetailNames
                let relatedNames = logic.getRelatedDetailNames() || [];
                if (Object.is(name, '') || relatedNames.indexOf(name) != -1) {
                    let ret = this.verifyGroupLogic(this.data, logic);
                    switch (logic.logicCat) {
                        // 动态空输入，不满足则必填
                        case 'ITEMBLANK':
                            this.detailsModel[detail.name].required = !ret;
                            break;
                        // 动态启用，满足则启用
                        case 'ITEMENABLE':
                            this.detailsModel[detail.name].setDisabled(!ret);
                            break;
                        // 动态显示，满足则显示
                        case 'PANELVISIBLE':
                            this.detailsModel[detail.name].setVisible(ret);
                            break;
                    }
                }
            });
        });
        // 表单项更新
        let formDetail = ModelTool.getFormDetailByName(this.controlInstance, name);
        const formItemUpdate = (_a = formDetail === null || formDetail === void 0 ? void 0 : formDetail.getPSDEFormItemUpdate) === null || _a === void 0 ? void 0 : _a.call(formDetail);
        if (formItemUpdate) {
            if (await this.checkItem(formDetail.name)) {
                if (formItemUpdate.customCode) {
                    if (formItemUpdate.scriptCode) {
                        const context = Util.deepCopy(this.context);
                        const viewparams = Util.deepCopy(this.viewparams);
                        let data = this.data;
                        eval(formItemUpdate.scriptCode);
                    }
                }
                else {
                    const showBusyIndicator = formItemUpdate.showBusyIndicator;
                    const getPSAppDEMethod = formItemUpdate.getPSAppDEMethod();
                    const getPSDEFIUpdateDetails = formItemUpdate.getPSDEFIUpdateDetails();
                    let details = [];
                    getPSDEFIUpdateDetails === null || getPSDEFIUpdateDetails === void 0 ? void 0 : getPSDEFIUpdateDetails.forEach((item) => {
                        details.push(item.name);
                    });
                    this.updateFormItems(getPSAppDEMethod === null || getPSAppDEMethod === void 0 ? void 0 : getPSAppDEMethod.codeName, this.data, details, showBusyIndicator);
                }
            }
        }
        //强制刷新,解决某些情况下detailsModel改变而页面不刷新的问题。
        this.$forceUpdate();
    }
    /**
     * 校验动态逻辑结果
     *
     * @param {*} data 数据对象
     * @param {*} logic 逻辑对象
     * @returns
     * @memberof EditFormControlBase
     */
    verifyGroupLogic(data, logic) {
        var _a, _b, _c, _d;
        if (logic.logicType == 'GROUP' && ((_a = logic === null || logic === void 0 ? void 0 : logic.getPSDEFDLogics()) === null || _a === void 0 ? void 0 : _a.length)) {
            let result = true;
            if (logic.groupOP == 'AND') {
                let falseItem = (_b = logic.getPSDEFDLogics()) === null || _b === void 0 ? void 0 : _b.find((childLogic) => {
                    return !this.verifyGroupLogic(data, childLogic);
                });
                result = falseItem == undefined;
            }
            else if (logic.groupOP == 'OR') {
                let trueItem = (_c = logic.getPSDEFDLogics()) === null || _c === void 0 ? void 0 : _c.find((childLogic) => {
                    return this.verifyGroupLogic(data, childLogic);
                });
                result = trueItem != undefined;
            }
            // 是否取反
            return logic.notMode ? !result : result;
        }
        else if (logic.logicType == 'SINGLE') {
            let singleLogic = logic;
            return Verify.testCond(data[(_d = singleLogic.dEFDName) === null || _d === void 0 ? void 0 : _d.toLowerCase()], singleLogic.condOP, singleLogic.value);
        }
        return false;
    }
    /**
     * 处理操作列点击
     *
     * @param {*} event 事件对象
     * @param {*} formDetail 表单成员模型对象
     * @param {*} actionDetal 界面行为模型对象
     * @memberof EditFormControlBase
     */
    handleActionClick(event, formDetail, actionDetal) {
        AppViewLogicService.getInstance().executeViewLogic(this.getViewLogicTag(this.controlInstance.name, formDetail.codeName, actionDetal.name), event, this, undefined, this.controlInstance.getPSAppViewLogics() || []);
    }
}
