import io from '../vendor/socket.io'
// import _ from 'lodash'
import ajaxurl from '../ajaxurl'
import storage from '../storage'
import IMService from './api-im'
import store from '../../../store'

let loginDoctor = storage.getItem(storage.API_LOGIN_DOCTOR)

// socket 发送登录事件
function loginIM(sessionId) {
  let socket = io.connect(ajaxurl.socketUrl)
  socket.emit('login', { userId: loginDoctor.uid, password: loginDoctor.uid, sessionId: sessionId, clientType: 'pc_doctor' })
  return socket
}

// 消息推送IM
function mesPushLogin() {
  let socket = io.connect(ajaxurl.socketUrl)
  socket.emit('login', { userId: loginDoctor.uid, password: loginDoctor.uid, sessionId: '', clientType: 'pc_doctor' })
  return socket
}

//登录本地的托盘socket
function loginLocalSocket() {
  let socket = io.connect(ajaxurl.localSocket)
  socket.emit('login', { userId: loginDoctor.uid })
  return socket
}

async function createP2pSession(patientCode, patientName) {
  // let hasPatientRes = await IMService.Sessions.getParticipants(),
  //     existingPatient = hasPatient(hasPatientRes)

  // // p2p: sessionId是由（患者code+医生code）的hash值构成，所以对于确定的一对一聊天sessionId是不变的
  let sessionRes = await IMService.Sessions.createP2pSession(loginDoctor.uid, patientCode, patientName),
    sessionResult = sessionRes.data,
    sessionData = sessionResult.data,
    sessionId = sessionData.id

  // // 登录
  // emitLogin(sessionId)

  // // 消息监听
  // onMessage(existingPatient)

  // // 错误监听
  // onError()

  // // 应答监听
  // onAck()

  return sessionId
}

async function createGroupSession(sesstionId, sessionType, sessionName, participants, videoconferencing) {
  let sessionRes = await IMService.Sessions.createGroupSession(sesstionId, sessionType, sessionName, participants, videoconferencing),
    sessionResult = sessionRes.data,
    sessionData = sessionResult.data,
    sessionId = sessionData.id
  return sessionId
}

async function addParticipant(sessionId, participantId) {
  let sessionRes = await IMService.Sessions.addParticipant(sessionId, participantId),
    sessionResult = sessionRes.data;
  return sessionResult;
}

export default {
  async createSocketConnect({ patientCode, patientName }) {
    let sessionId = await createP2pSession(patientCode, patientName)
    return sessionId
  },
  async createGroupSession({ sessionId, sessionType, sessionName, participants }) {
    console.log("createGroupSession sessionId = " + sessionId);
    let sessionId1 = await createGroupSession(sessionId, sessionType, sessionName, participants)
    return sessionId1
  },
  async addParticipant({ sessionId, participantId }) {
    let res = await addParticipant(sessionId, participantId)
    return res
  },
  loginIM: loginIM,
  mesPushLogin: mesPushLogin,
  loginLocalSocket: loginLocalSocket,
  /**
   * @api {GET}  /doctor/admin-teams/{team_id}/members
   * @apiVersion 0.0.1
   * @desc 根据医生code返回所有团队的医生
   */
  getAllDocMembers() {
    return http.get(`/doctor/admin-teams/doctorTeamMembers`, {})
  }
}

