<template>
<div class='view-container apppanelview app-panel-view '>
    <app-studioaction :viewTitle="$t(model.srfCaption)" viewName="apppanelview"></app-studioaction>
    <card class='view-card   view-no-toolbar' dis-hover :bordered="false">
<div slot='title' class="header-container">
    <span class='caption-info' :title="$t(model.srfCaption)">{{$t(model.srfCaption)}}</span>
</div>
        <div class='content-container'>
            <div class='view-top-messages'>
            </div>
            <div class='view-bottom-messages'>
            </div>
        </div>
    </card>
</div>
</template>

<script lang='tsx'>
import { Vue, Component, Prop, Provide, Emit, Watch,Inject } from 'vue-property-decorator';
import { UIActionTool, Util } from '@/utils';
import { AppMessageBox } from '@/utils/app-message-box/app-message-box';
import NavDataService from '@/service/app/navdata-service';
import { Subject,Subscription } from 'rxjs';




@Component({
    components: {
    },
})
export default class AppPanelViewBase extends Vue {
    
    /**
     * 数据变化
     *
     * @param {*} val
     * @returns {*}
     * @memberof AppPanelViewBase
     */
    @Emit() 
    public viewDatasChange(val: any):any {
        return val;
    }

    /**
     * 传入视图上下文
     *
     * @type {string}
     * @memberof AppPanelViewBase
     */
    @Prop() public viewdata!: string;

    /**
     * 传入视图参数
     *
     * @type {string}
     * @memberof AppPanelViewBase
     */
    @Prop() public viewparam!: string;

    /**
     * 视图默认使用
     *
     * @type {boolean}
     * @memberof AppPanelViewBase
     */
    @Prop({ default: true }) public viewDefaultUsage!: boolean;

    /**
     * 视图默认使用
     *
     * @type {string}
     * @memberof AppPanelViewBase
     */
    @Inject({from:'navModel',default: 'tab'})
    public navModel!:string;

	/**
	 * 视图标识
	 *
	 * @type {string}
	 * @memberof AppPanelViewBase
	 */
	public viewtag: string = '201acedb447253ee1add1c791fa31fd4';

    /**
	 * 视图类型
	 *
	 * @type {string}
	 * @memberof AppPanelViewBase
	 */
	public viewType: string = 'APPPANELVIEW';

	/**
	 * 自定义视图导航上下文集合
	 *
	 * @type {*}
	 * @memberof AppPanelViewBase
	 */
    public customViewNavContexts:any ={
    };

	/**
	 * 自定义视图导航参数集合
	 *
	 * @type {*}
	 * @memberof AppPanelViewBase
	 */
    public customViewParams:any ={
    };

    /**
     * 视图模型数据
     *
     * @type {*}
     * @memberof AppPanelViewBase
     */
    public model: any = {
        srfCaption: 'app.views.apppanelview.caption',
        srfTitle: 'app.views.apppanelview.title',
        srfSubTitle: 'app.views.apppanelview.subtitle',
        dataInfo: ''
    }

    /**
     * 视图参数变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof AppPanelViewBase
     */
    @Watch('viewparam',{immediate: true, deep: true})
    onParamData(newVal: any, oldVal: any) {
        if(newVal){
            this.viewparams = {};
            if(typeof newVal == 'string') {
                Object.assign(this.viewparams, JSON.parse(this.viewparam));
            }else{
                this.viewparams = Util.deepCopy(this.viewparam);
            }
            
        } 
    }

    /**
     * 处理应用上下文变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof AppPanelViewBase
     */
    @Watch('viewdata')
    onViewData(newVal: any, oldVal: any) {
        const _this: any = this;
        
        if (!Object.is(newVal, oldVal) && _this.engine) {
            this.$nextTick(()=>{
              _this.parseViewParam();
              _this.engine.load();
            });
        } else if(!Object.is(newVal, oldVal) && _this.refresh && _this.refresh instanceof Function) {
            _this.refresh();
        }
    }

    /**
     * 容器模型
     *
     * @type {*}
     * @memberof AppPanelViewBase
     */
    public containerModel: any = {
        view_panel: { name: 'panel', type: 'PANEL' },
    };

    /**
     * 视图操作参数
     *
     * @type {*}
     * @readonly
     * @memberof AppPanelViewBase
     */
    public viewCtx: any = {};

    /**
     *  计数器刷新
     *
     * @memberof AppPanelViewBase
     */
    public counterRefresh(){
        const _this:any =this;
        if(_this.counterServiceArray && _this.counterServiceArray.length >0){
            _this.counterServiceArray.forEach((item:any) =>{
                if(item.refreshData && item.refreshData instanceof Function){
                    item.refreshData();
                }
            })
        }
    }

    /**
     * 视图状态订阅对象
     *
     * @public
     * @type {Subject<{action: string, data: any}>}
     * @memberof AppPanelViewBase
     */
    public viewState: Subject<ViewState> = new Subject();



    /**
     * 引擎初始化
     *
     * @public
     * @memberof AppPanelViewBase
     */
    public engineInit(): void {
    }

    /**
     * 应用导航服务
     *
     * @type {*}
     * @memberof AppPanelViewBase
     */
    public  navDataService = NavDataService.getInstance();

    /**
    * 导航服务事件
    *
    * @public
    * @type {(Subscription | undefined)}
    * @memberof AppPanelViewBase
    */
    public serviceStateEvent: Subscription | undefined;

    /**
     * 门户部件状态对象
     *
     * @type {*}
     * @memberof AppPanelViewBase
     */
    @Prop() public portletState?: any;

   /**
   * 门户部件状态事件
   *
   * @public
   * @type {(Subscription | undefined)}
   * @memberof AppPanelViewBase
   */
    public portletStateEvent: Subscription | undefined;

    /**
    * 门户部件状态事件
    *
    * @public
    * @type {(Subscription | undefined)}
    * @memberof AppPanelViewBase
    */
    public formDruipartEvent: Subscription | undefined;

    /**
     * 应用上下文
     *
     * @type {*}
     * @memberof AppPanelViewBase
     */
    public context:any = {};

    /**
     * 视图参数
     *
     * @type {*}
     * @memberof AppPanelViewBase
     */
    public viewparams:any = {};

    /**
     * 视图缓存数据
     *
     * @type {*}
     * @memberof AppPanelViewBase
     */
    public viewCacheData:any;


    /**
     * 计数器服务对象集合
     *
     * @type {Array<*>}
     * @memberof AppPanelViewBase
     */    
    public counterServiceArray:Array<any> = [];

    /**
     * 解析视图参数
     *
     * @public
     * @memberof AppPanelViewBase
     */
    public parseViewParam(inputvalue:any = null): void {
        for(let key in this.context){
            delete this.context[key];
        }
        if(this.$store.getters.getAppData() && this.$store.getters.getAppData().context){
            Object.assign(this.context,this.$store.getters.getAppData().context);
        }
        if (!this.viewDefaultUsage && this.viewdata && !Object.is(this.viewdata, '')) {
            if(typeof this.viewdata == 'string') {
                Object.assign(this.context, JSON.parse(this.viewdata));
            }
            if(this.context && this.context.srfparentdename){
                Object.assign(this.viewparams,{srfparentdename:this.context.srfparentdename});
            }
            if(this.context && this.context.srfparentkey){
                Object.assign(this.viewparams,{srfparentkey:this.context.srfparentkey});
            }
            this.handleCustomViewData();
            return;
        }
        const path = (this.$route.matched[this.$route.matched.length - 1]).path;
        const keys: Array<any> = [];
        const curReg = this.$pathToRegExp.pathToRegexp(path, keys);
        const matchArray = curReg.exec(this.$route.path);
        let tempValue: Object = {};
        keys.forEach((item: any, index: number) => {
            if(matchArray[index + 1]){
                Object.defineProperty(tempValue, item.name, {
                    enumerable: true,
                    value: decodeURIComponent(matchArray[index + 1])
                });
            }
        });
        this.$viewTool.formatRouteParams(tempValue,this.$route,this.context,this.viewparams);
        this.handleCustomViewData();
        //初始化导航数据
        this.initNavDataWithRoute();
    }

    /**
     * 处理自定义视图数据
     *
     * @memberof AppPanelViewBase
     */
	public handleCustomViewData(){
		if(Object.keys(this.customViewNavContexts).length > 0){
			Object.keys(this.customViewNavContexts).forEach((item:any) =>{
				let tempContext:any = {};
				let curNavContext:any = this.customViewNavContexts[item];
				this.handleCustomDataLogic(curNavContext,tempContext,item);
				Object.assign(this.context,tempContext);
			})
		}
		if(Object.keys(this.customViewParams).length > 0){
			Object.keys(this.customViewParams).forEach((item:any) =>{
				let tempParam:any = {};
				let curNavParam:any = this.customViewParams[item];
				this.handleCustomDataLogic(curNavParam,tempParam,item);
				Object.assign(this.viewparams,tempParam);
			})
		}
	}

    /**
     * 处理自定义视图数据逻辑
     *
     * @memberof AppPanelViewBase
     */
	public handleCustomDataLogic(curNavData:any,tempData:any,item:string){
		// 直接值直接赋值
		if(curNavData.isRawValue){
			if(Object.is(curNavData.value,"null") || Object.is(curNavData.value,"")){
                Object.defineProperty(tempData, item.toLowerCase(), {
                    value: null,
                    writable : true,
                    enumerable : true,
                    configurable : true
                });
            }else{
                Object.defineProperty(tempData, item.toLowerCase(), {
                    value: curNavData.value,
                    writable : true,
                    enumerable : true,
                    configurable : true
                });
            }
		}else{
			// 先从导航上下文取数，没有再从导航参数（URL）取数，如果导航上下文和导航参数都没有则为null
			if(this.context[(curNavData.value).toLowerCase()] != null){
				Object.defineProperty(tempData, item.toLowerCase(), {
					value: this.context[(curNavData.value).toLowerCase()],
					writable : true,
					enumerable : true,
					configurable : true
				});
			}else{
				if(this.viewparams[(curNavData.value).toLowerCase()] != null){
					Object.defineProperty(tempData, item.toLowerCase(), {
						value: this.viewparams[(curNavData.value).toLowerCase()],
						writable : true,
						enumerable : true,
						configurable : true
					});
				}else{
					Object.defineProperty(tempData, item.toLowerCase(), {
						value: null,
						writable : true,
						enumerable : true,
						configurable : true
					});
				}
			}
		}
	}

    /**
     * 初始化导航数据(路由模式)
     *
     * @memberof AppPanelViewBase
     */
    public initNavDataWithRoute(data:any = null, isNew:boolean = false,  isAlways:boolean = false){
        if( isAlways || (this.viewDefaultUsage && Object.is(this.navModel,"route")) ){
            this.navDataService.addNavData({id:'app-panel-view',tag:this.viewtag,srfkey:isNew ? null : null,title:this.$t(this.model.srfCaption),data:data,context:this.context,viewparams:this.viewparams,path:this.$route.fullPath});
        }
    }

    /**
     * 初始化导航数据(分页模式)
     *
     * @memberof AppPanelViewBase
     */
    public initNavDataWithTab(data:any = null,isOnlyAdd:boolean = true, isAlways:boolean = false){
        if( isAlways || (this.viewDefaultUsage && !Object.is(this.navModel,"route")) ){
            this.navDataService.addNavDataByOnly({id:'app-panel-view',tag:this.viewtag,srfkey:null,title:this.$t(this.model.srfCaption),data:data,context:this.context,viewparams:this.viewparams,path:this.$route.fullPath},isOnlyAdd);
        }
    }
	

    /**
     * Vue声明周期
     *
     * @memberof AppPanelViewBase
     */
    public created() {
        this.afterCreated();
    }

    /**
     * 执行created后的逻辑
     *
     * @memberof AppPanelViewBase
     */    
    public afterCreated(){
        let _this:any = this;
        const secondtag = _this.$util.createUUID();
        _this.$store.commit('viewaction/createdView', { viewtag: _this.viewtag, secondtag: secondtag });
        _this.viewtag = secondtag;
        _this.parseViewParam();
        _this.serviceStateEvent = _this.navDataService.serviceState.subscribe(({ action,name, data }:{ action:string,name:any,data:any }) => {
            if(!Object.is(name,'app-panel-view')){
                return;
            }
            if (Object.is(action, 'viewrefresh')) {
                _this.$nextTick(()=>{
                    _this.parseViewParam(data);
                    if(_this.engine){
                        _this.engine.load();
                    }
                }); 
            }
        });
        if(_this.portletState){
            _this.portletStateEvent = _this.portletState.subscribe((res:any) =>{
                if(!Object.is(res.name,'AppPanelView')){
                    return;
                }
                if(Object.is(res.action,'refresh') && _this.refresh && _this.refresh instanceof Function){
                    _this.refresh();
                }
            })
        }
        _this.initViewCtx();
    }

    /**
     * 初始化视图操作参数
     *
     * @memberof AppPanelViewBase
     */  
    initViewCtx() {
        Object.assign(this.viewCtx, {
            app: this.$root,
            view: this,
            viewGlobal: {},
            viewNavData: {},
            viewNavContext: this.context,
            viewNavParam: this.viewparams,
            messagebox: AppMessageBox.getInstance(),
        });
        Object.assign(this.viewCtx, { appGlobal: this.$store.getters.getAppGlobal() });
        if (this.$store.getters.getRouteViewGlobal(this.context.srfsessionid)) {
            Object.assign(this.viewCtx, { routeViewGlobal: this.$store.getters.getRouteViewGlobal(this.context.srfsessionid) });
        } else {
            this.$store.commit('addRouteViewGlobal', { tag: this.context.srfsessionid, param: {} });
            Object.assign(this.viewCtx, { routeViewGlobal: this.$store.getters.getRouteViewGlobal(this.context.srfsessionid) });
        }
        if (!this.viewDefaultUsage && this.viewdata && !Object.is(this.viewdata, '')) {
            //  嵌入视图
            Object.assign(this.viewCtx, {
                topview: this.$store.getters.getView(this.context.srfsessionid)
            });
        } else {
            //  顶层视图
            this.$store.commit('addView', { tag: this.context.srfsessionid, param: this });
            Object.assign(this.viewCtx, { topview: this });
        }
    }

    /**
     * 销毁之前
     *
     * @memberof AppPanelViewBase
     */
    public beforeDestroy() {
        this.$store.commit('viewaction/removeView', this.viewtag);

        let _this: any = this
        if (_this.serviceStateEvent) {
            _this.serviceStateEvent.unsubscribe();
        }
        if (_this.portletStateEvent) {
            _this.portletStateEvent.unsubscribe();
        }
        if (_this.engine) {
            _this.engine.destroy();
        }
    }

    /**
     * Vue声明周期(组件初始化完毕)
     *
     * @memberof AppPanelViewBase
     */
    public mounted() {
        this.afterMounted();
    }

    /**
     * 执行mounted后的逻辑
     * 
     * @memberof AppPanelViewBase
     */
    public afterMounted(){
        const _this: any = this;
        _this.engineInit();
            if (_this.loadModel && _this.loadModel instanceof Function) {
                _this.loadModel();
            }
    }




    /**
     * 关闭视图
     *
     * @param {any[]} args
     * @memberof AppPanelViewBase
     */
    public closeView(args: any[]): void {
        let _view: any = this;
        if (_view.viewdata) {
            _view.$emit('viewdataschange', Array.isArray(args)?args:[args]);
            _view.$emit('close', Array.isArray(args)?args:[args]);
        } else if (_view.$tabPageExp) {
            _view.$tabPageExp.onClose(_view.$route.fullPath);
        }
    }

}
</script>

<style lang='less'>
@import './app-panel-view.less';
</style>