<template>
    <div id="app">
        <router-view />
    </div>
</template>
<script>
import portal from '@/api/portal.js'
export default {
    name: 'app',
    data(){
        return {
            hasToken: false,
            heartCheck: null,
            lockReconnect: false
        }
    },
    created(){
        this.hasToken = this.hasParams();
        this.$store.dispatch('login/hasToken', this.hasToken)
        this.heartCheckFun();
        this.initWebSocket()
    },
    mounted() {
        // 因为resize事件在整个项目中只能监听一次，所以这里通过全局广播发送这个事件
        window.onresize = () => {
            this.$root.$emit('resize')
        }
        this.$bus.$on('login', () => {
            this.initWebSocket()
        })
    },
    methods: {
        hasParams() {
            const query = window.location.search.substring(1)
            if (!query) {
                return false
            }
            const vars = query.split('&')
            const newVars = []
            for (var i = 0; i < vars.length; i++) {
                var pair = vars[i].split('=')
                if (pair[0] == 'token') {
                    return true
                }
            }
        },
        initWebSocket() {
            // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
            var url =
                window.context.WebSocket
                    .replace('https://', 'wss://')
                    .replace('http://', 'ws://') +
                '/websocket' 
            this.websock = new WebSocket(url)
            this.websock.onopen = this.websocketOnopen
            this.websock.onerror = this.websocketOnerror
            this.websock.onmessage = this.websocketOnmessage
            this.websock.onclose = this.websocketOnclose
        },
        websocketOnopen(){
            console.log('WebSocket连接成功')
            this.heartCheck.start()
        },
        websocketOnerror:() =>{
            console.log(e, 'WebSocket连接发生错误')
            this.reconnect()
        },
        websocketOnmessage(e){
            console.log('-----接收消息-------', e.data)
            var data = eval('(' + e.data + ')') //解析对象
            if (data.cmd == 'dict') {
                // 重载字典
                this.getSysDict()
            }
            this.heartCheck.reset()
        },
        websocketOnclose(e){
            console.log('connection closed (' + e.code + ')')
            this.reconnect();
        },
        websocketSend(text) {
            // 数据发送
            try {
                this.websock.send(text)
            } catch (err) {
                console.log('send failed (' + err.code + ')')
            }
        },
        reconnect() {
            if (this.lockReconnect) return
            this.lockReconnect = true
            //没连接上会一直重连，设置延迟避免请求过多
            setTimeout(() => {
                console.info('尝试重连...')
                this.initWebSocket()
                this.lockReconnect = false
            }, 5000)
        },
        heartCheckFun() {
            var that = this
            //心跳检测,每10s心跳一次
            this.heartCheck = {
                timeout: 1000 * 60 *10,  
                timeoutObj: null,
                serverTimeoutObj: null,
                reset: function () {
                    clearTimeout(this.timeoutObj)
                    this.start();
                    return this
                },
                start: function () {
                    var self = this
                    this.timeoutObj = setTimeout(function () {
                        //这里发送一个心跳，后端收到后，返回一个心跳消息，
                        //onmessage拿到返回的心跳就说明连接正常
                        // const account = JSON.parse(
                        //     sessionStorage.getItem('currentUser')
                        // ).account
                        that.websocketSend('{"messageType":"ping","message":"web"}')
                        console.info('客户端发送心跳')
                        //self.serverTimeoutObj = setTimeout(function(){//如果超过一定时间还没重置，说明后端主动断开了
                        //  that.websock.close();//如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
                        //}, self.timeout)
                    }, this.timeout);
                },
            }
        },
        //---------websocket 接收字典被修改的信息，请求新字典数据。-------------

        getSysDict() {
            portal.getSysDict().then((data) => {
                if (data) {
                    sessionStorage.setItem('dict_data', JSON.stringify(data))
                }
            })
        },
    },
}
</script>
<style lang="scss" scoped>
#app {
    background-color: #e9ecf3;
}
</style>
