//变量
var system = 'other' //系统版本
var socket = null // netty连接
var company_code = '' // 企业ID
var agent_id = '' //坐席ID
var ext_id = '' //分机ID
var nettyTimer = null // netty定时器心跳包
var logTimer = null //日志定时器
var pingCount = 0 //未收到回应次数
var clientip = '' //IPS
var nowUuid = '' // 正在通话的UUID  A路
var nowClientUuid = ''
var consultUuid = '' //被咨询UUID
var callingPhone = '' //正在通话的Phone
var reqIdArr = [] //唯一ID数组
var nowStatus = 'OFFLINE' //当前状态
var agent_pwd = null //坐席密码
var ext_pwd = null //分机密码
var ua = null //RTC对象
var pbx = null //pbx地址
var rtcAddress = null
var hasVideo = false
var hasAudio = true
var sessionall = null
var localStream_1 = null //本地流
var localStreamScreen = null //共享流
var switchStream = null // 切换视频流
var isAdmin = false //是否质检功能
var remoteStream = null //远端流
var callType = '' // 主叫被叫
var nowPixels = ''
var hasCameras = false
var ls_vt = null //共享屏幕原始视频流信息
var vague = false //是否开启模糊背景
var virtua = false //虚拟
var backgroundImgUrl = '' //背景图片
var getAgentListXhr = null 
var token = null // 质检token
var linkUrl = null  //ws连接地址
var socketTimer = null
var wsUrl = baseUrl
var dominUrl = httpUrl
var baseCount = 0
var login_type = '1'
var extRegister = false // 分机注册状态
var isCheckIn = false //是否已迁入
var registrationAttempts = 0; // sip注册失败尝试继续注册
var init_req_id = ''
// 创建WebSocket对象
function createSocket(){
  let linkObj = {
    "agent_id": company_code + '_' + agent_id,
    "company_code": company_code,
    "os": system
  }
  linkUrl = wsUrl  + window.btoa(JSON.stringify(linkObj))
  socket = new WebSocket(linkUrl);
  socket.onopen = onopen
  socket.onmessage = onmessage
  socket.onerror = onerror
  socket.onclose = onclose
  if (socket && !socketTimer){
    socketTimer = setInterval(() => {
    if (socket.readyState === WebSocket.CLOSED) {
        if (typeof isCheckIn != 'undefined' && isCheckIn){
          setLog('neety非正常断开连接')
          toastMessage(i18ntc('neety非正常断开连接'))
          isCheckIn = false
          // if(ua){
          //   ua.unregister()
          //   closeAllStream()
          // }
        }
        socket = null
        clearInterval(socketTimer)
        socketTimer = null
        if (dualPlatform){
          getBaseUrl()
        } else {
          createSocket()
        }
      }
    }, 1000);
  }
}

function messageEvent(data){
  let backMsg = JSON.parse(data)
  // 底层服务挂了
  if (backMsg.code && backMsg.code == '5103'){
    if (window.event_cmdres){
      window.event_cmdres(JSON.stringify(backMsg))
    }
    try {
      msgEvent.event_cmdres(JSON.stringify(backMsg))
    } catch (error) {
    }
    return
  }
  if (reqIdArr.includes(backMsg.req_id) || ['change_status','connect','connect_error','callin','callback','kick_off','agent_hangup','asr_online',].includes(backMsg.msg_type)) {
    // 删除该值
    if (reqIdArr.indexOf(backMsg.req_id) > -1){
      reqIdArr.splice(reqIdArr.indexOf(backMsg.req_id), 1);
    }
    setLog('回复匹配唯一ID' + data)
    switch(backMsg.msg_type){
      case 'pong':
        pingCount = 0
      break;
      case 'consult':
        if(backMsg.code == '0' && backMsg.consult_uuid){
          consultUuid = backMsg.consult_uuid
        }
      break;
      case 'call':
        if (backMsg.code == 0){
          nowUuid = backMsg.uuid
        }
        if(document.getElementById('exhaledSound')){
            document.getElementById('hangupSound').pause()
            document.getElementById('exhaledSound').currentTime = 0
            document.getElementById('exhaledSound').play().catch(function(error) {
              // 忽略错误
              setLog(error)
            });
        }
      break;
      case 'connect':
        uploadLog()
      break;
      case 'eavesdrop':
        if (backMsg.code == 0){
          nowUuid = backMsg.uuid
        }
      break;
      case 'whisper':
        if (backMsg.code == 0){
          nowUuid = backMsg.uuid
        }
      break;
      case 'interrupt_call':
        if (backMsg.code == 0){
          nowUuid = backMsg.uuid
        }
      break;
      case 'force_call':
        if (backMsg.code == 0){
          nowUuid = backMsg.uuid
        }
      break;
      case 'substitute':
        if (backMsg.code == 0){
          nowUuid = backMsg.uuid
        }
      break;
      case 'change_status':
        if (backMsg.code == 1){
          if(['BUSY'].includes(backMsg.agent_status)){
            if (sessionall){
              return
            } else {
              callType = ''
              closeAllStream()
            }
          }
        } else{
          if(['FREE','BUSY','ARRANGE','REST','OFFLINE'].includes(backMsg.agent_status)){
            document.getElementById('play_calling').pause()
            document.getElementById('play_calling').currentTime = 0;
            callType = ''
            // closeAllStream()
          }
          if (['CALLING'].includes(backMsg.agent_status)){
            document.getElementById('play_calling').pause()
            document.getElementById('play_calling').currentTime = 0;
          }
          if (['RINGING'].includes(backMsg.agent_status) && callType == 'callin'){
            document.getElementById('play_calling').play().catch(function(error) {
              setLog(error)
            });
          }
        }
      break;
      case 'callin':
        callType = 'callin'
        nowUuid = backMsg.uuid
        nowClientUuid = backMsg.client_uuid
        callingPhone = backMsg.caller_number
        if(document.getElementById('hangupSound')){
          try {
            document.getElementById('hangupSound').pause()
          } catch(error){
            setLog(error)
          }
        }
      break;
      case 'get_status':
        if (backMsg.code == '0'){
          nowStatus = backMsg.status
        }
      break;
      case 'checkin':
        if (backMsg.code == '0'){
          let switchRoom = false
          if (pbx && pbx != backMsg.pbx){
            switchRoom = true
            try {
              toastMessage(i18ntc('已切换机房'))
            } catch (error) {
              console.log(error)
            }
          }
          isCheckIn = true
          pbx = backMsg.pbx
          rtcAddress = backMsg.rtc_address
          ext_pwd = backMsg.ext_pwd
          token = backMsg.token
          login_type = backMsg.login_type
          if (backMsg.ext_id && backMsg.ext_id.indexOf('_') > -1){
            ext_id = backMsg.ext_id.split('_')[1]
          }
          if (backMsg.login_type == '1'){
            if (!extRegister || switchRoom){
              registerRTC()
            }
          }
        } else if (backMsg.code == '1012'){
          try {
            toastMessage(i18ntc(backMsg.msg))
          } catch (error) {
            console.log(error)
          }
        }
      break;
      case 'checkout':
        if (backMsg.code == '0'){
          nowStatus = 'OFFLINE'
          isCheckIn = false
        }
      break;
      case 'kick_off':
        if (backMsg.code == '0'){
          document.getElementById('play_calling').pause()
          document.getElementById('play_calling').currentTime = 0;
          isCheckIn = false
          ua.stop()
          ua = null
          closeWebSocket()
        }
      break;
      case 'change_media':
      break;
      
    }
    if (backMsg.agent_status){
      nowStatus = backMsg.agent_status
      if (nowStatus == 'OFFLINE'){
        isCheckIn = false
        if(ua){
          ua.unregister()
          ua.stop()
          ua = null
          closeWebSocket()
        }
      }
      if (['RINGING','CALLING'].includes(backMsg.agent_status) && backMsg.uuid){
        nowUuid = backMsg.uuid
      }
    }
    // 暴露报文
    if (window.event_cmdres){
      window.event_cmdres(JSON.stringify(backMsg))
    }
    try {
      msgEvent.event_cmdres(JSON.stringify(backMsg))
    } catch (error) {
    }
  } else {
    setLog('回复不匹配唯一ID' + data)
  }
}
function UAEvent(ua) {
  //  RTC开始尝试连接
  ua.on('connecting', (args) => {
    setLog('RTC开始尝试连接')
  });
  //  RTC连接失败
  ua.on('connection_error', (args) => {
    if (typeof isCheckIn != 'undefined' && isCheckIn){
      signOut()
    }
    try {
      toastMessage(i18ntc('RTC连接失败'))
    } catch (error) {
      console.log(error)
    }
  });
  // RTC连接完毕
  ua.on('connected', () => {
    setLog('RTC连接完毕')
  });
  // RTC连接中断
  ua.on('disconnected', () => {
    if (typeof isCheckIn != 'undefined' && isCheckIn){
      signOut()
      setLog('RTC非正常断开连接')
      try {
        toastMessage(i18ntc('RTC断开连接'))
      } catch (error) {
        console.log(error)
      }
    } else {
      setLog('RTC正常断开连接')
    }
  })

  // SIP 注册成功
  ua.on('registered', e => {
    registrationAttempts = 0
    extRegister = true
    if (typeof isCheckIn != 'undefined' && !isCheckIn){
      signIn(nowStatus)
    }
    setLog('SIP注册成功')
  });

  //  SIP 注册失败
  ua.on('registrationFailed', e => {
    setLog('SIP注册失败')
    if (typeof isCheckIn != 'undefined' && isCheckIn){
      signOut()
    }
    extRegister = false
    registrationAttempts++
    if (registrationAttempts < 3){
      setTimeout(()=>{
        ua.register();
      },500)
    } else {
      try {
        toastMessage(i18ntc('SIP注册失败,请联系技术人员排查。'))
      } catch (error) {
        console.log(error)
      }
      setLog('注册失败，已达到最大重试次数')
    }
  });

  // SIP 取消注册
  ua.on('unregistered', e => {
    if (typeof isCheckIn != 'undefined' && isCheckIn){
      signOut()
      setLog('未注册上RTC,签出netty')
    }
    extRegister = false
    setLog('SIP主动取消注册或注册后定期重新注册失败')
  });

  // IM消息 事件
  ua.on('newMessage', e => console.log('im新消息事件'));

  // 来电或者外呼事件
  ua.on('newRTCSession', e => {
    // 检查是否已经有活跃的通话
    if (sessionall) {
      // 如果有，拒绝新的邀请
      e.request.reply(486);
      return
    }
    setLog(callType + e.request.getHeader('From'))
    const session = e.session;
    sessionall = session;
    var remoteVideo = document.getElementById('remoteVideo');
    var localVideo = document.getElementById('localVideo');
    // 接听失败
    session.on('failed', mdata => {
      init();
      if(document.getElementById('hangupSound')){
          document.getElementById('hangupSound').currentTime = 0
          document.getElementById('hangupSound').play().catch(function(error) {
            // 忽略错误
            setLog(error)
          });
      }
      setLog(`来电的时候拒接或者还没接听对方自己就挂断了`);
    });

    // 接听成功
    session.on("accepted", (response, cause) => {
      if (e.session.connection.getLocalStreams().length > 0) {
        localStream_1 = new window.MediaStream();
        e.session.connection.getLocalStreams()[0].getTracks().forEach(function (track) {
          localStream_1.addTrack(track)
        });
        localVideo.srcObject = localStream_1
        localVideo.volume = 0;
      }
      if (e.session._connection.getRemoteStreams().length > 0) {
        remoteStream = e.session.connection.getRemoteStreams()[0];
        remoteVideo.srcObject = remoteStream
      }
    });
    ua.on('sessionEnded', function(event) {
      var session = event.session;
      if (session == sessionall) {
        // 如果结束的会话是当前通话，重置currentCall
        sessionall = null;
      }
    });
    // 接听成功后 挂断
    session.on('ended', () => {
      setLog('接听结束');
      init();
      if(document.getElementById('hangupSound')){
          document.getElementById('hangupSound').currentTime = 0
          document.getElementById('hangupSound').play().catch(function(error) {
            // 忽略错误
            setLog(error)
          });
      }
    });
    if (callType == 'callout' || (typeof setParam !== 'undefined' && setParam.agentAnswerMode == '2')){
      setLog('准备接听' + e.request.getHeader('From'))
      pickUp()
    }
  });
}
function init() {
  sessionall = null;
}
function onopen(){
  if (!nettyTimer){
    nettyTimer = setInterval(()=>{
      let msgObj = {
        msg_type: 'ping'
      }
      msgType(msgObj)
    },10000)
  }
}
function onmessage(e){
  messageEvent(e.data)
}
function onerror(){
  try {
    toastMessage(i18ntc('WebSocket连接失败,正在尝试重新连接，如遇长时间连接失败,请联系技术人员排查。'))
    backMsg = {
      code: '0',
      msg: 'WebSocket连接失败',
      ts: +new Date(),
      msg_type: 'connect_error',
      req_id: init_req_id
    }
    messageEvent(JSON.stringify(backMsg))
  } catch (error) {
    console.log('WebSocket连接失败,正在尝试重新连接，如遇长时间连接失败,请联系技术人员排查。')
  }
  setLog('netty连接失败')
}
function onclose(){
  try {
    backMsg = {
      code: '0',
      msg: 'WebSocket连接已关闭',
      ts: +new Date(),
      msg_type: 'connect_close',
      req_id: init_req_id
    }
    messageEvent(JSON.stringify(backMsg))
  } catch (error) {
    console.log('WebSocket连接已关闭')
  }
  setLog('netty已关闭')
}
function closeWebSocket(){
  if (socket){
    socket.close()
    socket = null
    clearInterval(socketTimer)
    socketTimer = null
  }
}
function sendMsg(msg){
  let backMsg = {}
  if (socket && socket.readyState === 1) {
    socket.send(msg)
    setLog('已发出报文' + msg)
    backMsg.code = '0'
    return backMsg
  } else {
    setLog('未发出的报文' + msg)
    backMsg.code = '1'
    backMsg.msg = '连接不可用'
    return backMsg
  }
}
function msgType(msg){
  let msgObj = {
    req_id: generateUUID(),
    company_code: company_code,
    agent_id: company_code + '_' + agent_id,
    ext_id: company_code + '_' + (ext_id || agent_id),
    os: system,
    token
  }
  let sendMsgObj = Object.assign(msgObj,msg)
  let backMsg = sendMsg(JSON.stringify(sendMsgObj))
  backMsg.req_id = msgObj.req_id || ''
  return backMsg
}
//获取系统版本
function getPosType() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('iphone') >= 0 || userAgent.indexOf('ipad') >= 0 || userAgent.indexOf('ipod') >= 0) {
    // IOS
    system = 'IOS'
  } else if (userAgent.indexOf('android') >= 0) {
    // Android
    system = 'Android'
  } else if (userAgent.indexOf('mac') >= 0) {
    // Mac
    system = 'Mac'
  } else if (userAgent.indexOf('win') >= 0) {
    // Windows
    system = 'Windows'
  } else {
    // 其他操作系统
    system = 'other'
  }
}
// 获取本地IP地址
function getLocalIPs() {
  var RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
  var ips = []
  if (RTCPeerConnection) (()=>{
      var rtc = new RTCPeerConnection()
      rtc.createDataChannel(''); //创建一个可以发送任意数据的数据通道
      rtc.createOffer( offerDesc => { //创建并存储一个sdp数据
      rtc.setLocalDescription(offerDesc)
  }, e => { console.log(e)})
  rtc.onicecandidate = (evt) => { //监听candidate事件
      if (evt && evt.candidate && evt.candidate.candidate){
          let ip_rule = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
          let ip4 = /([0-9]{1,3}(\.[0-9]{1,3}){3})/
          var ip_addr = ''
          if (Array.isArray(ip_rule.exec(evt.candidate.candidate))){
            ip_addr = ip_rule.exec(evt.candidate.candidate)[1]
          }
          if (!ips.includes(ip_addr) && ip4.test(ip_addr)){
            ips.push(ip_addr)
          }
          clientip = ips.join(',')
        }}
  })()
  else{setLog("没有找到任何IP")}
}
//生成唯一性ID
function generateUUID() {
  var d = new Date().getTime();
  if (window.performance && typeof window.performance.now === "function") {
    d += performance.now(); // use high-precision timer if available
  }
  var uuid = 'xxxxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
  reqIdArr.push(uuid)
  return uuid;
}
//上传日志本地存储 后续接口
function uploadLog(){
  if (!logTimer){
    logTimer = setInterval(()=>{
      if (localStorage.getItem('SDKLOG')){
        ajax({
          type: 'POST',
          url: dominUrl + 'cloudcc-client-server/openapi/sdk-logger',
          data: {json: localStorage.getItem('SDKLOG'),empAccId:company_code + '_' + agent_id},
          success: function (res) {
            localStorage.setItem('SDKLOG','')
          }
        })
      }
    },60000)
  }
}
//生成LOG日志
function setLog(msg){
  let now = new Date()
  const year = now.getFullYear(); // 获取年份
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 获取月份，并补零
  const date = String(now.getDate()).padStart(2, '0'); // 获取日期，并补零
  const hours = String(now.getHours()).padStart(2, '0'); // 获取小时，并补零
  const minutes = String(now.getMinutes()).padStart(2, '0'); // 获取分钟，并补零
  const seconds = String(now.getSeconds()).padStart(2, '0'); // 获取秒，并补零
  const milliseconds = String(now.getMilliseconds()).padStart(3, '0');
  let msgText = `${year}-${month}-${date} ${hours}:${minutes}:${seconds}.${milliseconds} ${company_code}_${agent_id}` +'调用'+ msg + '\n'
  let full = false
  let size = 0
  for(item in window.localStorage){
    if(window.localStorage.hasOwnProperty(item)) {
        size += window.localStorage.getItem(item).length;
    }
  }
  if ((size / 1024 / 1024).toFixed(2) > 4){
    full = true
  } else {
    full = false
  }
  if (localStorage.getItem('SDKLOG')){
    msgText = localStorage.getItem('SDKLOG') + msgText
  }
  if (full){
    localStorage.setItem('SDKLOG', '存储已满，删除记录')
  } else {
    localStorage.setItem('SDKLOG', msgText)
  }
}
getPosType()
getLocalIPs()
/*
 * 以下内容方法为对外接口
 */
//初始化账号信息
function initialization(vccId,agent,extid,pwd){
    if (agent_id && agent_id != agent){
      isCheckIn = false
      extRegister = false
    }
    company_code = vccId
    agent_id = agent
    ext_id = extid||agent
    agent_pwd = pwd
    if (dualPlatform){
      getBaseUrl()
    } else {
      createSocket()
    }
    setLog('初始化方法' + vccId + ',' + agent + ',' + navigator.userAgent)
    if(!document.getElementById('localVideo')){
      creatVideoTags()
    }
    if(!document.getElementById('exhaledSound')){
      creatSound()
    }
    let backMsg = {
      req_id: generateUUID(),
      code: '0'
    }
    init_req_id = backMsg.req_id
    try{
      handleSeatAssistantBoxInitFun && handleSeatAssistantBoxInitFun();
    }catch(res){}
    
    return backMsg
 }
 // 初始化audio标签
 function creatSound(){
  var exhaledSound = document.createElement('audio');
  var hangupSound = document.createElement('audio');
  var playCalling = document.createElement('audio');
  exhaledSound.id = 'exhaledSound'
  hangupSound.id = 'hangupSound'
  playCalling.id = 'play_calling'
  exhaledSound.src = `${resourceUrl}/audio/callout.wav`
  hangupSound.src = `${resourceUrl}/audio/hangup.wav`
  playCalling.src = `${resourceUrl}/audio/ringtone_1.wav`
  exhaledSound.loop = false
  hangupSound.loop = false
  playCalling.loop = true
  exhaledSound.style.display = 'none';
  hangupSound.style.display = 'none';
  playCalling.style.display = 'none';
  document.body.appendChild(exhaledSound);
  document.body.appendChild(hangupSound);
  document.body.appendChild(playCalling);
 }
 // 初始化VIDEO标签
 function creatVideoTags(){
  var localVideo = document.createElement('video');
  var remoteVideo = document.createElement('video');
  // 设置 video 元素的 id
  localVideo.id = 'localVideo';
  localVideo.setAttribute('muted','muted')
  localVideo.setAttribute('autoplay','autoplay')
  remoteVideo.setAttribute('autoplay','autoplay')
  remoteVideo.id = 'remoteVideo';
  // 设置 video 元素不可见
  localVideo.style.display = 'none';
  remoteVideo.style.display = 'none';
  // 将 video 元素添加到 body 中
  document.body.appendChild(localVideo);
  document.body.appendChild(remoteVideo);
 }
// 签入分机
function signIn(startStatus){
  let msgObj = {
    msg_type: 'checkin',
    agent_ip: clientip,
    agent_pwd,
    start_status: startStatus || 'FREE',
  }
  if (socket){
    let backMsg = msgType(msgObj)
    return backMsg
  } else {
    if (dualPlatform){
      getBaseUrl()
    } else {
      createSocket()
    }
    sendCheckin(msgObj)
  }
}

function sendCheckin(msgObj){
  let timer = setInterval(()=>{
    if (socket && socket.readyState === WebSocket.OPEN){
      clearInterval(timer)
      msgType(msgObj)
    }
  },100)
}
//复位
function reset(){
  closeAllStream()
  let msgObj = {
    msg_type: 'checkin',
    agent_ip: clientip,
    agent_pwd,
    start_status: '',
    reset: true,
  }
  let backMsg = msgType(msgObj)
  return backMsg
}
// 签出分机
function signOut(){
  let msgObj = {
    msg_type: 'checkout',
    agent_ip: clientip,
  }
  let backMsg = msgType(msgObj)
  return backMsg
}
//切换状态(包含强制)
function changeStatus(action,rest_min,operated_ext_id,operated_agent_id,service_direct){
  let msgObj = {
    msg_type: 'change_status',
    action,
    rest_min,
    operated_ext_id: company_code + '_' + operated_ext_id,
    operated_agent_id:  company_code + '_' + operated_agent_id,
    service_direct
  }
  let backMsg = msgType(msgObj)
  return backMsg
}
//呼出
function callOut(numbers,audio,video,service_direct,pixels,line,max_ring_time,max_call_time,record_start,record_contact,is_stereo,file_name){
  return new Promise(function (resolve,reject) {
    if (!['FREE','BUSY','ARRANGE','REST'].includes(nowStatus)){
      resolve(nowStatus)
    } else {
      callType = 'callout'
      let number = numbers.replace(/\s/g, "")
      let callNumber = number
      let lineOut = callNumber.substring(0,1) == '#'?0:1
      callNumber.indexOf('_') > -1?lineOut=0:lineOut
      callNumber = (callNumber.substring(0,1) == '#'?company_code+'_'+callNumber.slice(1):number)
      nowPixels = pixels || ''
      callingPhone = callNumber
      if (audio!=0){
        hasAudio = true
      } else {
        hasAudio = false
      }
      if (video &&  video!=0){
        hasVideo = true
      } else {
        hasVideo = false
      }
      let msgObj = {
        msg_type: 'call',
        callee_number: callNumber,
        out_line: line || lineOut,
        audio: audio || 3,
        video: video || 0,
        pixels: pixels || '',
        max_ring_time: max_ring_time || '',
        max_call_time: max_call_time || '',
        record_start: record_start || '',
        record_contact: record_contact || '',
        is_stereo: is_stereo || '',
        file_name: file_name || '',
        service_direct
      }
      let backMsg = msgType(msgObj)
      resolve(backMsg)
    }
  })
}
//保持/取消 1保持0取消
function hold(hold,service_direct){
  let msgObj = {
    msg_type: 'hold',
    uuid: nowUuid,
    hold:hold,
    service_direct
  }
  let backMsg = msgType(msgObj)
  return backMsg
}
//静音/取消 1静音0取消 发报文
function mute(mute){
  let msgObj = {
    msg_type: 'mute',
    uuid: nowUuid,
    mute:mute,
  }
  let backMsg = msgType(msgObj)
  return backMsg
}
//切换服务模式
function toggleServiceMode(service_mode){
  let msgObj = {
    msg_type: 'toggle_service_mode',
    service_mode,
  }
  let backMsg = msgType(msgObj)
  return backMsg
}
// 本地操作是否有音频
function localMute(mute) {
  return new Promise(function (resolve,reject) {
    if (!sessionall) {
      reject('error');
    }
    var pc = sessionall.connection;
    if (pc.getSenders) {
        pc.getSenders().forEach(function (sender) {
            if (sender.track.kind === 'audio') {
              if (mute == '1'){
                sender.track.enabled = false
                setLog('mute' + sender.track.enabled)
                resolve('mute')
              } else {
                sender.track.enabled = true
                setLog('unmute' + sender.track.enabled)
                resolve('unmute')
              }
            }
        });
    } else {
        pc.getLocalStreams().forEach(function (stream) {
            stream.getAudioTracks().forEach(function (track) {
                if (track.kind === 'audio') {
                  if (mute == '1'){
                    track.enabled = false;
                    setLog('mute' + track.enabled)
                    resolve('mute')
                  } else {
                    track.enabled = true;
                    setLog('unmute' + track.enabled)
                    resolve('unmute')
                  }
                }
            });
        });
    }
  })
}
// 本地关闭视频
function localHasVideo(val){
  return new Promise(function (resolve,reject) {
    if (!sessionall) {
      reject('error');
    }
    var pc = sessionall.connection;
    if (pc.getSenders) {
        pc.getSenders().forEach(function (sender) {
            if (sender.track.kind == 'video') {
              if (val == '1'){
                sender.track.enabled = false
                resolve('close')
              } else {
                sender.track.enabled = true
                resolve('open')
              }
            }
        });
    } else {
        pc.getLocalStreams().forEach(function (stream) {
            stream.getAudioTracks().forEach(function (track) {
                if (track.kind == 'video') {
                  if (val == '1'){
                    track.enabled = false;
                    resolve('close')
                  } else {
                    track.enabled = true;
                    resolve('open')
                  }
                }
            });
        });
    }
  })
}
//关闭视频/取消 1关闭0打开
function change_video(video){
  let msgObj = {
    msg_type: 'video',
    uuid: nowUuid,
    video,
  }
  let backMsg = msgType(msgObj)
  return backMsg
}
//挂断电话
function hangUp(){
  let msgObj = {
    msg_type: 'hangup',
    uuid: nowUuid,
  }
  let backMsg = msgType(msgObj)
  return backMsg
}
//获取状态
function getStatus(){
  let msgObj = {
    msg_type: 'get_status',
  }
  let backMsg = msgType(msgObj)
  return backMsg
}
//盲转/咨询中转
function transfer(service_direct){
  let msgObj = {
    msg_type: 'consult_to_trans',
    consult_uuid: consultUuid,
    service_direct
  }
  let backMsg = msgType(msgObj)
  return backMsg
}
//转接|满意度
function transferCall(number,trans_type,type,service_direct,audio,video,pixels,max_ring_time,max_call_time,record_start,record_contact,is_stereo,file_name){
  let msgObj = {
    msg_type: 'trans',
    uuid: nowUuid,
    type: type || '1',
    trans_type: trans_type || '1',
    trans_number: number || '',
    audio: audio || 3,
    video: video || 0,
    pixels: pixels || '',
    max_ring_time: max_ring_time || '',
    max_call_time: max_call_time || '',
    record_start: record_start || '',
    record_contact: record_contact || '',
    is_stereo: is_stereo || '',
    file_name: file_name || '',
    service_direct
  }
  let backMsg = msgType(msgObj)
  return backMsg
}
//咨询/取消咨询
function consultingCall(number,consulting_type,type,service_direct,audio,video,pixels,max_ring_time,max_call_time,record_start,record_contact,is_stereo,file_name){
  let msgObj = {
    msg_type: 'consult',
    uuid: nowUuid,
    type: type || '1',
    consult_type: consulting_type,
    consult_number: number || '',
    audio: audio || 3,
    video: video || 0,
    pixels: pixels || '',
    max_ring_time: max_ring_time || '',
    max_call_time: max_call_time || '',
    record_start: record_start || '',
    record_contact: record_contact || '',
    is_stereo: is_stereo || '',
    file_name: file_name || '',
    service_direct
  }
  let backMsg = msgType(msgObj)
  return backMsg
}
//三方通话
function multiCall(number,three_way_type,type,service_direct,audio,video,pixels,max_ring_time,max_call_time,record_start,record_contact,is_stereo,file_name){
  let msgObj = {
    msg_type: 'three_way',
    uuid: nowUuid,
    three_way_type: three_way_type,
    three_way_number: number || '',
    type: type || '1',
    audio: audio || 3,
    video: video || 0,
    pixels: pixels || '',
    max_ring_time: max_ring_time || '',
    max_call_time: max_call_time || '',
    record_start: record_start || '',
    record_contact: record_contact || '',
    is_stereo: is_stereo || '',
    file_name: file_name || '',
    service_direct
  }
  let backMsg = msgType(msgObj)
  return backMsg
}
//dtmf
function dtmfCall(content,service_direct){
  let msgObj = {
    msg_type: 'dtmf',
    uuid: nowUuid,
    content: content || '',
    dtmf_type: 3,
    service_direct
  }
  let backMsg = msgType(msgObj)
  return backMsg
}
//监听
function monitorCall(operated_ext_id,operated_agent_id,service_direct){
  let msgObj = {
    msg_type: 'eavesdrop',
    operated_ext_id: company_code + '_' + operated_ext_id,
    operated_agent_id:  company_code + '_' + operated_agent_id,
    token,
    service_direct
  }
  let backMsg = msgType(msgObj)
  return backMsg
}
//耳语
function whisperCall(operated_ext_id,operated_agent_id,service_direct){
  let msgObj = {
    msg_type: 'whisper',
    operated_ext_id: company_code + '_' + operated_ext_id,
    operated_agent_id:  company_code + '_' + operated_agent_id,
    token,
    service_direct
  }
  let backMsg = msgType(msgObj)
  return backMsg
}
//代接
function substituteCall(operated_ext_id,operated_agent_id,service_direct){
  let msgObj = {
    msg_type: 'substitute',
    operated_ext_id: company_code + '_' + operated_ext_id,
    operated_agent_id:  company_code + '_' + operated_agent_id,
    token,
    service_direct
  }
  let backMsg = msgType(msgObj)
  return backMsg
}
//强拆
function interruptCall(operated_ext_id,operated_agent_id,service_direct){
  let msgObj = {
    msg_type: 'interrupt_call',
    operated_ext_id: company_code + '_' + operated_ext_id,
    operated_agent_id:  company_code + '_' + operated_agent_id,
    token,
    service_direct
  }
  let backMsg = msgType(msgObj)
  return backMsg
}
//强插
function forceCall(operated_ext_id,operated_agent_id,service_direct){
  let msgObj = {
    msg_type: 'force_call',
    operated_ext_id: company_code + '_' + operated_ext_id,
    operated_agent_id:  company_code + '_' + operated_agent_id,
    token,
    service_direct
  }
  let backMsg = msgType(msgObj)
  return backMsg
}
//音视频切换
function changeMedia(val,service_direct){
  hasVideo = val == 'video'?true:false
  let msgObj = {
    msg_type: 'change_media',
    pixels: nowPixels,
    audio: 3,
    video: val == 'video'?3:0,
    uuid: nowUuid,
    service_direct
  }
  let backMsg = msgType(msgObj)
  return backMsg
}
function callBackAudio(){
  hasVideo = false
}
function registerRTC(){
  var rtcSocket = new JsSIP.WebSocketInterface((window.location.href.indexOf('https:')>-1?"wss://":"wss://") + rtcAddress);
  var configuration = {
    sockets: [rtcSocket],
    uri: "sip:" + company_code + '_' + ext_id + '@' + pbx,
    password: ext_pwd,
    authorization_user: company_code +'_' + ext_id,
    user_agent: 'cloudcc_' + system,
    displayName: company_code +'_' + ext_id,
    register: true,
    register_expires: 300,
    session_expires: 120
  };

  ua = new JsSIP.UA(configuration);
  setLog('registerRTC方法开始注册RTC' + (window.location.href.indexOf('https:')>-1?"wss://":"ws://") + rtcAddress)
  UAEvent(ua);
  ua.start();
  onLoad()
}
function createSilentVideoTrack() {
  const canvas = document.createElement("canvas");
  canvas.width = 50;
  canvas.height = 30;
  canvas.getContext("2d").fillRect(0, 0, canvas.width, canvas.height);
  animateCanvas(canvas);
  const stream = canvas.captureStream(1);
  const tracks = stream.getTracks();
  const _videoTrack = tracks[0];
  return _videoTrack;
}
//应答
function pickUp(){
  try {
    sessionall.answer({
      media: {
        constraints: {
          audio: hasAudio,
          video: hasVideo
        },
      },
      callbacks: {
        onFailed : function() {
          console.log('Answer failed');
          setLog('Answer failed')
        }
      }
    })
  } catch (error){
    setLog(error)
  }
}
/**
 * 截图
 * @param {string} fileName                             -图片名称
 * @param {string} picType                              -图片类型(png,jpeg)
 * @param {boolean} isDownload                          -是否下载
 * @memberof Stream
 */
function takeSnapshot(fileName, picType, isDownload = true, isAddWaterMark = false) {
      let photo_dom = document.getElementById('remoteVideo');
      // if (this._virtualBackground && this._virtualBackground._canvasPerson) {
      //     photo_dom = this._virtualBackground._canvasPerson;
      // }
      let canvas = document.createElement('canvas');
      canvas.width = document.getElementById('remoteVideo').offsetWidth
      canvas.height = document.getElementById('remoteVideo').offsetHeight

      let ctx = canvas.getContext('2d');
      // if (this._virtualBackground) {
      //     ctx.drawImage(this._virtualBackground.getCanvas(), 0, 0, canvas.width, canvas.height);
      // } else {
      ctx.drawImage(photo_dom, 0, 0, canvas.width, canvas.height);
      // }
      if (isAddWaterMark) {
          let curdateString = getCurDateStringWithFormat('yyyy-MM-dd hh:mm:ss');
          let fontSize = 12;
          let bottomSpace = 20;
          let textHeight = 20;
          let textWidth = 30;
          let rightSpace = 20;
  
          ctx.fillStyle = '#7F7F7F';
          ctx.textBaseline  = 'middle';
          ctx.textAlign = 'left';
          ctx.font = fontSize + 'px normal';
          let text = ctx.measureText(curdateString);
          let name = ctx.measureText(fileName);
  
          while (canvas.width < text.width) {
              fontSize = fontSize - 1;
              ctx.font = fontSize + 'px normal';
              text = ctx.measureText(curdateString);
              name = ctx.measureText(fileName);
          }
          textWidth = text.width;
          textHeight = text.actualBoundingBoxAscent + text.actualBoundingBoxDescent;
          if (name.width > text.width) {
              textWidth = name.width;
              textHeight = name.actualBoundingBoxAscent + name.actualBoundingBoxDescent;
          }
  
          ctx.fillText(curdateString, canvas.width - textWidth - rightSpace, canvas.height - textHeight * 2 - bottomSpace * 2);
          ctx.fillText(fileName, canvas.width - textWidth - rightSpace,  canvas.height - textHeight - bottomSpace);
      }

      let imgURL = canvas.toDataURL('image/' + picType);
      if (isDownload) {
          let dlLink = document.createElement('a');
          dlLink.download = fileName  + '_' + Date.parse(new Date());
          dlLink.href = imgURL;
          document.body.appendChild(dlLink);
          dlLink.click();
          document.body.removeChild(dlLink);
      }
      return imgURL;
}
//录屏
let mediaRecorder = null;
let recordedChunks = [];
function  startRecording(){
const options = { mimeType: 'video/webm;codecs=h264' }; //文件格式
mediaRecorder = new MediaRecorder(remoteStream, options);
mediaRecorder.ondataavailable = function (e) {
if (e.data.size > 0) {
recordedChunks.push(e.data);
}
};

mediaRecorder.onstop = function (e) {
const blob = new Blob(recordedChunks, { type: 'video/mp4' });
recordedChunks = [];
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a');
document.body.appendChild(a);
a.style = 'display: none';
a.href = url;
a.download = agent_id + '_recorded_' + getCurDateStringWithFormat('yyyy-MM-dd hh:mm:ss') + '.mp4';
a.click();
window.URL.revokeObjectURL(url);
};

mediaRecorder.start();
};

function stopRecording (){
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
mediaRecorder.stop();
}
};
function getCurDateStringWithFormat(fmt) {
    //yyyy-MM-dd hh:mm:ss 或者 yyyy-MM-dd
    let date = new Date();
    let o = { 
        'M+': date.getMonth() + 1,                 //月份 
        'd+': date.getDate(),                    //日 
        'h+': date.getHours(),                   //小时 
        'm+': date.getMinutes(),                 //分 
        's+': date.getSeconds(),                 //秒 
        'q+': Math.floor((date.getMonth() + 3) / 3), //季度 
        'S': date.getMilliseconds()             //毫秒 
    }; 
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)); 
    }
    for (let k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
        }
    }
    return fmt; 
}

// 屏幕共享
function share_screen() {
  return new Promise(function (resolve,reject) {
    let option = {
      audio: true,
      video: true,
      screen: true,
    };
    localStreamScreen = RTC.createStream(option);
    ls_vt = localStream_1.getVideoTracks()[0];
    localStreamScreen.isAdapterDevice = true;
    //该回调通知应用已获取本地摄像头／麦克风使用权限。
    localStreamScreen.on(RTC.Events.AccessAllowed, event => {
    });
    //该回调通知应用已禁止本地摄像头／麦克风使用权限
    localStreamScreen.on(RTC.Events.AccessDenied, event => {
    });
    //该回调通知应用屏幕共享已停止
    localStreamScreen.on(RTC.Events.StopScreenSharing, streamId => {
      var pc = sessionall.connection;
      let svt = localStreamScreen.getVideoTrack();
      localStream_1.removeTrack(svt)
      localStream_1.addTrack(ls_vt)
      pc.getSenders().forEach(sender => {
        if (sender.track.kind == 'video') {
            sender.replaceTrack(ls_vt)
        }
      });
      if (window.stop_screen_back){
        stop_screen_back()
      }
    });

    //1080p_2高清  720p_2较清晰  480p_2不太清晰
    // if(true) {
    //     localStreamScreen.setScreenProfile('720p_2');
    // }else{
    //     localStreamScreen.setScreenProfile('480p_2');
    // }
    localStreamScreen.setScreenProfile('720p_2');
    localStreamScreen.init(() => {
      var pc = sessionall.connection;
      let svt = localStreamScreen.getVideoTrack();
      localStream_1.removeTrack(ls_vt)
      localStream_1.addTrack(svt)
      pc.getSenders().forEach(sender => {
        if (sender.track.kind == 'video') {
            sender.replaceTrack(svt)
            resolve(true)
        }
      });
  }, err => {
    reject(err)
  });
  })
}
// 停止共享
function stop_screen() {
  return new Promise(function (resolve,reject) {
    var pc = sessionall.connection;
    let svt = localStream_1.getVideoTracks()[0];
    localStream_1.removeTrack(svt)
    localStream_1.addTrack(ls_vt)
    pc.getSenders().forEach(sender => {
      if (sender.track.kind == 'video') {
          sender.replaceTrack(ls_vt)
          svt.stop();
          resolve(true)
      }
    });
  })
}
// 音视频切换
function switch_video(){
  var pc = sessionall.connection;
  closeAllStream()
  localStream_1 = new window.MediaStream();
  pc.getSenders().forEach(sender => {
      if (sender && sender.track){
        localStream_1.addTrack(sender.track)
      }
  });
  if (pc.getRemoteStreams().length > 0) {
    remoteStream = pc.getRemoteStreams()[0];
    document.getElementById('remoteVideo').srcObject = remoteStream
  }
  document.getElementById('localVideo').srcObject = localStream_1
}
/**
 * 虚拟背景相关
 */
var model = {
  architecture: 'MobileNetV1',
  outputStride: 16,   //8,16  值越小，输出分辨率越大，模型越精确，速度越慢
  multiplier: 0.75,   // 0.5,0.75,1  值越大，层越大，模型越精确，速度越慢
  quantBytes: 2    /* 1,2,4  此参数控制用于权重量化的字节  
                     '4. 每个浮点数 4 个字节（无量化）。最高精度&原始模型尺寸',
                     '2. 每个浮点数 2 个字节。精度略低，模型尺寸减小 2 倍',
                     '1. 每个浮点数 1 个字节。精度降低, 模型尺寸减少 4 倍' 
                   */
}
let net = null
let flag = false
var refVirtua = null
if (typeof bodyPix !== 'undefined') {
  bodyPix.load(model).then(res=>{
    net = res
  })
}

function blurBackground(){
  const img = document.getElementById('localVideo')  // 获取视频帧
  let videoCanvas =  document.getElementById('backgroundImg')
  videoCanvas.style.display = 'block'
  let segmentation = null   
  net.segmentPerson(img).then(res =>{
      segmentation = res
      bodyPix.drawBokehEffect(
          videoCanvas, img, segmentation, 2,
          2, false);
  })
  let stream = videoCanvas.captureStream(15)
  let track = stream.getVideoTracks()[0]
  var pc = sessionall.connection;
  pc.getSenders().forEach(sender => {
    if (sender.track.kind == 'video' && sender.track.readyState != 'ended') {
        sender.replaceTrack(track)
    }
  });
  if(vague) {
    setTimeout(()=>{
      blurBackground()
    },30)
  } else {
    videoCanvas.style.display = 'none'
    let track = localStream_1.getVideoTracks()[0]
    pc.getSenders().forEach(sender => {
      if (sender.track.kind == 'video' && sender.track.readyState != 'ended') {
          sender.replaceTrack(track)
      }
    });
  }
}
function startBlurBackground(){
  vague = true
  blurBackground()
}
function stopBlurBackground(){
  vague = false
}
function startVirtua(imgURL){
  backgroundImgUrl = imgURL
  virtua = true
  replaceBackground()
}
function stopVirtua(){
  backgroundImgUrl = ''
  virtua = false
}
function replaceBackground() {
  const img = document.getElementById('localVideo')  // 获取视频帧
  let videoCanvas =  document.getElementById('backgroundImg')
  videoCanvas.style.display = 'block'
  let segmentation = null
  const foregroundColor = { r: 0, g: 0, b: 0, a: 0 }    // 前景色  设为完全透明
  const backgroundColor = { r: 0, g: 0, b: 0, a: 255 }   // 背景色
  var backgroundImg = new Image();  
  backgroundImg.src= backgroundImgUrl
  let backgroundDarkeningMask  = null
  net.segmentPerson(img).then(res =>{
      segmentation = res
      backgroundDarkeningMask  = bodyPix.toMask(
          segmentation,
          foregroundColor,
          backgroundColor
        )
      let context = videoCanvas.getContext('2d')
      // 合成
      context.putImageData(backgroundDarkeningMask , 0, 0)
      context.globalCompositeOperation = 'source-in' // 新图形只在重合区域绘制
      context.drawImage(backgroundImg, 0, 0, videoCanvas.width, videoCanvas.height)
      context.globalCompositeOperation = 'destination-over' // 新图形只在不重合的区域绘制
      context.drawImage(img, 0, 0, videoCanvas.width, videoCanvas.height)
      context.globalCompositeOperation = 'source-over' // 恢复
      let stream = videoCanvas.captureStream(15)
      let track = stream.getVideoTracks()[0]
      var pc = sessionall.connection;
      pc.getSenders().forEach(sender => {
        if (sender.track.kind == 'video' && sender.track.readyState != 'ended') {
           try {
            sender.replaceTrack(track)
           } catch (err){
              console.log(err)
           }
        }
      });
      if(virtua) {
        setTimeout(()=>{
          replaceBackground()
        },30)
      } else {
        videoCanvas.style.display = 'none'
        let track = localStream_1.getVideoTracks()[0]
        pc.getSenders().forEach(sender => {
          if (sender.track.kind == 'video' && sender.track.readyState != 'ended') {
              sender.replaceTrack(track)
          }
        });
      }
  })
}

/*虚拟背景结束

**/

//ajax封装
function ajax({ type, url, data, success,error }) {
  let xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function () {
    try {
      if (xhr.readyState === 4 ){
        if (xhr.status === 200) {
          let res = xhr.responseText;
          // res 是服务器返回的结果
          getAgentListXhr = null
          success(res);
        } else {
          error()
        }
      }
    } catch (err) {
      setLog(url +'接口发生异常：' + err.message);
    }
  }
  if (url.indexOf('get-agent-list') >-1){
    if (getAgentListXhr){
      getAgentListXhr.abort();
    }
    getAgentListXhr = xhr
  }
  if(type != 'FormData') {
    // 需要把传递进来的对象，转成字符串格式
    let arr = [];
    for (let key in data) {
      // key 表示键：id | appkey | bookname
      // data[key] 表示值： 1 | laotang | zs
      arr.push(key + '=' + data[key]);  // 'id=1'
    }
    let str = arr.join('&');
  
  
    // 判断是什么请求方式
    if (type === 'GET') {
      xhr.open(type, url + '?' + str);
      if (token){
        xhr.setRequestHeader('SDK-TOKEN', token);
      }
      if(company_code) {
        xhr.setRequestHeader('X-Tenant-Id', company_code);
      }
      xhr.send();
    } else if (type === 'POST') {
      xhr.open(type, url);
      if (token){
        xhr.setRequestHeader('SDK-TOKEN', token);
      }
      if(company_code) {
        xhr.setRequestHeader('X-Tenant-Id', company_code);
      }
      xhr.setRequestHeader('Content-Type', 'application/json');
      xhr.send(JSON.stringify(data));
    }
  }else{
    xhr.open("POST", url, true);
    if (token){
      xhr.setRequestHeader('SDK-TOKEN', token);
    }
    if(company_code) {
      xhr.setRequestHeader('X-Tenant-Id', company_code);
    }
    xhr.send(data);
  }
}


// 切换设备相关

function swithc_mic(deviceId){
  var pc = sessionall.connection;
  var constraints = {
    audio: {deviceId},
    video: false
  }
  navigator.mediaDevices.getUserMedia(constraints).then(stream => {
      let svt = localStream_1.getAudioTracks()[0];
      localStream_1.removeTrack(svt)
      pc.getSenders().forEach(sender => {
          localStream_1.getAudioTracks()[0].replaceTrack(stream.getAudioTracks()[0])
          if (sender.track.kind == 'audio') {
            sender.replaceTrack(stream.getAudioTracks()[0])
            localStream_1.addTrack(stream.getAudioTracks()[0])
          }
      });
  }).catch(error => {
      console.error('切换视频，失败原因：', error)
  });
}
function swithc_cameras(deviceId){
  var pc = sessionall.connection;
  var constraints = {
    audio: false,
    video: {deviceId}
  }
  navigator.mediaDevices.getUserMedia(constraints).then(stream => {
      let svt = localStream_1.getVideoTracks()[0];
      localStream_1.removeTrack(svt)
      pc.getSenders().forEach(sender => {
          if (sender.track.kind == 'video') {
            sender.replaceTrack(stream.getVideoTracks()[0])
            localStream_1.addTrack(stream.getVideoTracks()[0])
          }
      });
  }).catch(error => {
      console.error('切换视频，失败原因：', error)
  });
}
function swithc_speaker(deviceId){
  let basic_four_audio = document.getElementById('remoteVideo');
  basic_four_audio.setSinkId(deviceId);
}
function closeAllStream(){
  if (localStream_1){
    const tracks = localStream_1.getTracks();
    tracks.forEach(track => track.stop());
    localStream_1 = null
  }
  if (remoteStream){
    const tracks = remoteStream.getTracks();
    tracks.forEach(track => track.stop());
    remoteStream = null
  }
  if (switchStream){
    const tracks = switchStream.getTracks();
    tracks.forEach(track => track.stop());
    switchStream = null
  }
  if (localStreamScreen && localStreamScreen.stop){
    localStreamScreen.stop()
    localStreamScreen = null
  }
}

function getCameras() {
  return new Promise(function (resolve, reject) {
      navigator.mediaDevices.enumerateDevices().then(deviceInfos => {
          let datas = [];
          for (let i = 0; i !== deviceInfos.length; ++i) {
              let deviceInfo = deviceInfos[i];
              if (deviceInfo.kind === 'videoinput') {
                  let mediaDeviceInfo = {};
                  mediaDeviceInfo.deviceId = deviceInfo.deviceId;
                  mediaDeviceInfo.kind = 'videoinput';
                  mediaDeviceInfo.label = deviceInfo.label;
                  datas.push(mediaDeviceInfo);
              }
          }
          resolve(datas);
      }).catch(function (error) {
          reject([]);
      });
  })
}

function onLoad(){
  window.addEventListener('beforeunload', function (e) {
    // 在这里执行你想要在页面刷新前执行的代码
    setLog('此处可能刷新页面或者退出界面')
    if (['RINGING','CALLING'].includes(nowStatus)){
      hangUp()
    }
  });
}

function getBaseUrl(){
  try {
    ajax({
      type: 'POST',
      url: dominUrl + 'cloudcc-client-server/openapi/heart-beat',
      data: {req_id:generateUUID(),os: system},
      success: function (res) {
        let result = JSON.parse(res)
        if (result.code == 200 || result.code == 0){
          baseCount = 0
          wsUrl = result.master || result.slave
          if (dualPlatform){
            if (result.room && result.room == 'B'){
              dominUrl = standbyUrl
            } else {
              dominUrl = httpUrl
            }
          }
          createSocket()
        } else {
          againGetBase()
        }
      },
      error: function() {
        againGetBase()
      }
    })
  }catch(error){
    againGetBase()
  }
}

function againGetBase(){
  baseCount++
  setLog(baseCount + '尝试获取域名')
  if (baseCount < 10){
    dominUrl==httpUrl?dominUrl=standbyUrl:dominUrl=httpUrl
    setTimeout(()=>{
      getBaseUrl()
    },100)
  } else {
    setLog('无法获取主备域名System Error')
  }
}