<template>
  <div style="display: none">通知</div>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { DEFINE } from '@/utils/dict/config'

export default {
  name: 'Initial',
  data() {
    return {
      processMsgWsApiUrl: process.env.VUE_APP_WEB_SOCKET_URL_MESSAGE,
      reconnectId: null,
      ws: null
    }
  },
  computed: {
    ...mapGetters(['userId'])
  },
  watch: {
    userId: {
      handler(val) {
        if (val) {
          // this.initWebSocket()
        }
      }
    }
  },
  created() {
    if (this.auth()) this.GetInfo().then()
  },
  mounted() {
    // setTimeout(() => this.initWebSocket(), 1000)
  },
  destroyed() {
    this.ws.close()
  },
  methods: {
    auth() {
      const token = getToken()
      if (!token) return false
    },
    initWebSocket() {
      this.ws = new WebSocket(`${this.processMsgWsApiUrl}/${this.userId}?Authorization=Bearer ${getToken()}`)
      this.ws.onmessage = (e) => this.onMessage(e)
      this.ws.onopen = (e) => this.onOpen(e)
      this.ws.onerror = (e) => this.onError(e)
      this.ws.onclose = (e) => this.onClose(e)
    },
    onOpen() {
      window.clearTimeout(this.reconnectId)
    },
    onError() {
    },
    onMessage(e) {
      const data = e.data
      if (this.isJsonString(data)) {
        this.$bus.emit(DEFINE.ON_PROCESS_MSG, JSON.parse(data))
      }
    },
    send(Data) { // 数据发送
      this.ws.send(Data)
    },
    onClose(e) { // 关闭
      const time = 5
      console.log('onClose,断开连接,', time, '秒后重连')
      this.reconnectId = window.setTimeout(() => {
        this.initWebSocket()
      }, time * 1000)
    },
    ...mapActions(['GetInfo']),
    isJsonString(str) {
      try {
        if (typeof JSON.parse(str) === 'object') {
          return true
        }
      } catch (e) {
        console.log('not json')
      }
      return false
    }
  }
}

</script>
