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

export default {
  name: 'Initial',
  data() {
    return {
      wsApiUrl: process.env.VUE_APP_WEB_SOCKET_URL,
      reconnectId: null,
      ws: null
    }
  },
  created() {
    // this.initWebSocket()
  },
  destroyed() {
    this.ws.close()
  },
  methods: {
    auth() {
      const token = getToken()
      if (!token) return false
    },
    initWebSocket() {
      this.ws = new WebSocket(`${this.wsApiUrl}?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 tag = e.data
      // 开始查重
      if (tag === 'true') this.$bus.emit(DEFINE.ON_PLATFORM_TOY_REPEAT, true)
      if (tag === 'false') {
        setTimeout(() => {
          this.$bus.emit(DEFINE.ON_PLATFORM_TOY_REPEAT, false)
        }, 1000)
      }
    },
    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'])
  }
}

</script>
