<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"
            :isSinglePage="sysConfig.isSinglePage"
        >
            <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"
                @onBlankPage="item.blankPageFunc"
                @onCopyLink="item.copyLinkFunc"
                @onIframeLoad="handleIframeLoad"
                @onBeforeClose="handleBeforeClose"
                @onSelected="handleSelected"
                @onBeforeRefresh="handleBeforeRefresh"
            >
                <template v-if="item.type&&item.type=='home'">
                    <PortalSys
                        :itemData="item"
                        ref="portalSysHome"
                    ></PortalSys>
                </template>
                <template v-if="item.type&&item.type=='work'">
                    <PortalUser
                        :itemData="item"
                        ref="portalUserWork"
                    ></PortalUser>
                </template>
            </p-tabpanel>
        </p-tabs>
        <el-dialog class="miniLoginBox" width="450px" :visible.sync="isMiniLogin" :close-on-click-modal="false" :append-to-body="true">
            <iframe v-if="isMiniLogin" width="100%" height="450px" :src="miniLoginUrl" style="border:none;"></iframe>
        </el-dialog>
        <div class="menuOpenBox" v-if="menuOpenList.length>0">
            <el-dialog v-for="(item,index) in menuOpenList" :key="'menuOpenList'+index" class="menuOpenDialog" width="50%" top="5vh" :visible.sync="item.uid" :close-on-click-modal="false" :modal-append-to-body="false" @closed="handleCloseMenuDialog(item)">
                <iframe width="100%" height="100%" :src="item.url" style="border:none;height:60vh;"></iframe>
            </el-dialog>
        </div>
    </div>
</template>
<script>
import {changeBz} from "@main/api/user";
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,notificationFunc,sortMapTurnArr } 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 = sortMapTurnArr(cfg.sysDefTabs) || [];
        let setTabs = Array.isArray(cfg.sysSetTabs) ? cfg.sysSetTabs : sortMapTurnArr(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
            if(!window._global){//正式环境
                item.url=utils.string.setUrlValue(item.url,"pn",window.HIVUI_SETTING.projectName);
            }
            if(item.url){
                let isDifferentDomains=(item.url.startsWith("http")&&(item.url.indexOf(location.host)==-1));//判断是否不同域
                if(!item.noToken){
                    isDifferentDomains&&getToken()&&(item.url=utils.string.setUrlValue(item.url,"access_token",getToken()));
                }else{
                    delete item.noToken;
                }
            }
            // if(cfg.isSinglePage){//单页面模式
            //     id="123456789";
            // }
            item.actived && (defTabKey = id);
            if (item.url && getUrlValue(item.url, "__tabId") == "") {
                //关系到用户调用，防止Scp.context.closeCurPage取不到__tabId出错
                item.url = utils.string.setUrlValue(item.url, "__tabId", id);
            }
            /*if(cfg.isSinglePage){
                list[0]={
                    title: item.title,
                    url: item.url,
                    close: item.close,
                    id: id,
                    type: item.type,
                };
            }else*/{
                list.push({
                    title: item.title,
                    url: item.url,
                    close: item.close,
                    id: id,
                    type: item.type,
                    blankPageFunc:()=>{
                        window.open(item.url,"_blank");
                    }
                });
            }
        });
        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;
            uriStr = item.resUrl;
            if(!window._global){//正式环境
                uriStr=utils.string.setUrlValue(uriStr,"pn",window.HIVUI_SETTING.projectName);
            }
            if(uriStr){
                let isDifferentDomains=(uriStr.startsWith("http")&&(uriStr.indexOf(location.host)==-1));//判断是否不同域
                if(!item.noToken){
                    isDifferentDomains&&getToken()&&(uriStr=utils.string.setUrlValue(uriStr,"access_token",getToken()));
                }else{
                    delete item.noToken;
                }
            }
            if(uriStr.indexOf("http")==-1){
                uriStr=location.origin+uriStr;
            }
            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,
                blankPageFunc:()=>{
                    window.open(uriStr,"_blank");
                }
            });
        });
        // 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)&&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 uriStr = menusList[i].resUrl;
                if(!window._global){//正式环境
                    uriStr=utils.string.setUrlValue(uriStr,"pn",window.HIVUI_SETTING.projectName);
                }
                if(uriStr){
                    let isDifferentDomains=(uriStr.startsWith("http")&&(uriStr.indexOf(location.host)==-1));//判断是否不同域
                    if(!menusList[i].noToken){
                        isDifferentDomains&&getToken()&&(uriStr=utils.string.setUrlValue(uriStr,"access_token",getToken()));
                    }else{
                        delete menusList[i].noToken;
                    }
                }
                if(uriStr.indexOf("http")==-1){
                    uriStr=location.origin+uriStr;
                }
                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, //默认选中
                    blankPageFunc:()=>{
                        window.open(uriStr,"_blank");
                    }
                });
                break;
            }
        }
        if(cfg.isPageCache&&window.localStorage.getItem('pageCacheArr')){
            JSON.parse(window.localStorage.getItem('pageCacheArr')).map((item,index)=>{
                uriStr = item.url;
                if(!window._global){//正式环境
                    uriStr=utils.string.setUrlValue(uriStr,"pn",window.HIVUI_SETTING.projectName);
                }
                if(uriStr){
                    let isDifferentDomains=(uriStr.startsWith("http")&&(uriStr.indexOf(location.host)==-1));//判断是否不同域
                    if(!item.noToken){
                        isDifferentDomains&&getToken()&&(uriStr=utils.string.setUrlValue(uriStr,"access_token",getToken()));
                    }else{
                        delete item.noToken;
                    }
                }                
                if(uriStr.indexOf("http")==-1){
                    uriStr=location.origin+uriStr;
                }
                let id = md5(uriStr);
                uriStr = utils.string.setUrlValue(uriStr, "__tabId", id);
                defTabKey = id;
                list.push({
                    title: item.title,
                    url: uriStr,
                    close: true,
                    id: id,
                    //type: item.type,
                    blankPageFunc:()=>{
                        window.open(uriStr,"_blank");
                    }
                });
            });
        }
        //地址栏打开标签
        if(top.location.hash){
            let hashTabParam={};
            top.location.hash.replace("#/","").split("&zhc&").forEach((item=>{
                if(item.indexOf("tabUrl=")==0){
                    hashTabParam.resUrl=item.replace("tabUrl=","");
                }else if(item.indexOf("tabTitle=")==0){
                    hashTabParam.name=decodeURIComponent(item.replace("tabTitle=",""));
                }
            }));
            if(hashTabParam.resUrl){
                if(hashTabParam.resUrl.indexOf("about:blank")==-1){//下推页面无法重新载入
                    //消除tabId干扰
                    let tabIdStr=hashTabParam.resUrl.match(/\__tabId=.*?&/)||hashTabParam.resUrl.match(/\?__tabId=.*/);
                    if(tabIdStr&&tabIdStr[0]){
                        hashTabParam.resUrl=hashTabParam.resUrl.replace(tabIdStr[0],"").replace("?&","?");
                    }
                    let id = md5(hashTabParam.resUrl);
                    location.href=setUrlValue(location.href,"__tabId",id);
                    let existsItem=list.filter(item=>{//标签已存在
                        if(item.url&&hashTabParam.resUrl){
                            let itemMainUrl=item.url.split("?")[0];
                            let hashTabMainUrl=hashTabParam.resUrl.split("?")[0];
                            if(hashTabParam.resUrl.indexOf(itemMainUrl)!=-1){
                                return item;
                            }
                        }
                    });
                    if(!existsItem[0]){
                        defTabKey = id;
                        hashTabParam.resUrl = utils.string.setUrlValue(hashTabParam.resUrl, "__tabId", id);
                        list.push({
                            title: hashTabParam.name,
                            url: hashTabParam.resUrl,
                            close: true,
                            id: id,
                            actived:true, //默认选中
                            blankPageFunc:()=>{
                                window.open(hashTabParam.resUrl,"_blank");
                            }
                        });
                    }else{
                        defTabKey=existsItem[0].id;
                    }
                }
            }
        }
        list.forEach(item=>{ 
            item.copyLinkFunc=()=>{
                this.handleCopyLinkFunc(item.url);
            };
        });
        console.log('sys default tabs :', list);
        return {
            defTabKey: defTabKey || "",
            tabList: list,
            sysConfig: this.$store.state.app.config,
            isFullScreen: false,
            isMiniLogin:false,
            miniLoginUrl:"",
            menuOpenList:[],
        };
    },
    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(me.sysConfig.isSinglePage){//单页面模式
                //     uid="123456789";
                // }else 
                if(me.sysConfig.isPageCache){//页面标签缓存模式
                    let _pcarr=window.localStorage.getItem('pageCacheArr');
                    let cacheArr=_pcarr?JSON.parse(_pcarr):[];
                    cacheArr=cacheArr.filter((item)=>{
                        if(url!=item.url){
                            return item
                        }
                    });
                    cacheArr.push({
                        "url":url,
                        "title":title,
                    });
                    if(cacheArr.length>20){
                        cacheArr.shift();
                    }
                    window.localStorage.setItem('pageCacheArr',JSON.stringify(cacheArr));
                }
                if (!(url == "" || url == "about:blank")) {
                    uid = md5(url);
                }
                if(!window._global){//正式环境
                    url=utils.string.setUrlValue(url,"pn",window.HIVUI_SETTING.projectName);
                }
                if(url){
                    let isDifferentDomains=(url.startsWith("http")&&(url.indexOf(location.host)==-1));//判断是否不同域
                    isDifferentDomains&&getToken()&&(url=utils.string.setUrlValue(url,"access_token",getToken()));
                }
                let tabs = me.tabList.filter((item, index) => {
                    if(item.id == uid){
                        item.title=title;
                        return item;
                    }
                });
                if (tabs.length/*&&!me.sysConfig.isSinglePage*/) {
                    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);
                }
                /*if(me.sysConfig.isSinglePage){
                    me.tabList.pop();
                    me.$nextTick(()=>{
                        me.tabList.push({
                            title: title,
                            url: url,
                            close: true,
                            id: uid,
                            listeners: {
                                load: onLoad,
                            },
                        })
                    })
                }else{*/
                    me.tabList.push({
                        title: title,
                        url: url,
                        close: true,
                        id: uid,
                        listeners: {
                            load: onLoad,
                        },
                        blankPageFunc:()=>{
                            window.open(url,"_blank");
                        },
                        copyLinkFunc:()=>{
                            me.handleCopyLinkFunc(url);
                        }
                    });
                //}
                
                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
            closeTab(uid) {
                cTabs.closeItem(uid);
            },
            closeSeldTab() {
                cTabs.closeCurItem();
            },
        };


        window.SysPage={
            newPage : function(title, url, params, method, target) {
                var uid , tab;
                if(params&&params.ftaskguid&&window.__sysConfig.openTabBytaskId){
                    uid=md5(url+"?tguid="+params.ftaskguid);
                }else if(params&&params.__viewItemId&&!target){
                    uid=md5(url+"?vItemId="+params.__viewItemId);
                }else{
                    uid=md5(url);
                }
				function formSubmit(cfg){ 
                    cfg.autoDestroy = true;
                    var form = me.creatForm(cfg);
                    for(let item of me.tabList){
                        if(item.id==uid){
                            item.blankPageFunc=()=>{
                                let __cfg={...cfg};
                                __cfg.target="_blank";
                                var __form = me.creatForm(__cfg);
                                __form.submit();
                            }
                            item.copyLinkFunc =()=>{
                                let __cfg={...cfg};
                                __cfg.target="_blank";
                                var __form = me.creatForm(__cfg);
                                var actionUrl = __form.getUrl();
                                if(actionUrl && !/^https?:\/\//i.test(actionUrl)) {
                                    actionUrl = location.origin + actionUrl;
                                }
                                me.handleCopyLinkFunc(actionUrl);
                            }
                        }
                    }
                    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("");	
                        }*/
                        uid=tab.id;
					}
                    /***
                     * 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){
                            if(!window._global){//正式环境
                                url=utils.string.setUrlValue(url,"pn",window.HIVUI_SETTING.projectName);
                            }
                            if(url){
                                let isDifferentDomains=(url.startsWith("http")&&(url.indexOf(location.host)==-1));//判断是否不同域
                                if(!(params&&params.noToken)){
                                    isDifferentDomains&&getToken()&&(url=utils.string.setUrlValue(url,"access_token",getToken()));
                                }else{
                                    delete params.noToken;
                                }
                            }
                            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.closeTab(id);
				}else{
					window.parent.Sys.closeSeldTab();
				}
				
			},
			closeCurPage:function(){
				if(!window.parent.Sys){					
					return;
				}
				var id = getUrlValue(window.location.search||window.location.hash,'__tabId');
				window.parent.Sys.closeTab(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();
				}
            },
            //小登录弹窗打开
            openMiniLogin:function(isRefresh){
                if(window.HIVUI_SETTING.isSingleLogin||me.isMiniLogin){
                    return;
                }
                me.isMiniLogin=true;
                let params="questType=ajax"+(isRefresh?"&isRefresh=true":"")+"#";
                let __login=window.HIVUI_SETTING.loginUrl.split("#");
                me.miniLoginUrl=window.HIVUI_SETTING.customLoginUrl ? window.HIVUI_SETTING.customLoginUrl : (__login[0]+(__login[0].indexOf("?")==-1?"?":"&")+params+(__login[1]||"")+"miniLogin");
            },
            //小登录弹窗关闭
            closeMiniLogin:function(isRefresh){
                me.isMiniLogin=false;
                changeBz({
                    bzid:me.$store.state.user.userInfo.fbzid
                });
                //let tabId=location.href.match(/\?__tabId=.*?&/)[0].replace("?__tabId=","").replace("&","");
                let tabId=getUrlValue(location.href,"__tabId");
                if(tabId){
                    //如果token不一致，替换掉然后重新载入
                    let iframeLocation=document.querySelector("iframe[name='iframe"+tabId+"']").contentWindow.location;
                    let urlToken=getUrlValue(iframeLocation.href,"access_token");
                    let nowToken=getToken();
                    if(false&&!window._global&&urlToken&&nowToken&&(urlToken!=nowToken)){//正式环境
                        document.querySelector("iframe[name='iframe"+tabId+"']").contentWindow.location.href=setUrlValue(decodeURIComponent(iframeLocation.href),"access_token",nowToken);
                        //iframeLocation.reload();
                    }
                    if(isRefresh){
                        iframeLocation.reload();
                    }
                }
            },
            //消息通知
            notificationFunc:notificationFunc,
        };



        if (this.defTabKey == "" && this.tabList.length)
            this.defTabKey = this.tabList[0].id;
        //默认如果指向下面两个的话，标识一下已经加载过
        if (this.$refs["portalSysHome"]) {
            //this.$store.dispatch("portal/loadSysList"); //重新加载系统门户列表
            // console.log('加载系统门户列表~！');
            let itemData = this.$refs["portalSysHome"][0].itemData;
            if (itemData.id == this.defTabKey) {
                this.$refs["portalSysHome"][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: {
        handleCopyLinkFunc(url){
                // 创建一个临时的textarea元素用于复制
                const textarea = document.createElement('textarea');
                textarea.value = url;
                textarea.style.position = 'fixed';
                textarea.style.left = '-9999px';
                document.body.appendChild(textarea);
                textarea.select();
                
                try {
                    const success = document.execCommand('copy');
                    if (success) {
                        this.$message && this.$message.success('链接复制成功');
                    } else {
                        this.$message && this.$message.error('链接复制失败');
                    }
                } catch (err) {
                    // 使用Clipboard API作为备选方案
                    navigator.clipboard.writeText(url).then(() => {
                        this.$message && this.$message.success('链接复制成功');
                    }).catch(() => {
                        this.$message && this.$message.error('链接复制失败');
                    });
                } finally {
                    document.body.removeChild(textarea);
                }
        },
        //将框架页里头的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();
            }
        },
        async handleBeforeClose(panel, evt) {
            let ifm = panel.$refs["iframe"];
            try {
                //let flag = ifm.contentWindow.Scp.context.beforeunloadFn(evt, 1);
                let flag = await ifm.contentWindow.eap.page.beforePageClose(panel, evt);
                return flag;
            } catch (e) {
                !document.all &&
                    window.console.log(
                        "iframe : Scp.context.beforeunloadFn();"
                    );
            }
        },
        //判断标签页关闭前事件返回值
        async returnBeforeCloseValue(targetName){
            try {
                let targetIframe=document.querySelector("iframe[name='iframe"+targetName+"']");
                if(targetIframe.contentWindow.eap.page.beforePageClose){
                    this.defTabKey = targetName;
                    let flag = await targetIframe.contentWindow.eap.page.beforePageClose();
                    if(flag===false){
                        return false;
                    }
                }
                return true;
            } catch (e) {
                return true;
            }
        },

        handleActiveTab(panel) {
            if (!panel) return;
            top.location.hash="#/tabUrl="+panel.url+"&zhc&tabTitle="+panel.title;
            if (panel.itemData.type == "home") {
                this.$refs["portalSysHome"][0].doRender();
            }
            if (panel.itemData.type == "work") {
                this.$refs["portalUserWork"][0].doRender();
            }
            try {
                let tab = this.$refs["cmp-tabs"].getItemObj(panel.name);
                //tab.tabPanelIframeEl.contentDocument.trigger("iframeActiving", [panel.name]);
                tab.tabPanelIframeEl.contentDocument.dispatchEvent(
                    new CustomEvent('iframeActiving',
                        {
                            detail:[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) {}
        },
        async handleRemoveTab(targetName) {
            let tabs = this.tabList;
            let activeName = this.defTabKey;
            if(!await this.returnBeforeCloseValue(targetName)){
                return;
            }
            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";
            }
        },
        async handleRemoveAllTab() {
            let tabs = this.tabList;
            let resultList=[];
            let end=false;
            let endIndex=0;
            for(let i=0;i<tabs.length;i++){
                let tab=tabs[i];
                if(!await this.returnBeforeCloseValue(tab.id)){
                    end=true;
                    endIndex=resultList.length;
                }
                if(end||!tab.close){
                    resultList.push(tab);
                }
            };
            this.$set(this, "tabList", resultList);
            let l = this.tabList.length;
            this.defTabKey = endIndex ? this.tabList[endIndex].id : (l ? this.tabList[l - 1].id : "");
        },
        async handleRemoveLeftTab(name, index) {
            let tabs = this.tabList;
            let resultList=[];
            let end=false;
            let endIndex=0;
            let defTabKey = this.defTabKey;
            for(let i=0;i<tabs.length;i++){
                let tab=tabs[i];
                if (tab.id == defTabKey && i < index) {
                    //当前的选中，是在关闭区内
                    defTabKey = name;
                }
                if(!await this.returnBeforeCloseValue(tab.id)){
                    end=true;
                    endIndex=resultList.length;
                }
                if(end||(tab.close == false || i >= index)){
                    resultList.push(tab);
                }
            };
            this.$set(this, "tabList", resultList);
            this.defTabKey = endIndex ? this.tabList[endIndex].id : defTabKey;
        },
        async handleRemoveRightTab(name, index) {
            let tabs = this.tabList;
            let resultList=[];
            let end=false;
            let endIndex=0;
            let defTabKey = this.defTabKey;
            for(let i=0;i<tabs.length;i++){
                let tab=tabs[i];
                if (tab.id == defTabKey && i > index) {
                    //当前的选中，是在关闭区内
                    defTabKey = name;
                }
                if(!await this.returnBeforeCloseValue(tab.id)){
                    end=true;
                    endIndex=resultList.length;
                }
                if(end||(tab.close == false || i <= index)){
                    resultList.push(tab);
                }
            };
            this.$set(this, "tabList", resultList);
            this.defTabKey = endIndex ? this.tabList[endIndex].id : defTabKey;
        },
        async handleRemoveOtherTab(name, index) {
            let tabs = this.tabList;
            let resultList=[];
            let end=false;
            let endIndex=0;
            for(let i=0;i<tabs.length;i++){
                let tab=tabs[i];
                if(!await this.returnBeforeCloseValue(tab.id)){
                    end=true;
                    endIndex=resultList.length;
                }
                if(end||(tab.close == false || i == index)){
                    resultList.push(tab);
                }
            };
            this.$set(this, "tabList", resultList);
            this.defTabKey = endIndex ? this.tabList[endIndex].id : 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 style="display:none;" 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.getUrl = ()=>{
                return _form.getAttribute('action');
            }
            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){
                    let parms=decodeURIComponent(_opt.url).split("?");//URL解码
                    if(parms.length>2){
                        parms[1]=[...parms].slice(1).join("?");
                    }
                    parms=parms[1];
                    var item,i=0,len;
                    if(parms!=null){
                        parms = parms.split("&");
                        for(i=0,len=parms.length;i<len;i++){
                            item = parms[i].split("=");
                            let isDifferentDomains=(item[1].startsWith("http")&&(item[1].indexOf(location.host)==-1));//判断是否不同域
                            if(isDifferentDomains&&item.length>2){
                                let __name=item.shift();
                                _opt.data[__name]=item.join("=")+(i<len?"&":"")+parms.slice(i+1).join("&");//参数带地址则后面的全拼成一个字符串
                                break;
                            }else{
                                _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;
        },
        handleCloseMenuDialog(item){
            this.menuOpenList=this.menuOpenList.filter((__item)=>{
                if(__item.uid!=item.uid){
                    return __item;
                }
            });
        }
    },
};
</script>
<style lang="less" scoped>
    .miniLoginBox{
        ::v-deep .el-dialog__body{
            padding-top:0;
        }
    }
    .menuOpenBox{
        ::v-deep .v-modal{
            top:98px;
            height:calc(100% - 98px);
        }
        .menuOpenDialog{
            top:98px;
        }
    }
</style>