
var ws, n = 0, seatComming,
  timer, hidTel, hidCallID, hidActionID,
  directType, sendType, mesCont,
  eorrorConnect, errorState = false,OperatorLogText,
  makeCallId = "", lockReconnect = false,
  obj = {}, cls = 0, ivrState, clsCookie, LoginState,
  lasttime = new Date().getTime(),
  reconnecTion, recon, loginOr = false, GetState;

//创建scoket连接
function createWebSocket () {
  try {
    $("#top-search li i").removeClass("active");
    //Connect();
  } catch (e) {
    reconnect();
  }
}
function closeSocket (e) {

  if (event.clientX > document.body.clientWidth && event.clientY < 0 || event.altKey) {
  } else {
    //ws.close();
    if (helper.cookies.get('callState') != "1") {
      ws.close();
    }

    //helper.cookies.set('clsCookie', 1);


  }
}
if (helper.cookies.get('callState') == "5" || helper.cookies.get('callState') == "2") {
  Connect()
}


function Connect () {
  //+ huayi.config.socket_ip + ":" + huayi.config.socket_port  121.196.219.217:8081
  // ws = new WebSocket("ws://10.200.46.27:8081");
  ws = new WebSocket("ws://192.168.8.7:8081");
  //ws = new WebSocket("ws://121.196.219.217:8081");
  //ws = new WebSocket("ws://" + ZXDT.config.socket_ip + ":" + ZXDT.config.socket_port);
  ws.onopen = function () {
    console.log(new Date() + "    " + "建立连接");
    helper.cookies.set('clsCookie', 1);
    cls = 0;
    var usercode = document.getElementById("txtLabourwork").value;
    var extnumber = document.getElementById("txtPhoneNum").value;

    if (helper.cookies.get('callState') == "1" || helper.cookies.get('callState') == null) {
      $(".popRemind").hide();
      obj = {};
      obj.Type = "Login";
      obj.AgentID = usercode;
      obj.AgentExten = extnumber;
      obj.AgentGroup = "12";
      obj.AgentType = "0";
      Send();
      //setTimeout("SetLogin(helper.cookies.get('callState'))", 1000);
    } else {
      setTimeout("SetLogin(helper.cookies.get('callState'))", 1000);
    }

  };
  //接收到消息的回调方法
  ws.onmessage = function (evt) {
    //如果获取到消息，心跳检测重置
    //拿到任何消息都说明当前连接是正常的
    //heartCheck.reset().start();
    heartCheck.reset().reset
    var myDate = new Date();
    console.log(myDate + "  receive  " + evt.data);
    var data = JSON.parse(evt.data)[0];
    if (data) {
      var rlt = data.Result;
      if (rlt == true) {
        var type = data.Type;
        switch (type.toLowerCase()) {
          case "login":
            button_QRCall();
            break; //签入
          case "logout":
            LogoutBack();
            break; //签出
          case "dropcall":
            DropCallBack();
            //button_ReleaseAnswer();
            break; //挂断
          case "makecall": //MakeCall
            //外呼先示忙
            makecallBack();
            break; //外呼
          case "setstate":
            SetState(data);
            break; //置忙置闲
          case "meeting":
            //OpenWindowShow1('telmanage/calloutopt.aspx?otype=3', '多方通话', 800, 500);
            break; //多方通话
          case "transfer":
            transferBack();
            break; //转移
          case "hold":
            //button_KeepCall(); //保持方法
            break; //保持
          case "retrieve":
            //button_GetKeepCall();
            break; //接回
          case "incoming":
            Form_callCommingCaller(data);
            break; //来电
          case "subscribe":
            //SubScribeBack();
            break; //监测
          case "subscribecancel":
            //SubScribeCancelBack();
            break; //停止监测
          case "agentstate":
            AgentStateBack(data);
            break; //坐席状态
          case "linestate":
            LineStateBack(data);
            break; //线路状态
          case "motorsetstate":
          //SayFreeBack();
          case "agentstateagent":
            agentstateagent(data);
            break; //班长置闲
          case "linestateagent":
            LineStateAgentBack(data);
            break; //线路状态通知
          case "callid":
            //CallIDBack(data);
            break; //获取callid
          case "listen":
            listenBack();
            break; //获取callid
          case "insert":
            insertBack(data);
            break; //获取callid
          case "recordpath":
            //RecordPathBack(data);
            break; //录音返回
        }
      } else {
        var type = data.Type;
        if (type.toLowerCase() == "waitcount") {
          WaitCountBack(data);
        }
        if (rlt == false) {
          //$(".hwzt").text('操作失败！');
          //外呼失败的文字展示
          if (data.Type.toLowerCase() == "makecall") {
            switch (data.ErrorCode) {
              case 1: layer.msg('挂机，请重试'); break;
              case 2: layer.msg('FS外呼命令失败，请重试！'); break;
              case 3: layer.msg('外呼获取座席失败，请重试！'); break;
              case 4: layer.msg('座席置忙禁止座席外呼，请重试！'); break;
              case 5: layer.msg('主叫座席分机非空闲或摘机拨号，请重试！'); break;
              case 6: layer.msg('为外呼设置座席状态失败，请重试！'); break;
              case 7: layer.msg('被叫座席非空闲，请重试！'); break;
              case 8: layer.msg('执行分机呼叫失败, 未找到分机通道，请重试！'); break;
              case 9: layer.msg('执行分机呼叫失败, 无法绑定分机通道，请重试！'); break;
              case 10: layer.msg('禁止分机自呼，请重试！'); break;
              case 11: layer.msg('发送分机呼叫Esl命令失败，请重试！'); break;
              case 12: layer.msg('目标分机非空闲，请重试！'); break;
              case 13: layer.msg('主控通道非空闲，请重试！'); break;
              case 14: layer.msg('校验不通过绑定本端逻辑线路失败，请重试！'); break;
              case 15: layer.msg('校验不通过本端当前线路忙，请重试！'); break;
              case 16: layer.msg('校验不通过对端线路状态忙，请重试！'); break;
              case 17: layer.msg('被叫关机，请重试！'); break;
              case 18: layer.msg('无效号码，请重试！'); break;
              case 19: layer.msg('无人接听，请重试！'); break;
              case 20: layer.msg('交换机错误(用户无法接通)，请重试！'); break;
              case 21: layer.msg('话机外呼执行数据交换操作失败未找到分机通道，请重试！'); break;
              case 22: layer.msg('话机外呼执行数据交换操作失败分机通道未绑定任务，请重试！'); break;
              case 23: layer.msg('执行设备外呼任务失败无法获取对应线路，请重试！'); break;
            }
          }
          if (data.Type == 'AcdConnectNotify') {
            $("#top-search li i").removeClass("active");
            layer.msg('Acd未连接');
          }
        } else {
          //layer.msg(rlt);
        }
      }
    }
  };
  //连接关闭的回调方法
  ws.onclose = function (evt) {

    if (cls == 0) {
      cls = 1;

      layer.msg('连接关闭！');
      $("#top-search li i").removeClass("active");
      if (helper.cookies.get('clsCookie')) {
        if (helper.cookies.get('callState') != "1") {
          Connect()
        }

      } else {
        reconnect();
      }
    }
    console.log("111")
  };
  //连接发生错误的回调方法
  ws.onerror = function (evt) {
    //产生异常
    //layer.msg('连接出现异常！');
    console.log(ws);
    if (ws == null || ws.readyState != ws.OPEN) {
      console.log(new Date() + "开始重连");
      reconnect();
    }

  };
}

//重连
function reconnect () {
  if (lockReconnect) return;
  lockReconnect = true;
  //没连接上会一直重连，设置延迟避免请求过多
  setTimeout(function () {
    console.log(new Date() + "    " + "重连中……");
    createWebSocket("ws://121.196.219.217:8081");
    lockReconnect = false;
  }, 2000);
}

//发送
function Send () {
  if (ws.readyState != ws.OPEN) {
    if (loginOr) {
      errorState = true;
      layer.msg('连接异常！');
      reconnect();
    } else {
      errorState = false;
      layer.msg('连接异常！');
      reconnect();
    }
  }
  if (ws.readyState == ws.OPEN) {
    console.log(new Date() + "  send  " + JSON.stringify(obj));
    ws.send(JSON.stringify(obj));
  }
}
//心跳检测
var heartCheck = {
  timeout: 25000, //25秒
  timeoutObj: null,
  serverTimeoutObj: null,
  reset: function () {
    clearTimeout(this.timeoutObj);
    clearTimeout(this.serverTimeoutObj);
    return this;
  },
  start: function () {
    var self = this;
    this.timeoutObj = setTimeout(function () {
      //这里发送一个心跳，后端收到后，返回一个心跳消息，
      //onmessage拿到返回的心跳就说明连接正常
      obj.Type = "Heart";
      Send();
      self.serverTimeoutObj = setTimeout(function () { //如果超过一定时间还没重置，说明后端主动断开了
        //ws.close(); //如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
        //同步签出状态
        $("#top-search li i").removeClass("active");
        $(".Login").addClass("active");
        $(".zxzt").removeClass("bl").addClass("br");
        $(".fwzt").removeClass("bl").addClass("br");
        $(".hwzt").text('');
        if (cls == 0) {
          cls = 1;
          reconnect();
        }
      }, self.timeout)
    }, this.timeout)
  }
}

//默认记忆上次是否签入，是否置忙置闲 0表示已签入 空闲，1表示签入置忙，2表示签出 

function SetLogin (state) {

  if (state == 1) { return; }
  var usercode = document.getElementById("txtLabourwork").value;
  var extnumber = document.getElementById("txtPhoneNum").value;
  obj = {};
  obj.Type = "Login";
  obj.AgentID = usercode;
  obj.AgentExten = extnumber;
  obj.AgentGroup = "12";
  obj.AgentType = "0";

  Send();

  if (state == 5) {
    setTimeout('SayBusy()', 1000);

  }
}
//置忙
function SayBusy () {
  obj.Type = "SayBusy";
  Send();

}
//签入
function button_QRCall () {
  $(".fa-phone").addClass("selectClass");
  $(".fa-phone").removeClass("defaultClass");
  $(".fa-pause").addClass("selectClass");
  $(".fa-pause").removeClass("defaultClass");
  $('#imgServerState').attr('src', '/Content/images/server1.png');
  $('#imgAgentState').attr('src', '/Content/images/zx1.png');
  $('#imgServerState').attr('alt', '签入');
  layer.msg('签入成功');
  helper.cookies.set('callState', 2);
  OperatorLogText = "签入"
  OperatorLog(OperatorLogText)
  try {
    var result = OCX_AgentLogOut();
  }
  catch (e) {
    document.getElementById("spanServerRes").innerHTML = e.message;
  }
  //AgentQR();
}
//签出
function LogoutBack () {
  $(".fa-phone").removeClass("selectClass");
  $(".fa-phone").addClass("defaultClass");
  $(".fa-play").removeClass("selectClass");
  $(".fa-play").addClass("defaultClass");
  $(".fa-pause").removeClass("selectClass");
  $(".fa-pause").addClass("defaultClass");
  $('#imgServerState').attr('src', '/Content/images/server0.png');
  $('#imgAgentState').attr('src', '/Content/images/zx2.png');
  $('#imgServerState').attr('alt', '未签入');
  layer.msg('签出成功');
  OperatorLogText = "签出"
  OperatorLog(OperatorLogText)
  helper.cookies.set('callState', 1);
  ws.close();

}
// 监听
function listenBack () {
  seatComming = false
  layer.msg('监听成功');
}
function insertBack () {
  seatComming = false
  layer.msg('强插成功');
}
//排队数量

function WaitCountBack (data) {
  console.log(data.WaitCount)
  document.getElementById("spanqueuingnum").innerHTML = data.WaitCount;

}
function makecallBack () {
  layer.msg('外呼成功');
  $(".fa-play").removeClass("selectClass");
  $(".fa-play").addClass("defaultClass");
  $(".fa-pause").removeClass("selectClass");
  $(".fa-pause").addClass("defaultClass");
}
//来电弹屏事件
function Form_callCommingCaller (data) {
  if (seatComming) {
    return
  }
  becallout = false;
  becallcome = true;
  callerNum = data.Number;
  $(".fa-play").removeClass("selectClass");
  $(".fa-play").addClass("defaultClass");
  $(".fa-pause").removeClass("selectClass");
  $(".fa-pause").addClass("defaultClass");
  document.getElementById("forZYnumber").value = callerNum;
  document.getElementById("callnum").value = callerNum;
  var timeno = new Date().getTime();
  //document.getElementById("mainframe").src = "/CallRecord/CallScreen/?workOrderNum=10929";

  //try {
  var userid = document.getElementById("txtAgentId").value;
  var usercode = document.getElementById("txtLabourwork").value;
  var username = document.getElementById("txtAgentName").value;
  var extnumber = document.getElementById("txtPhoneNum").value;
  //获取呼叫编号
  var callid = data.CallID;
  CBnumber = data.CallID
  document.getElementById("CallHjbh").value = CBnumber;
  helper.cookies.set('CallID', CBnumber);
  username = encodeURI(username);

  var opturl = "/OCXOpt/OCXOptCallAjax/?optaction=zhenlingEvent&timeno=" + timeno + "&callid=" + CBnumber + "&userid=" + userid + "&usercode=" + usercode + "&username=" + username + "&extnumber=" + extnumber + "&callerNum=" + callerNum;
  console.log("/OCXOpt/OCXOptCallAjax/?optaction=zhenlingEvent&timeno=" + timeno + "&callid=" + CBnumber + "&userid=" + userid + "&usercode=" + usercode + "&username=" + username + "&extnumber=" + extnumber + "&callerNum=" + callerNum)
 
    $.ajax({

        url: "/OCXOpt/writelog",
        type: "post",
        async: false,//同步请求

        dataType: "json",
        cache: false,
        data: { message: opturl },
        success: function (res) {
        }
    });






  $.ajax({
    type: 'get',
    url: opturl,
    dataType: 'html',
    async: false,
    cache: false,
    success: function (res) {
      if (res != "error") {
        $(".callScreen").show()
        $("#workOrderNum").val(res)
        lineState();
        resOrder()

        //document.getElementById("mainframe").src = "/CallRecord/CallScreen/?workOrderNum=" + res;
        
        //layer.open({
            //type: 2,
           // anim: 4,
            //scrollbar: false,
            //content: '/CallRecord/CallScreen/?workOrderNum=' + res,
            //area: ['100%', '100%'],
           // id: 'WorkOrderAllListReport',
            //title: '来电弹屏'

        //});
      }else{

        //document.getElementById("mainframe").src = "/CallRecord/CallScreen/?workOrderNum=111";

        //layer.open({
         // type: 2,
         // anim: 4,
          //scrollbar: false,
          //content: '/CallRecord/CallScreen/?workOrderNum=111',
          //area: ['100%', '100%'],
          //id: 'WorkOrderAllListReport',
         // title: '来电弹屏' 

       // }); 
      }
    }
  });//更新摘机事件
  //} catch (e) {
  //alert(e.Message);
  //}
  //f_addTab('callin_' + CBnumber + callerNum, callerNum + '来电', '../telmanage/callinoptbbzx.aspx?callid=' + CBnumber + "&phone=" + callerNum + "&timeno=" + timeno);

}
//***************************************************
function CallIDBack (data) {
  //$(".hidCallID").val(data.CurrID);
}

//挂断
function DropCallBack () {
  //if(ivrState){ return };
  helper.cookies.set('initDrop', 0);
  layer.msg('挂断成功');
  var usercode = document.getElementById("txtLabourwork").value;
  var extnumber = document.getElementById("txtPhoneNum").value;
  obj = {};
  obj.Type = "SayBusy";
  obj.AgentID = usercode;
  obj.AgentExten = extnumber;
  obj.AgentGroup = "12";
  obj.AgentType = "0";
  Send();
}
function transferBack(){
  layer.msg('转接成功');
}
//线路状态通知
function LineStateAgentBack (data) {
  var objiframe = $("iframe:visible")
  //0分机不可用，1空闲，2摘机等待拨号，3正在拨号，4呼出振铃，5来电振铃，6通话中，7播放忙音中，8移除IP分机，9通话保持中
  if (data.State == '0') {
    $('#imgAgentState').attr('src', '/Content/images/zx4.png');
  }
  if (data.State == '1') {
    $('#imgAgentState').attr('src', '/Content/images/zx1.png');
    helper.cookies.set('callState', 2);
  }
  if (data.State == '2') {
    $('#imgAgentState').attr('src', '/Content/images/zx4.png');
  }
  if (data.State == '3') {
    $('#imgAgentState').attr('src', '/Content/images/zx4.png');
  }
  if (data.State == '4') {
    $('#imgAgentState').attr('src', '/Content/images/zx4.png');
  }
  if (data.State == '5') {
    $('#imgAgentState').attr('src', '/Content/images/zx4.png');
  }
  if (data.State == '6') {
    $('#imgAgentState').attr('src', '/Content/images/zx4.png');
  }
  if (data.State == '7') {
    $('#imgAgentState').attr('src', '/Content/images/zx4.png');
  }
  if (data.State == '8') {
    $('#imgAgentState').attr('src', '/Content/images/zx4.png');
  }
  if (data.State == '9') {
    $('#imgAgentState').attr('src', '/Content/images/zx4.png');
  }
}

function toDub (i) {
  return i < 10 ? "0" + i : "" + i;
}
//外呼
function MakeCallBack (data) {
  var makeCallPhone = $.cookie("makeCallPhone");

}

//置忙置闲
function SetState (obj) {

  if (obj.State == '5') {
    $(".fa-pause").addClass("defaultClass");
    $(".fa-pause").removeClass("selectClass");
    $(".fa-play").addClass("selectClass");
    $(".fa-play").removeClass("defaultClass");
    $('#imgAgentState').attr('src', '/Content/images/zx3.png');
    //$.cookie("callState", obj.State, {expires: 7});
    OperatorLogText = "置忙"
    OperatorLog(OperatorLogText)
    helper.cookies.set('callState', obj.State);
    //$('#imgAgentState').attr('src', '/Content/images/zx2.png');
  }
  if (obj.State == '2') {
    $(".fa-pause").addClass("selectClass");
    $(".fa-pause").removeClass("defaultClass");
    $(".fa-play").addClass("defaultClass");
    $(".fa-play").removeClass("selectClass");
    $('#imgAgentState').attr('src', '/Content/images/zx1.png');
    OperatorLogText = "置闲"
    OperatorLog(OperatorLogText)
    //$.cookie("callState", obj.State, {expires: 7});
    helper.cookies.set('callState', obj.State);
  }
}

function OperatorLog(OperatorLogText){
  console.log(OperatorLogText)
  var data = {
    typeName:OperatorLogText
  }
  $.ajax({
    url: "/main/addOPeratorLog",
    type: "post",
    async: false,//同步请求
    contentType: "application/json",
    dataType: "text",
    cache: false,
    data: JSON.stringify(data),
    success: function (thisResult) {

    },
    error: function (error) {
      return false;
    }
  });
}



function agentstateagent (data) {

  if (data.AgentState == '5') {
    $(".fa-pause").addClass("defaultClass");
    $(".fa-pause").removeClass("selectClass");
    $(".fa-play").addClass("selectClass");
    $(".fa-play").removeClass("defaultClass");
    $('#imgAgentState').attr('src', '/Content/images/zx3.png');
    //$.cookie("callState", obj.State, {expires: 7});
    helper.cookies.set('callState', obj.State);
    //$('#imgAgentState').attr('src', '/Content/images/zx2.png');
  }

  if (data.AgentState == '2') {
    $(".fa-pause").addClass("selectClass");
    $(".fa-pause").removeClass("defaultClass");
    $(".fa-play").addClass("defaultClass");
    $(".fa-play").removeClass("selectClass");
    $('#imgAgentState').attr('src', '/Content/images/zx1.png');
    //$.cookie("callState", obj.State, {expires: 7});
    helper.cookies.set('callState', obj.State);
  }

  if (data.AgentState == '7'&& LogoutState) {
    $(".popRemind").show();
    $(".fa-phone").removeClass("selectClass");
    $(".fa-phone").addClass("defaultClass");
    $(".fa-play").removeClass("selectClass");
    $(".fa-play").addClass("defaultClass");
    $(".fa-pause").removeClass("selectClass");
    $(".fa-pause").addClass("defaultClass");
    $('#imgServerState').attr('src', '/Content/images/server0.png');
    $('#imgAgentState').attr('src', '/Content/images/zx2.png');
    $('#imgServerState').attr('alt', '未签入');
    helper.cookies.set('callState', 1);
    ws.close();
  }

}

//多方通话
function MeetingBack () {

}
//转移
function TransferBack () {
}
//保持
function HoldBack () {
}
//接回
function RetrieveBack () {
}
//监测
function SubScribeBack () {
  navBar
}
//取消监测
function SubScribeCancelBack () {

}
//班长监测返回状态
//坐席状态
function AgentStateBack (data) {
  //console.log("监控")
  console.log(data.AgentID + "&&agentstate" + data.State)
  //0离线， 1登陆中， 2空闲， 3通话中 4话后处理 5小休 6被请求 7 注销
  //$('#navBar ul li').find("dd.layui-this").children("a").attr("data-url") GetState(data.AgentID, data.State)	
  //var seatMonit =$('#navBar ul li').find("dd.layui-this").children("a")
  if (data.State == '0') { GetState = "0" } //0离线
  if (data.State == '1') { GetState = "99" } //1登陆中
  if (data.State == '2') { GetState = "2" } //2空闲
  if (data.State == '3') { GetState = "3" } //3通话中
  if (data.State == '4') { GetState = "5" } //4话后处理
  if (data.State == '5') { GetState = "4" } //5小休
  if (data.State == '6') { GetState = "9" } //6被请求
  if (data.State == '7') { GetState = "0" } //7 注销
  //window.frames[obj.attr("name")].UpdateAgentState(data.AgentID, data.State);
  console.log(window.frames[1].GetState)
  if (window.frames[1].GetState) {
    window.frames[1].GetState(data.AgentID, GetState)
  }

}
//线路状态
function LineStateBack (data) {
  console.log(data.AgentID + "&&linestate" + data.State)
  //0分机不可用，1空闲，2摘记等待拨号，3正在拨号，4呼出振铃，5来电振铃，6通话中
  //7播放忙音中，8通话保持中，9话机移除，10保持/空闲，11保持/摘机等待拨号
  //12保持/正在拨号，13保持/呼出振铃,14保持/通话中
  if (data.State == '0') { GetState = "99" } //0分机不可用
  if (data.State == '1') {
    if (GetState == "4") {
      GetState == "4"
    } else {
      GetState = "2"
    }

  } //1空闲
  if (data.State == '2') { GetState = "99" } //2摘记等待拨号
  if (data.State == '3') { GetState = "9" } //3正在拨号
  if (data.State == '4') { GetState = "9" } //4呼出振铃
  if (data.State == '5') { GetState = "9" } //5来电振铃
  if (data.State == '6') { GetState = "3" } //6通话中
  if (data.State == '7') { GetState = "99" } //7播放忙音中
  if (data.State == '8') { GetState = "99" } //8通话保持中
  if (data.State == '9') { GetState = "99" } //9话机移除
  if (data.State == '10') { GetState = "99" } //10保持/空闲
  if (data.State == '11') { GetState = "99" } //11保持/摘机等待拨号
  if (data.State == '12') { GetState = "99" } //12保持/正在拨号
  if (data.State == '13') { GetState = "99" } //13保持/呼出振铃
  if (data.State == '14') { GetState = "99" } //14保持/通话中
  if (window.frames["mainframe"].GetState) {
    window.frames["mainframe"].GetState(data.AgentID, GetState)
  }
}
//录音返回
function RecordPathBack (data) {
}
//获取当前的日期时间 格式“yyyy-MM-dd HH:mm:ss”
function getNowFormatDate () {
  var date = new Date();
  var seperator1 = "-";
  var seperator2 = ":";
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
    " " + date.getHours() + seperator2 + date.getMinutes() +
    seperator2 + date.getSeconds();
  return currentdate;
}






