layui.use(['layer', 'form', 'admin', 'notice', 'socket', 'upload', 'table', 'tableSelect', 'contextMenu', 'element'], function() {
    // 聊天窗口部分
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var admin = layui.admin;
    var notice = layui.notice;
    var socket = layui.socket;
    var upload = layui.upload;
    var table = layui.table;
    var tableSelect = layui.tableSelect;
    var contextMenu = layui.contextMenu;
    var element = layui.element;


    //列表显示模式   1 正常  2精简
    var list_type = admin.getTempData('list_type', true) ? admin.getTempData('list_type', true) : 1;
    //用户下线自动消失时间
    var timely_time = admin.getTempData('timely_time', true) ? admin.getTempData('timely_time', true) : 5;

    //消息提示开关
    var chat_info_open = admin.getTempData('chat_info_open', true) ? admin.getTempData('chat_info_open', true) : 2;

    //业务逻辑
    var c = $('.timely-chat-cont-text');
    //表情开关
    var flag = 1;
    //客服基本信息
    var kf_info = {
        uid: uid,
        mc_code: mc_code,
        name: name,
        avatar: avatar
    };
    var shuru_log = {};
    var select_vid = 0;
    //操作方法类
    var kefu = {
        encode: function(method, data) {
            //组装发送数据
            var msg = {};
            msg.method = method;
            msg.param = data;
            return JSON.stringify(msg);
        },
        decode: function(obj) {
            //解析数据
            return JSON.parse(obj);
        },
        kefu_online: function() {
            //登陆成功
            notice.success({
                title: '提示',
                message: '上线成功!',
                position: 'bottomRight',
                audio: '3',
            });
            $(".layui-bg-black").find('.online').removeClass('layui-hide');
            $(".layui-bg-black").find('.offline').addClass('layui-hide');
            //获取正在通讯的用户列表
            kefu.getQueue();
        },
        sendMessage: function(message) {
            var select = $('.chat-list-div').find('.layui-this');
            if (select.length == 0) return true;
            if (select.hasClass('inserting')) {
                layer.msg('用户不在线！');
                return true;
            }
            socket.send(kefu.encode('message', {
                from_id: kf_info.uid,
                from_name: kf_info.name,
                from_avatar: kf_info.avatar,
                to_id: select.data('vid'),
                to_name: select.data('name'),
                to_avatar: select.data('avatar'),
                message: message,
                mc_code: kf_info.mc_code
            }));
        },
        getQueue: function() {
            admin.req(api + '/work/index/getQueue', {}, function(res) {
                if (res.code == 200 && res.data.length > 0) {
                    $(' .chat-list-div .conversation ').removeClass('layui-show').addClass('layui-hide');
                    $(' .chat-list-div .conversation ').nextAll().not('#inserting').remove();
                    $.each(res.data, function(key, item) {
                        addChatLi(item);
                    });
                } else {
                    $(' .chat-list-div .conversation ').removeClass('layui-hide').addClass('layui-show');
                    $('#num').nextAll().remove();
                }
            }, 'post', { headers: { token: token } });
            return true;
        },
        readme: function(o) {
            if (o.code == 200) {
                var ids = o.data.ids.split(',');
                $.each(ids, function(index, value) {
                    c.find('div[data-id="' + value + '"]').attr('data-read', 2);
                });
            }
            return true;
        },
        readChat: function(o) {
            if (o.code == 200) {
                var ids = o.data.ids.split(',');
                $.each(ids, function(index, value) {
                    c.find('div[data-id="' + value + '"]').find('.is-read').addClass('active');
                    c.find('div[data-id="' + value + '"]').find('.is-read').text('已读');
                });
            }
        },
        message: function(o) {
            //发送消息成功
            if (o.code == 200) {
                if (o.data.hasOwnProperty('to_id') == true) {
                    var select = $('.chat-list-div').find('div[data-vid="' + o.data.to_id + '"]');

                    if (select.length < 1) return true;

                    if (select.hasClass('layui-this') != true) return true;
                }

                if (c.find('div[data-id="' + o.data.log_id + '"]').length < 1) {
                    var html = kefu.add_message(o.data);
                    c.append(html);
                };
                readChat();
            }
            scrollBottom();
            if (shuru_log.hasOwnProperty(o.data.to_id) == true) {
                delete(shuru_log[o.data.to_id]);
            }
            $('#text').val('');
        },
        chatMessage: function(o) {
            var select = $('.chat-list-div').find('div[data-vid="' + o.data.from_id + '"]');
            if (select.length < 1) return true;

            if (select.hasClass('layui-this') == true) {
                var html = kefu.to_add_message(o.data);
                c.append(html);
                scrollBottom();
            } else {
                var add = select.find('.layui-badge');
                if (add.length <= 0) {
                    select.prepend('<div style="float: right;font-size: 14px;margin-right: 5px;margin-top: 5px;"><span class="layui-badge">new</span></div>')
                }
            }
            select.find('.desc').text(o.data.message);
            if (chat_info_open == 1) {
                notice.show({
                    image: o.data.from_avatar,
                    imageWidth: 71,
                    title: '消息通知',
                    message: o.data.message,
                    audio: '1',
                    targetFirst: false,
                    timeout: 1500
                });

            }
            if (chat_info_open == 2) {
                playAudioNewMsg();
            }

            if (chat_info_open != 3 && document.hidden) {
                ipc.send('have-message', uuid());
            }

            return false;
        },
        userUpper: function(o) {
            //游客上线
            var item = o.data;
            addChatLi(item);
        },
        diffClose: function(o) {
            //游客下线
            if (o.code == 400) {
                return true;
            }
            removeChat(o);
            return true;
        },
        queuePop: function(o) {
            layer.msg(o.msg)
        },
        transferChat: function(o) {
            layer.msg(o.msg);
            if (o.code == 200) {
                layer.closeAll('page');
                removeChat(o)
            }
        },
        getChatLog: function(log_id, uid) {
            admin.req(api + '/work/index/getUserChatLog', {
                uid: uid,
                kf_code: kf_info.uid,
                mc_code: kf_info.mc_code,
                log_id: log_id
            }, function(res) {
                kefu.setLogNum(res.count);
                if (res.code == 200 && res.data.length > 0) {
                    $.each(res.data, function(key, item) {
                        var html = '';
                        if (c.find('div[data-id="' + item.log_id + '"]').length >= 1) {
                            return true;
                        }
                        if (item.log == 'visitor') {
                            html = kefu.to_add_message(item);
                        } else if (item.log == 'kefu') {
                            var select = $('.chat-list-div').find("div[data-vid='" + item.visitor_id + "']");

                            html = kefu.add_message(item);
                        }
                        $('#num').after(html);

                    });

                    //判断是否需要显示更多数据
                    if ((c.find('.chat-content').length + c.find('.is-tipsdot').length) < res.count) {
                        c.find('.history').removeClass('layui-hide');
                    } else {
                        c.find('.history').addClass('layui-hide');
                    }
                    //第一次进来滚动到最底部
                    if (log_id == 0) {
                        scrollBottom();
                    }
                }
                readChat();
            }, 'post', { headers: { token: token } });
        },
        add_message: function(h) {
            var message_type = h.message_type == undefined ? 1 : h.message_type;
            if (message_type == 1) {
                var html = '<div class="chat-content" data-id="' + h.log_id + '" data-uid="' + h.from_id + '">' +

                    ' <div class="kf-side"><div class="avater">' +
                    ' <img src="' + (api + h.from_avatar) + '" alt="avatar" style="width: 100%;height: 100%;">' +
                    '</div> ' +
                    '<div class="cont">' +
                    '<p style="margin-bottom: 5px;z-index: 999;color: #999;">' + h.create_time + '</p>' +
                    '<label class="is-read ' + (h.read_status == 2 ? 'active' : '') + '"> ' + (h.read_status == 2 ? '已读' : '未读') + '</label>' +
                    '<div class="kf-info"> ' +
                    '<div class="text">' + content(h.message) +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +

                    '</div>';
            } else {
                var html = '<div class="tips is-tipsdot" data-id="' + h.log_id + '"><p>' + content(h.message) + '</p></div>'
            }

            return html;
        },
        to_add_message: function(h) {
            var html = '<div data-id="' + h.log_id + '" data-uid="' + h.from_id + '" data-read="' + h.read_status + '" class="chat-content"><div class="user-side"> <div class="avater"> <img src="' + getUrl(h.from_avatar) + '" alt="avatar" style="width: 100%;height: 100%;"></div> <div class="cont"> <p style="margin-bottom: 5px;z-index: 999;color: #999;">' + h.create_time + '</p><div class="user-info"> <div class="text"> ' + content(h.message) + ' </div> <div class="arrow-l"></div></div></div></div> </div>'
            return html;
        },
        setLogNum: function(num) {
            $('#num').attr('data-num', num)
        },
        loginOut: function(o) {
            //退出成功
            if (o.code == 200) {
                //  window.location.href = '/work/Login/loginOut';
                ipc.send('loginOut');
            }
        }

    };

    $(function() {
        //websoket 服务
        socket.init({
            wsUrl: protocol + '://' + monitor_address + ':' + port,
            HeartBeat: kefu.encode('heartBeat', { str: 'ping' }) //心跳数据
                ,
            timeout: 1000 //60秒发送心跳包
                ,
            onopen: function() {
                console.log('连接成功');
                //发送客服登陆事件
                socket.send(kefu.encode('kefuLogin', { uid: kf_info.uid }));
            },
            onmessage: function(event) {
                var obj = kefu.decode(event.data);
                return kefu[obj.method] ? kefu[obj.method].call(this, obj) : true;
            },
            onerror: function(event) {
                console.log("服务错误....");
            },
            onclose: function(event) {
                console.log("断开连接");
            }
        });
    });

    // 判断页面是否激活
    var hiddenProperty = 'hidden' in document ? 'hidden' :
        'webkitHidden' in document ? 'webkitHidden' :
        'mozHidden' in document ? 'mozHidden' :
        null;
    var visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange');

    var onVisibilityChange = function() {
        if (!document[hiddenProperty]) {
            // 处理未读消息
            readChat();
        }
    };
    document.addEventListener(visibilityChangeEvent, onVisibilityChange);

    //处理未读消息
    function readChat() {
        if ($('.layui-nav-tree').find('.layui-this').hasClass('nav-second') == true) {
            return true;
        }
        var unReadIds = [];

        c.find('div[data-read="1"]').each(function() {
            unReadIds.push($(this).data('id'));
        });

        if (unReadIds.length > 0) {
            var uid = $('.chat-list-div').find('.layui-this').data('vid');
            socket.send(kefu.encode('readChat', {
                visitor_id: uid,
                ids: unReadIds.join(','),
            }));
        }
    }

    //监听客服状态切换
    element.on('nav(status)', function(elem) {
        var status = $(elem).data('status');
        admin.req(api + '/work/index/saveStatus', { status: status }, function(res) {
            if (res.code == 1000) {
                if (status == 1) {
                    $(".layui-bg-black").find('.online').removeClass('layui-hide');
                    $(".layui-bg-black").find('.manglu').addClass('layui-hide');
                } else {
                    $(".layui-bg-black").find('.online').addClass('layui-hide');
                    $(".layui-bg-black").find('.manglu').removeClass('layui-hide');
                }
            }
        }, 'post', { headers: { token: token } });
    });

    //用户下线
    function removeChat(o) {
        var item = o.data;
        var select = $('.chat-list-div').find('div[data-vid="' + item.visitor_id + '"]');

        if (select.length <= 0) {
            return true;
        }
        if (!select.hasClass('inserting')) {
            select.addClass('inserting');
            var serverTime = new Date().getTime();
            select.attr('data-time', serverTime);
        }
        select.remove();
        $("#inserting").after(select);

    }
    // 用户上线 增加聊天列表
    function addChatLi(item, is_span = 0) {
        var select = $('.chat-list-div').find("div[data-vid='" + item.visitor_id + "']");
        if (select.length > 0) {
            if (select.hasClass('inserting')) {
                select.removeClass('inserting');
                select.remove();
                $("#inserting").before(select);

            }
            return true;
        }
        //判断是否关闭当前暂无会话
        if ($('.chat-list-div .conversation ').hasClass('layui-show') == true) {
            $('.chat-list-div .conversation ').removeClass('layui-show').addClass('layui-hide');
        }

        var html = '<div class="wait-list ' + (list_type == 2 ? 'retrench' : '') + '" data-vid="' + item.visitor_id + '" data-from="' + item.source + '" data-ip="' + item.visitor_ip + '" data-name="' + item.visitor_name + '" data-addr="' + item.address + '" data-avatar="' + getUrl(item.visitor_avatar) + '"> <div class="avater" > <img src="' + getUrl(item.visitor_avatar) + '" alt=""> </div> <div class="txt"> <div class="name">' + item.visitor_name + '</div><div class="desc">' + item.address + '</div></div>  <i class="layui-icon layui-hide" style="margin-left: 5px;margin-top: 5px;font-size: 15px;" onclick="CloseUser(this)">&#x1006;</i></div>';
        //$('.chat-list-div').append(html);
        $("#inserting").before(html);

        return true;
    }

    //退出事件
    $(document).on('click', '#logout', function(e) {
        e.preventDefault();
        layer.confirm('您确定要退出吗？', {
            btn: ['确定', '关闭'] //按钮
        }, function(index) {
            socket.send(kefu.encode('kefuClose', {
                mc_code: kf_info.mc_code
            }));
            layer.close(index);
        }, function() {});
    });


    //滚动条滚到最底部
    function scrollBottom() {
        c.scrollTop(c[0].scrollHeight),
            c.children("div:last").find("img").load(function() {
                c.scrollTop(c[0].scrollHeight)
            });
    }


    //加载更多聊天记录
    c.on("click", "#listmore", function(e) {
        e.preventDefault();
        var log_id = $('#num').next().data('id');

        var select = $('.chat-list-div').find('.layui-this');
        if (select.length == 0) return false;

        var uid = select.data('vid');
        log_id = log_id != undefined ? log_id : 0;
        kefu.getChatLog(log_id, uid);
    });



    //发送聊天消息
    $('#btn').on("click", function(e) {

        var content = $('#text').val();
        if (content.length <= 0) {
            return true;
        }
        var select = $('.chat-list-div').find('.layui-this');
        if (select.hasClass('inserting')) {
            layer.msg('用户不在线！');
            return true;
        }
        kefu.sendMessage(content);

    });


    //快速搜索
    $("#text").bind("keyup", function(e) {
        e.preventDefault();
        var content = $(this).val().replace(/^\s+|\s+$/g, "");
        if (content.length <= 0) {
            if ($('.chat-center-text').find('.measure').length > 0) {
                $('.chat-center-text').find('.measure').remove();
            }
        }
        if (content[0] == '#') {
            if ($('.chat-center-text').find('.measure').length <= 0) {
                $('.chat-center-text').append('<div class="measure inline-block  mini-bar"><p>请输入更多内容</p></div>')
            }
        }
        if (content.length > 1 && content[0] == '#') {
            var str = content.slice(1);
            admin.req(api + '/work/index/getQuick', { reply: str }, function(res) {
                if (res.code == 1000 && res.data.length > 0) {
                    var html = '';
                    $.each(res.data, function(key, item) {
                        html += '<p  lay-tips="' + item.qr_desc + '"  lay-direction="4">' + item.qr_desc + '</p>';
                    });

                } else {
                    var html = '<p>请输入更多内容</p>';
                }
                $('.chat-center-text').find('.measure').html(html)
            }, 'post', { headers: { token: token } });
        }
        shuru_log[select_vid] = content;
    });

    //快速搜索选择时间
    $(document).on('click', '.chat-center-text .measure p ', function(e) {
        e.preventDefault();
        var text = $(this).text();
        $('.chat-center-text').find('.measure').remove();
        layer.closeAll('tips');
        $("#text").val(text);
        shuru_log[select_vid] = text;
    });

    //回车发送事件
    $(document).keyup(function(event) {
        if (event.keyCode == 13) {
            if ($('.chat-center-text').find('.measure').length > 0) {
                $('.chat-center-text').find('.measure').remove();
                $("#text").val('');
            }
            $('#container #btn').click();
        }
    });



    //结束会话
    $('#chat-cont-end').on('click', function(e) {
        e.preventDefault();
        var select = $('.chat-list-div').find('.layui-this');
        if (select.length <= 0) {
            return true;
        }
        if (select.hasClass('inserting')) {
            layer.msg('用户不在线！');
            return true;
        }
        var name = select.data('name');
        var vid = select.data('vid');
        layer.confirm('您确定关闭【' + name + '】的当前会话吗？', {
            btn: ['确定', '关闭'] //按钮
        }, function(index) {
            socket.send(kefu.encode('closeUser', {
                vid: vid,
                mc_code: kf_info.mc_code
            }));
            layer.close(index);
        }, function() {});
    });

    //添加黑名单
    $('#chat-cont-blacklist').on('click', function(e) {
        e.preventDefault();
        var select = $('.chat-list-div').find('.layui-this');
        if (select.length <= 0) {
            return true;
        }
        var name = select.data('name');
        var vid = select.data('vid');
        var ip = select.data('ip');

        layer.confirm('您确定要把【' + name + '】加入黑名单吗？', {
            btn: ['确定', '关闭'] //按钮
        }, function(index) {
            admin.req(api + '/work/index/addBalck', { name: name, vid: vid, ip: ip }, function(res) {
                layer.msg(res.message);
            }, 'post', { headers: { token: token } });
            layer.close(index);
        }, function() {});
    });


    //上传图片
    upload.render({
        elem: "#timely-chat-upload-img",
        url: api + "/work/upload/uploadImg",
        method: "POST",
        exts: 'jpg|jpeg|png|gif',
        accept: "images",
        size: 1024 * 10,
        before: function() {
            var select = $('.chat-list-div').find('.layui-this');
            if (select.hasClass('inserting')) {
                layer.msg('用户不在线！');
                return true;
            }
            index = layer.load(0, { shade: false });
        },
        done: function(res) {
            layer.close(index);
            kefu.sendMessage('img[' + res.data.src + ']');
        },
        error: function(a) {
            layer.msg(a.msg || "上传失败");
        }
    });
    //上传文件
    upload.render({
        elem: '#timely-chat-upload-file',
        accept: 'file',
        exts: 'zip|rar|txt|doc|docx|xls|xlsx',
        url: api + '/work/upload/uploadFile',
        before: function() {
            var select = $('.chat-list-div').find('.layui-this');
            if (select.hasClass('inserting')) {
                layer.msg('用户不在线！');
                return true;
            }
            index = layer.load(0, { shade: false });
        },
        done: function(res) {
            layer.close(index);
            kefu.sendMessage('file(' + res.data.src + ')[' + res.data.name + ']');

        },
        error: function(a) {
            // 请求异常回调
            layer.close(index);
            layer.msg(a.msg || "上传失败");
        }
    });
    //转换内容
    var content = function(content) {
        //支持的html标签
        var html = function(end) {
            return new RegExp('\\n*\\[' + (end || '') + '(code|pre|div|span|p|table|thead|th|tbody|tr|td|ul|li|ol|li|dl|dt|dd|h2|h3|h4|h5)([\\s\\S]*?)\\]\\n*', 'g');
        };
        content = (content || '')
            .replace(/@(\S+)(\s+?|$)/g, '@<a href="javascript:;">$1</a>$2') //转义@

        .replace(/face\[([^\s\[\]]+?)\]/g, function(face) { //转义表情
                var alt = face.replace(/^face/g, '');
                return '<img alt="' + alt + '" title="' + alt + '" src="' + faces(alt) + '" style="width: 20px;height: 20px;">';
            })
            .replace(/img\[([^\s]+?)\]/g, function(img) { //转义图片
                return '<img class="layui-timely-photos" src="' + (api + img.replace(/(^img\[)|(\]$)/g, '')) + '" style="width: 100px;height: 100px;">';
            })
            .replace(/file\([\s\S]+?\)\[[\s\S]*?\]/g, function(str) { //转义文件
                var href = (str.match(/file\(([\s\S]+?)\)\[/) || [])[1];
                var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
                if (!href) return str;
                return '<a class="layui-timely-file" href="' + href + '" download target="_blank"><i class="layui-icon" style="font-size: 30px;">&#xe61e;</i><cite>' + (text || href) + '</cite></a>';
            })
            .replace(/audio\[([^\s]+?)\]/g, function(audio) { //转义音频
                return '<div class="layui-unselect layui-timely-audio" layim-event="playAudio" data-src="' + audio.replace(/(^audio\[)|(\]$)/g, '') + '"><i class="layui-icon">&#xe652;</i><p>音频消息</p></div>';
            })
            .replace(/video\[([^\s]+?)\]/g, function(video) { //转义音频
                return '<div class="layui-unselect layui-timely-video" layim-event="playVideo" data-src="' + video.replace(/(^video\[)|(\]$)/g, '') + '"><i class="layui-icon">&#xe652;</i></div>';
            })

        .replace(/a\([\s\S]+?\)\[[\s\S]*?\]/g, function(str) { //转义链接
                var href = (str.match(/a\(([\s\S]+?)\)\[/) || [])[1];
                var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
                if (!href) return str;
                return '<a href="' + href + '" target="_blank">' + (text || href) + '</a>';
            }).replace(html(), '\<$1 $2\>').replace(html('/'), '\</$1\>') //转移HTML代码
            .replace(/\n/g, '<br>') //转义换行
        return content;
    };
    window.getFacesIcon = function() {
        return ["[微笑]", "[嘻嘻]", "[哈哈]", "[可爱]", "[可怜]", "[挖鼻]", "[吃惊]", "[害羞]", "[挤眼]", "[闭嘴]", "[鄙视]",
            "[爱你]", "[泪]", "[偷笑]", "[亲亲]", "[生病]", "[太开心]", "[白眼]", "[右哼哼]", "[左哼哼]", "[嘘]", "[衰]",
            "[委屈]", "[吐]", "[哈欠]", "[抱抱]", "[怒]", "[疑问]", "[馋嘴]", "[拜拜]", "[思考]", "[汗]", "[困]", "[睡]",
            "[钱]", "[失望]", "[酷]", "[色]", "[哼]", "[鼓掌]", "[晕]", "[悲伤]", "[抓狂]", "[黑线]", "[阴险]", "[怒骂]",
            "[互粉]", "[心]", "[伤心]", "[猪头]", "[熊猫]", "[兔子]", "[ok]", "[耶]", "[good]", "[NO]", "[赞]", "[来]",
            "[弱]", "[草泥马]", "[神马]", "[囧]", "[浮云]", "[给力]", "[围观]", "[威武]", "[奥特曼]", "[礼物]", "[钟]",
            "[话筒]", "[蜡烛]", "[蛋糕]"
        ]
    };
    // 表情替换
    window.faces = function(select) {
        var alt = getFacesIcon(),
            arr = {};
        $.each(alt, function(index, item) {
            arr[item] = '../assets/libs/layui/images/face/' + index + '.gif';
        });
        return arr[select];
    };

    // 封装一个获取当前时间对的函数
    function getdate() {
        var now = new Date(),
            y = now.getFullYear(),
            m = ("0" + (now.getMonth() + 1)).slice(1)
        d = ("0" + now.getDate()).slice(1);

        return y + "-" + m + "-" + d + " " + now.toTimeString().substr(0, 8);
    }



    // 控制显示index和search
    $('#search-btn').click(function() {
        $('.search-main').css('display', 'block');
        $('.layui-row').css('display', 'none');
    })
    $('#index-btn').click(function() {
        $('.layui-row').css('display', 'block');
        $('.search-main').css('display', 'none');
    });



    // 人工会话与会话查询的切换
    $('.nav-second').click(function() {
        $('.nav-first').removeClass('nav-first')
    })

    // 控制快捷回复"编辑"与"完成"的来回切换
    $('.edit').click(function() {
        if ($('.edit i').hasClass('layui-icon-edit')) {
            $('.edit i').removeClass('layui-icon-edit').addClass('layui-icon-ok-circle')
            $('.edit span').text('完成')
            $('.top-title i').css('display', 'inline')
        } else {
            $('.edit i').removeClass('layui-icon-ok-circle').addClass('layui-icon-edit')
            $('.edit span').text('编辑')
            $('.top-title i').css('display', 'none')
        }
    });


    //发送快捷回复
    $(document).on('click', '.chat-area-quickCont .layui-tab-item ul li span ', function(e) {
        e.preventDefault();
        var message = $(this).text();
        kefu.sendMessage(message);
    });

    //添加快捷回复
    $("#addQuick").on('click', function() {
        admin.open({
            type: 1,
            title: false,
            closeBtn: 0,
            shadeClose: true,
            area: ['500px', '300px'],
            skin: 'yourclass',
            content: $('#quickModal').html(),
            success: function(layero, index) {
                //关闭弹窗
                $('.cancel').click(function() {
                        layer.close(index)
                    })
                    //提交信息
                form.on('submit(addQuickInfo)', function(data) {
                    layer.load(2);
                    admin.req(api + '/work/index/addQuick', data.field, function(res) {
                        layer.closeAll('loading');
                        if (res.code == 1000) {
                            if (res.data.status == 2) {
                                $('#private_list').append('<li data-id="' + res.data.qr_id + '"><span>' + data.field.desc + '</span><a class="layui-btn layui-btn layui-btn-danger  layui-btn-xs pull-right text-center" style="margin-top: 10px;" onclick="deleteUserQuick(this)">删除</a></li>');
                            }
                            layer.close(index);
                            layer.msg(res.message, { icon: 1 });
                        } else {
                            layer.msg(res.message, { icon: 2 });
                        }
                    }, 'post', { headers: { token: token } });
                    return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                });

            }
        });
    });



    // 会话设置
    $('#btn-setting').click(function() {
        $('.setting').css('right', '0px')
        admin.popupRight({
            type: 1,
            content: $('#setting').html(),
            success: function(layero, index) {
                //关闭弹窗
                $('.close-btn').click(function() {
                    layer.close(index)
                });
                form.render();
                form.val('list_type', { list_type: list_type });
                form.val('timely_time', { timely_time: timely_time });
                form.val('chat_info_opens', { chat_info_open: chat_info_open });

                form.on('radio(list_typed)', function(data) {
                    list_type = data.value;
                    admin.putTempData('list_type', list_type, true);
                    $(".chat-list-div").find('.wait-list').each(function() {
                        if (list_type == 2) {
                            $(this).addClass('retrench');
                        } else {
                            $(this).removeClass('retrench');
                        }
                    });
                });
                form.on('radio(timely_time)', function(data) {

                    timely_time = data.value;
                    admin.putTempData('timely_time', timely_time, true);
                });
                form.on('radio(chat_info_open)', function(data) {
                    //得到radio原始DOM对象
                    chat_info_open = data.value;
                    admin.putTempData('chat_info_open', chat_info_open, true);

                });

            }
        });
    });


    //修改密码
    $('#save-password').on('click', function(e) {
        admin.open({
            type: 1,
            title: false,
            closeBtn: 0,
            shadeClose: true,
            skin: 'yourclass',
            content: $('#savepassword').html(),
            success: function(layero, index) {
                //关闭弹窗
                $('#passq').click(function() {
                    layer.close(index)
                });
                //提交
                form.on('submit(submit-psw)', function(data) {
                    layer.load(2);
                    admin.req(api + '/work/index/savePassword', data.field, function(res) {

                        layer.closeAll('loading');
                        if (res.code == 1000) {
                            layer.close(index);
                            layer.msg(res.message, { icon: 1 });
                        } else {
                            layer.msg(res.message, { icon: 2 });
                        }
                    }, 'post', { headers: { token: token } });
                    return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                });
            }
        });

    });
    //转接会话
    $('#chat-cont-transfer').on('click', function(e) {
        e.preventDefault();
        var select = $('.chat-list-div').find('.layui-this');
        if (select.length <= 0) {
            return true;
        }
        if (select.hasClass('inserting')) {
            layer.msg('用户不在线！');
            return true;
        }
        var name = select.data('name');
        var vid = select.data('vid');
        admin.open({
            type: 1,
            title: false,
            closeBtn: 0,
            shadeClose: true,
            area: ['500px', '450px'],
            skin: 'yourclass',
            content: $('#kefuModel').html(),
            success: function(layero, index) {
                //获取在线客服列表
                admin.req(api + '/work/index/getOnlineKefu', {}, function(res) {
                    if (res.data.length > 0) {
                        $.each(res.data, function(key, item) {
                            var html = '<div class="content-item" data-code="' + item.kf_code + '"><div class="paragraph"> <span class="item-title">' + item.kf_name + '</span> <span class="item-content">' + item.g_name + '</span> </div></div>'
                            $(layero).find('.service-content .layui-tab-item .content-menu').append(html)

                        });
                    }
                }, 'post', { headers: { token: token } });
                //关闭弹窗
                $('.close-icon').click(function() {
                    layer.close(index)

                });
                $('.cancel-transfer').click(function() {
                    layer.close(index)
                });
                //div 点击选中事件
                $(layero).on('click', '.service-content .layui-tab-item .content-menu .content-item', function() {

                    $(this).css('background', '#f5f5dc');
                    $(this).addClass('layui-this');
                    $(this).siblings().removeClass('layui-this');
                    $(this).siblings().css('background', '#FFF');

                });
                //提交
                $(layero).on('click', '.submit-transfer', function() {
                    var kefu_code = $(layero).find('.service-content .layui-tab-item .content-menu .layui-this');

                    if (kefu_code.data('code') == undefined) {
                        layer.msg('请选择转接客服')
                    }
                    socket.send(kefu.encode('transferChat', {
                        visitor_id: vid,
                        mc_code: kf_info.mc_code,
                        transfer_kf_code: kefu_code.data('code')
                    }));
                })


            }
        });

    });




    //监听列表页移除移入会话
    //列表移入事件
    $('body').on("mouseover", ".chat-list-div .wait-list", function() {
        $(this).css('background-color', '#ccdaff');
        if ($(this).hasClass('inserting')) {
            $(this).find('i').removeClass('layui-hide');
        }

    });
    //列表移除事件
    $('body').on("mouseout", ".chat-list-div .wait-list", function() {
        if ($(this).hasClass('layui-this') == false) {
            $(this).css('background-color', '#ffffff');

        }
        if ($(this).hasClass('inserting')) {
            $(this).find('i').addClass('layui-hide');
        }
    });
    //列表点击事件
    $('body').on("click", ".chat-list-div .wait-list:not(i)", function(e) {
        e.preventDefault();
        if ($('.layui-body .item2').hasClass('layui-hide')) {
            $('.layui-body .item2').removeClass('layui-hide')
        }
        if ($('.layui-body .item3').hasClass('layui-hide')) {
            $('.layui-body .item3').removeClass('layui-hide')
        }
        if (!$('#not-chat').hasClass('layui-hide')) {
            $('#not-chat').addClass('layui-hide');
        }
        select_vid = $(this).data('vid');
        $("#text").val('');
        if (shuru_log.hasOwnProperty(select_vid) == true) {
            $("#text").val(shuru_log[select_vid]);
        }
        if ($(this).hasClass('layui-this') == true) {
            return true;
        } else {
            $(this).find('.layui-badge').remove();
            $(this).siblings().removeClass('layui-this');
            $(this).siblings().css('background-color', '#ffffff');
            $(this).addClass('layui-this');
            $(this).find('i').addClass('layui-hide');
            $('#num').nextAll().remove();
            kefu.getChatLog(0, $(this).data('vid'));
            getVitotorInfo();
        }
        return true;
    });


    //获取右侧个人信息
    function getVitotorInfo() {
        var select = $('.chat-list-div').find('.layui-this');
        if (select.length == 0) {
            $('#soures').text('--');
            $('#IP').text('--');
            $('#address').text('--');
            $('#nickname').text('--');
            $('#visitor_name').text('');
            form.val("userInfoForm", { //formTest 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
                "real_name": "",
                "phone": "",
                "wc_num": "",
                "qq": "",
                "email": "",
                "grade": "0",
                'vip_account': ""
            });
        } else {
            $('#soures').text(select.data('from'));
            $('#IP').text(select.data('ip'));
            $('#address').text(select.data('addr'));
            $('#nickname').text(select.data('vid'));
            $('#visitor_name').text(select.data('name'));
            admin.req(api + '/work/index/getUserInfo', {
                vid: select.data('vid'),
                mc_code: kf_info.mc_code,
            }, function(res) {
                form.val("userInfoForm", res.data);
            }, 'post', { headers: { token: token } });
        }

    }

    //提交个人信息
    form.on('submit(userInfo)', function(data) {
        var select = $('.chat-list-div').find('.layui-this');
        if (select.length == 0) return false;

        data.field.vid = select.data('vid');
        data.field.mc_code = kf_info.mc_code;

        admin.req(api + '/work/index/saveUserInfo', data.field, function(res) {
            layer.msg(res.message);
        }, 'post', { headers: { token: token } });
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });

    //展示大图
    $("body").on('click', '.timely-chat-cont-text .layui-timely-photos', function() {
        var src = this.src;
        layer.photos({
            photos: {
                data: [{
                    "src": src
                }]
            },
            shade: 0.5,
            closeBtn: 2,
            anim: 0,
            resize: false,
            success: function(layero, index) {

            }
        });
    });

    //渲染会话记录
    var insTb = table.render({
        elem: '#tableHistor',
        url: api + '/work/index/getServiceLog',
        headers: { token: token },
        page: true,
        limit: 15,
        limits: [15, 30, 50],
        cellMinWidth: 100,
        response: {
            statusCode: 1000 //规定成功的状态码，默认：0
        },
        cols: [
            [
                { field: 'start_time', title: '会话开始时间', align: 'center' },
                {
                    field: 'end_time',
                    title: '会话结束时间',
                    align: 'center',
                    templet: function(d) {
                        if (d.end_time == null) {
                            return '---';
                        } else {
                            return d.end_time;
                        }
                    }
                },
                { field: 'visitor_name', title: '游客名称', align: 'center' },
                { field: 'source', title: '访问来源', align: 'center', width: 100 },
                { field: 'visitor_ip', title: 'IP', align: 'center' },
                { field: 'address', title: '地区', align: 'center' },
                { field: 'kf_name', title: '接待人', align: 'center', width: 100 },
                {
                    field: 'degree',
                    title: '满意度',
                    align: 'center',
                    templet: function(d) {
                        var strs = {
                            0: '---',
                            1: '非常不满意',
                            2: '不满意',
                            3: '一般',
                            4: '满意',
                            5: '非常满意',
                        };
                        return strs[d.degree];
                    }
                },

            ]
        ],
        text: {
            none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
        }
    });

    //刷新表格
    $("#formSubSearchUser").on('click', function() {
        insTb.reload({ page: { curr: 1 } }, 'data');
    });

    //渲染等待列表
    tableSelect.render({
        elem: '#wait-list', //定义输入框input对象
        checkedKey: 'qid', //表格的唯一建值，非常重要，影响到选中状态 必填
        searchKey: 'visitor_name', //搜索输入框的name值 默认keyword
        searchPlaceholder: '游客标识', //搜索输入框的提示文字 默认关键词搜索
        table: { //定义表格参数，与LAYUI的TABLE模块一致，只是无需再定义表格elem
            url: api + '/work/index/getdQueue',
            headers: { token: token },
            page: true,
            limit: 10,
            limits: [10],
            cellMinWidth: 100,
            response: {
                statusCode: 1000 //规定成功的状态码，默认：0
            },
            cols: [
                [
                    { type: 'radio' },
                    { field: 'visitor_name', title: '游客名称', align: 'center' },
                    { field: 'source', title: '访问来源', align: 'center' },
                    { field: 'visitor_ip', title: 'IP', align: 'center' },
                    { field: 'address', title: '地区', align: 'center' },
                ]
            ],
            text: {
                none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
            }
        },
        done: function(elem, data) {
            var item = data.data[0];
            socket.send(kefu.encode('queuePop', {
                visitor_id: item.visitor_id,
                mc_code: item.mc_code,
                name: name,
                avatar: avatar,
                client_id: item.client_id
            }));

        }
    });

    // 点击表情
    $('#timely-chat-face').click(function(e) {
        e.stopPropagation();

        if (1 == flag) {
            showFaces();

            $('#face-box').show();
            flag = 2;
        } else {
            $('#face-box').hide();
            flag = 1;
        }
    });

    // 监听点击旁边关闭表情
    document.addEventListener("click", function() {
        if (2 == flag) {
            $('#face-box').hide();
            flag = 1;
        }
    });


    // 展示表情数据
    window.showFaces = function() {
        var alt = getFacesIcon();
        var _html = '<ul class="layui-layim-face" style="width: 500px;height: 150px;">';
        var len = alt.length;
        for (var index = 0; index < len; index++) {
            _html += '<li title="' + alt[index] + '" onclick="checkFace(this)"><img  style="width: 22px;height: 22px;" src="../assets/libs/layui/images/face/' + index + '.gif" /></li>';
        }
        _html += '</ul>';
        $('#face-box').html(_html);
    };
    // 选择表情
    window.checkFace = function(obj) {
        var msg = $('#text').val();
        var text = msg + ' face' + obj.title + ' '
        $('#text').val(text);
        shuru_log[select_vid] = text;
        document.getElementById('face-box').style.display = 'none';
        $('#btn').attr('disabled', false);
        $('#btn').css('pointer-events', '');
        $('#btn').css('background-color', '#1e9fff');
        flag = 1;
    };

    //每分钟定时清除不在线超过30分钟用户
    window.setInterval(function() {
        var select = $('.chat-list-div').find('.inserting').each(function() {
            var nowTime = new Date().getTime();
            var xiaTime = $(this).data('time');
            var timestamp = nowTime - xiaTime;
            var fen = timestamp / 1000 / 60;
            if (fen >= timely_time) {
                if ($(this).hasClass('layui-this')) {
                    $('#num').nextAll().remove();
                    $('#num').prev().addClass('layui-hide');
                    getVitotorInfo();
                    kongXian();
                }
                $(this).remove();
            }
        });
        var chat_num = $('.chat-list-div .wait-list').length;
        if (chat_num == 0) {
            $('.chat-list-div .conversation ').removeClass('layui-hide').addClass('layui-show');
            kongXian();
        }
    }, 60000);



    //一键清除不在线用户
    $('#clear-user').click(function(e) {
        layer.confirm('您确定要清除所有不在线用户吗？', {
            btn: ['确定', '关闭'] //按钮
        }, function(index) {
            var select = $('.chat-list-div').find('.inserting').each(function() {
                if ($(this).hasClass('layui-this')) {
                    $('#num').nextAll().remove();
                    $('#num').prev().addClass('layui-hide');
                    getVitotorInfo();
                    kongXian();
                }
                $(this).remove();
            });
            var chat_num = $('.chat-list-div .wait-list').length;
            if (chat_num == 0) {
                $('.chat-list-div .conversation ').removeClass('layui-hide').addClass('layui-show');
                kongXian();
            }
            layer.close(index);
        }, function() {});

    });


    function kongXian() {
        if (!$('.layui-body .item2').hasClass('layui-hide')) {
            $('.layui-body .item2').addClass('layui-hide')
        }
        if (!$('.layui-body .item3').hasClass('layui-hide')) {
            $('.layui-body .item3').addClass('layui-hide')
        }
        if ($('#not-chat').hasClass('layui-hide')) {
            $('#not-chat').removeClass('layui-hide');
        }
    }

    window.CloseUser = function(obj) {
        e = window.event || e;
        if (e.stopPropagation) {
            e.stopPropagation(); //阻止事件 冒泡传播
        } else {
            e.cancelBubble = true; //ie兼容
        }
        var select = $(obj).parents('.wait-list');
        if (select.hasClass('layui-this')) {
            $('#num').nextAll().remove();
            $('#num').prev().addClass('layui-hide');
            getVitotorInfo();
            kongXian();
        }
        select.remove();
    }

    function uuid() {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";

        var uuid = s.join("");
        return uuid;
    }

    /**
     * 播放音频
     */


    const audioAssetsBase = '../assets/module/notice/'

    let audio = new Audio();
    audio.onended = function() {
        console.log('audio ')
    };
    audio.onerror = function() {
        console.log('audio onerror')
    };

    function playAudio(src) {
        try {
            audio.pause();
            audio.currentTime = 0;
            audio.src = audioAssetsBase + src;
            audio.play();
        } catch (e) {
            console.error('playAudio error', e);
        }
    }

    /**
     * 播放新消息接入声音
     */
    function playAudioNewMsg() {
        playAudio('1.wav')
    }


    //表格双击展示聊天记录
    table.on('rowDouble(tableHistor)', function(obj) {
        var data = obj.data;
        admin.open({
            type: 1,
            title: data.visitor_name + '的聊天记录',
            closeBtn: 2,
            shadeClose: true,
            area: ['800px', '600px'],
            skin: 'yourclass',
            content: $('#log').html(),
            success: function(layero, index) {
                $(layero).find('#history-side-form').text(data.source);
                $(layero).find('#visitor_avatar').attr('src', getUrl(data.visitor_avatar));
                $(layero).find('#visitor_ip').text(data.visitor_ip);
                //获取用户信息
                admin.req(api + '/work/index/getUserInfo', {
                    vid: data.visitor_id,
                }, function(res) {
                    if (res.code == 200) {
                        $(layero).find('#log-username').text(res.data.real_name);
                        $(layero).find('#log-phone').text(res.data.phone);
                        $(layero).find('#log-wx').text(res.data.wc_num);
                        $(layero).find('#log-email').text(res.data.email);
                        $(layero).find('#log-qq').text(res.data.qq);
                        var text = '';
                        if (res.data.grade == 1) {
                            text = '普通用户'
                        }
                        if (res.data.grade == 2) {
                            text = 'VIP用户'
                        }
                        $(layero).find('#log-type').text(text);

                    }
                }, 'post', { headers: { token: token } });
                var page = 1;
                getChatLog(data, page);

                function getChatLog(data, page, flag) {
                    //获取聊天记录
                    admin.req(api + '/work/index/getUserChatLogByPage', {
                        uid: data.visitor_id,
                        kf_code: kf_info.uid,
                        page: page
                    }, function(res) {

                        if (1000 == res.code && res.data.length > 0) {

                            if (res.msg == res.total) {
                                var _html = '';
                            } else {
                                var _html = '<div class="listmore"><a href="javascript:;" id="listmore"   data-page="' + parseInt(res.msg + 1) +
                                    '" onclick="getMore(this)">点击查看更多消息</a></div>';
                            }


                            var len = res.data.length;

                            for (var i = 0; i < len; i++) {
                                var item = res.data[i];
                                if (item.message_type == 1) {
                                    if ('visitor' != item.log) {

                                        _html += ' <div class="chat-main-self">';
                                        _html += '<div class="chat-main-selfCont">';
                                        _html += '<p class="chat-main-selfTop">';
                                        _html += '<span>' + item.from_name + '</span>';
                                        _html += '<span class="chat-main-selfTime">' + item.create_time + '</span></p>';
                                        _html += '<div class="chat-main-selfText">' + content(item.message);
                                        _html += '<span class="chat-main-selfTips"></span>';
                                        _html += '</div></div></div>'
                                    } else {

                                        _html += '<div class="chat-main-toInfo">';
                                        _html += '<div class="chat-main-selfCont">';
                                        _html += '<p class="chat-main-selfTop"><span>' + item.from_name + '</span><span  class="chat-main-selfTime">' + item.create_time + '</span></p>';
                                        _html += ' <div class="chat-main-selfText">' + content(item.message);
                                        _html += '<span class="chat-main-selfTips"></span>';
                                        _html += '</div></div> </div>'

                                    }
                                } else {
                                    _html += '<div class="tips is-tipsdot"  ><p>' + content(item.message) + '</p></div>'
                                }

                            }
                            if (typeof flag == 'undefined') {

                                $('.history-chat-cont').html(_html);
                                scrollBottom2();
                            } else {
                                $('.history-chat-cont').prepend(_html);
                            }

                        }
                    }, 'post', { headers: { token: token } });
                }
                //滚动条滚到最底部
                function scrollBottom2() {
                    var box = $(layero).find(".history-chat-cont");
                    box.scrollTop(box[0].scrollHeight);
                }
                window.getMore = function getMore(obj) {
                    $(obj).parent().remove();
                    var page = $(obj).attr('data-page');
                    getChatLog(data, page, 1);
                };

            }
        });
    });

    window.deleteUserQuick = function(obj) {
        e = window.event || e;
        if (e.stopPropagation) {
            e.stopPropagation(); //阻止事件 冒泡传播
        } else {
            e.cancelBubble = true; //ie兼容
        }
        var id = $(obj).parents('li').data('id');

        admin.req(api + '/work/index/delQuick', { id: id }, function(res) {
            layer.closeAll('loading');
            if (res.code == 1000) {
                $(obj).parents('li').remove();
                layer.msg(res.message, { icon: 1 });
            } else {
                layer.msg(res.message, { icon: 2 });
            }
        }, 'post', { headers: { token: token } });
    }

    window.getUrl = function(url) {
        if (url.substr(0, 7).toLowerCase() == "http://" || url.substr(0, 8).toLowerCase() == "https://") {
            var newurl = url;
        } else {
            var newurl = api + url;

        }
        return newurl;
    }
});