/* eslint-disable no-undef */
import { getDmsInfo } from '@/api/modules/common'
import Bus from '@/utils/Bus'
import ROP from '@/utils/Rop'
import { v4 as uuidV4 } from 'uuid'

class Dms {
  constructor() {
    this.uin = null
  }

  mixinsDmsEntry(uin) {
    this.uin = 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()
    ROP.Enter('', key, uuidV4(), true)
  }

  _DMSInit() {
    const activitiesTopic = `activity_manage_${this.uin}`
    // chat连接成功后的消息
    ROP.On('enter_suc', function () {
      // eslint-disable-next-line no-console
      console.info('DMS:服务器连接成功')
      ROP.Subscribe(activitiesTopic)
    })
    ROP.On('reconnect', function (err) {
      // eslint-disable-next-line no-console
      console.warn(`DMS:重连，错误${err}`)
    })
    // chat连接失败后的消息
    ROP.On('enter_fail', function (err) {
      // eslint-disable-next-line no-console
      console.error(`DMS:服务器连接失败，错误${err}`)
    })
    // chat接收到的消息
    ROP.On('publish_data', function (str, topic) {
      const data = JSON.parse(str)
      console.log(data);
      switch (topic) {
        case activitiesTopic:
          // 抽奖状态改变
          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)
          // }
          // 中奖结果
          if (data.cmd === 'draw_result') {
            Bus.$emit('LotteryResult', data)
          }
          break
        default:
          break
      }
    })
    // chat断开连接后的消息
    ROP.On('losed', function () {
      // eslint-disable-next-line no-console
      console.info('DMS:服务器断开连接')
    })
  }
}

export default new Dms()
