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

<script>
  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: '',
      }
    },
    created() {
      this.connectWebsocket()
    },
    destroyed() {
      clearInterval(this.interValId)
    },
    computed: {
      ...mapGetters({
        id: 'user/id',
        username: 'user/username',
      }),
    },
    methods: {
      connectWebsocket() {
        if (this.id) {
          this.ws = new WebSocket(this.url + this.id)
        } 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() {
        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
          const h = this.$createElement
          let tag = {
            style: {
              cursor: 'pointer',
            },
            on: {
              click: () => {
                // this.handleItem(data.content.body)
              },
            },
          }
          this.$notify({
            title: msg.msgTitle,
            position: 'top-right',
            type: 'warning',
            duration: 5000,
            dangerouslyUseHTMLString: true,
            message: h('div', {}, [h('div', tag, msg.msgContent)]),
          })
        }
      },
      // 执行路由跳转
      handleItem(item) {
        messageApi.getEntityById({ id: item.id }).then(() => {
          this.$baseEventBus.$emit('receivedMessage')
        })
      },
    },
  }
</script>
