const socket_io = require('./utils/socket.io-mp.js')

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' // 有人离开房间
  }
  // 事件监听
  io.on(eventName.startPlay, function (data) {
    console.log(data, 'socket')
    page.startPlay(data)
  })

  io.on(eventName.someoneInRoom, function (data) {
    data.persons = data.persons.filter(item => item.userId !== getApp().globalData.userinfo.user_id)
    page.createLivePull(data)
  })

  io.on(eventName.someoneLeaveRoom, function (data) {
    page.someoneLeave(data)
  })
  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()
}
