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

<script>
import { io } from 'socket.io-client'
import websocketMixin from '@/mixins/websocket'
import { getCurrentInstance } from 'vue'

export default {
  name: 'App',
  mixins: [websocketMixin],
  setup() {
    const instance = getCurrentInstance()
    const globalProperties = instance.appContext.config.globalProperties
    
    return {
      globalProperties
    }
  },
  created () {
    this.initSocket()
  },
  computed: {
    token () {
      return this.globalProperties.$myUtil.getToken()
    }
  },
  watch: {
    token (n, v) {
      if (n != v) {
        this.initSocket()
      }
    }
  },
  methods: {
    initSocket () {
      if (!this.token) return
      const socket = io(this.globalProperties.$myUtil.socketUrl, {
        withCredentials: true,
        extraHeaders: {
          'token': this.globalProperties.$myUtil.getToken()
        }
      })
      this.globalProperties.socket = socket
      // 连接和重新连接时触发。
      socket.on('connect', (e) => {
        console.log('socket连接成功')
      })
      socket.on('connect_error', () => {
        this.globalProperties.socket = null
        socket.connect()
      })
      socket.on('disconnect', () => {
        this.globalProperties.socket = null
        console.log('socket断开连接了')
      })

      // 后台群组发送了消息
      socket.on(this.globalProperties.$socketEvent.sendGroupMsg, (args) => {
        // let {group, message} = args;
        // 发送事件总线
        this.globalProperties.$eventBus.emit(this.globalProperties.$socketEvent.sendGroupMsg, args)
      })
    }
  }
}
</script>

<style lang="less">
.size{
  width: 100%;
  height: 100%;
}
html,body{
  .size;
  overflow: hidden;
  margin: 0;
  padding: 0;
}

#app {
  .size;
}

//有用
.relative {
  position: relative;
}

#luckysheet {
  margin: 0;
  padding: 0;
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}
</style>