<template>
  <div class="game-container">
    <game-notice></game-notice>
    <game-scene></game-scene>

    <game-desktop></game-desktop>
  </div>
</template>

<script>
import { getUrlParam } from '@/util/util'
import { getWsUrl } from '@/util/contract.js'
import WsManager from '@/util/wsManager.js'
import gameNotice from './notice'
import gameDesktop from './desktop'
import gameScene from './scene'
import API from '@/api'
import Bus from '@/js/bus'

export default {
  name: 'gameMain',
  data () {
    return {
    }
  },
  components: {
    gameNotice,
    gameDesktop,
    gameScene
  },
  computed: {
    account () {
      return this.$store.state.account
    }
  },
  watch: {
    account (to, from) {
      let name = to.name || ''
      this.socketConnect(name)
    }
  },
  methods: {
    // 连接socket
    socketConnect (name) {
      if (!window.WebSocket) {
        console.error('Error: WebSocket is not supported .')
        return
      }

      let host = getWsUrl() + '?player=' + name
      if (this.socket) {
        this.socket.destroy()
        this.socket = null
      }

      this.socket = new WsManager(host, {
        autoConnect: true, // 自动连接
        reconnection: true, // 断开自动重连
        reconnectionDelay: 5000, // 重连间隔时间，单位秒
        keepAliveContent: JSON.stringify({ act: 'alive', player: name }) // 心跳包内容
      })

      this.socket.on('open', res => {})

      this.socket.on('message', (data) => {
        data = JSON.parse(data)
        if (data.channel === 'k3:new_offer') {
          this.$store.commit('setNewOffer', data.data)
        }
        if (data.channel === 'k3:new_open') {
          this.$store.commit('setNewOpen', data.data)
        }
        if (data.channel === 'global:new_auction') {
          Bus.$emit('update:auctioninfo')
        }
      })
    }
  },
  created () {
    let name = getUrlParam('a')
    if (name) {
      this.$store.commit('setInvitee', name.replace('/', ''))
    }

    // 获取GT汇率
    API.game.getGtRate().then(({ data }) => {
      this.$store.commit('setGtRate', data.data.dig_rate / 10000)
    })
  }
}
</script>
<style lang="scss">
.game-container{
  position: relative;
}
</style>
