<template>
    <div class="app">
        <transition>
            <router-view v-if="$store.state.appStatus == 'success'" />
        </transition>
        <transition>

            <div v-if="$store.state.appStatus != 'success'" class="loader">
                <div class="pl-logo-lg fadeInUp animated">
                    <img :src="logoSrc" v-if="logoSrc != ''">
                </div>
                <span class="txt">
                    <span v-for="(str, index) in loadTexts" :key="index">{{ str }}</span>
                    <span class="msgInfo" v-if="$store.state.appStatus == 'loading'">{{ $t('hivuiMain_sysLoading')
                    }}</span>
                    <span class="msgInfo" v-if="$store.state.appStatus != 'loading' && !mainPageInitErrorJump"
                        style="color:red" @click="handleReload">{{ $store.state.appStatusMsg ||
                            $t('hivuiMain_loadedFailClickRefresh') }}</span>
                </span>
            </div>
        </transition>
    </div>
</template>
<script>
import Cookies from 'js-cookie'
import LoginPic from "@main/assets/logo_max.png"
import { getUrlValue, setUrlValue, getUrlSearch } from "@main/utils";
import { getToken , removeToken} from '@main/utils/auth'
import md5 from "js-md5";
import WebScoketManager from '@main/utils/websocket.js'
export default {
    data() {
        return {
            loadTexts: "",
            logoSrc: "",
            mainPageInitErrorJump: window.mainPageInitErrorJump,
            loginStatusWS: null
        };
    },
    methods: {
        handleReload() {
            window.location.reload();
        },
        detectZoom() {
            var ratio = 0,
                screen = window.screen,
                ua = navigator.userAgent.toLowerCase();
            if (window.devicePixelRatio !== undefined) {
                ratio = window.devicePixelRatio;
            }
            else if (~ua.indexOf('msie')) {
                if (screen.deviceXDPI && screen.logicalXDPI) {
                    ratio = screen.deviceXDPI / screen.logicalXDPI;
                }
            }
            else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
                ratio = window.outerWidth / window.innerWidth;
            }
            if (ratio) {
                ratio = Math.round(ratio * 100);
            }
            return ratio;
        },
        checkZoom() {
            let ratio = this.detectZoom();
            if (ratio != 100) {
                // this.$message.error('警告，浏览器没有按正常比例显示会影响部份功能！')
            }
        },

        createSocket() {
            let me = this;
            
            // 检查是否已经存在有效的WebSocket连接
            if (me.loginStatusWS && me.loginStatusWS.ws && me.loginStatusWS.connState) {
                console.log("WebSocket连接已存在，无需重复创建");
                return;
            }
            
            // 如果存在旧的连接实例，先关闭它
            if (me.loginStatusWS) {
                console.log("关闭现有的WebSocket连接");
                me.loginStatusWS.end();
                me.loginStatusWS = null;
            }
            
            if ("WebSocket" in window) {
                try {
                    // 构造 WebSocket 路径
                    let socketHost = window.HIVUI_SETTING?.serverUrl.replace("http", "ws");
                    let pName = window.HIVUI_SETTING?.pName;
                    let wsClientId = md5(getToken());
                    // let socketHost = "https://e52.hieap.cn".replace('http', 'ws')
                    // let pName = 'fdszh';
                    // let wsClientId = md5('eyJhbGciOiJIUzUxMiJ9.eyJ1aWQiOiJhZG1pbiIsImV4cGlyZXMiOjE3NjgyMjM4NjM2MDQsInBob25lIjoiMTg4ODg4MDA4ODgiLCJuYW1lIjoi566h55CG5ZGYIiwidGVybSI6InBjIiwidG9rZW4iOiIwYWRkZWJkNy0wOTc3LTQ2YzgtYmRjYi1jN2FmNzVkNTUzMDIifQ.5aJVU42LLVrsc5_cdOqkPLTv4qxeCMoa0c3MAPE9pb9-Lxv37bt0uRGYDG5zWtdBHMglbUaKWnCGUFhN3Ihkhw')
                    let url = socketHost + "/" + pName + "/ws/p2p/" + wsClientId;

                    // 创建 WebSocket 实例
                    me.loginStatusWS = new WebScoketManager({
                        link: url,
                        //"reConnect":true,
                    });
                    // 初始化 WebSocket 事件
                    me.initWSEvent();
                    console.log("WebSocket连接创建成功");

                } catch (error) {
                    console.error("WebSocket 初始化失败:", error);
                }
            } else {
                // 浏览器不支持 WebSocket
                alert("您的浏览器不支持 WebSocket!");
            }
        },
        //初始化WS事件
        initWSEvent() {
            let me = this;
            let _ws = me.loginStatusWS;
            if (!_ws) {
                console.log("WebSocket 实例未初始化");
                return;
            }
            console.log("Token", getToken());
            console.log("md5Token",md5(getToken()));
            console.log('开始连接websocket');
            //建立连接
            _ws.on("onopen", () => {
                console.log('数据发送中...');
            });
            //连接失败
            _ws.on("onclose", () => {
                console.log('连接已关闭...');
            });
            //超时关闭
            _ws.on("overtime", () => {
                console.log('服务器连接超时');
            });
            _ws.on("reConnect", () => {
                console.log('重新连接websocket中');
            });
            _ws.on("endReConnect", () => {
                console.log('重新连接次数超出上限，终止连接');
            });
            //接受消息
            _ws.on("onmessage", (data) => {
                console.log('数据已接收: ' + data);
                if (data.action.trim() == "kick") {
                    var message = window?.customSysCofig?.loginStatusMonitorWs?.message || "已在其他地方登录，请重新登录！"
                    this.$alert(message, {
                        confirmButtonText: '确定',
                        callback: action => {
                            removeToken();
                            location = window.HIVUI_SETTING.loginUrl;
                        }
                    });
                }
            });
        },
    },
    beforeDestroy() {
        // 组件销毁时关闭WebSocket连接
        if (this.loginStatusWS) {
            console.log("组件销毁，关闭WebSocket连接");
            this.loginStatusWS.end();
            this.loginStatusWS = null;
        }
    },
    mounted() {
        // this.checkZoom();
        // window.addEventListener('resize',()=>{
        //     this.checkZoom();
        // });
        let me = this;
        // 设置任务中心刷新状态
        top.window.__setRefreshTaskcenter = function (state) {
            if (state == undefined) {
                state = true;
            }
            top.window.__refreshTaskcenter = state;
        }
        let urlPn = getUrlValue(location.search, "pn");
        if (urlPn) {
            if (!getUrlValue(window.HIVUI_SETTING.loginUrl, "pn")) {
                window.HIVUI_SETTING.loginUrl += "?pn=" + urlPn;
            }
            if (!getUrlValue(window.HIVUI_SETTING.mainPageUrl, "pn")) {
                window.HIVUI_SETTING.mainPageUrl += "?pn=" + urlPn;
            }
            if (!getUrlValue(window.HIVUI_SETTING.customLoginUrl, "pn")) {
                window.HIVUI_SETTING.customLoginUrl += "?pn=" + urlPn;
            }
        }
        //如果token不一致，替换掉然后重新载入
        let urlToken = getUrlValue(location.href, "access_token");
        let nowToken = getToken();
        if (false && !window._global && urlToken && nowToken && (urlToken != nowToken)) {//正式环境
            let newUrl = setUrlValue(decodeURIComponent(location.href), "access_token", nowToken);
            location = newUrl;
            location.reload();
        }
        //系统间跳转，将ticket去除
        if (!window._global && getUrlValue(decodeURIComponent(location.href), "ticket")) {
            let newUrl = setUrlValue(decodeURIComponent(location.href), "ticket", "");
            location = newUrl.replace("&ticket=", "") + (location.hash ? location.hash : "#/");
            //location.reload();
        }
        window.Scp = {
            User: {
                id: "admin",
                name: "管理员",
                deptId: "",
                deptName: "",
                positionId: "GLY",
                postionName: "管理员",
                bzId: "admin_3",
                bzName: "管理员岗位3",
                bzDeptId: ".WLDJT.DGS",
                bzDeptName: "D公司",
                bzPositionId: "HQRY",
                bzPositionName: "后勤人员",
                orgId: "admin_3",
                defOrgId: "admin_3"
            }
        }
        //customSysCofig默认值
        window.customSysCofig = _.merge({
            showMiniLogin: true,
        }, window.customSysCofig);
        if (!window.localStorage.getItem("locale")) {
            window.localStorage.setItem("locale", JSON.stringify({
                desc: "中文",
                name: "zh-CN",
            }));
            Cookies.set("locale", "zh-CN");
        }
        window.__guid = new Date().valueOf();
        //window.customSysCofig=_.merge(window.default_customSysCfg,window.customSysCofig||{});
        window == top && window.customSysCofig && window.customSysCofig.thirdParty && window.customSysCofig.thirdParty.forEach((item) => {//第三方脚本样式资源引用
            let _dom;
            switch (item.type) {
                case "js":
                    _dom = document.createElement("script");
                    _dom.type = "text/javascript";
                    _dom.src = item.link;
                    if (item.callback) {
                        _dom.onload = () => {
                            item.callback();
                        }
                    }
                    break;
                case "css":
                    _dom = document.createElement("link");
                    _dom.rel = "stylesheet";
                    _dom.href = item.link;
                    break;
            }
            document.querySelector("head").appendChild(_dom);
        });
        setTimeout(() => {
            window.__sysConfig = _.merge({
                events: {
                    onLoad1: function () {

                    }
                },
                projectName: "eaptpl",
                /*sysProjectMange: {
                    id: __guid++,
                    name: '工程树',
                    iconClass: 'icon-tree',
                    uri: 'amreport/designer/tree/design.do',
                    url: '/amrept-web/amreport/designer/tree/design.do'
                },*/
                sysList: [

                ],
                langList: {
                    id: __guid++,
                    name: (window.localStorage.getItem("locale") ? (JSON.parse(window.localStorage.getItem("locale")).desc) : "中文"),
                    type: 'lang',
                    iconClass: 'icon-language',
                    children: [
                        {
                            id: __guid++,
                            name: "中文",
                            key: "zh-CN",
                        }, {
                            id: __guid++,
                            name: "English",
                            key: "en",
                        },
                    ]
                },
                userInfo: {
                    id: __guid++,
                    name: '${fusername}',
                    type: 'userInfo',
                    iconClass: 'icon-user',
                    children: [
                        {
                            id: __guid++,
                            name: me.$t('hivuiMain_app_user') + '：${fusername}/${fuserid}',
                            iconClass: 'icon-user',
                        },
                        {
                            id: __guid++,
                            name: me.$t('hivuiMain_app_orgbz') + '：${fbzname}/${fbzid}',
                            iconClass: 'icon-user',
                            type: "orgBz",
                        },
                        {
                            id: __guid++,
                            name: me.$t('hivuiMain_app_orgname') + '：${forgname}/${forgid}',
                            iconClass: 'icon-user',
                        },
                        {
                            id: __guid++,
                            name: me.$t('hivuiMain_app_rolename') + '：${frolename}/${froleid}',
                            iconClass: 'icon-user',
                        },
                        {
                            id: __guid++,
                            name: me.$t('hivuiMain_app_personal_Center'),
                            iconClass: 'icon-user',
                            type: "personalCenter"
                        },
                        /*{
                            id: __guid++,
                            iconClass:'icon-edit',
                            name:'修改用户信息',
                            type:'modifyUserInfo',
                        },*/
                        {
                            id: __guid++,
                            iconClass: 'icon-edit',
                            name: me.$t('hivuiMain_app_modifyPw'),
                            type: 'modifyPw',
                        },
                    ]
                },
            }, window.customSysCofig);
            if (window.customSysCofig.addLangList) {
                window.__sysConfig.langList.children = [...window.__sysConfig.langList.children, ...window.customSysCofig.addLangList];
            }
            this.$store.dispatch("app/getSysConfig").then(res => {
                let cfg = this.$store.state.app.config || {};
                let loadText = (cfg.sysLoadLogo && cfg.sysLoadLogo.title) || "";
                let logoSrc = (cfg.sysLoadLogo && cfg.sysLoadLogo.src) || "";
                this.loadTexts = loadText.split("");
                this.logoSrc = cfg.sysLoadLogo.hide ? "" : (logoSrc || LoginPic);
            });
        }, 0);

        console.log("--------------test", window.customSysCofig);
        if (window.customSysCofig.loginStatusMonitorWs && window.customSysCofig.loginStatusMonitorWs.enable) {
            this.createSocket();
        }


    }
};
</script>
<style scoped>
.app {
    height: 100%;
    background: linear-gradient(rgb(255, 255, 255) 0px,
            rgb(243, 248, 253) 50%,
            rgb(229, 240, 250));
}


</style>