<template>
    <div class="pl-main">
        <p-tabs
            ref="cmp-tabs"
            v-model="defTabKey"
            @onActiveTab="handleActiveTab"
            @onRemoveTab="handleRemoveTab"
            @onRemoveAllTab="handleRemoveAllTab"
            @onRemoveLeft="handleRemoveLeftTab"
            @onRemoveRight="handleRemoveRightTab"
            @onRemoveOther="handleRemoveOtherTab"
            @onFullScreen="handleFullScreen"
        >
            <p-tabpanel
                v-for="(item,index) in tabList"
                :key="item.id"
                :close="item.close"
                :title.sync="item.title"
                :name="item.id"
                :url="item.url"
                :itemData="item"
                @onIframeLoad="handleIframeLoad"
                @onBeforeClose="handleBeforeClose"
                @onSelected="handleSelected"
                @onBeforeRefresh="handleBeforeRefresh"
            >
                <template v-if="item.type&&item.type=='home'">
                    <PortalSys
                        :itemData="item"
                        ref="protalSysHome"
                    ></PortalSys>
                </template>
                <template v-if="item.type&&item.type=='work'">
                    <PortalUser
                        :itemData="item"
                        ref="portalUserWork"
                    ></PortalUser>
                </template>
            </p-tabpanel>
        </p-tabs>
    </div>
</template>
<script>
import { baseURL, codeProjectName,requestUrl } from "@main/config";
import { PTabs, PTabpanel } from "@main/components/tabpanel";
import PortalUser from "@main/views/Portal/user";
import PortalSys from "@main/views/Portal/sys";
import { getUrlValue, setUrlValue,getUrlSearch,closeWindow } from "@main/utils";
import { getToken } from '@main/utils/auth'
// import { type } from "os";
import md5 from "js-md5";
import { utils } from "hi-ui";
export default {
    inject: ["addTab", "showTab", "hideTab"],
    components: {
        PTabs,
        PTabpanel,
        PortalUser,
        PortalSys,
    },
    data() {
        let cfg = this.$store.state.app.config || {};
        let defTabs = cfg.sysDefTabs || [];
        let setTabs = cfg.sysSetTabs || [];
        let list = [],
            defTabKey = "";
        defTabs = setTabs.concat(defTabs);
        defTabs.map((item, i) => {
            let id = item.url ? md5(item.url) : item.id; //强转成 url md5 id
            item.actived && (defTabKey = id);
            if (item.url && getUrlValue(item.url, "__tabId") == "") {
                //关系到用户调用，防止Scp.context.closeCurPage取不到__tabId出错
                item.url = utils.string.setUrlValue(item.url, "__tabId", id);
            }
            list.push({
                title: item.title,
                url: item.url,
                close: item.close,
                id: id,
                type: item.type,
            });
        });
        console.log('page default open tabs :',defTabs);
        //系统菜单 后台默认配激活
        let menusDef2Tabs = this.$store.getters.defTabs,
            uriStr = "";
        console.log('menus default open tabs :',defTabs);
        menusDef2Tabs.map((item, i) => {
            uriStr = baseURL + codeProjectName + item.resUrl;
            let id = md5(uriStr);
            uriStr = utils.string.setUrlValue(uriStr, "__tabId", id);
            list.push({
                title: item.name,
                url: uriStr,
                close: true,
                id: id,
                type: item.type,
            });
        });
        // console.log('系统菜单',list);

        //第三方跳转过来地址自动打开功能tab
        let menusList = this.$store.getters.menusList;
        let searchObj = getUrlSearch(decodeURIComponent(this.$router.currentRoute.fullPath));
        for (let i = menusList.length - 1; i >= 0; i--) {
            if ((menusList[i].type=="func"||menusList[i].type=="flow" )&& searchObj.portal_func == menusList[i].resUrl) {
                console.log('跳转进来的功能：',searchObj.portal_func);
                //?portal_func=/project/rjwhzx/rjzcgl/funcdir/zcmcx.func&id=11111
                delete searchObj.portal_func;
                let uriStr = baseURL + codeProjectName + menusList[i].resUrl;
                let id = md5(uriStr);
                uriStr = utils.string.setUrlValue(uriStr, "__tabId", md5(uriStr));
                for(let key in searchObj){
                    uriStr = utils.string.setUrlValue(uriStr,key,searchObj[key]);
                }
                let inMenu = false;
                for (let j = list.length - 1; j >= 0; j--) {
                    if (list[j].id == id) {
                        inMenu = true;
                        break;
                    }
                }
                if (inMenu) break;
                defTabKey = id;
                list.push({
                    id: id,
                    title: menusList[i].name,
                    url: uriStr,
                    close: true,
                    actived:true //默认选中
                });
                break;
            }
        }
        console.log('sys default tabs :', list);
        return {
            defTabKey: defTabKey || "",
            tabList: list,
            sysConfig: this.$store.state.app.config,
            isFullScreen: false,
        };
    },
    mounted() {
        // console.log('主界面初始化~！');
        let me = this,
            cTabs = this.$refs["cmp-tabs"];
        window.Sys = {
            isVue: true,
            addEvent(evtName, fn) {
                //onLoad
                Bus.$on(evtName, fn);
            },
            tabPanel: {
                autoResize() {
                    cTabs.resize();
                },
            },
            getSideNavs() {
                return [...me.$store.getters.navs];
            },
            setSideNavs(data) {
                if (data == null && !(data instanceof Array)) return;
                //me.$store.dispatch("app/setQuickNav", data);
            },
            /**
             * @param {} url
             * @param {} title
             * @param {} uid
             * @param {} onLoad    //iframe 加载后
             * @param {} nearest  //标签页是否紧接在其右侧打开
             * @param {} renderedFn //渲染回调
             */
            addTab(url, title, uid, onLoad, nearest, renderedFn) { 
                if (!(url == "" || url == "about:blank")) {
                    uid = md5(url);
                }
                if(!window._global){//正式环境
                    url=utils.string.setUrlValue(url,"pn",window.HIVUI_SETTING.projectName);
                    url=utils.string.setUrlValue(url,"access_token",getToken());
                }
                let tabs = me.tabList.filter((item, index) => {
                    return item.id == uid;
                });
                if (tabs.length) {
                    me.defTabKey = uid;
                    me.$nextTick(
                        (function (fn) {
                            return function () {
                                let tab = cTabs.getItemObj(uid);
                                fn && fn(tab);
                            };
                        })(renderedFn)
                    );
                    return;
                }

                if (getUrlValue(url, "__tabId") == "") {
                    //关系到用户调用，防止Scp.context.closeCurPage取不到__tabId出错
                    url = utils.string.setUrlValue(url, "__tabId", uid);
                }

                me.tabList.push({
                    title: title,
                    url: url,
                    close: true,
                    id: uid,
                    listeners: {
                        load: onLoad,
                    },
                });
                me.defTabKey = uid;
                // window.____renderFunc = renderedFn;
                me.$nextTick(
                    (function (fn, _uid) {
                        return function () {
                            let tab = cTabs.getItemObj(_uid);
                            fn && fn(tab);
                        };
                    })(renderedFn, uid)
                );
                console.log('  addTab  ',me.tabList);
            },
            getTab(uid) {
                return cTabs.getItemObj(uid);
            },
            seldTab(uid) {
                cTabs.defTabKey = uid;
            },
            getSeldTab() {
                return cTabs.getSeldItemObj();
            },
            refreshTab(uid) {
                let tab = cTabs.getItemObj(uid);
                tab &&
                    tab.tabPanelIframeEl.contentWindow.window.location.reload();
            },
            //closeTab
            colseTab(uid) {
                cTabs.closeItem(uid);
            },
            colseSeldTab() {
                cTabs.closeCurItem();
            },
        };


        window.SysPage={
            newPage : function(title, url, params, method, target) {
                var uid = md5((params&&params._ftaskguid)?(url+"?tguid="+params._ftaskguid):url), tab;
				function formSubmit(cfg){ 
                    cfg.autoDestroy = true;
                    var form = me.creatForm(cfg);
                    form.submit();
                }
				if(method=="get"){
					//get 不刷新
					var tab = top.Sys.getTab(uid);
					if(tab){
						top.Sys.seldTab(uid);
						return;
					}
				}
				if(target=="opening"){
					var cfg = {
						url : utils.string.setUrlValue(url,"__tabId",uid),
						data : params,
						target : '_blank',
						method : method || "get"
					};
					formSubmit(cfg);
					//打开新标签 
					return;
				}else if(target=="me"){
					//本页：框架页的本页面	
					var cfg = {
						url : url,
						data : params,
						target : '_self',
						method : method || "get"
					};
					formSubmit(cfg);
				}else{
					if (target == "_self"){
                        tab = top.Sys.getSeldTab();
                        if(top.Sys.isVue){
                            var titleEl = tab.tabEl.querySelector('.pl-tabs-itemTxt');
                            titleEl.innerText = "";
                        }else{
                            tab.tabEl.find('.sys-tab-item-text').html("");	
                        }
					}else{
                        /***
                         * uid 让框架页可以关闭自己 closeCurPage
                         */
                        if(top.Sys.isVue){
                            //6个参数，第7个是vue渲染后回调
                            if(target == "_blank"){
                                uid+=utils.string.id(4);
                            }
                            top.Sys.addTab("about:blank",title,uid,null,true,function(tab){ 
                                var cfg = {
                                    url : utils.string.setUrlValue(url,"__tabId",uid),
                                    data : params,
                                    target : null,
                                    method : method || "get"
                                };
                                //var titleEl = tab.tabEl.querySelector('.pl-tabs-itemTxt');
                                //titleEl.innerText = "";
                                cfg.target = tab.tabPanelIframeEl.getAttribute('name');
                                formSubmit(cfg);
                            });
                        }else{
                            var cfg = {
                                url : utils.string.setUrlValue(url,"__tabId",uid),
                                data : params,
                                target : null,
                                method : method || "get"
                            };
                            //Sys.addTab(url, title, uid, callback)
                            tab = top.Sys.addTab("about:blank",title,uid);
                            tab.tabEl.find('.sys-tab-item-text').html("");
                            cfg.target = tab.tabPanelIframeEl.getAttribute('name');
                            formSubmit(cfg);
                        }
					}
				}
			},
			/**
			 * 通过url  进行对应的目标功能 调用目标页的callback方法
			 * @param id
             * @param url
             */
			closePage : function(id,url) {
				if (!top.Sys) {
					closeWindow()
					return;
				}
				var uid = md5(url||""), tab;
				if(!window.parent.Sys){					
					return;
				}
				
				var tab = window.parent.Sys.getTab(uid);
				if(tab){
					window.parent.Sys.seldTab(uid);
					//var _scp = tab.tabPanelIframeEl.contentWindow.window.Scp;
					//if(_scp){
					//	_scp.context&&_scp.context.callback&&_scp.context.callback.call(_scp.context);
					//}					
				}else{
					if(url&&url.trim()!=""){
						var tab = window.parent.Sys.addTab(url,"",null,null,true);
					}
				}

				if (id) {
					window.parent.Sys.colseTab(id);
				}else{
					window.parent.Sys.colseSeldTab();
				}
				
			},
			closeCurPage:function(){
				if(!window.parent.Sys){					
					return;
				}
				var id = getUrlValue('__tabId',window.location.search);
				window.parent.Sys.colseTab(id);
			},
			setPageTitle:function(title){
				if(!window.parent.Sys){					
					return;
				}
				var openway = getUrlValue('openway');
				if(openway=="openwin")return;
				var tab = window.parent.Sys.getSeldTab();
				if(title!=""){
					tab.tabEl.find('.sys-tab-item-text').html(title);
					window.parent.Sys.tabPanel.autoResize();
				}
			}
        };



        if (this.defTabKey == "" && this.tabList.length)
            this.defTabKey = this.tabList[0].id;
        //默认如果指向下面两个的话，标识一下已经加载过
        if (this.$refs["protalSysHome"]) {
            //this.$store.dispatch("portal/loadSysList"); //重新加载系统门户列表
            // console.log('加载系统门户列表~！');
            let itemData = this.$refs["protalSysHome"][0].itemData;
            if (itemData.id == this.defTabKey) {
                this.$refs["protalSysHome"][0].actived = true;
            }
        }
        if (this.$refs["portalUserWork"]) {
            //this.$store.dispatch("portal/loadList"); //重新加载工作台门户列表
            // console.log('加载工作台门户列表~！');
            let itemData = this.$refs["portalUserWork"][0].itemData;
            if (itemData.id == this.defTabKey) {
                this.$refs["portalUserWork"][0].actived = true;
            }
        }
        let events = this.sysConfig.events;
        if (events) {
            this.$nextTick((r) => {
                events.onLoad && events.onLoad();
            });
        }
    },
    methods: {
        //将框架页里头的a 标签进行转换
        initATagUrl(el) {
            let aList = el.querySelectorAll("a");
            aList.forEach(function (aTag, i) {
                if (aTag.href) {
                    var httpUrl = new RegExp(
                        "^((https|http|ftp|rtsp|mms)?://)"
                    );
                    if (
                        httpUrl.test(
                            aTag.href.replace(window.location.origin, "")
                        )
                    ) {
                        return false;
                    }
                    if (!aTag.onclick) {
                        if (aTag.target == "_blank") {
                            aTag.addEventListener("click", function (evt) {
                                evt.preventDefault();
                                evt.stopPropagation();
                                var tabTitle = "";
                                if (aTag.title) {
                                    tabTitle = aTag.title;
                                }
                                var url = this.getAttribute("href");
                                var reg = /^\//gi;
                                Sys.addTab(url, tabTitle, "", "", true);
                                return false;
                            });
                        }
                    }
                }
            });
            window.Sys.tabPanel.autoResize();
        },
        handleBeforeRefresh(panel, evt) {
            if (panel.itemData.type == "home") {
                // this.$store.state.app.sysList=[];
                //this.$store.dispatch("portal/loadSysList"); //重新加载系统门户列表
                return false;
            }
            if (panel.itemData.type == "work") {
                // this.$store.state.app.list=[];
                //this.$store.dispatch("portal/loadList"); //重新加载工作台门户列表
                return false;
            }
        },
        handleIframeLoad(panelCmp, evt) {
            let me = this,
                key = panelCmp.name;
            let ifm = panelCmp.$refs["iframe"];
            let tabData = panelCmp.itemData;
            if (tabData.listeners) {
                tabData.listeners.load && tabData.listeners.load();
            }
            //转换A标签
            me.initATagUrl(ifm.contentWindow.document.body);
            window.__UserInfo = {
                orgId: "",
                operator: "",
            };
            if (panelCmp.title == null || panelCmp.title == "") {
                let cTabs = me.$refs["cmp-tabs"];
                cTabs.resize();
            }
        },
        handleBeforeClose(panel, evt) {
            let ifm = panel.$refs["iframe"];
            try {
                let flag = ifm.contentWindow.Scp.context.beforeunloadFn(evt, 1);
                return flag;
            } catch (e) {
                !document.all &&
                    window.console.log(
                        "iframe : Scp.context.beforeunloadFn();"
                    );
            }
        },
        handleActiveTab(panel) {
            if (!panel) return;
            if (panel.itemData.type == "home") {
                this.$refs["protalSysHome"][0].doRender();
            }
            if (panel.itemData.type == "work") {
                this.$refs["portalUserWork"][0].doRender();
            }
            try {
                let tab = this.$refs["cmp-tabs"].getItemObj(panel.name);
                tab &&
                    tab.tabPanelIframeEl.contentWindow
                        .$(tab.tabPanelIframeEl.contentDocument)
                        .trigger("iframeActiving", [panel.name]);
            } catch (e) {
                console.log("iframeActiving error!");
            }
        },
        //面板上面的事件特别处理，现在暂时没用
        handleSelected(item) {
            return;
            let key = item.id;
            let ifm = this.$refs["dom-iframe" + key][0];
            try {
                let __orgId = ifm.contentWindow.Scp.User.getId();
                let __operator = ifm.contentWindow.Scp.User.getOperator();
                window.__UserInfo = {
                    orgId: __orgId,
                    operator: __operator,
                };
            } catch (e) {}
        },
        handleRemoveTab(targetName) {
            let tabs = this.tabList;
            let activeName = this.defTabKey;
            if (activeName === targetName) {
                tabs.forEach((tab, index) => {
                    if (tab.close && tab.id === targetName) {
                        let nextTab = tabs[index + 1] || tabs[index - 1];
                        if (nextTab) {
                            activeName = nextTab.id;
                        }
                    }
                });
            }
            this.defTabKey = activeName;
            tabs = tabs.filter((tab) => {
                return tab.close == false || tab.id !== targetName;
            });
            console.log('handleRemoveTab')
            this.$set(this, "tabList", tabs);
            if (this.tabList.length == 0) {
                this.defTabKey = "tabPanel_home";
            }
        },
        handleRemoveAllTab() {
            let tabs = this.tabList;
            this.tabList = tabs.filter((tab) => {
                return !tab.close;
            });
            let l = this.tabList.length;
            this.defTabKey = l ? this.tabList[l - 1].id : "";
        },
        handleRemoveLeftTab(name, index) {
            let tabs = this.tabList;
            let defTabKey = this.defTabKey;
            this.tabList = tabs.filter((tab, i) => {
                if (tab.id == defTabKey && i < index) {
                    //当前的选中，是在关闭区内
                    defTabKey = name;
                }
                return tab.close == false || i >= index;
            });

            this.defTabKey = defTabKey;
        },
        handleRemoveRightTab(name, index) {
            let tabs = this.tabList;
            let defTabKey = this.defTabKey;
            this.tabList = tabs.filter((tab, i) => {
                if (tab.id == defTabKey && i > index) {
                    //当前的选中，是在关闭区内
                    defTabKey = name;
                }
                return tab.close == false || i <= index;
            });
            this.defTabKey = defTabKey;
        },
        handleRemoveOtherTab(name, index) {
            let tabs = this.tabList;
            tabs = tabs.filter((tab, i) => {
                return tab.close == false || i == index;
            });
            this.$set(this, "tabList", tabs);
            this.defTabKey = name;
        },
        handleFullScreen() {
            this.$emit("onFullScreen");
            // screenfull.toggle()
        },
        creatForm(opt){
            let that=this;
            var _opt={
                autoShow:false,
                cancelAction:false,
                url:null,
                target:null,
                action:null,
                method:null,
                params:null,
                data:null,
                autoDestroy:false,
                _id:utils.string.id(8),
            };
            Object.assign(_opt,opt);
            var _formTpl=`<form id="${_opt._id}"><input type="submit" value="submit" id="submit_${_opt._id}"/></form>`;
            var _el=document.createElement("div");
            _el.innerHTML=_formTpl;
            document.getElementsByTagName("body")[0].appendChild(_el);
            var _form=_el.getElementsByTagName("form")[0];
            this.setTarget=(str)=>{
                _opt.target = str;
                _form.setAttribute('target',str);
            }
            this.setUrl=(str)=>{
                this.formateUrl(str);
                var url =  utils.string.setUrlValue(_opt.url,"_____r",new Date().getTime());
                _form.setAttribute('action',url);
            }
            this.setMethod=(str)=>{
                _opt.method = str||'get';
                _form.setAttribute('method',str);
            }
            this.setParams=(params)=>{
                _opt.params = params;
            }
            this.setData=(obj)=>{
                _opt.data = obj||{};
                if(_opt.method=="get"&&_opt.url!=null){
                    var parms =_opt.url.split("?")[1],
                        item,i=0,len;
                    if(parms!=null){
                        parms = parms.split("&");
                        for(i=0,len=parms.length;i<len;i++){
                            item = parms[i].split("=");
                            _opt.data[item[0]]=item[1];
                        }
                    }
                }
                _.each(_opt.data,function(value,key){
                    if(_.isObject(value)){
                        value = JSON.stringify(value);
                    }
                    var _hiddenInput=document.createElement("input");
                    _hiddenInput.setAttribute("type","hidden");
                    _form.appendChild(_hiddenInput);
                    _hiddenInput.setAttribute('name',key);
                    _hiddenInput.setAttribute('value',value);
                });
            }
            this.removeData=()=>{
                _opt.data = null;
                _form.children().remove();
            }
            this.addData=(data)=>{
                _opt.data = _.extend({},_opt.data||{},data||{});
                _form.children().remove();
                this.setData(_opt.data);
            }
            this.delData=(keys)=>{		
                _.each(keys||[],function(val,i){
                    if((val in _opt.data)){
                        delete _opt.data[val];
                    }
                });		
                _form.children().remove();
                this.setData(_opt.data);
            }
            this.formateUrl=(url)=>{
                var params= this.formateParams(_opt.params);
                if(!url)return;
                _opt.url = url;
                if(params){			
                    if(_opt.url.indexOf('?')>0){
                        _opt.url+='&'+params;
                    }else{
                        _opt.url+='?'+params;
                    }
                }
            }
            this.formateParams=(obj)=>{
                if(obj==null) return null;
                return $.param(obj||{});
            }
            this.submit=()=>{
                if(_opt.cancelAction) return;
                _opt.cancelAction = false;
                
                if(_opt.autoDestroy){
                    setTimeout(function(){
                        _form.submit()
                        //_form.find('#submit'+me.id).click();//谷歌下面要用  按钮才有效果
                    },0);
                    setTimeout(function(){that.destroy();},1000);			
                }else{
                    _form.submit();
                }
            }
            this.destroy=()=>{
                _el.remove();
            }
            
            this.setTarget(_opt.target);
            this.setMethod(_opt.method);
            this.setUrl(_opt.url);
            this.setData(_opt.data);
            return that;
        },
    },
};
</script>
<style scoped>
</style>