var robot_nickname = '';
//获取url中"?"符后的字串 
function getRequest(url) {
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}

$(function () {
    // 初始化JMessage
    $.get('/admin/Jmessage/auth', function (res) {
        var res = JSON.parse(res);
        if (res.error === 0) {
            JIM.init({
                "appkey": res.data.appkey,
                "random_str": res.data.random_str,
                "signature": res.data.signature,
                "timestamp": res.data.timestamp + "",
                "flag": "0"
            }).onSuccess(function (data) {
                JIM.login({
                    'username': res.data.username,
                    'password': 'password'
                }).onSuccess(function (data) {
                    new PNotify({
                        title: '提示',
                        text: data.message,
                        type: "success"
                    });
                }).onFail(function (data) {
                    new PNotify({
                        title: '提示',
                        text: data.message,
                        type: "error"
                    });
                });
            }).onFail(function (data) {
                new PNotify({
                    title: '提示',
                    text: data.message,
                    type: "error"
                });
            });
        }
    });
    /**
     * 极光推送
     * @param  {[type]} data
     * @return {[type]}       [description]
     */
    JIM.onMsgReceive(function (data) {
        var res = data.messages[0].content.msg_body;
        var extras = res.extras;
        if (extras.action == 'chat_record') {
            var $ele = $("#item_" + extras.robot_id);
            var is_active = $ele.hasClass('active');
            if ($ele && is_active) {
                appendRobotChating(extras.robot_id, extras.contact_id);
            }
        } else if (extras.action == 'new_message') {
            var message = $.parseJSON(extras.message);
            robotHasMsg(message.robot_id, true);
            // 消息提示
            if (message.is_group == 1 && typeof message.group != 'undefined') {
                userHasMsg(message.group.id, true);
                if (extras.self) {
                    renderUserHint(message.to_user.id, message);
                } else {
                    renderUserHint(message.group.id, message);
                }
                var $ele = currentUserTabItem(message.group.id);
            } else {
                if (extras.self) {
                    var user_id = message.to_user.id;
                } else {
                    var user_id = message.user.id;
                }
                userHasMsg(user_id, true);
                renderUserHint(user_id, message);
                var $ele = currentUserTabItem(user_id);
            }
            var is_active = $ele.hasClass('active');
            // 提交消息到聊天框
            if ($ele && is_active) {
                if (extras.self) {
                    appendRightItemToRecord(message);
                } else {
                    appendLeftItemToRecord(message);
                }
                setChatToRead(extras.robot_id, $ele.attr('uid'));
            }
        }
    });
    // 该页面禁止鼠标右键
    // $(document).bind("contextmenu",function(e){
    //     return false;
    // });
    $('.chat-wrapper').css('height', $(window).height() - 65);
    $(".chat-col-content").css('height', $(window).height() - 130);
    // 用户列表
    $(".chat-col-content.user-list").css('height', $(window).height() - 165);
    // 聊天区域
    $("#chating-panel .chat-col-content").css('height', $(window).height() - 330);
    $("#chating-panel .chat-input-wapper").css('height', 200);
    // 聊天内容区域滚动到底部
    scrollToContentBottom();

    $(".chat-col-content").niceScroll({
        styler: "fb",
        cursorcolor: "#4ECDC4",
        cursorwidth: '5',
        cursorborderradius: '10px',
        background: '#404040',
        spacebarenabled: false,
        cursorborder: ''
    });
    $('#chat-users-tab a, #user-info-tab a').click(function (e) {
        e.preventDefault();
        $(this).tab('show')
    });

    $('.robot-item').unbind('click').bind('click', function (event) {
        event.preventDefault();
        var _this = $(this);
        robot_nickname = _this.attr('nickname');
        _this.addClass("active").siblings(".robot-item").removeClass("active");
        var oid = _this.attr('oid');
        var status = _this.attr('status');
        if (status != 2) {
            new PNotify({
                title: '提示',
                text: '该机器人未运行，请前往机器人管理中设置',
                type: "error"
            });
            _this.removeClass('active');
            return;
        };
        // 清空用户区
        $('#chatings-container').html('');
        $('#contacts-container').html('');
        $('#search-container').show().end().find('#search-keyword').val('');
        // 重置加载更多按钮
        $('#load-more-chating').parent('div').removeClass('show').addClass('hidden').end().attr({
            opage: 1,
            oid: oid
        });
        $('#load-more-contacts').parent('div').removeClass('show').addClass('hidden').end().attr({
            opage: 1,
            oid: oid
        });
        // 请求数据
        getRobotChatings(oid, 1, null);
        getRobotContacts(oid, 1, null);

        // 清空聊天区 用户资料区
        clearRightPanel3And4();
        // 清除消息提示
        // robotHasMsg(oid, false);
        // 搜索
        $('#nickname-addon').unbind('click').bind('click', function (event) {
            var tab_index = $('#chat-users-tab').children('li.active').index();
            if (tab_index == 1) {
                $('#contacts-container').html('');
                getRobotContacts(oid, 1, null);
            } else {
                $('#chatings-container').html('');
                getRobotChatings(oid, 1, null);
            }
        });
    });

    // 加载更多聊天用户
    $('#load-more-chating').unbind('click').bind('click', function (event) {
        event.preventDefault();
        var _this = $(this);
        var page = _this.attr('opage');
        var oid = _this.attr('oid');
        var $btn = _this.button('loading');
        getRobotChatings(oid, page, $btn);
    });
    // 加载更多通讯录好友
    $('#load-more-contacts').unbind('click').bind('click', function (event) {
        event.preventDefault();
        var _this = $(this);
        var page = _this.attr('opage');
        var oid = _this.attr('oid');
        var $btn = _this.button('loading');
        getRobotContacts(oid, page, $btn);
    });
    // 加载更多聊天记录
    $('#load-more-content').unbind('click').bind('click', function (event) {
        event.preventDefault();
        var _this = $(this);
        var page = _this.attr('opage');
        var oid = _this.attr('oid');
        var uid = _this.attr('uid');
        var nickname = _this.attr('nickname');
        var $btn = _this.button('loading');
        getChatingContent(oid, uid, nickname, page, false, $btn);
    });

    // 发送按钮
    $('#btn-send').unbind('click').bind('click', function (event) {
        event.preventDefault();
        var _this = $(this);
        var $btn = _this.button('loading');
        var _textarea = $('#chating-text');
        var msg = _textarea.val();
        var robot_id = _this.attr('robot_id');
        var uid = _this.attr('uid');

        if (robot_id && uid && robot_id != 0 && uid != 0) {
            sendChatingTextMsg(robot_id, uid, msg, $btn);
        } else if (msg.length == 0 || msg == '') {
            $btn.button('reset');
            return;
        } else {
            new PNotify({
                title: '提示',
                text: '错误的聊天对象，请选择好友',
                type: "error"
            });
            $btn.button('reset');
            return;
        }
        // 清空输入区
        _textarea.val('');
    });

    // Ctrl + 回车
    $("#chating-text").unbind('keypress').bind('keypress', function (event) {
        var _this = $(this);
        var _that = $('#btn-send');
        if (event.ctrlKey && event.keyCode == 13) {
            var msg = _this.val();
            var robot_id = _that.attr('robot_id');
            var uid = _that.attr('uid');
            var $btn = _that.button('loading');
            if (robot_id && uid && robot_id != 0 && uid != 0) {
                sendChatingTextMsg(robot_id, uid, msg, $btn);
            } else if (msg.length == 0 || msg == '') {
                $btn.button('reset');
                return;
            } else {
                new PNotify({
                    title: '提示',
                    text: '错误的聊天对象，请选择好友',
                    type: "error"
                });
                $btn.button('reset');
                return;
            }
            // 清空输入区
            _this.val('');
        };
    });

    // 发送图片
    var imgUploader = Qiniu.uploader({
        runtimes: 'html5,flash,html4', // 上传模式，依次退化
        browse_button: 'image', // 上传选择的点选按钮，必需
        uptoken_url: '/admin/upload/uptoken', // Ajax请求uptoken的Url
        get_new_uptoken: false, // 设置上传文件的时候是否每次都重新获取新的uptoken
        domain: 'http://botfile.imgondar.com/', // bucket域名，下载资源时用到，必需
        container: 'image-input-container', // 上传区域DOM ID，默认是browser_button的父元素
        max_file_size: '100mb', // 最大文件体积限制
        flash_swf_url: '/static/plupload/Moxie.swf', //引入flash，相对路径
        max_retries: 3, // 上传失败最大重试次数
        dragdrop: true, // 开启可拖曳上传
        drop_element: 'chating-text', // 拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
        chunk_size: '4mb', // 分块上传时，每块的体积
        auto_start: true, // 选择文件后自动上传，若关闭需要自己绑定事件触发上传
        multi_selection: false,
        unique_names: true,
        filters: {
            mime_types: [{
                    title: "Image files",
                    extensions: "jpg,gif,png,jpeg"
                } // 限定jpg,gif,png后缀上传
            ]
        },
        init: {
            'FilesAdded': function (up, files) {},
            'BeforeUpload': function (up, file) {
                var _that = $('#btn-send');
                var robot_id = _that.attr('robot_id');
                var uid = _that.attr('uid');
                if (!robot_id || !uid || robot_id == 0 && uid == 0) {
                    new PNotify({
                        title: '提示',
                        text: '错误的聊天对象，请选择好友',
                        type: "error"
                    });
                    imgUploader.stop();
                    imgUploader.removeFile(file);
                }
            },
            'UploadProgress': function (up, file) {},
            'UploadComplete': function () {},
            'FileUploaded': function (up, file, info) {
                var domain = up.getOption('domain');
                var res = $.parseJSON(info);
                // 获取上传成功后的文件的Url
                var sourceLink = domain + res.key;
                sendChatingFileMsg(sourceLink, 'image', res.key);
            },
            'Error': function (up, err, errTip) {
                //上传出错时，处理相关的事情
                new PNotify({
                    title: '提示',
                    text: "文件上传出错"
                });
                imgUploader.stop();
                imgUploader.removeFile(err.file);
            },
        }
    });

    // 文件上传
    var fileUploader = Qiniu.uploader({
        runtimes: 'html5,flash,html4', // 上传模式，依次退化
        browse_button: 'file', // 上传选择的点选按钮，必需
        uptoken_url: '/admin/upload/uptoken', // Ajax请求uptoken的Url
        get_new_uptoken: false, // 设置上传文件的时候是否每次都重新获取新的uptoken
        domain: 'http://botfile.imgondar.com/', // bucket域名，下载资源时用到，必需
        container: 'file-input-container', // 上传区域DOM ID，默认是browser_button的父元素
        max_file_size: '100mb', // 最大文件体积限制
        flash_swf_url: '/static/plupload/Moxie.swf', //引入flash，相对路径
        max_retries: 3, // 上传失败最大重试次数
        dragdrop: true, // 开启可拖曳上传
        drop_element: 'chating-text', // 拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
        chunk_size: '4mb', // 分块上传时，每块的体积
        auto_start: true, // 选择文件后自动上传，若关闭需要自己绑定事件触发上传
        multi_selection: false,
        unique_names: true,
        init: {
            'FilesAdded': function (up, files) {},
            'BeforeUpload': function (up, file) {
                var _that = $('#btn-send');
                var robot_id = _that.attr('robot_id');
                var uid = _that.attr('uid');
                if (!robot_id || !uid || robot_id == 0 && uid == 0) {
                    new PNotify({
                        title: '提示',
                        text: '错误的聊天对象，请选择好友',
                        type: "error"
                    });
                    fileUploader.stop();
                    fileUploader.removeFile(file);
                }
            },
            'UploadProgress': function (up, file) {},
            'UploadComplete': function () {},
            'FileUploaded': function (up, file, info) {
                var domain = up.getOption('domain');
                var res = $.parseJSON(info);
                // 获取上传成功后的文件的Url
                var sourceLink = domain + res.key;
                sendChatingFileMsg(sourceLink, 'file', res.key);
            },
            'Error': function (up, err, errTip) {
                //上传出错时，处理相关的事情
                new PNotify({
                    title: '提示',
                    text: "文件上传出错"
                });
                fileUploader.stop();
                fileUploader.removeFile(err.file);
            },
        }
    });

    // 自动加载聊天对象
    var queries = new getRequest(window.location.search);
    if (queries['rid'] && queries['cid']) {
        autoGetChating(queries['rid'], queries['cid']);
    }
});

/**
 * 自动加载某个聊天对象
 */
function autoGetChating(robot_id, contact_id) {
    // 模拟点击该机器人
    $('#item_' + robot_id).click();

    setTimeout(function () {
        appendRobotChating(robot_id, contact_id, function () {
            $('#chatings_item_' + contact_id).click();
        });
    }, 1000);
}

/**
 * 加载聊天列表
 * @param  {int} robot_id  机器人id
 * @param  {int} page 页码
 * @param  {element} btn  加载按钮
 * @return {[type]}      [description]
 */
function getRobotChatings(robot_id, page, btn) {
    var search = $.trim($('#search-keyword').val());
    $.ajax({
            url: '/admin/Chat/chatings',
            type: 'GET',
            dataType: 'json',
            data: {
                id: robot_id,
                page: page,
                keyword: search
            },
            cache: false
        })
        .done(function (res) {
            var res = JSON.parse(res);
            if (res.error) {
                new PNotify({
                    title: '提示',
                    text: res.msg
                });
            } else {
                if (res.data.data.length == 0) {
                    new PNotify({
                        title: '提示',
                        text: "没有更多聊天好友了"
                    });
                    $('#load-more-chating').parent('div').removeClass('show').addClass('hidden');
                    return;
                };
                $('#load-more-chating').parent('div').removeClass('hidden').addClass('show').end().attr({
                    opage: parseInt(res.data.current_page) + 1,
                    oid: robot_id
                });
                var html = template('robot-chatings', res.data);
                $('#chatings-container').append(html);

                // 更新滚动条
                $(".user-list").css('height', $(".user-list").height() + 1);
                // 头像检测
                loadAvatarImg();

                // 点击事件
                $('.chatings-item').unbind('click').bind('click', function () {
                    event.preventDefault();
                    var _this = $(this);
                    var nickname = _this.attr('nickname');
                    var uid = _this.attr('uid');
                    var type = _this.attr('group');
                    $('.contacts-item').removeClass('active');
                    _this.addClass("active").siblings(".chatings-item").removeClass("active");

                    // 清空聊天区 用户资料区
                    clearRightPanel3And4();
                    // 获取聊天数据
                    getChatingContent(robot_id, uid, nickname, 1, true);
                    // 获取该用户资料
                    getChatingUserInfo(robot_id, uid);
                    // 群没有画像
                    if (type == 1) {
                        getChatingUserPic(robot_id, uid);
                    }

                    // 清除消息提示
                    userHasMsg(uid, false);
                });
            }
        })
        .fail(function () {
            new PNotify({
                title: '提示',
                text: '网络请求失败',
                type: 'error'
            });
        })
        .always(function () {
            if (btn) {
                btn.button('reset');
            };
        });
}

/**
 * 获取机器人通讯录
 * @param  {int} robot_id  机器人id
 * @param  {int} page 页码
 * @param  {element} btn  加载按钮
 * @return {[type]}      [description]
 */
function getRobotContacts(robot_id, page, btn) {
    var search = $.trim($('#search-keyword').val());
    $.ajax({
            url: '/admin/Chat/contacts',
            type: 'GET',
            dataType: 'json',
            data: {
                id: robot_id,
                page: page,
                keyword: search
            },
            cache: false
        })
        .done(function (res) {
            var res = JSON.parse(res);
            if (res.error) {
                new PNotify({
                    title: '提示',
                    text: res.msg
                });
            } else {
                if (res.data.data.length == 0) {
                    new PNotify({
                        title: '提示',
                        text: "通讯录没有更多好友了"
                    });
                    $('#load-more-contacts').parent('div').removeClass('show').addClass('hidden');
                    return;
                };
                $('#load-more-contacts').parent('div').removeClass('hidden').addClass('show').end().attr({
                    opage: parseInt(res.data.current_page) + 1,
                    oid: robot_id
                });
                var html = template('robot-contacts', res.data);
                $('#contacts-container').append(html);

                // 更新滚动条
                $(".user-list").css('height', $(".user-list").height() + 1);
                // 头像检测
                loadAvatarImg();

                // 点击事件
                $('.contacts-item').unbind('click').bind('click', function () {
                    event.preventDefault();
                    var _this = $(this);
                    var nickname = _this.attr('nickname');
                    var uid = _this.attr('uid');
                    var type = _this.attr('group');
                    $('.chatings-item').removeClass('active');
                    _this.addClass("active").siblings(".contacts-item").removeClass("active");

                    // 清空聊天区 用户资料区
                    clearRightPanel3And4();
                    // 获取聊天数据
                    getChatingContent(robot_id, uid, nickname, 1, true);
                    // 获取该用户资料
                    getChatingUserInfo(robot_id, uid);
                    // 群没有画像
                    if (type == 1) {
                        getChatingUserPic(robot_id, uid);
                    }

                    // 清除消息提示
                    userHasMsg(uid, false);
                });
            }
        })
        .fail(function () {
            new PNotify({
                title: '提示',
                text: '网络请求失败',
                type: 'error'
            });
        })
        .always(function () {
            if (btn) {
                btn.button('reset');
            };
        });
}

/**
 * 追加聊天列表
 * @param {*} robot_id 
 * @param {*} contact_id 
 */
function appendRobotChating(robot_id, contact_id, callback) {
    $.ajax({
            url: '/admin/Chat/chating',
            type: 'GET',
            dataType: 'json',
            data: {
                id: robot_id,
                cid: contact_id
            },
            cache: false
        })
        .done(function (res) {
            var res = JSON.parse(res);
            if (res.error) {
                new PNotify({
                    title: '提示',
                    text: res.msg
                });
            } else {
                var $ele = $('#chatings_item_' + contact_id);
                if ($ele.length == 0) {
                    var html = template('robot-chatings', res);
                    $('#chatings-container').prepend(html);
                } else {
                    var item = $ele.clone();
                    $ele.remove();
                    $('#chatings-container').prepend(item);
                }

                // 更新滚动条
                $(".user-list").css('height', $(".user-list").height() + 1);
                // 头像检测
                loadAvatarImg();

                // 点击事件
                $('.chatings-item').unbind('click').bind('click', function () {
                    event.preventDefault();
                    var _this = $(this);
                    var nickname = _this.attr('nickname');
                    var uid = _this.attr('uid');
                    var type = _this.attr('group');
                    $('.contacts-item').removeClass('active');
                    _this.addClass("active").siblings(".chatings-item").removeClass("active");

                    // 清空聊天区 用户资料区
                    clearRightPanel3And4();
                    // 获取聊天数据
                    getChatingContent(robot_id, uid, nickname, 1, true);
                    // 获取该用户资料
                    getChatingUserInfo(robot_id, uid);
                    // 群没有画像
                    if (type == 1) {
                        getChatingUserPic(robot_id, uid);
                    }

                    // 清除消息提示
                    userHasMsg(uid, false);
                });
            }
        })
        .fail(function () {
            new PNotify({
                title: '提示',
                text: '网络请求失败',
                type: 'error'
            });
        })
        .always(function () {
            typeof callback == 'function' && callback();
        });
}

/**
 * 获取聊天数据
 * @param  {int} robot_id 机器人id
 * @param  {string} nickname 用户昵称
 * @param  {int} page     页码
 * @param  {bool} page     是否刚开始聊天
 * @return {[type]}          [description]
 */
function getChatingContent(robot_id, uid, nickname, page, begin, btn) {
    $.ajax({
            url: '/admin/Chat/content',
            type: 'GET',
            dataType: 'json',
            data: {
                id: robot_id,
                uid: uid,
                page: page
            },
            cache: false
        })
        .done(function (res) {
            var res = JSON.parse(res);
            if (res.error) {
                new PNotify({
                    title: '提示',
                    text: res.msg
                });
            } else {
                $('#chating-user-nickname').html(nickname);
                var html = "";
                for (var i = 0; i < res.data.length; i++) {
                    // 如果该消息已存在
                    if ($('#msg-item-' + res.data[i]['id']).length > 0) {
                        continue;
                    };
                    // 对方发的消息 左
                    // 机器人消息在右
                    // 私聊 | 群聊
                    if (res.data[i].is_group == 0) {
                        if (res.data[i].nickname == nickname) {
                            html += template('left-content', res.data[i]);
                        } else {
                            html += template('right-content', res.data[i]);
                        }
                    } else {
                        if (res.data[i].user.nickname == robot_nickname) {
                            html += template('right-content', res.data[i]);
                        } else {
                            html += template('left-content', res.data[i]);
                        }
                    }
                };
                $('#chating-content').prepend(html);

                // 设置发送按钮属性值
                $('#btn-send').attr({
                    robot_id: robot_id,
                    uid: uid
                });

                // 内容区滚动到底部
                if (begin) {
                    scrollToContentBottom();
                };
                // 头像检测
                loadAvatarImg();
                // 语音事件
                bindAudioAction();

                if (res.data.length == 0) {
                    new PNotify({
                        title: '提示',
                        text: "没有更多聊天记录了"
                    });
                    $('#load-more-content').parent('div').removeClass('show').addClass('hidden');
                    return;
                };
                $('#load-more-content').parent('div').removeClass('hidden').addClass('show').end().attr({
                    opage: parseInt(page) + 1,
                    oid: robot_id,
                    uid: uid,
                    nickname: nickname
                });

                // 设置机器人未读状态
                if (res.has_un_read) {
                    robotHasMsg(robot_id, true);
                } else {
                    robotHasMsg(robot_id, false);
                }
            }
        })
        .fail(function () {
            new PNotify({
                title: '提示',
                text: '网络请求失败',
                type: 'error'
            });
        })
        .always(function (res) {
            if (btn) {
                btn.button('reset');
            };
        });
}

/**
 * 获取用户资料
 * @param  {int} robot_id 机器人id
 * @param  {string} nickname 用户昵称
 * @return {[type]}          [description]
 */
function getChatingUserInfo(robot_id, uid) {
    $.ajax({
            url: '/admin/Chat/userinfo',
            type: 'GET',
            dataType: 'json',
            data: {
                id: robot_id,
                uid: uid
            },
            cache: false
        })
        .done(function (res) {
            var res = JSON.parse(res);
            if (res.error) {
                new PNotify({
                    title: '提示',
                    text: res.msg
                });
            } else {
                var html = template('user-info', res.data);
                $('#userinfo-container').html(html);
                // 头像检测
                loadAvatarImg();
            }
        })
        .fail(function () {
            new PNotify({
                title: '提示',
                text: '网络请求失败',
                type: 'error'
            });
        })
        .always(function (res) {});
}

/**
 * 获取用户画像
 * @param  {[type]} robot_id [description]
 * @param  {[type]} uid      [description]
 * @return {[type]}          [description]
 */
function getChatingUserPic(robot_id, uid, btn) {
    $.ajax({
            url: '/admin/Chat/userpic',
            type: 'GET',
            dataType: 'json',
            data: {
                id: robot_id,
                uid: uid
            },
            cache: false
        })
        .done(function (res) {
            var res = JSON.parse(res);
            if (res.error) {
                // new PNotify({
                //     title: '提示',
                //     text: res.msg
                // });
                console.log("111==>" + res.msg);
                var html = template('pic-info', null);
                $('#picinfo-container').html(html);
                $('#picinfo-container').find('#uid').val(uid);
                // 绑定事件
                bindUserPicEvent(robot_id, uid);
            } else {
                var html = template('pic-info', res.data);
                $('#picinfo-container').html(html);
                $('#picinfo-container').find('#uid').val(uid);

                // 默认身份
                $('#identity').children('option').each(function () {
                    if ($(this).val() == res.data.ident) {
                        $(this).attr('selected', 'selected');
                    }
                });
                var key = $('#identity').children('option:selected').attr('okey');
                changeIdentity(key);
                // 默认科室
                $('#department').children('option').each(function () {
                    if ($(this).val() == res.data.department) {
                        $(this).attr('selected', 'selected');
                    }
                });
                // 默认职称
                $('#duty').children('option').each(function () {
                    if ($(this).val() == res.data.duties) {
                        $(this).attr('selected', 'selected');
                    }
                });

                // 默认省份
                $('#province').children('option').each(function () {
                    if ($(this).val() == res.data.province) {
                        $(this).attr('selected', 'selected');
                    }
                });
                getCities(res.data.province, function () {
                    $('#city').children('option').each(function () {
                        if ($(this).val() == res.data.city) {
                            $(this).attr('selected', 'selected');
                        }
                    });
                });
                getCounties(res.data.city, res.data.province, function () {
                    $('#county').children('option').each(function () {
                        if ($(this).val() == res.data.area) {
                            $(this).attr('selected', 'selected');
                        }
                    });
                });
                getHospitals(res.data.area, res.data.city, res.data.province, function () {
                    $('#hospital').children('option').each(function () {
                        if ($(this).val() == res.data.companyName) {
                            $(this).attr('selected', 'selected');
                        }
                    });
                });
                // 绑定事件
                bindUserPicEvent(robot_id, uid);
            }
        })
        .fail(function () {
            new PNotify({
                title: '提示',
                text: '网络请求失败',
                type: 'error'
            });
        })
        .always(function () {
            if (btn) {
                btn.button('reset');
            };
        });
}

/**
 * 发送聊天文字
 * @param  {[type]} robot_id [description]
 * @param  {[type]} uid      [description]
 * @param  {[type]} btn      [description]
 * @return {[type]}          [description]
 */
function sendChatingTextMsg(robot_id, uid, msg, btn) {
    $.ajax({
            url: '/admin/Chat/sendMsg',
            type: 'POST',
            dataType: 'json',
            data: {
                id: robot_id,
                uid: uid,
                content: msg,
                type: 'text'
            },
            cache: false
        })
        .done(function (res) {
            var res = JSON.parse(res);
            if (res.error) {
                new PNotify({
                    title: '提示',
                    text: res.msg
                });
            } else {
                new PNotify({
                    title: '提示',
                    text: res.msg,
                    type: 'success'
                });
                // 处理ui
                appendRightItemToRecord(res.result);
                // 更新当前用户下面的消息提示
                renderUserHint(uid, res.result);
            }
        })
        .fail(function () {
            new PNotify({
                title: '提示',
                text: '网络请求失败',
                type: 'error'
            });
        })
        .always(function () {
            if (btn) {
                btn.button('reset');
            };
        });

}

/**
 * 发送图片
 * @param  {[type]} robot_id [description]
 * @param  {[type]} uid      [description]
 * @return {[type]}          [description]
 */
function sendChatingFileMsg(url, type, filename) {
    var _that = $('#btn-send');
    var robot_id = _that.attr('robot_id');
    var uid = _that.attr('uid');
    $.ajax({
            url: '/admin/Chat/sendMsg',
            type: 'POST',
            dataType: 'json',
            data: {
                id: robot_id,
                uid: uid,
                content: url,
                type: type,
                filename: filename
            },
            cache: false
        })
        .done(function (res) {
            var res = JSON.parse(res);
            if (res.error) {
                new PNotify({
                    title: '提示',
                    text: res.msg
                });
            } else {
                new PNotify({
                    title: '提示',
                    text: res.msg,
                    type: 'success'
                });
                // 处理ui
                appendRightItemToRecord(res.result);
                // 更新当前用户下面的消息提示
                renderUserHint(uid, res.result);
            }
        })
        .fail(function () {
            new PNotify({
                title: '提示',
                text: '网络请求失败',
                type: 'error'
            });
        })
        .always(function () {});
}

/**
 * 获取城市
 * @param {*} province 
 */
function getCities(province, callback) {
    $.ajax({
            url: '/api/Hospital/getCities',
            type: 'POST',
            dataType: 'json',
            data: {
                province: province
            },
            cache: false
        })
        .done(function (res) {
            var res = JSON.parse(res);
            if (res.error) {
                new PNotify({
                    title: '提示',
                    text: res.msg
                });
            } else {
                var html = template('city-tmp', res.data);
                $('#city').html(html);

                typeof callback == 'function' && callback(res.data);
            }
        })
        .fail(function () {
            new PNotify({
                title: '提示',
                text: '网络请求失败',
                type: 'error'
            });
        })
        .always(function () {});
}

/**
 * 获取区县
 * @param {*} city 
 * @param {*} province 
 */
function getCounties(city, province, callback) {
    $.ajax({
            url: '/api/Hospital/getCounties',
            type: 'POST',
            dataType: 'json',
            data: {
                city: city,
                province: province
            },
            cache: false
        })
        .done(function (res) {
            var res = JSON.parse(res);
            if (res.error) {
                new PNotify({
                    title: '提示',
                    text: res.msg
                });
            } else {
                var html = template('county-tmp', res.data);
                $('#county').html(html);

                typeof callback == 'function' && callback(res.data);
            }
        })
        .fail(function () {
            new PNotify({
                title: '提示',
                text: '网络请求失败',
                type: 'error'
            });
        })
        .always(function () {});
}

/**
 * 获取医院
 * @param {*} county 
 * @param {*} city 
 * @param {*} province 
 */
function getHospitals(county, city, province, callback) {
    $.ajax({
            url: '/api/Hospital/getHospitals',
            type: 'POST',
            dataType: 'json',
            data: {
                county: county,
                city: city,
                province: province
            },
            cache: false
        })
        .done(function (res) {
            var res = JSON.parse(res);
            if (res.error) {
                new PNotify({
                    title: '提示',
                    text: res.msg
                });
            } else {
                var html = template('hospital-tmp', res.data);
                $('#hospital').html(html);

                typeof callback == 'function' && callback(res.data);
            }
        })
        .fail(function () {
            new PNotify({
                title: '提示',
                text: '网络请求失败',
                type: 'error'
            });
        })
        .always(function () {});
}

/**
 * 同步好友画像
 */
function syncChatingUserPic(robot_id, uid, phone, btn) {
    $.ajax({
            url: '/admin/Chat/syncUserpic',
            type: 'GET',
            dataType: 'json',
            data: {
                id: robot_id,
                uid: uid,
                phone: phone
            },
            cache: false
        })
        .done(function (res) {
            var res = JSON.parse(res);
            if (res.error) {
                new PNotify({
                    title: '提示',
                    text: res.msg
                });
            } else {
                new PNotify({
                    title: '提示',
                    text: res.msg,
                    type: 'success'
                });

                // 同步用户画像
                getChatingUserPic(robot_id, uid);
                // getChatingUserInfo(robot_id, uid, phone, btn);
            }
        })
        .fail(function () {
            new PNotify({
                title: '提示',
                text: '网络请求失败',
                type: 'error'
            });
        })
        .always(function () {
            if (btn) {
                btn.button('reset');
            };
        });
}

/**
 * 保存用户画像
 * @param  {[type]} uid [description]
 * @param  {[type]} btn [description]
 * @return {[type]}     [description]
 */
function saveUserPic(btn) {
    var formData = $('#pic-info-form').serialize();
    $.ajax({
            url: '/admin/Chat/sendUserPic',
            type: 'POST',
            dataType: 'json',
            data: formData,
            cache: false
        })
        .done(function (res) {
            var res = JSON.parse(res);
            if (res.error) {
                new PNotify({
                    title: '提示',
                    text: res.msg,
                    type: 'error'
                });
            } else {
                new PNotify({
                    title: '提示',
                    text: res.msg,
                    type: 'success'
                });
            }
        })
        .fail(function () {
            new PNotify({
                title: '提示',
                text: '网络请求失败',
                type: 'error'
            });
        })
        .always(function () {
            if (btn) {
                btn.button('reset');
            };
        });
}

/**
 * 检测机器人未读消息状态
 */
function setChatToRead(robot_id, contact_id) {
    $.ajax({
            url: '/admin/Chat/setChatToRead',
            type: 'POST',
            dataType: 'json',
            data: {
                id: robot_id,
                cid: contact_id
            },
            cache: false
        })
        .done(function (res) {
            var res = JSON.parse(res);
            if (res.has) {
                robotHasMsg(robot_id, true);
            } else {
                robotHasMsg(robot_id, false);
            }
        })
        .fail(function () {
            new PNotify({
                title: '提示',
                text: '网络请求失败',
                type: 'error'
            });
        })
        .always(function () {});
}

/**
 * 绑定语音播放时间
 * @return {[type]} [description]
 */
function bindAudioAction() {
    $('.app-voice').unbind('click').bind('click', function (event) {
        event.preventDefault();
        var _this = $(this);
        var _state = _this.children('.app-voice-state');
        var src = _this.attr('voiceSrc');
        var audio = document.getElementById('audio_ele');
        if (audio !== null) {
            $('#audio_ele').find('source').attr('src', src);
            if (audio.pause) {
                audio.pause;
            };
            audio.load();
            audio.play();
            _state.removeClass('app-voice-pause').addClass('app-voice-play');
            audio.addEventListener('ended', function () {
                _state.removeClass('app-voice-play').addClass('app-voice-pause');
            });
        } else {
            new PNotify({
                title: '提示',
                text: '不支持播放'
            });
        }
    });
}

/**
 * 绑定用户画像内的事件
 */
function bindUserPicEvent(robot_id, uid) {
    // 身份切换
    $('#identity').unbind('change').bind('change', function (event) {
        event.preventDefault();
        var _this = $(this);
        var key = _this.children('option:selected').attr('okey');
        changeIdentity(key);
    });

    // 省份切换
    $('#province').unbind('change').bind('change', function (event) {
        event.preventDefault();
        var _this = $(this);
        var oname = _this.val();
        if (oname != 0 && oname != '') {
            getCities(oname);
        } else {
            $('#city').html('<option value="0">选择城市</option>');
        }
    });
    // 城市切换
    $('#city').unbind('change').bind('change', function (event) {
        event.preventDefault();
        var _this = $(this);
        var oname = _this.val();
        var province = $('#province').val();
        if (oname != '' && oname != 0) {
            getCounties(oname, province);
        } else {
            $('#county').html('<option value="0">选择区县</option>');
        }
    });
    // 区县切换
    $('#county').unbind('change').bind('change', function (event) {
        event.preventDefault();
        var _this = $(this);
        var oname = _this.val();
        var city = $('#city').val();
        var province = $('#province').val();
        if (oname != '' && oname != 0) {
            getHospitals(oname, city, province);
        } else {
            $('#hospital').html('<option value="0">选择医院</option>');
        }
    });
    // 保存
    $('#btn-save-pic').unbind('click').bind('click', function (event) {
        event.preventDefault();
        var _this = $(this);
        var $btn = _this.button('loading');
        saveUserPic($btn);
    });

    // 同步画像资料
    $('#btn-sync-pic').unbind('click').bind('click', function (event) {
        event.preventDefault();
        var _this = $(this);
        var $btn = _this.button('loading');
        var uid = _this.siblings('input[name=uid]').val();
        var phone = $('#pic-info-form').find('input[name=phone]').val();
        if (!phone || $.trim(phone).length == 0) {
            new PNotify({
                title: '提示',
                text: '请先给该用户设置手机号，保存之后再同步'
            });
            $btn.button('reset');
            return;
        }
        syncChatingUserPic(robot_id, uid, phone, $btn);
    });
}

/**
 * 向聊天内容区添加一条 机器人消息 记录
 * @param  {[type]} data [description]
 * @return {[type]}      [description]
 */
function appendRightItemToRecord(data) {
    // 机器人消息在右
    var html = template('right-content', data);
    $('#chating-content').append(html);
    scrollToContentBottom();
}

/**
 * 向聊天内容区添加一条 用户消息 记录
 * @param  {[type]} data [description]
 * @return {[type]}      [description]
 */
function appendLeftItemToRecord(data) {
    // 用户消息在左
    var html = template('left-content', data);
    $('#chating-content').append(html);
    scrollToContentBottom();
    // 语音事件
    bindAudioAction();
}

/**
 * 更新当前用户下面的消息提示
 * @param  {[type]} data [description]
 * @return {[type]}      [description]
 */
function renderUserHint(uid, message) {
    var $ele = $('#chatings_item_' + uid);
    if (message.type == 1) {
        $ele.find('.text-hint').html(message.data.content);
    } else if (message.type == 2) {
        $ele.find('.text-hint').html(message.data.uri);
    } else if (message.type == 3) {
        $ele.find('.text-hint').html(message.data.filename);
    }
}

/**
 * 切换身份，显示不同选项
 * @param {*} key 
 */
function changeIdentity(key) {
    switch (parseInt(key)) {
        case 1:
            $('#hospital-container').removeClass('hidden');
            $('#department-container').removeClass('hidden');
            $('#duty-container').removeClass('hidden');
            $('#school-container').addClass('hidden');
            $('#profession-container').addClass('hidden');
            $('#position-container').addClass('hidden');
            break;
        case 2:
        case 3:
            $('#hospital-container').removeClass('hidden');
            $('#department-container').addClass('hidden');
            $('#duty-container').removeClass('hidden');
            $('#school-container').addClass('hidden');
            $('#profession-container').addClass('hidden');
            $('#position-container').addClass('hidden');
            break;
        case 4:
            $('#hospital-container').addClass('hidden');
            $('#department-container').addClass('hidden');
            $('#duty-container').addClass('hidden');
            $('#school-container').removeClass('hidden');
            $('#profession-container').removeClass('hidden');
            $('#position-container').addClass('hidden');
            break;
        case 5:
            $('#hospital-container').removeClass('hidden');
            $('#department-container').addClass('hidden');
            $('#duty-container').addClass('hidden');
            $('#school-container').addClass('hidden');
            $('#profession-container').addClass('hidden');
            $('#position-container').removeClass('hidden');
            break;
        default:
            $('#hospital-container').addClass('hidden');
            $('#department-container').addClass('hidden');
            $('#duty-container').addClass('hidden');
            $('#school-container').addClass('hidden');
            $('#profession-container').addClass('hidden');
            $('#position-container').addClass('hidden');
            break;
    }
}

/**
 * [scrollToContentBottom description]
 * @return {[type]} [description]
 */
function scrollToContentBottom() {
    // 等待图片加载
    var timer = setTimeout(function () {
        $('#chating-panel .chat-col-content').scrollTo($('#chating-content').height(), 400, 'easing');
        clearTimeout(timer);
    }, 400);
}

/**
 * 头像加载失败处理
 * @return {[type]} [description]
 */
function loadAvatarImg() {
    // 头像图片加载检测
    $('.img-avatar').error(function () {
        $(this).attr('src', '/static/img/ui-sam.jpg');
    });
}

/**
 * 机器人有新消息
 * @param  {[type]} robot_id [description]
 * @param  {[type]} flag     [description]
 * @return {[type]}          [description]
 */
function robotHasMsg(robot_id, flag) {
    var $ele = $("#item_" + robot_id);
    // var is_active = $ele.hasClass('active');
    if ($ele && flag) {
        $ele.children('.has-msg').removeClass('hidden').addClass('show');
    } else {
        $ele.children('.has-msg').removeClass('show').addClass('hidden');
    }
}

/**
 * 用户是否有新消息
 * @param  {[type]} id   [description]
 * @param  {[type]} flag [description]
 * @return {[type]}      [description]
 */
function userHasMsg(id, flag) {
    var $ele = currentUserTabItem(id);
    var is_active = $ele.hasClass('active');
    if ($ele && !is_active && flag) {
        $ele.children('.has-msg').removeClass('hidden').addClass('show');
    } else {
        $ele.children('.has-msg').removeClass('show').addClass('hidden');
    }
}

/**
 * 获取当前好友列表 item
 * @param  {[type]} id [description]
 * @return {[type]}    [description]
 */
function currentUserTabItem(id) {
    var tab_index = $('#chat-users-tab').children('li.active').index();
    if (tab_index == 1) {
        $ele = $("#contacts_item_" + id);
    } else {
        $ele = $("#chatings_item_" + id);
    }
    return $ele;
}

/**
 * 清空聊天区 用户资料区
 * @return {[type]} [description]
 */
function clearRightPanel3And4() {
    $('#chating-user-nickname').html('');
    $('#chating-content').html('');
    $('#userinfo-container').html('');
    $('#picinfo-container').html('');
    $('#btn-send').attr({
        robot_id: 0,
        uid: 0
    });
}