
var ws, n = 0, timer;
var obj = {};

var cls = 0;
var lockReconnect = false;
//话务日志参数
var errorState=false;
var reconnecTion;
var recon;
var loginOr=false;
var directType;
var sendType;
var mesCont;
var eorrorConnect;
//创建scoket连接
function createWebSocket() {
    try {
        $("#top-search li i").removeClass("active");
        $(".hw_show  i").removeClass("Turn110_c"); 
    	$(".hw_show  i").addClass("Turn110");  
        Connect();
    } catch (e) {
    	//打印日志
		directType="lianjie";
		sendType="异常错误"; //JSON.stringify(data)
		mesCont=e.message;
		debuggerLog();
        reconnect();
    }
}

//连接
function Connect() {
    try {
        ws = new WebSocket("ws://" + huayi.config.socket_ip + ":" + huayi.config.socket_port);
        ws.onopen = function () {
            console.log(new Date() + "    " + "建立连接");
            //心跳检测重置
            heartCheck.reset().start();
            cls = 0;
            $("#top-search li i").removeClass("active");
            $(".hw_show  i").removeClass("Turn110_c"); 
    		$(".hw_show  i").addClass("Turn110");  
            $(".Login").addClass("active");
        };
        //接收到消息的回调方法
        ws.onmessage = function (evt) {
            heartCheck.reset().start();
            var myDate = new Date();
            console.log(myDate + "  receive  " + evt.data);

            var data = JSON.parse(evt.data)[0];
            //打印日志
			directType="recive";
			sendType=data.Type; //JSON.stringify(data)
			mesCont=JSON.stringify(evt);
			debuggerLog()
            if (data) {
                var rlt = data.Result;
                if (rlt == true) {
                    var type = data.Type;
                    switch (type.toLowerCase()) {

                        case "login": LoginBack(); break;//签入
                        case "logout": LogoutBack(); break;//签出
                        case "dropcall": DropCallBack(); break;//挂断
                        case "makecall": MakeCallBack(); break;//外呼
                        case "setstate": SetState(data); break;//置忙置闲
                            //case "saybusy": SayBusyBack(data); break;
                            //case "sayfree": SayFreeBack(data); break;
                        case "meeting": MeetingBack(); break;//多方通话
                        case "transfer": TransferBack(); break;//转移
                        case "hold": HoldBack(); break;//保持
                        case "retrieve": RetrieveBack(); break;//接回
                        case "incoming": IncomingBack(data); break;//来电
                        case "subscribe": SubScribeBack(); break;//监测
                        case "subscribecancel": SubScribeCancelBack(); break;//停止监测
                        case "agentstate": AgentStateBack(data); break;//坐席状态
                        case "linestate": LineStateBack(data); break;//线路状态
                        case "motorsetstate": SayFreeBack(); break;//班长置闲
                        case "linestateagent": LineStateAgentBack(data); break;//线路状态通知
                        case "callid": CallIDBack(data); break;//获取callid
                        case "recordpath": RecordPathBack(data); break;//录音返回
                        case "LineOutState": LineOutState(data); break;//录音返回
                    }
                }
                else {
                    if (rlt == false) {
                        //layer.confirm('操作失败！', {
                        //    btn: ['确定'] 
                        //});
                        $(".hwzt").text('操作失败！');
                    }
                    else {
                        $(".hwzt").text(rlt);
                        //layer.confirm(rlt, {
                        //    btn: ['确定']
                        //});
                    }
                }
            }
        };
        //连接关闭的回调方法
        ws.onclose = function (evt) {
        	directType="recive";
			sendType="close"; //JSON.stringify(data)
			mesCont=JSON.stringify(evt);
			debuggerLog();
            if (cls == 0) {
                cls = 1;

                $(".hwzt").text('连接关闭！');
                $("#top-search li i").removeClass("active");
				$(".hw_show  i").removeClass("Turn110_c"); 
    			$(".hw_show  i").addClass("Turn110"); 
                console.log(ws);
                if (ws == null || ws.readyState != ws.OPEN) {
                    console.log(new Date() + "开始重连");
                    reconnect();
                }
            }
        };
        //连接发生错误的回调方法
        ws.onerror = function (evt) {
        	directType="recive";
			sendType="连接错误 "; //JSON.stringify(data)
			mesCont=JSON.stringify(evt);
			debuggerLog();
            //产生异常
            $(".hwzt").text('连接异常！');
            $("#top-search li i").removeClass("active");
			$(".hw_show  i").removeClass("Turn110_c"); 
    		$(".hw_show  i").addClass("Turn110"); 
            console.log(ws);
            if (ws == null || ws.readyState != ws.OPEN) {
                console.log(new Date() + "开始重连");
                reconnect();
            }
        };
    }
    catch (ex) {
        //layer.confirm('连接失败！', {
        //    btn: ['确定']
        //});
        $(".hwzt").text('连接失败！');
        $("#top-search li i").removeClass("active");
        $(".hw_show  i").removeClass("Turn110_c"); 
    	$(".hw_show  i").addClass("Turn110"); 
    }
}

//重连
function reconnect() {
    if (lockReconnect) return;
    lockReconnect = true;
    //没连接上会一直重连，设置延迟避免请求过多
    setTimeout(function () {
    	directType="send";
		sendType="重连中 "; //JSON.stringify(data)
		mesCont="重连中";
		debuggerLog();
        console.log(new Date() + "    " + "重连中……");
        createWebSocket();
        lockReconnect = false;
    }, 2000);
}
function debuggerLog(){
	$.post(huayi.config.callcenter_url + 'Log/CallOpt', {
		direct: directType,
		type: sendType,
		cont: mesCont,
		"token": $.cookie("token")
	}, function(result) {
		result = $.parseJSON(result);
		if(result.state.toLowerCase() == "warning") {
			//layer.msg("创建工单成功");
		}
	})
}
//异常重连
function errorFun(){
	clearInterval(timer);
	var errorNum=0
	timer = setInterval(function() {
		errorNum++;
		if (errorNum>2) {
			$(".hwzt").text('连接异常！');
		}else{
			$("#top-search li i").removeClass("active");
			$(".Login").addClass("active");
			$(".zxzt").removeClass("bl").addClass("br");
			$(".fwzt").removeClass("bl").addClass("br");
			$(".hwzt").text('');
		}
		reconnect();
		$(".hwzt").text('连接异常！');
	}, 15000);
}
noLine();
clearInterval(recon);
recon = setInterval(function () { 
	if(loginOr){
		noLine();
		setTimeout(function () {
			lineState();
    	}, 2000);
	}
}, 1000*10);
function lineState(){
	if (reconnecTion) {
		reconnecTion=false;
	}else{
		directType="send";
		sendType="断网 "; //JSON.stringify(data)
		mesCont="断网";
		debuggerLog();
	}
}
function noLine(){
	$.ajax({
		type: "get",
		url: huayi.config.callcenter_url + 'UserAccount/GetNowUser',
		async: true,
		dataType: 'json',
		data: {
			"token": $.cookie("token")
		},
		success: function(data) {
			reconnecTion = data.data.user.F_UserCode;
		}
	});
}
//发送
function Send() {
    if (ws.readyState != ws.OPEN) {
    	directType="send";
		sendType=ws.readyState; //JSON.stringify(data)
		mesCont="异常了";
		debuggerLog();
        Connect();
    }
    if (ws.readyState == ws.OPEN) {
    	if (obj.Type) {
			directType="send";
			sendType=obj.Type;
			mesCont=JSON.stringify(obj);
			debuggerLog()
		}else{
			directType="send";
			sendType="建立连接";
			mesCont=JSON.stringify(obj);
			debuggerLog()
		}
        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导致重连两次
            	//打印日志
				directType="heart";
				sendType="心跳"; //JSON.stringify(data)
				mesCont="未收到";
				debuggerLog();
            }, self.timeout)
        }, this.timeout)
    }
}

//签入
function LoginBack() {
    $("#top-search li i").removeClass("active");
    $(".hw_show  i").removeClass("Turn110_c"); 
    $(".hw_show  i").addClass("Turn110"); 
    $(".Logout").addClass("active");
    $(".SayBusy").addClass("active");
    $(".MakeCall").addClass("active");
    $(".zx").removeClass("br").addClass("bl");
    $(".xl").removeClass("br").addClass("bl");
    $(".hwzt").text('');
}
//签出
function LogoutBack() {
    $("#top-search li i").removeClass("active");
    $(".hw_show  i").removeClass("Turn110_c"); 
    $(".hw_show  i").addClass("Turn110"); 
    $(".Login").addClass("active");
    $(".zx").removeClass("bl").addClass("br");
    $(".xl").removeClass("bl").addClass("br");
}

//来电
function IncomingBack(data) {
    clearworkorder();
    $(".ldhm").val(data.Number);
    $(".hidTel").val(data.Number);
    $(".tel").text(data.Number); 
    $(".lxr").text(data.Number);
    $(".ldtime").text(getNowFormatDate());
    $(".thsc").text("00:00");
    //获取callid
    $.ajaxSettings.async = false;
    $.getJSON(huayi.config.callcenter_url + 'CallInScreen/GetCallIdByPhone', { "tel": $(".hidTel").val(), "token": $.cookie("token") }, function (result) {
        $.ajaxSettings.async = true;
        if (result.state.toLowerCase() == "success") {
            $(".hidCallID").val(result.data.CallId);
        }
    })
    //获取电话所属地
    $.getJSON(huayi.config.callcenter_url + 'CallInScreen/GetPhoneLocation', { "tel": $(".hidTel").val(), "token": $.cookie("token") }, function (result) {
        if (result.state.toLowerCase() == "success") {
            $(".ldlocation").text(result.data[0].F_Name);
            $(".khgsd").text(result.data[0].F_Name);
        }
    })
    //获取客户信息
    $(".ttsdh").text($(".hidTel").val());
    $(".tsdh").val($(".hidTel").val());
    $.getJSON(huayi.config.callcenter_url + 'CallInScreen/GetCustomerByTel', { "tel": $(".hidTel").val(), "token": $.cookie("token") }, function (result) {
        if (result.state.toLowerCase() == "success") {
            if (result.data.length > 0) {
                $(".khmc").val(result.data[0].F_CustomerName);
                $(".tkhmc").text(result.data[0].F_CustomerName);
                $("#khid").val(result.data[0].F_CustomerId);
                $(".lxdh").val(result.data[0].F_Telephone);
                $(".tsdh").val(result.data[0].F_Mobile);
                $(".ttsdh").text(result.data[0].F_Mobile);
                $(".lxr").val(result.data[0].F_CustomerEName);
                $(".postcode").val(result.data[0].F_PostCode);
                $(".email").val(result.data[0].F_Email);
            }
        }
    })

    $('.maxOpen').trigger("click");
    $('.head-pic .lahei .la-before').show();
    $('.head-pic .lahei .la-after').hide();
    $(".Bacha").hide();
}
function CallIDBack(data) {
    //$(".hidCallID").val(data.CurrID);
}
//挂断
function DropCallBack() {
    $("#top-search li i").removeClass("active");
    $(".hw_show  i").removeClass("Turn110_c"); 
    $(".hw_show  i").addClass("Turn110"); 
    $(".Logout").addClass("active");
    $(".SayBusy").addClass("active");
    $(".MakeCall").addClass("active");

    $(".td-call").hide();
    //$('.ldtp-con').css("display", 'none');
}
function LineStateAgentBack(data) {
    if (data.State == '1') {
        $(".xl").removeClass("br").addClass("bl");
        clearInterval(timer);

        if ($(".hidTel").val() && $(".hidCallID").val()) {
            $.post(huayi.config.callcenter_url + 'CallInScreen/UpdateGJ', { callid: $(".hidCallID").val(), "token": $.cookie("token") }, function (result) {
                result = JSON.parse(result);
                if (result.state.toLowerCase() == "success") {
                }
            })
        }

        $("#top-search li i").removeClass("active");
        $(".hw_show  i").removeClass("Turn110_c"); 
    	$(".hw_show  i").addClass("Turn110"); 
        $(".Logout").addClass("active");
        $(".SayBusy").addClass("active");
        $(".MakeCall").addClass("active");

        $(".td-call").hide();
        $(".Bacha").show();

        //$(".hidTel").val("");
        //$(".hidCallID").val("");
    }
    if (data.State == '5') {
        $(".xl").removeClass("bl").addClass("br");
        if ($(".hidTel").val() && $(".hidCallID").val()) {
            $.post(huayi.config.callcenter_url + 'CallInScreen/UpdateZL', { callid: $(".hidCallID").val(), "token": $.cookie("token") }, function (result) {
                result = JSON.parse(result);
                if (result.state.toLowerCase() == "success") {
                }
            })
        }
    }
    if (data.State == '6') {
        $(".xl").removeClass("bl").addClass("br");
        if ($(".hidTel").val() && $(".hidCallID").val()) {
            $.post(huayi.config.callcenter_url + 'CallInScreen/UpdateZJ', { callid: $(".hidCallID").val(), "token": $.cookie("token") }, function (result) {
                result = JSON.parse(result);
                if (result.state.toLowerCase() == "success") {
                }
            })
        }

        $(".td-call").show();
        n = 0;
        $("#top-search li i").removeClass("active");
        $(".hw_show  i").addClass("Turn110_c"); 
    	$(".hw_show  i").removeClass("Turn110"); 
        $(".DropCall").addClass("active");
        $(".Hold").addClass("active");
        $(".Transfer").addClass("active");
        $(".Meeting").addClass("active");

        clearInterval(timer);
        timer = setInterval(function () {
            n++;
            var m = parseInt(n / 60 % 60);
            var s = parseInt(n % 60);
            $(".thsc").text(toDub(m) + ":" + toDub(s));
        }, 1000);
    }
}
function toDub(i) {
    return i < 10 ? "0" + i : "" + i;
}
//外呼
function MakeCallBack() {
    $("#top-search li i").removeClass("active");
    $(".hw_show  i").addClass("Turn110_c"); 
    $(".hw_show  i").removeClass("Turn110"); 
    $(".DropCall").addClass("active");
}

//置忙置闲
function SetState(obj) {
    if (obj.State == '5') {
        $(".SayBusy").removeClass("active");
        $(".SayFree").addClass("active");
    }
    if (obj.State == '2') {
        $(".SayBusy").addClass("active");
        $(".SayFree").removeClass("active");
    }
    $.cookie("socket_state", obj.State);
}
//置忙
function SayBusyBack() {
    $(".SayBusy").removeClass("active");
    $(".SayFree").addClass("active");
}
//置闲
function SayFreeBack() {
    $(".SayBusy").addClass("active");
    $(".SayFree").removeClass("active");
}
//多方通话
function MeetingBack() {

}
//转移
function TransferBack() {
    $("#top-search li i").removeClass("active");
    $(".hw_show  i").removeClass("Turn110_c"); 
    $(".hw_show  i").addClass("Turn110"); 
    $(".Logout").addClass("active");
    $(".SayBusy").addClass("active");
    $(".MakeCall").addClass("active");
}
//保持
function HoldBack() {
    $(".Hold").removeClass("active");
    $(".Retrieve").addClass("active");
}
//接回
function RetrieveBack() {
    $(".Hold").addClass("active");
    $(".Retrieve").removeClass("active");
}
//监测
function SubScribeBack() {
    var obj = $("iframe:visible")
    if (obj.attr("data-id") == "./TelCall/SeatMonitor.html") {
        window.frames[obj.attr("name")].Start();
    }
}
//取消监测
function SubScribeCancelBack() {
    var obj = $("iframe:visible")
    if (obj.attr("data-id") == "./TelCall/SeatMonitor.html") {
        window.frames[obj.attr("name")].Stop();
    }
}
//班长监测返回状态
//坐席状态
function AgentStateBack(data) {
    var obj = $("iframe:visible")
    if (obj.attr("data-id") == "./TelCall/SeatMonitor.html") {
        window.frames[obj.attr("name")].UpdateAgentState(data.AgentID, data.State);
    }
}
//线路状态
function LineStateBack(data) {
    var obj = $("iframe:visible")
    if (obj.attr("data-id") == "./TelCall/SeatMonitor.html") {
        window.frames[obj.attr("name")].UpdateLineState(data.AgentID, data.State);
    }
}
//录音返回
function RecordPathBack(data) {
    if ($(".hidTel").val() && $(".hidCallID").val()) {
        $.post(huayi.config.callcenter_url + 'CallInScreen/UpdateLY', { callid: $(".hidCallID").val(),path:data.RecPath, "token": $.cookie("token") }, function (result) {
            result = JSON.parse(result);
            if (result.state.toLowerCase() == "success") {
            }
        })
    }
}

//录音返回
function LineOutState(data) {
    if (lineOutHang) {
    	layer.confirm('外线已挂断！', {
            btn: ['确定']
        });
        lineOutHang=false;
    }
}

//获取当前的日期时间 格式“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;
}