/* eslint-disable no-undef */
import { getDmsInfo } from '@/api/modules/common'
import { mapGetters } from 'vuex'
import Bus from '@/utils/Bus'
import ROP from '@/utils/Rop'

export default {
  computed: {
    ...mapGetters(['uin']),
    topic() {
      return `activity_manage_${this.uin}`
    }
  },
  methods: {
    mixinsDmsEntry(uin) {
      getDmsInfo({ uin }).then(res => {
        const { code, errorCode, data } = res
        if (code === 200 && errorCode === 0) {
          this._makeClientId(data.subKey)
          this._DMSInit()
        }
      })
    },
    enterDms(key) {
      if (key) {
        this._makeClientId(key)
        this._DMSInit()
      }
    },
    _makeClientId(key) {
      ROP.Leave()
      let token
      try {
        token = this.$cookie.get(process.env.TOKEN_KEY).substr(16, 26)
      } catch {
        token = 'zyzyzydfsl'
      }
      const ramdomNum = String(Math.floor(Math.random() * 65566566) + new Date().getTime())
      const clientId = token + '_' + ramdomNum
      ROP.Enter('', key, clientId, true)
    },
    _DMSInit() {
      const self = this
      // chat连接成功后的消息
      ROP.On('enter_suc', function() {
        console.info('DMS:服务器连接成功')
        ROP.Subscribe(self.topic)
      })
      ROP.On('reconnect', function(err) {
        console.warn(`DMS:重连，错误${err}`)
      })
      // chat连接失败后的消息
      ROP.On('enter_fail', function(err) {
        console.error(`DMS:服务器连接失败，错误${err}`)
      })
      // chat接收到的消息
      ROP.On('publish_data', function(str, topic) {
        const data = JSON.parse(str)
        switch (topic) {
          case self.topic:
            // 抽奖状态改变
            if (data.cmd === 'draw_service') {
              Bus.$emit('LotteryStateUpdate', data)
            }
            // 数据更新
            if (data.cmd === 'draw_update') {
              Bus.$emit('LotteryInfoUpdate', data)
            }
            // 抽奖时间更新
            if (data.cmd === 'draw_time_start') {
              Bus.$emit('LotteryInfoUpdate', data)
            }
            break
          default:
            break
        }
      })
      // chat断开连接后的消息
      ROP.On('losed', function() {
        console.info('DMS:服务器断开连接')
      })
    }
  }
}
