const socket_io = require('./socket.io-mp')
const {
  IM_HOST
} = require('../config/config')

let io = ''
export function initSocket(page, options) {
  const defaultOpts = {
    customerId: '',
    agentId: '',
    role: 'agent',
    nickName: '',
    roomId: '',
    isClient: true
  }

  io = socket_io(IM_HOST, {
    path: '/vr-node',
    query: Object.assign(defaultOpts, options)
  })
  const eventName = {
    startPlay: 'answer', // 开始语音
    someoneInRoom: 'vr_request', // 有人加入房间
    someoneLeaveRoom: 'putup', // 有人离开房间
    action: 'action', // 点击操作
  }
  // 事件监听
  io.on(eventName.startPlay, function (data) {
    console.log(data, 'startplay')
    page.startPlay(data)
  })
  
  io.on(eventName.someoneInRoom, function (data) {
    console.log('有人来了')
    console.log(data)
    if (data.persons.length < 2) {
      return
    }
    console.log(data)
    let user = data.persons.find(item => item.userId === getApp().globalData.userinfo.user_id)
    // page.enterAudioRoom(user)
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.record']) {
          wx.authorize({
            scope: 'scope.record',
            success: (res) => {
              // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
              console.log('同意', res);
              page.enterAudioRoom(user)
            },
            fail: res => {
              console.log('拒绝', res);
              cbError && cbError();
            }
          })
        } else {
          page.enterAudioRoom(user)
        }
      }
    })
  })

  io.on(eventName.someoneLeaveRoom, function (data) {
    page.someoneLeave(data)
  })

  io.on(eventName.action, (data) => {
    if (data && data.name === 'delegation' && data.role === 'agent') {
      page.changeDelegetionStatus()
    }
  })
  return io
}

export function emitSendMsg(target_id) {
  let app = getApp()
  io.emit('sendMsg', {
    user_id: app.globalData.userinfo.user_id,
    target_id: target_id
  })
}

export function emitInRoom() {
  let app = getApp()
  io.emit('inRoom', {
    user_id: app.globalData.userinfo.user_id,
    room_id: app.globalData.room_id
  })
}

export function emitLeaveRoom() {
  let app = getApp()
  io.emit('leaveRoom', {
    user_id: app.globalData.userinfo.user_id,
    room_id: app.globalData.room_id
  })
}

export function disconnect() {
  return io.disconnect()
}