import { WFDynaEditViewEngine, Util, ModelTool, GetModelService, LogUtil, throttle } from '@ibizstudio/runtime';
import { AppCenterService, AppViewLogicService } from '../app-service';
import { MainViewBase } from './mainview-base';
/**
 * 工作流动态编辑视图基类
 *
 * @export
 * @class WFDynaEditViewBase
 * @extends {MainViewBase}
 */
export class WFDynaEditViewBase extends MainViewBase {
    constructor() {
        super(...arguments);
        /**
         * 视图引擎
         *
         * @public
         * @type {Engine}
         * @memberof WFDynaEditViewBase
         */
        this.engine = new WFDynaEditViewEngine();
        /**
         * 工具栏模型数据
         *
         * @memberof WFDynaEditViewBase
         */
        this.linkModel = [];
        /**
         * 视图引用数据
         *
         * @memberof WFDynaEditViewBase
         */
        this.viewRefData = {};
        /**
         * 关系数据分页部件分页
         *
         * @type {IPSDEDRTabPage[] | null}
         * @memberof WFDynaEditViewBase
         */
        this.deDRTabPages = [];
        /**
         * 是否可编辑
         *
         * @type {boolean}
         * @memberof WFDynaEditViewBase
         */
        this.isEditable = true;
        /**
         * 工作流附加功能类型映射关系对象
         *
         * @memberof WFDynaEditViewBase
         */
        this.wfAddiFeatureRef = {
            "reassign": { featureTag: "REASSIGN", action: "TransFerTask" },
            "addstepbefore": { featureTag: "ADDSTEPBEFORE", action: "BeforeSign" },
            "sendback": { featureTag: "SENDBACK", action: "SendBack" },
            "sendcopy": { featureTag: "SENDCOPY", action: "sendCopy" }
        };
    }
    /**
     * 引擎初始化
     *
     * @public
     * @memberof WFDynaEditViewBase
     */
    engineInit() {
        if (this.Environment && this.Environment.isPreviewMode) {
            return;
        }
        this.engine.init({
            view: this,
            parentContainer: this.$parent,
            keyPSDEField: this.appDeCodeName.toLowerCase(),
            majorPSDEField: this.appDeMajorFieldName.toLowerCase(),
            isLoadDefault: this.viewInstance.loadDefault,
        });
    }
    /**
     * 初始化挂载状态集合
     *
     * @memberof WFDynaEditViewBase
     */
    initMountedMap() {
        this.mountedMap.set('self', false);
    }
    /**
     * 设置已经绘制完成状态
     *
     * @memberof WFDynaEditViewBase
     */
    setIsMounted(name = 'self') {
        var _a;
        super.setIsMounted(name);
        if (((_a = this.editFormInstance) === null || _a === void 0 ? void 0 : _a.name) == name) {
            this.viewState.next({ tag: this.editFormInstance.name, action: 'autoload', data: { srfkey: this.context[this.appDeCodeName.toLowerCase()] } });
        }
    }
    /**
     * 初始化编辑视图实例
     *
     * @memberof WFDynaEditViewBase
     */
    async viewModelInit() {
        var _a;
        await super.viewModelInit();
        this.viewRefData = await ModelTool.loadedAppViewRef(this.viewInstance);
        this.drtabInstance = ModelTool.findPSControlByName('drtab', this.viewInstance.getPSControls());
        this.deDRTabPages = (_a = this.drtabInstance) === null || _a === void 0 ? void 0 : _a.getPSDEDRTabPages();
    }
    /**
     * 初始化工具栏数据
     *
     * @memberof WFDynaEditViewBase
     */
    renderToolBar() {
        var _a, _b;
        return (<div slot="toolbar">
                <div class='toolbar-container'>
                    {this.linkModel.map((linkItem) => {
                return (<tooltip transfer={true} max-width={600}>
                                    <i-button on-click={(event) => { throttle(this.dynamic_toolbar_click, [linkItem, event], this); }} loading={this.viewLoadingService.isLoading}>
                                        <span class='caption'>{linkItem.sequenceFlowName}</span>
                                    </i-button>
                                    <div slot='content'>{linkItem.sequenceFlowName}</div>
                                </tooltip>);
            })}
                    {this.uiActionGroup && ((_b = (_a = this.uiActionGroup) === null || _a === void 0 ? void 0 : _a.details) === null || _b === void 0 ? void 0 : _b.map((item) => {
                return (<tooltip v-show={item.visabled} transfer={true} max-width={600}>
                              <i-button disabled={item.disabled} on-click={(event) => { throttle(this.handleActionClick, [event, item], this); }} loading={this.viewLoadingService.isLoading}>
                                  <span class='caption'>{item.caption}</span>
                              </i-button>
                              <div slot='content'>{item.caption}</div>
                          </tooltip>);
            }))}
                </div>
            </div>);
    }
    /**
     * 渲染视图主体内容区
     *
     * @memberof WFDynaEditViewBase
     */
    renderMainContent() {
        var _a;
        if (!this.editFormInstance) {
            return;
        }
        if (this.deDRTabPages && this.deDRTabPages.length > 0) {
            const tempContext = Util.deepCopy(this.context);
            const tabsName = `${(_a = this.appDeCodeName) === null || _a === void 0 ? void 0 : _a.toLowerCase()}_${this.viewInstance.codeName.toLowerCase()}`;
            return (<tabs animated={false} name={tabsName} class="workflow-tabs-container">
                    <tab-pane tab={tabsName} label={this.editFormInstance.logicName}>
                        {this.renderFormContent()}
                    </tab-pane>
                    {this.deDRTabPages.map((deDRTabPage) => {
                    var _a, _b, _c;
                    return (<tab-pane tab={tabsName} label={this.$tl((_a = deDRTabPage.getCapPSLanguageRes()) === null || _a === void 0 ? void 0 : _a.lanResTag, deDRTabPage.caption)}>
                                {this.$createElement('app-view-shell', {
                            props: {
                                staticProps: {
                                    viewDefaultUsage: false,
                                    appDeCodeName: this.appDeCodeName
                                },
                                dynamicProps: {
                                    viewdata: JSON.stringify(Object.assign(tempContext, { viewpath: (_c = (_b = deDRTabPage === null || deDRTabPage === void 0 ? void 0 : deDRTabPage.M) === null || _b === void 0 ? void 0 : _b.getPSAppView) === null || _c === void 0 ? void 0 : _c.path })),
                                    viewparam: JSON.stringify(this.viewparams),
                                },
                            }
                        })}
                            </tab-pane>);
                })}
                </tabs>);
        }
        else {
            return this.renderFormContent();
        }
    }
    /**
     * 渲染流程表单内容区
     *
     * @memberof WFDynaEditViewBase
     */
    renderFormContent() {
        if (!this.editFormInstance) {
            return;
        }
        let { targetCtrlName, targetCtrlParam, targetCtrlEvent } = this.computeTargetCtrlData(this.editFormInstance);
        Object.assign(targetCtrlParam.staticProps, {
            iseditable: this.isEditable
        });
        return (this.$createElement(targetCtrlName, { slot: 'default', props: targetCtrlParam, ref: this.editFormInstance.name, on: targetCtrlEvent }));
    }
    /**
     * 获取动态表单模型
     *
     * @memberof WFDynaEditViewBase
     */
    getFormModel() {
        return new Promise((resolve, reject) => {
            let datas = [];
            if (Object.keys(this.viewparams).length > 0) {
                Object.assign(datas, { 'processDefinitionKey': this.viewparams.processDefinitionKey });
                Object.assign(datas, { 'taskDefinitionKey': this.viewparams.taskDefinitionKey });
            }
            this.appEntityService.getWFStep(JSON.parse(JSON.stringify(this.context)), datas, true).then((response) => {
                if (response && response.status === 200) {
                    const data = response.data;
                    this.isEditable = data.iseditable === 'true';
                    if (data && data['process-form']) {
                        this.computeActivedForm(data['process-form']);
                    }
                    else {
                        this.computeActivedForm(null);
                    }
                }
            }).catch((response) => {
                this.$throw(response, 'getFormModel');
            });
        });
    }
    /**
     * 获取工具栏按钮
     *
     * @memberof WFDynaEditViewBase
     */
    getWFLinkModel(arg) {
        return new Promise((resolve, reject) => {
            let datas = [];
            if (Object.keys(this.viewparams).length > 0) {
                Object.assign(datas, { 'processDefinitionKey': this.viewparams.processDefinitionKey });
                Object.assign(datas, { 'taskDefinitionKey': this.viewparams.taskDefinitionKey });
            }
            if (arg && Object.keys(arg).length > 0) {
                Object.assign(datas, { activedata: arg });
            }
            this.appEntityService.GetWFLink(JSON.parse(JSON.stringify(this.context)), datas, true).then((response) => {
                if (response && response.status === 200) {
                    this.linkModel = response.data;
                }
            }).catch((response) => {
                this.$throw(response, 'getWFLinkModel');
            });
        });
    }
    /**
     * 计算激活表单
     *
     * @memberof WFDynaEditViewBase
     */
    computeActivedForm(inputForm) {
        if (!inputForm) {
            this.editFormInstance = ModelTool.findPSControlByName('form', this.viewInstance.getPSControls());
        }
        else {
            this.editFormInstance = ModelTool.findPSControlByName(`wfform_${inputForm.toLowerCase()}`, this.viewInstance.getPSControls());
        }
        this.computeFormGroup();
        this.mountedMap.set(this.editFormInstance.name, false);
        this.$forceUpdate();
    }
    /**
     * @description 计算需要重绘的表单分组
     * @memberof WFDynaEditViewBase
     */
    computeFormGroup() {
        var _a, _b, _c, _d, _e, _f;
        // 获取表单第一个分组，如果它有界面行为组则赋值
        let formGroup = (_a = ModelTool.getAllFormDetails(this.editFormInstance)) === null || _a === void 0 ? void 0 : _a.find((item) => {
            return item.detailType == 'GROUPPANEL';
        });
        if (((_e = (_d = (_c = (_b = formGroup === null || formGroup === void 0 ? void 0 : formGroup.getPSUIActionGroup) === null || _b === void 0 ? void 0 : _b.call(formGroup)) === null || _c === void 0 ? void 0 : _c.getPSUIActionGroupDetails) === null || _d === void 0 ? void 0 : _d.call(_c)) === null || _e === void 0 ? void 0 : _e.length) > 0) {
            this.firstFormGroup = formGroup;
        }
        if (this.firstFormGroup) {
            var style = document.createElement('style');
            style.innerHTML = `#${this.firstFormGroup.codeName} .ivu-card-extra .ui-actions{ display:none; }`;
            (_f = document.getElementById(this.viewInstance.codeName)) === null || _f === void 0 ? void 0 : _f.appendChild(style);
        }
    }
    /**
     * 动态工具栏点击
     *
     * @memberof WFDynaEditViewBase
     */
    dynamic_toolbar_click(linkItem, $event) {
        const _this = this;
        let datas = [];
        let xData = this.$refs[this.editFormInstance.name].ctrl;
        if (xData.getDatas && xData.getDatas instanceof Function) {
            datas = [...xData.getDatas()];
        }
        const submit = (submitData, linkItem) => {
            xData.wfsubmit(submitData, linkItem).then((response) => {
                if (!response || response.status !== 200) {
                    return;
                }
                const { data: _data } = response;
                if (_this.viewdata) {
                    _this.$emit('view-event', { viewName: this.viewInstance.name, action: 'viewdataschange', data: [Object.assign({}, _data)] });
                    _this.$emit('view-event', { viewName: this.viewInstance.name, action: 'close', data: null });
                }
                else {
                    this.closeView([Object.assign({}, _data)]);
                }
            });
        };
        const submitAction = () => {
            var _a;
            if (linkItem && linkItem.sequenceflowview) {
                const targetViewRef = this.viewRefData.find((item) => {
                    return item.name === `WFACTION@${linkItem.sequenceflowview}`;
                });
                if (targetViewRef) {
                    let tempContext = Util.deepCopy(_this.context);
                    Object.assign(tempContext, { [this.appDeCodeName.toLowerCase()]: datas && datas[0].srfkey });
                    let tempViewParam = { actionView: linkItem.sequenceflowview, actionForm: linkItem.sequenceflowform };
                    Object.assign(tempContext, { viewpath: (_a = targetViewRef === null || targetViewRef === void 0 ? void 0 : targetViewRef.getRefPSAppView) === null || _a === void 0 ? void 0 : _a.path });
                    GetModelService(tempContext).then((modelService) => {
                        var _a;
                        modelService.getPSAppView((_a = targetViewRef === null || targetViewRef === void 0 ? void 0 : targetViewRef.getRefPSAppView) === null || _a === void 0 ? void 0 : _a.path).then((viewResult) => {
                            var _a;
                            const appmodal = _this.$appmodal.openModal({ viewname: 'app-view-shell', title: this.$tl((_a = viewResult.getCapPSLanguageRes()) === null || _a === void 0 ? void 0 : _a.lanResTag, viewResult.caption), height: viewResult.height, width: viewResult.width }, tempContext, tempViewParam);
                            appmodal.subscribe((result) => {
                                if (!result || !Object.is(result.ret, 'OK')) {
                                    return;
                                }
                                let tempSubmitData = Util.deepCopy(datas[0]);
                                if (result.datas && result.datas[0]) {
                                    const resultData = result.datas[0];
                                    if (Object.keys(resultData).length > 0) {
                                        let tempData = {};
                                        Object.keys(resultData).forEach((key) => {
                                            if (resultData[key] && (key !== "srfuf"))
                                                tempData[key] = resultData[key];
                                        });
                                        Object.assign(tempSubmitData, tempData);
                                    }
                                }
                                submit([tempSubmitData], linkItem);
                            });
                        });
                    });
                }
            }
            else {
                submit(datas, linkItem);
            }
        };
        if (linkItem && linkItem.type) {
            if (Object.is(linkItem.type, "finish")) {
                submitAction();
            }
            else {
                this.handleWFAddiFeature(linkItem);
            }
        }
        else {
            submitAction();
        }
    }
    /**
     * 处理工作流辅助功能
     *
     * @memberof WFDynaEditViewBase
     */
    handleWFAddiFeature(linkItem) {
        var _a, _b;
        let featureTag = (_a = this.wfAddiFeatureRef[linkItem === null || linkItem === void 0 ? void 0 : linkItem.type]) === null || _a === void 0 ? void 0 : _a.featureTag;
        if (!featureTag)
            return;
        let targetViewRef = this.viewRefData.find((item) => {
            return item.name === `WFUTILACTION@${featureTag}`;
        });
        if (!targetViewRef) {
            LogUtil.warn(this.$t('app.wizardpanel.nofind'));
            return;
        }
        // 准备参数
        let datas = [];
        let xData = this.$refs[this.editFormInstance.name].ctrl;
        if (xData.getDatas && xData.getDatas instanceof Function) {
            datas = [...xData.getDatas()];
        }
        let tempContext = Util.deepCopy(this.context);
        Object.assign(tempContext, { [this.appDeCodeName.toLowerCase()]: datas && datas[0].srfkey });
        let tempViewParam = { actionView: linkItem.sequenceflowview, actionForm: linkItem.sequenceflowform };
        Object.assign(tempContext, { viewpath: (_b = targetViewRef === null || targetViewRef === void 0 ? void 0 : targetViewRef.getRefPSAppView) === null || _b === void 0 ? void 0 : _b.path });
        GetModelService(tempContext).then((modelService) => {
            var _a;
            modelService.getPSAppView((_a = targetViewRef === null || targetViewRef === void 0 ? void 0 : targetViewRef.getRefPSAppView) === null || _a === void 0 ? void 0 : _a.path).then((viewResult) => {
                var _a;
                const appmodal = this.$appmodal.openModal({ viewname: 'app-view-shell', title: this.$tl((_a = viewResult.getCapPSLanguageRes()) === null || _a === void 0 ? void 0 : _a.lanResTag, viewResult.caption), height: viewResult.height, width: viewResult.width }, tempContext, tempViewParam);
                appmodal.subscribe((result) => {
                    if (!result || !Object.is(result.ret, 'OK')) {
                        return;
                    }
                    let tempSubmitData = Util.deepCopy(datas[0]);
                    if (result.datas && result.datas[0]) {
                        const resultData = result.datas[0];
                        if (Object.keys(resultData).length > 0) {
                            let tempData = {};
                            Object.keys(resultData).forEach((key) => {
                                if (resultData[key] && (key !== "srfuf"))
                                    tempData[key] = resultData[key];
                            });
                            Object.assign(tempSubmitData, tempData);
                        }
                        this.submitWFAddiFeature(linkItem, tempSubmitData);
                    }
                });
            });
        });
    }
    /**
     * 提交工作流辅助功能
     *
     * @memberof WFDynaEditViewBase
     */
    submitWFAddiFeature(linkItem, submitData) {
        var _a;
        let tempSubmitData = Object.assign(linkItem, { "activedata": submitData });
        let action = (_a = this.wfAddiFeatureRef[linkItem === null || linkItem === void 0 ? void 0 : linkItem.type]) === null || _a === void 0 ? void 0 : _a.action;
        if (!action)
            return;
        this.appEntityService[action](Util.deepCopy(this.context), tempSubmitData).then((response) => {
            const { data: data } = response;
            if (!response || response.status !== 200) {
                this.$throw(response, 'submitWFAddiFeature');
                return;
            }
            let _this = this;
            if (_this.viewdata) {
                _this.$emit('view-event', { viewName: this.viewInstance.name, action: 'viewdataschange', data: [Object.assign({}, data)] });
                _this.$emit('view-event', { viewName: this.viewInstance.name, action: 'close', data: null });
            }
            else {
                this.closeView([Object.assign({}, data)]);
            }
            AppCenterService.notifyMessage({ name: this.appDeCodeName, action: 'appRefresh', data: data });
            this.$success((data === null || data === void 0 ? void 0 : data.message) ? data.message : this.$t('app.wizardpanel.success'), 'submitWFAddiFeature');
        }).catch((error) => {
            this.$throw(error, 'submitWFAddiFeature');
        });
    }
    /**
     * 将待办任务标记为已读
     *
     * @param data 业务数据
     * @memberof WFDynaEditViewBase
     */
    readTask(data) {
        this.appEntityService.ReadTask(this.context, data).then((response) => {
            if (!response || response.status !== 200) {
                LogUtil.warn(this.$t('app.wizardpanel.error'));
                return;
            }
            AppCenterService.notifyMessage({ name: this.appDeCodeName, action: 'appRefresh', data: data });
        }).catch((error) => {
            LogUtil.warn(this.$t('app.wizardpanel.error'));
        });
    }
    /**
     * 处理操作列点击
     *
     * @param {*} event 事件对象
     * @param {*} item 界面行为的运行时模型对象
     * @memberof WFDynaEditViewBase
     */
    handleActionClick(event, item) {
        var _a, _b, _c;
        let actionDetal = (_c = (_b = (_a = this.firstFormGroup) === null || _a === void 0 ? void 0 : _a.getPSUIActionGroup()) === null || _b === void 0 ? void 0 : _b.getPSUIActionGroupDetails()) === null || _c === void 0 ? void 0 : _c.find((groupDetail) => {
            return item.name == `${this.firstFormGroup.name}_${groupDetail.name}`;
        });
        let formEl = this.$refs[this.editFormInstance.name].ctrl;
        if (actionDetal && formEl) {
            AppViewLogicService.getInstance().executeViewLogic(`${this.editFormInstance.name}_${this.firstFormGroup.codeName}_${actionDetal.name}_click`, event, formEl, undefined, this.editFormInstance.getPSAppViewLogics() || []);
        }
    }
    /**
     * 部件事件机制
     *
     * @param {string} ctrlName
     * @param {string} eventName
     * @param {*} args
     * @memberof CalendarExpViewEngine
     */
    onCtrlEvent(ctrlName, eventName, args) {
        var _a, _b;
        super.onCtrlEvent(ctrlName, eventName, args);
        if (ctrlName == ((_a = this.editFormInstance) === null || _a === void 0 ? void 0 : _a.name) && eventName == "load") {
            // 处理第一个表单分组的界面行为组
            if (this.firstFormGroup) {
                let formEl = this.$refs[this.editFormInstance.name].ctrl;
                this.uiActionGroup = (_b = formEl.detailsModel[this.firstFormGroup.name]) === null || _b === void 0 ? void 0 : _b.uiActionGroup;
            }
        }
    }
}
