import { Subject } from 'rxjs';
import { AppCenterService } from '../app-service';
import { AppWizardPanelService } from '../ctrl-service';
import { MainControlBase } from './main-control-base';
export class WizardPanelControlBase extends MainControlBase {
    constructor() {
        super(...arguments);
        /**
         * 向导表单参数
         *
         * @type {*}
         * @memberof WizardPanelControlBase
         */
        this.formParam = {};
        /**
         * 执行过的表单
         *
         * @public
         * @type {Array<string>}
         * @memberof WizardPanelControlBase
         */
        this.historyForms = [];
        /**
         * 步骤行为集合
         *
         * @type {*}
         * @memberof WizardPanelControlBase
         */
        this.stepActions = {};
        /**
         * 向导表单集合
         *
         * @type {Array<any>}
         * @memberof WizardPanelControlBase
         */
        this.wizardForms = [];
        /**
         * 当前状态
         *
         * @memberof WizardPanelControlBase
         */
        this.curState = '';
        /**
         * 当前激活表单
         *
         * @type {string}
         * @memberof WizardPanelControlBase
         */
        this.activeForm = '';
        /**
         * 步骤标识集合
         *
         * @type {*}
         * @memberof WizardPanelControlBase
         */
        this.stepTags = {};
        /**
         * 步骤集合
         *
         * @type {*}
         * @memberof WizardPanelControlBase
         */
        this.steps = [];
        /**
         * 视图状态订阅对象
         *
         * @public
         * @type {Subject<{action: string, data: any}>}
         * @memberof WizardPanelControlBase
         */
        this.wizardState = new Subject();
        /**
         * 是否FormLoad被阻塞
         *
         * @type {boolean}
         * @memberof WizardPanelControlBase
         */
        this.hasFormLoadBlocked = false;
    }
    /**
     * 部件模型数据初始化实例
     *
     * @memberof WizardPanelControlBase
     */
    async ctrlModelInit(args) {
        var _a, _b, _c, _d;
        await super.ctrlModelInit(args);
        await this.ctrlModelFill();
        this.initAction = ((_b = (_a = this.controlInstance.getInitPSControlAction()) === null || _a === void 0 ? void 0 : _a.getPSAppDEMethod()) === null || _b === void 0 ? void 0 : _b.codeName) || 'Get';
        this.finishAction = ((_d = (_c = this.controlInstance.getFinishPSControlAction()) === null || _c === void 0 ? void 0 : _c.getPSAppDEMethod()) === null || _d === void 0 ? void 0 : _d.codeName) || 'Update';
        if (!(this.Environment && this.Environment.isPreviewMode)) {
            this.service = new AppWizardPanelService(this.controlInstance, this.context);
            await this.service.loaded();
        }
        this.initActiveForm();
    }
    /**
     * 部件模型填充
     *
     * @return {*}
     * @memberof WizardPanelControlBase
     */
    async ctrlModelFill() {
        var _a;
        const wizard = this.controlInstance.getPSDEWizard();
        if (!wizard) {
            return;
        }
        await this.controlInstance.fill();
        const wizardForms = wizard.getPSDEWizardForms() || [];
        for (const form of wizardForms) {
            await form.fill();
            await ((_a = form.getPSDEWizardStep()) === null || _a === void 0 ? void 0 : _a.fill());
        }
    }
    /**
     * 部件初始化
     *
     * @memberof WizardPanelControlBase
     */
    ctrlInit() {
        super.ctrlInit();
        this.regFormActions();
        if (this.activeForm) {
            this.historyForms.push(this.activeForm);
        }
    }
    viewStateAction(tag, action, data) {
        if (!Object.is(tag, this.name)) {
            return;
        }
        super.viewStateAction(tag, action, data);
        if (Object.is('load', action)) {
            this.doInit(data);
        }
    }
    /**
     * 部件挂载
     *
     * @memberof ControlBase
     */
    ctrlMounted(args) {
        var _a;
        super.ctrlMounted(args);
        (_a = this.controlInstance.getPSDEEditForms()) === null || _a === void 0 ? void 0 : _a.forEach((item) => {
            this.mountedMap.set(item.name, false);
        });
    }
    /**
     * 初始化当前激活表单
     *
     * @memberof WizardPanelControlBase
     */
    initActiveForm() {
        var _a;
        const wizard = this.controlInstance.getPSDEWizard();
        const wizardForms = (wizard === null || wizard === void 0 ? void 0 : wizard.getPSDEWizardForms()) || [];
        if (wizard && wizardForms.length > 0) {
            const firstForm = wizardForms.find((form) => {
                return form.firstForm;
            });
            this.activeForm = `${this.controlInstance.name}_form_${(_a = firstForm.formTag) === null || _a === void 0 ? void 0 : _a.toLowerCase()}`;
        }
    }
    /**
     * 注册表单步骤行为
     *
     * @memberof WizardPanelControlBase
     */
    regFormActions() {
        const wizard = this.controlInstance.getPSDEWizard();
        const wizardForms = (wizard === null || wizard === void 0 ? void 0 : wizard.getPSDEWizardForms()) || [];
        const wizardSteps = (wizard === null || wizard === void 0 ? void 0 : wizard.getPSDEWizardSteps()) || [];
        if (wizard && wizardForms.length > 0) {
            wizardForms.forEach((stepForm) => {
                var _a, _b, _c, _d, _e;
                const formName = `${this.controlInstance.name}_form_${(_a = stepForm.formTag) === null || _a === void 0 ? void 0 : _a.toLowerCase()}`;
                const editForm = (this.controlInstance.getPSDEEditForms() || []).find((form) => {
                    return form.name === formName;
                });
                const action = {
                    loadAction: ((_b = editForm === null || editForm === void 0 ? void 0 : editForm.getGetPSControlAction()) === null || _b === void 0 ? void 0 : _b.actionName) || 'Get',
                    preAction: (_c = editForm === null || editForm === void 0 ? void 0 : editForm.getGoBackPSControlAction()) === null || _c === void 0 ? void 0 : _c.actionName,
                    saveAction: ((_d = editForm === null || editForm === void 0 ? void 0 : editForm.getUpdatePSControlAction()) === null || _d === void 0 ? void 0 : _d.actionName) || 'Update',
                    actions: stepForm.getStepActions() || [],
                };
                this.regFormAction(formName, action, this.getStepTag(wizardSteps, (_e = stepForm === null || stepForm === void 0 ? void 0 : stepForm.getPSDEWizardStep()) === null || _e === void 0 ? void 0 : _e.stepTag));
            });
        }
        if (wizardSteps.length > 0) {
            wizardSteps.forEach((steps) => {
                this.steps.push(steps.stepTag);
            });
        }
    }
    /**
     * 上一步
     *
     * @memberof WizardPanelControlBase
     */
    onClickPrev() {
        const length = this.historyForms.length;
        if (length > 1) {
            this.curState = 'PREV';
            if (this.stepActions[this.activeForm].preAction) {
                this.wizardState.next({ tag: this.activeForm, action: 'panelaction', data: { action: this.stepActions[this.activeForm].preAction, emitAction: 'save', data: this.formParam } });
            }
            else {
                this.activeForm = this.historyForms[length - 1];
                setTimeout(() => {
                    this.formLoad();
                }, 1);
                this.historyForms.splice(length - 1, 1);
            }
        }
    }
    /**
     * 下一步
     *
     * @memberof WizardPanelControlBase
     */
    onClickNext() {
        var _a;
        if (this.Environment && this.Environment.isPreviewMode) {
            return;
        }
        if (this.activeForm) {
            if (this.$refs && ((_a = this.$refs[this.activeForm]) === null || _a === void 0 ? void 0 : _a.ctrl)) {
                let form = this.$refs[this.activeForm].ctrl;
                if (form.formValidateStatus()) {
                    this.curState = 'NEXT';
                    this.wizardState.next({ tag: this.activeForm, action: 'panelaction', data: { action: this.stepActions[this.activeForm].saveAction, emitAction: 'save', data: this.formParam } });
                }
                else {
                    this.$throw(this.$t('app.commonwords.rulesexception'), 'onClickNext');
                }
            }
        }
    }
    /**
     * 完成
     *
     * @memberof WizardPanelControlBase
     */
    onClickFinish() {
        if (this.activeForm) {
            if (this.$refs && this.$refs[this.activeForm] && this.$refs[this.activeForm].ctrl) {
                let form = this.$refs[this.activeForm].ctrl;
                if (form.formValidateStatus()) {
                    this.curState = 'FINISH';
                    this.wizardState.next({ tag: this.activeForm, action: 'panelaction', data: { action: this.stepActions[this.activeForm].saveAction, emitAction: 'save', data: this.formParam } });
                }
                else {
                    this.$throw(this.$t('app.commonwords.rulesexception'), 'onClickFinish');
                }
            }
        }
    }
    /**
     * 向导表单加载完成
     *
     * @param {*} args
     * @param {string} name
     * @memberof WizardPanelControlBase
     */
    wizardpanelFormload(args, name) {
        if (args) {
            Object.assign(this.formParam, args);
        }
    }
    /**
     * 向导表单保存完成
     *
     * @param {*} args
     * @param {string} name
     * @memberof WizardPanelControlBase
     */
    wizardpanelFormsave(args, name) {
        Object.assign(this.formParam, args);
        if (Object.is(this.curState, 'NEXT')) {
            this.historyForms.push(name);
            if (this.getNextForm()) {
                this.activeForm = this.getNextForm();
                setTimeout(() => {
                    this.formLoad();
                }, 1);
            }
            else {
                this.doFinish();
            }
        }
        else if (Object.is(this.curState, 'PREV')) {
            const length = this.historyForms.length;
            if (length > 1) {
                this.activeForm = this.historyForms[length - 1];
                setTimeout(() => {
                    this.formLoad();
                }, 1);
                this.historyForms.splice(length - 1, 1);
            }
        }
        else if (Object.is(this.curState, 'FINISH')) {
            this.doFinish();
        }
    }
    /**
     * 获取步骤标识
     *
     * @memberof WizardPanelControlBase
     */
    getStepTag(wizardSteps, tag) {
        if (wizardSteps && wizardSteps.length > 0 && tag) {
            const curStep = wizardSteps.find((step) => {
                return step.stepTag === tag;
            });
            return curStep.stepTag || tag;
        }
        else {
            return tag;
        }
    }
    /**
     * 注册表单步骤行为
     *
     * @memberof WizardPanelControlBase
     */
    regFormAction(name, actionParams, stepTag) {
        this.stepActions[name] = actionParams;
        this.stepTags[name] = stepTag;
        this.wizardForms.push(name);
    }
    /**
     * 初始化行为
     *
     * @memberof WizardPanelControlBase
     */
    doInit(opt = {}) {
        const arg = Object.assign({}, opt);
        Object.assign(arg, { viewparams: this.viewparams });
        let tempContext = JSON.parse(JSON.stringify(this.context));
        this.onControlRequset('doInit', tempContext, arg);
        const post = this.service.init(this.initAction, tempContext, arg, this.showBusyIndicator);
        post
            .then((response) => {
            this.onControlResponse('doInit', response);
            if (!response.status || response.status !== 200) {
                this.$throw(response, 'doInit');
                return;
            }
            this.formParam = response.data;
            if (response.data[this.appDeCodeName.toLowerCase()]) {
                Object.assign(this.context, { [this.appDeCodeName.toLowerCase()]: response.data[this.appDeCodeName.toLowerCase()] });
            }
            this.formLoad();
        })
            .catch((response) => {
            this.onControlResponse('doInit', response);
            this.$throw(response, 'doInit');
        });
    }
    /**
     * 表单加载
     *
     * @memberof WizardPanelControlBase
     */
    formLoad() {
        if (!this.mountedMap.get(this.activeForm)) {
            this.hasFormLoadBlocked = true;
            return;
        }
        if (this.activeForm) {
            this.wizardState.next({ tag: this.activeForm, action: 'panelaction', data: { action: this.stepActions[this.activeForm].loadAction, emitAction: 'load', data: this.formParam } });
        }
    }
    /**
     * 完成行为
     *
     * @memberof WizardPanelControlBase
     */
    doFinish() {
        let arg = {};
        Object.assign(arg, this.formParam);
        Object.assign(arg, { viewparams: this.viewparams });
        let tempContext = JSON.parse(JSON.stringify(this.context));
        this.onControlRequset('doFinish', tempContext, arg);
        if (this.context.srfcallbacktype && this.context.srfcallbackid) {
            Object.assign(arg, { srfcallbacktype: this.context.srfcallbacktype, srfcallbackid: this.context.srfcallbackid });
        }
        const post = this.service.finish(this.finishAction, tempContext, arg, this.showBusyIndicator);
        post
            .then((response) => {
            this.onControlResponse('doFinish', response);
            if (!response.status || response.status !== 200) {
                this.$throw(response, 'doFinish');
                return;
            }
            const data = response.data;
            this.ctrlEvent({
                controlname: this.controlInstance.name,
                action: 'finish',
                data: data,
            });
            AppCenterService.notifyMessage({ name: this.appDeCodeName, action: 'appRefresh', data: data });
        })
            .catch((response) => {
            this.onControlResponse('doFinish', response);
            this.$throw(response, 'doFinish');
        });
    }
    /**
     * 获取下一步向导表单
     *
     * @memberof WizardPanelControlBase
     */
    getNextForm() {
        if (this.formParam && this.formParam['srfnextform']) {
            return `${this.controlInstance.name}_form_${this.formParam['srfnextform'].toLowerCase()}`;
        }
        else {
            let index = this.wizardForms.indexOf(this.activeForm);
            if (index >= 0) {
                if (this.wizardForms[index + 1]) {
                    return this.wizardForms[index + 1];
                }
            }
            return undefined;
        }
    }
    /**
     * 是否隐藏
     *
     * @param {string} type
     * @memberof WizardPanelControlBase
     */
    isHidden(type) {
        const actions = this.stepActions[this.activeForm].actions;
        if (actions && actions.indexOf(type) < 0) {
            return true;
        }
        return false;
    }
    /**
     * 部件事件
     * @param ctrl 部件
     * @param action  行为
     * @param data 数据
     *
     * @memberof WizardPanelControlBase
     */
    onCtrlEvent(controlname, action, data) {
        if (action == 'controlIsMounted') {
            this.setIsMounted(controlname);
            if (this.hasFormLoadBlocked) {
                this.formLoad();
                this.hasFormLoadBlocked = false;
            }
        }
        else if (Object.is(action, 'save')) {
            this.wizardpanelFormsave(data, controlname);
        }
        else if (Object.is(action, 'load')) {
            this.wizardpanelFormload(data, controlname);
        }
    }
    ctrlDestroyed() {
        super.ctrlDestroyed();
        this.wizardState.complete();
    }
}
