import Vue from 'vue';
import qs from 'qs';
import { AppServiceBase, GetModelService, SandboxInstance, Util } from '@ibizstudio/runtime';
import { AppComponentService, AppNavHistory } from '../app-service';
// import { CommunicationService } from '@ibiz/model-location';
/**
 * 视图容器基类
 *
 * @export
 * @class ViewContainerBase
 * @extends {Vue}
 */
export class ViewContainerBase extends Vue {
    constructor() {
        super(...arguments);
        /**
         * 动态模型文件路径
         *
         * @public
         * @type {StringConstructor}
         * @memberof ViewContainerBase
         */
        this.dynaModelFilePath = '';
        /**
         * 视图标识
         *
         * @type {string}
         * @memberof ViewContainerBase
         */
        this.viewtag = '';
        /**
         * 视图容器
         *
         * @type {any}
         * @memberof ViewContainerBase
         */
        this.viewContainerName = '';
        /**
         * 临时动态视图上下文环境参数
         *
         * @type {ViewContext}
         * @memberof ViewBase
         */
        this.tempViewContext = {};
        /**
         * 动态视图上下文环境参数
         *
         * @type {*}
         * @memberof ViewBase
         */
        this.viewContext = {};
        /**
         * 应用上下文
         *
         * @type {*}
         * @memberof ViewContainerBase
         */
        this.context = {};
    }
    created() {
        const env = AppServiceBase.getInstance().getAppEnvironment();
        if (env.devMode) {
            this.selfPreview = this.selfPreview.bind(this);
            // const m = CommunicationService.getInstance();
            // m.evt.on('preview-view', this.selfPreview);
        }
    }
    destroyed() {
        const env = AppServiceBase.getInstance().getAppEnvironment();
        if (env.devMode) {
            // const m = CommunicationService.getInstance();
            // m.evt.off('preview-view', this.selfPreview);
        }
    }
    async selfPreview(res) {
        const model = res.model;
        if (model.dynaModelFilePath === this.dynaModelFilePath) {
            const s = await GetModelService(this.context);
            s.store.modelObject.delete(model.dynaModelFilePath);
            const view = (await s.getPSAppView(model));
            this.initViewContext({ modeldata: view });
            this.viewContainerName = '';
            setTimeout(() => {
                var _a;
                if (view) {
                    this.viewContainerName = AppComponentService.getViewComponents(view.viewType, view.viewStyle, (_a = view.getPSSysPFPlugin) === null || _a === void 0 ? void 0 : _a.pluginCode);
                }
                this.$forceUpdate();
            }, 100);
            this.$forceUpdate();
        }
    }
    /**
     * 视图容器初始化
     *
     * @memberof ViewContainerBase
     */
    async ViewContainerInit() {
        if (this.dynamicProps && this.dynamicProps.viewdata) {
            if (typeof this.dynamicProps.viewdata == 'string') {
                this.context = JSON.parse(this.dynamicProps.viewdata);
            }
            else {
                this.context = Util.deepCopy(this.dynamicProps.viewdata);
            }
            // 初始化沙箱实例
            if (this.context && this.context.hasOwnProperty('srfsandboxtag')) {
                await this.initSandBoxInst(this.context);
            }
            if (this.context && this.context.srfinsttag && this.context.srfinsttag2) {
                let dynainstParam = (await GetModelService({ srfsandboxtag: this.context.srfsandboxtag, instTag: this.context.srfinsttag, instTag2: this.context.srfinsttag2 })).getDynaInsConfig();
                Object.assign(this.context, { srfdynainstid: dynainstParam.id });
            }
            await this.computeDynaModelFilePath();
            this.loadDynamicModelData();
            return;
        }
        await this.computeDynaModelFilePath();
        // 路由打开
        if (this.$route && this.$route.fullPath && this.$route.fullPath.indexOf('?') > -1) {
            let tempViewParam = {};
            const tempViewparam = this.$route.fullPath.slice(this.$route.fullPath.indexOf('?') + 1);
            const viewparamArray = decodeURIComponent(tempViewparam).split(';');
            if (viewparamArray.length > 0) {
                viewparamArray.forEach((item) => {
                    Object.assign(tempViewParam, qs.parse(item));
                });
            }
            // 初始化沙箱实例
            if (tempViewParam && tempViewParam.hasOwnProperty('srfsandboxtag')) {
                await this.initSandBoxInst(tempViewParam);
            }
            if (tempViewParam.srfinsttag && tempViewParam.srfinsttag2) {
                let dynainstParam = (await GetModelService({ srfsandboxtag: tempViewParam.srfsandboxtag, instTag: tempViewParam.srfinsttag, instTag2: tempViewParam.srfinsttag2 })).getDynaInsConfig();
                this.context = { srfdynainstid: dynainstParam.id };
            }
            if (tempViewParam.srfdynainstid) {
                this.context = { srfdynainstid: tempViewParam.srfdynainstid };
            }
            // 补充沙箱实例参数（路由）
            if (tempViewParam && tempViewParam.hasOwnProperty('srfsandboxtag')) {
                Object.assign(this.context, { srfsandboxtag: tempViewParam.srfsandboxtag });
            }
        }
        this.loadDynamicModelData();
    }
    /**
     * 初始化沙箱实例
     *
     * @memberof ViewContainerBase
     */
    async initSandBoxInst(args) {
        if (args && args.srfsandboxtag) {
            const tempSandboxInst = new SandboxInstance(args);
            await tempSandboxInst.initSandBox();
        }
    }
    /**
     * 加载动态模型数据
     *
     * @type {Array<*>}
     * @memberof ViewContainerBase
     */
    async loadDynamicModelData() {
        var _a, _b, _c, _d, _e, _f;
        if (this.staticProps && this.staticProps.viewModelData) {
            this.modeldata = this.staticProps.viewModelData;
        }
        else {
            if (this.dynaModelFilePath) {
                const modelService = await GetModelService(this.context);
                this.modeldata = await modelService.getPSAppView(this.dynaModelFilePath);
            }
        }
        //  未找到模型数据跳转404页面
        if (Util.isEmpty(this.modeldata)) {
            console.warn(`未找到模型 ${this.dynaModelFilePath}, 跳转 404 界面`);
            this.$router.push('/404');
            return;
        }
        // 视图壳加载视图数据
        await ((_b = (_a = this.modeldata) === null || _a === void 0 ? void 0 : _a.fill) === null || _b === void 0 ? void 0 : _b.call(_a, true));
        this.initViewContext({ modeldata: this.modeldata });
        this.initViewMateInfo(this.modeldata);
        this.viewContainerName = AppComponentService.getViewComponents((_c = this.modeldata) === null || _c === void 0 ? void 0 : _c.viewType, (_d = this.modeldata) === null || _d === void 0 ? void 0 : _d.viewStyle, (_f = (_e = this.modeldata) === null || _e === void 0 ? void 0 : _e.getPSSysPFPlugin()) === null || _f === void 0 ? void 0 : _f.pluginCode);
        this.$forceUpdate();
    }
    /**
     * 初始化动态视图上下文环境参数
     *
     * @type {*} opts
     * @memberof ViewContainerBase
     */
    initViewContext(opts) {
        let temp = {};
        Object.defineProperty(temp, 'modeldata', { enumerable: false, writable: true });
        Object.assign(temp, this.tempViewContext, opts, Object.assign({ viewtag: this.viewtag, viewcontainer: this.context }, this.staticProps));
        // 删除viewModelData，避免递归
        if (temp.viewModelData) {
            delete temp.viewModelData;
        }
        this.viewContext = temp;
    }
    /**
     * 初始化视图容器元数据
     *
     * @type {*} opts
     * @memberof ViewContainerBase
     */
    initViewMateInfo(opts) {
        var _a, _b, _c;
        if (!this.dynamicProps || !this.dynamicProps.viewdata) {
            const initNavData = () => {
                if (this.$route.meta && !this.$route.meta.ignoreAddPage) {
                    let navHistory = AppServiceBase.getInstance().getAppNavDataService();
                    if (!navHistory) {
                        AppServiceBase.getInstance().setAppNavDataService(new AppNavHistory());
                        navHistory = AppServiceBase.getInstance().getAppNavDataService();
                    }
                    navHistory.add(this.$route);
                }
            };
            // 设置路由meta数据
            let activedView = this.$route.meta.parameters.find((item) => {
                return item.pathName === 'views';
            });
            if (Object.is(activedView.parameterName, 'view') && Object.is(activedView.pathName, 'views')) {
                this.$route.meta.captionTag = (_a = opts.getCapPSLanguageRes()) === null || _a === void 0 ? void 0 : _a.lanResTag;
                this.$route.meta.caption = opts === null || opts === void 0 ? void 0 : opts.caption;
                this.$route.meta.title = opts === null || opts === void 0 ? void 0 : opts.title;
                this.$route.meta.imgPath = (_b = opts === null || opts === void 0 ? void 0 : opts.getPSSysImage()) === null || _b === void 0 ? void 0 : _b.imagePath;
                this.$route.meta.iconCls = (_c = opts === null || opts === void 0 ? void 0 : opts.getPSSysImage()) === null || _c === void 0 ? void 0 : _c.cssClass;
                if (opts.accUserMode && (opts.accUserMode == 0 || opts.accUserMode == 3)) {
                    this.$route.meta.requireAuth = false;
                }
                else {
                    this.$route.meta.requireAuth = true;
                }
                this.$store.commit('setCurPageCaption', {
                    route: this.$route,
                    caption: this.$route.meta.caption,
                    info: '',
                });
                initNavData();
            }
            else {
                initNavData();
            }
        }
    }
    /**
     * 处理部件事件
     *
     * @memberof ViewContainerBase
     */
    handleViewEvent(opts) {
        if (opts.action) {
            this.$emit(opts.action, opts.data ? opts.data : null, opts.viewName);
        }
    }
    /**
     * 计算视图动态路径
     *
     * @memberof ViewContainerBase
     */
    async computeDynaModelFilePath() {
        if (this.dynamicProps && this.dynamicProps.viewdata) {
            // 嵌入视图
            if (this.context.viewpath) {
                this.dynaModelFilePath = this.context.viewpath;
                delete this.context.viewpath;
            }
        }
        else {
            // 路由打开
            if (this.$route && this.$route.meta && this.$route.meta.parameters) {
                let resource = this.$route.meta.resource ? this.$route.meta.resource.toLowerCase() : '';
                let activedView = this.$route.meta.parameters.find((item) => {
                    return item.pathName === 'views';
                });
                let localActivedView = Util.deepCopy(activedView);
                if (Object.is(localActivedView.parameterName, 'view') && Object.is(localActivedView.pathName, 'views')) {
                    localActivedView.parameterName = this.parseUrlDynamicParam().view;
                }
                if (localActivedView && localActivedView.parameterName) {
                    const modelService = await GetModelService(this.context);
                    const path = modelService.getPSAppViewPath(`${resource}${localActivedView.parameterName}`);
                    if (path) {
                        this.dynaModelFilePath = path;
                    }
                }
            }
        }
    }
    /**
     * 解析路由动态参数
     *
     * @memberof ViewContainerBase
     */
    parseUrlDynamicParam() {
        const path = this.$route.matched[this.$route.matched.length - 1].path;
        const keys = [];
        const curReg = this.$pathToRegExp.pathToRegexp(path, keys);
        const matchArray = curReg.exec(this.$route.path);
        let tempValue = {};
        keys.forEach((item, index) => {
            if (matchArray[index + 1]) {
                Object.defineProperty(tempValue, item.name, {
                    enumerable: true,
                    value: decodeURIComponent(matchArray[index + 1]),
                });
            }
        });
        return tempValue;
    }
}
