var protocol = location.protocol === 'https:' ? 'wss://' : 'ws://';
var maxReconnect = 6 ;

try {
    WS = new ReconnectingWebSocket(protocol + WS,null,{ maxReconnectAttempts:maxReconnect });
}catch (e){
    handFails();
}
/*try {
    WS = new ReconnectingWebSocket(protocol + WS);
} catch (e) {
    handFails();
    console.log(e);
}*/

WS.onopen = function () {
    console.log('握手成功');
    handSuccess();
    var login_info = '{"type":"kefu_login","fromid":' + IM_user.from_id + ',"group":' + IM_user.from_group + ',"name":"' + IM_user.from_nick + '","avatar":"' + IM_user.from_avatar + '"}'
    WS.send(login_info);
    //每30秒ping服务器
    setInterval(function () {
        WS.send(JSON.stringify({
            type: 'ping',
            group: IM_user.from_group,
            fromid: IM_user.from_id
        }));
    }, 30000);
};

WS.onmessage = function (evt) {
    let data = JSON.parse(evt.data);
    console.log(data);
    switch (data.type) {
        case 'ping':
            WS.send(JSON.stringify({
                type: 'ping',
                group: IM_user.from_group,
                fromid: IM_user.from_id
            }));
            break;
        case 'youke_list':
            loadOnlineLists(data.data, null);
            break;
        case 'youke_onopen':
            loadOnlineLists(null, data.data);
            break;
        case 'no_online':
            we_im_msg('对方不在线，已留言');
            break;
        case 'customerpay':
            we_im_msg(data.data);
            break;
        case 'offline':
            offline(data.data);
            break;
        case 'say':
            // 更新对话列表
            we_im_new_ShowChats(data.data);
            // 栏目未读数显示
            jiaUnread();

            // 更新当前聊天内容
            if (data.data.utype == 'say_from' && $('#wrap').hasClass('current-visi-' + data.data.send)) {
                we_im_update_current_left_message(data.data);
            }
            break;
        case 'auto'://自动回复
            data.data.receive_avatar = data.data.send_avatar;
            we_im_update_current_right_message(data.data);
            break;
    }
};

WS.onclose = function (e) {

};

/*WS.onerror = function (e) {
    handFails();
};*/
WS.onerror = function(e) {
    if( WS.reconnectAttempts >= maxReconnect ){
        console.log('连接失败');
        handFails();
    }else{
        console.log('重连中');
        handReconnect();
    }
};

/**
 * 游客离线
 */
Array.prototype.remove = function (val) {
    var index = this.indexOf(val.toString());
    if (index > -1) {
        this.splice(index, 1);
    }
};

function offline(ykid) {
    var online_lists = Cookies.get('online_ids_' + IM_user.from_id).split(',');
    if (online_lists) {
        online_lists.remove(ykid);
        Cookies.set('online_ids_' + IM_user.from_id, online_lists.join(","));
    }
    $('#logue-item-' + ykid).find('i.notice').removeClass('user-state-1');
    $('#logue-item-' + ykid).find('.v-avatar').addClass('offline-avatar');
        $('#basic-state').text('离线');
}

/**
 * 栏目未读数显示
 */
function jiaUnread() {
    if (!$('.category-2').hasClass('active')) {
        /*var number = Cookies.get('unread_number');
        if (number) {
            number = parseInt(number) + 1;
        } else {
            number = 1;
        }
        Cookies.set('unread_number', number);*/
        unread('getcount','',function (result) {
            console.log('jiaUnread',result);
            var number = result.number;
            $('.category-2 .notice-icon').show().text(number);
            // 提示音
            playPrompt();
        });
    }else{
        console.log('autoclean');
        unread('clean','',function (result) {
            // 提示音
            playPrompt();
        });
    }
}

/**
 * 刷新在线列表
 */
function loadOnlineLists(ids, online_list) {
    var online_lists = [];
    // 为真说明是发送来的最新在线列表
    if (online_list) {
        online_lists = online_list;
        Cookies.set('online_ids_' + IM_user.from_id, online_list.join(","));
    } else if (ids) {
        online_lists = Cookies.get('online_ids_' + IM_user.from_id).split(',');
    }
    $.each(online_lists, function (index, item) {
        $('#logue-item-' + item).find('i.notice').addClass('user-state-1');
        $('#logue-item-' + item).find('img.v-avatar').removeClass('offline-avatar');
    });
    console.log($('.list-group-item.d4e8ff').find('.v-avatar'));
    if( $('.list-group-item.d4e8ff').find('.v-avatar').hasClass('offline-avatar') ){
        $('#basic-state').text('离线');
    }else{
        $('#basic-state').text('在线');
    }
}

/**
 * 播放声音
 */
function playPrompt() {
    if ($('#new-chat').length > 0) {
        $('#new-chat')[0].play();
    }
}

function rtrim(s) {
    var lastIndex = s.lastIndexOf('|');
    if (lastIndex > -1) {
        s = s.substring(0, lastIndex);
    }
    return s;
}

/**
 * 更新对话列表
 * @param data
 */
function we_im_new_ShowChats(data) {
    loadOnlineLists(null, data.online_list);
    var obj = $('#logue-item-' + data.send);
    // 更新当前对话未读信息数 只有不在当前才会执行
    if (!obj.hasClass('d4e8ff')) {
        /*var fgids = 'unread_list_ids';
        var fg = 'unread_list_number_' + data.send;
        var unread = Cookies.get(fg);
        var unread_ids = Cookies.get(fgids);
        if (unread) {
            Cookies.set(fg, (parseInt(unread) + 1), {expires: 2});
        } else {
            Cookies.set(fg, 1, {expires: 2});
        }
        if (unread_ids) {
            var ids = Cookies.get(fgids) + ',' + data.send;
            Cookies.set(fgids, $.unique(ids.split(',')).join(','), {expires: 2});
        } else {
            Cookies.set(fgids, data.send, {expires: 2});
        }

        obj.find('.notice-icon').removeClass('hide').text(Cookies.get(fg));*/
        var message = '{"uid":"' + data.send + '"}';
        unread('add',message,function (result) {
            console.log('we_im_new_ShowChats',result);
            obj.find('.notice-icon').removeClass('hide').text(result.number);
        });
    }

    we_im_ShowChats();
    // 已存在
    // if (obj.length > 0) {
    //     if (data.send != data.receive) {
    //         var newmsg = $(data.content).text();
    //         if (/href/.test(data.content)) {
    //             newmsg = '[超链接]';
    //         } else if (/uploads/.test(data.content)
    //             || /mess-img/.test(data.content)
    //             || /<img/.test(data.content))
    //         {
    //             newmsg = '[图片]';
    //         } else if (/emoji/.test(data.content)) {
    //             newmsg = '[表情]';
    //         } else if (/audio/.test(data.content)) {
    //             newmsg = '[语音]';
    //         } else if ($(data.content).text() > 30) {
    //             newmsg = $(data.content).text();
    //         } else if (/mess-file/.test(data.content)) {
    //             newmsg = '[文件]';
    //         }
    //         obj.find('.newmsg').html(newmsg);
    //     }
    // } else {
    //     we_im_ShowChats();
    //     setTimeout(function() {
    //         $('#logue-item-' + data.send).removeClass('jiagray');
    //         $('#logue-item-' + data.send).find('i.notice').addClass('user-state-1');
    //     },1000);
    // }
}

/**
 * 更新游客聊天信息
 */
function we_im_update_current_left_message(data) {
    var from_tpl = '<li class="chatmsg">' +
        '<div class="showtime">'+timestamp(item.send_time)+'</div>' +
        '<div class="say-left">' +
        '<img class="my-circle cu_pic" src="' + data.send_avatar + '" width="50px" height="50px">' +
        '</div>' +
        '<div class="outer-left">' +
        '<div class="customer">' +
        '<pre>' + data.content + '</pre>' +
        '</div>' +
        '</div>' +
        '</li>';
    $('.conversation').append(from_tpl);
    setTimeout(function () {
        $('#wrap').scrollTop($("#wrap")[0].scrollHeight);
    }, 10);
}

/**
 * 加载黑名单
 */
function we_im_ShowBlacklist() {
    $.ajax({
        type: "get",
        url: IM_config.getBlacklist,
        dataType: "json",
        success: function (r) {
            if (r.code == 200) {
                var black_list = "";
                $.each(r.data, function (i, v) {
                    black_list += '<div class="visiter" id="blacklist-' + v.id + '">' +
                        '<img class="am-radius v-avatar" src="' + v.avatar + '" width="50px">' +
                        '<span>' + v.nick + '</span>' +
                        '<div class="am-btn-danger">' +
                        '<i class="iconfont icon-shanchu" data-id="' + v.id + '" data-vsid="' + v.vsid + '"></i>' +
                        '</div>' +
                        '</div>';
                });
                // Cookies.set('currentvisiid', null);
                $('#tab-4').html(black_list);
            }
        }
    });
}

/**
 * 加载当前客服游客对话
 */
function we_im_ShowChats() {
    $.ajax({
        type: "get",
        url: IM_toget_config.getchats,
        dataType: "json",
        success: function (r) {
            if (r.code == 200) {
                var group_list = "";
                var online_ids = Cookies.get('online_ids_' + IM_user.from_id);
                $.each(r.data, function (i, v) {
                    var notice = '<span class="notice-icon hide">0</span>';
                    if (v.unread_count > 0) {
                        notice = '<span class="notice-icon">' + v.unread_count + '</span>';
                    }
                    group_list += '<li class="list-group-item" id="logue-item-' + v.vsid + '" vsid="' + v.vsid + '">' +
                        '<div class="visiter">' +
                        '<div class="visit_content">' +
                        '<i class="notice"></i>' + notice + '<img class="am-radius v-avatar icon_gray offline-avatar" src="' + v.avatar + '" width="50px">' +
                        '<span class="c_name">' + v.nick + '</span>' +
                        '<div class="newmsg">' + v.new_cont + '</div>' +
                        '</div>' +
                        '</div>' +
                        '</li>';
                });
                $('.list-group').html(group_list);
                if (online_ids) {
                    $.each(online_ids.split(','), function (index, item) {
                        $('#logue-item-' + item).removeClass('jiagray');
                        $('#logue-item-' + item).find('i.notice').addClass('user-state-1');
                        $('#logue-item-' + item + ' .v-avatar').removeClass('offline-avatar');
                        // $('#logue-item-' + item).find('.v-avatar').removeClass('offline-avatar');
                    });
                }

                // var unread_list_ids = Cookies.get('unread_list_ids');
                unread('lists','',function (result,currentvisiid) {
                    console.log('lists',result);
                    if (result.lists) {
                        $.each(result.lists, function (index, item) {

                                $('#logue-item-' + item.uid).find('.notice-icon')
                                    .removeClass('hide').text(item.number);
                        });
                    }
                    $('#logue-item-' + currentvisiid).addClass('d4e8ff');
                });
                /*if (unread_list_ids) {
                    $.each(unread_list_ids.split(','), function (index, item) {
                        var nbr = Cookies.get('unread_list_number_' + item);
                        if (nbr > 0 && currentvisiid != item) {
                            $('#logue-item-' + item).find('.notice-icon')
                                .removeClass('hide').text(nbr);
                        }
                    });
                }
                $('#logue-item-' + currentvisiid).addClass('d4e8ff');*/
            }
        }
    });
    // 判断上次聊天对象
    if (currentvisiid) {
        $('.chatbox').removeClass('hide');
        $('.pages-empty-box').addClass('hide');
        $('#wrap').addClass('current-visi-' + currentvisiid);
    }
}

var isConnectWsDialogId = '';

// 判断握手状态操作函数
function handSuccess() {

    if ($("#wsStatus").length > 0) {
        $("#wsStatus").removeClass('bg-warning').addClass('bg-cyan').find('.statusText').text('成功');
    }
}

function handFails() {

    if ($("#wsStatus").length > 0) {
        $("#wsStatus").removeClass('bg-cyan').addClass('bg-warning').find('.statusText').text('失败');
        if (!isConnectWsDialogId && connectHelpUrl) {
            openFailsDialog();
        }
    }
}

function openFailsDialog() {

    isConnectWsDialogId = layer.open({
        type: 2,
        id: 'connectHelp',
        title: '连接教程' + '<a style="margin-left: 10px;" target="_blank" href="' + connectHelpUrl + '">新窗口打开教程</a>',
        shade: 0,
        offset: 'rb',
        move: false,
        scrollbar: false,
        area: ['500px', '400px'],
        anim: 2,
        fixed: false,
        resize: false,
        isOutAnim: false,
        content: connectHelpUrl,
        success: function (layero, index) {
            $('.layui-layer-content').css({'padding': '0'});
            $('.layui-layer-iframe').css('background', 'white');
        },
        cancel: function () {
        }
    });
}

// 重连
function handReconnect(){

    if( !$("#wsStatus").length ){
        return false ;
    }

    if( $("#wsStatus").find('.statusText').text() != '重连中...'){
        $("#wsStatus").removeClass('bg-warning').addClass('bg-cyan').find('.statusText').text('重连中...');
    }
}