<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
  import store from '@/store'
  import { mapGetters } from 'vuex'
  import messageApi from '@/api/system/message'

  export default {
    name: 'App',
    data() {
      return {
        url: process.env.VUE_APP_WEBSOCKET_URL + '?uid=',
        ws: null,
        interValId: '',
        timerId: '',
      }
    },
    computed: {
      ...mapGetters({
        userid: 'user/id',
        username: 'user/username',
      }),
    },
    created() {
      this.connectWebsocket()
    },
    destroyed() {
      clearInterval(this.interValId)
    },
    methods: {
      connectWebsocket() {
        if (this.userid) {
          this.ws = new WebSocket(this.url + this.userid + '-pc')
        } else {
          this.ws = null
          console.info('uid为空')
        }
        try {
          if (this.ws) {
            // ws连接成功
            this.ws.onopen = function () {
              console.info('WebSocket Server [' + this.url + '] 连接成功！')
            }
            // ws连接关闭
            this.ws.onclose = this.onClose
            // ws连接错误
            this.ws.onerror = this.onError
            // ws数据返回处理
            this.ws.onmessage = this.onMessage
          }
        } catch (e) {
          console.error(e)
        }

        this.interValId = setInterval(this.heartAndReconnect, 10000)
      },
      // 心跳且重新
      heartAndReconnect() {
        let hasToken = store.getters['user/token']
        console.log('hasToken', hasToken)
        if (!hasToken) {
          clearInterval(this.interValId)
          this.connectWebsocket()
          return
        }

        if (this.ws) {
          let data = {
            type: 'heartbeat',
          }
          this.ws.send(JSON.stringify(data))
        } else {
          clearInterval(this.interValId)
          this.connectWebsocket()
        }
      },
      // 关闭
      onClose() {
        if (this.ws) {
          this.ws.close()
          this.ws = null
        }
        console.info('WebSocket Server [' + this.url + '] 连接关闭！')
      },
      // 处理链接错误
      onError() {
        if (this.ws) {
          this.ws.close()
          this.ws = null
        }
        console.info('WebSocket Server [' + this.url + '] 连接错误！')
      },
      onMessage(result) {
        console.info(' > ' + result.data)
        this.showMessage(result.data)
      },
      // 打开消息弹窗
      showMessage(item) {
        let data = JSON.parse(item)
        if (data.type === 'SendMessage' && data.content.body) {
          this.$baseEventBus.$emit('receivedMessage')
          let msg = JSON.parse(item).content.body
          this.$notify({
            title: msg.msgTitle,
            position: 'top-right',
            type: 'info',
            customClass: 'notify-msg',
            duration: 1000 * 60 * 5,
            dangerouslyUseHTMLString: true,
            message: msg.msgContent,
          })
        }
      },
      // 执行路由跳转
      handleItem(item) {
        messageApi.getEntityById({ id: item.id }).then(() => {
          this.$baseEventBus.$emit('receivedMessage')
        })
      },
    },
  }
</script>
