function showQRDialog(img, oid, callback) {
    _this = $('#login-qr-modal');
    _this.modal('toggle');
    _this.find("#qr-img").attr('src', img);
    _this.find(".btn-reset").attr('oid', oid).unbind('click').bind('click', function (event) {
        event.preventDefault();
        _this.modal('hide');
        var _that = $(this);
        var $btn = _that.button('loading');
        $.ajax({
                url: "/admin/Robot/reset",
                type: 'POST',
                dataType: 'json',
                data: {
                    id: oid
                },
                cache: false
            })
            .done(function () {
                window.location.reload();
            })
            .fail(function () {
                new PNotify({
                    title: '提示',
                    text: '网络请求失败',
                    'type': 'error'
                });
            })
            .always(function () {
                $btn.button('reset');
            });
    });;
    _this.find(".btn-sure").on('click', function (event) {
        typeof callback == "function" && callback();
        _this.modal('hide');
    });
}

var exceptsvalues = [];
/**
 * 获取业务集合
 */
function getauthitem(robot_id,nickname) {
    $.post('/admin/Sbusiness/get_auth_item?robot_id='+robot_id, function (res) {
        var res = JSON.parse(res);
        if (res.error == 1) {
            // javascript 的默认弹出提示方法
            new PNotify({
                title: '提示',
                text: res.msg,
                'type': 'error'
            });
        } else {
            var data = res.data;
            var option_str;
            exceptsvalues = [];
            for (var i = 0; i < data.length; i++) {
                option_str+='<option name="option" value="'+data[i].id+'">'+data[i].key+'</option>';
                var config = JSON.parse(data[i].config);
                if (config!=null) {
                    if (config.excepts!=null && $.inArray(nickname, config.excepts)!=-1) {
                        exceptsvalues.push(data[i].id);
                    }
                }
            }
            $("#values").val(exceptsvalues);
            $('option[name="option"]').remove();
            $('#add_tags').append(option_str);
            //destroy销毁上一次的设置，select设置选中项
            $('#add_tags').multiselect("destroy").multiselect('select', exceptsvalues).multiselect({
                includeSelectAllOption: true,
                enableFiltering: true,
                filterPlaceholder: '搜索',
                selectAllText: '全选',
                nonSelectedText: '选择目标',
                allSelectedText: '已选择全部',
            });
        }
    });
}
$(function () {
    $('[data-toggle="tooltip"]').tooltip();

    // 初始化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"
                });
            });
        }
    });
    JIM.onMsgReceive(function (data) {
        var res = data.messages[0].content.msg_body;
        if (res.extras.action == 'login') {
            window.location.reload();
        } else if (res.extras.action == 'reset') {
            window.location.reload();
        } else if (res.extras.action == 'sync') {
            $('#contact_status_' + res.extras.id).text('最新数据');
            new PNotify({
                title: '提示',
                text: res.text,
                type: "success"
            });
        };
    });

    // 详情
    $('.right-show').unbind('click').bind('click', function (event) {
        event.stopPropagation();
        event.preventDefault();
        document.getElementById('right-detail-content').innerHTML = "";
        var url = "/admin/Robot/read";
        var oid = $(this).attr('oid');
        showRightDetail(function () {
            $.get(url + "?id=" + oid, function (res) {
                var res = JSON.parse(res);
                if (res.error === 0) {
                    var html = template('robot', res.data);
                    document.getElementById('right-detail-content').innerHTML = html;
                    // 添加群用户为好友
                    $('.btn-add-friends').unbind('click').bind('click', function () {
                        var _this = $(this);
                        var $btn = _this.button('loading');
                        var group = $.trim($('#group-selected').val());
                        var verify = $.trim($('#verify-content').val());
                        if (group.length <= 0 || group == '') {
                            new PNotify({
                                title: '提示',
                                text: '请选择一个群'
                            });
                            $btn.button('reset');
                            return;
                        };
                        $.ajax({
                                url: "/admin/Robot/addFriends",
                                type: 'POST',
                                dataType: 'json',
                                data: {
                                    id: oid,
                                    gid: group,
                                    verify: verify
                                },
                                cache: false,
                            })
                            .done(function (res) {
                                var res = JSON.parse(res);
                                new PNotify({
                                    title: '提示',
                                    text: res.msg
                                });
                            })
                            .fail(function () {
                                new PNotify({
                                    title: '提示',
                                    text: '网络请求失败',
                                    'type': 'error'
                                });
                            })
                            .always(function () {
                                $btn.button('reset');
                            });
                    });
                    // 首次加好友自动回复
                    $('.btn-first-reply').unbind('click').bind('click', function () {
                        var _this = $(this);
                        var $btn = _this.button('loading');
                        var content = $.trim($('#reply-content').val());
                        if (content.length <= 0 || content == '') {
                            new PNotify({
                                title: '提示',
                                text: '回复内容为空'
                            });
                            $btn.button('reset');
                            return;
                        };
                        $.ajax({
                                url: "/admin/Robot/addFirstReply",
                                type: 'POST',
                                dataType: 'json',
                                data: {
                                    id: oid,
                                    content: content
                                },
                                cache: false,
                            })
                            .done(function (res) {
                                var res = JSON.parse(res);
                                new PNotify({
                                    title: '提示',
                                    text: res.msg
                                });
                            })
                            .fail(function () {
                                new PNotify({
                                    title: '提示',
                                    text: '网络请求失败',
                                    'type': 'error'
                                });
                            })
                            .always(function () {
                                $btn.button('reset');
                            });
                    });
                } else {
                    new PNotify({
                        title: '提示',
                        text: res.msg,
                        type: 'error'
                    });
                };
            });
        });
    });

    // 启动
    $('.btn-start').unbind('click').bind('click', function (event) {
        var _this = $(this);
        var url = "/admin/Robot/start";
        var oid = _this.attr('oid');
        showDialog("启动机器人", "确定启动机器人？", function () {
            var $btn = _this.button('loading');
            showLoading();
            $.get(url + "?id=" + oid, function (res) {
                var res = JSON.parse(res);
                if (res.error) {
                    new PNotify({
                        title: '提示',
                        text: res.msg
                    });
                    $btn.button('reset');
                } else {
                    _this.remove();
                    $('#qr_' + oid).attr('obj', res.data.login_qr).show();
                    $('#status_' + oid).text('等待扫码登陆');
                    showQRDialog(res.data.login_qr, oid);
                }
                hideLoading();
            });
        });
    });
    // 显示二维码
    $('.btn-qr').unbind('click').bind('click', function () {
        var _this = $(this);
        var oid = _this.attr('oid');
        var obj = _this.attr('obj');
        showQRDialog(obj, oid);
    });

    // 下线
    $('.btn-shutdown').unbind('click').bind('click', function (event) {
        var url = "/admin/Robot/shutdown";
        var oid = $(this).attr('oid');
        showDialog("下线机器人", "确定下线机器人？", function () {
            $.ajax({
                    url: url + "?id=" + oid,
                    type: 'GET',
                    dataType: 'json',
                    data: {},
                    cache: false,
                })
                .done(function (res) {
                    var res = JSON.parse(res);
                    if (res.error) {
                        new PNotify({
                            title: '提示',
                            text: res.msg
                        });
                    } else {
                        window.location.reload();
                    }
                })
                .fail(function () {
                    new PNotify({
                        title: '提示',
                        text: '网络请求失败',
                        'type': 'error'
                    });
                });
        });
    });

    // 删除
    $('.btn-delete').unbind('click').bind('click', function (event) {
        var url = "/admin/Robot/delete";
        var oid = $(this).attr('oid');
        showDialog("删除机器人", "确定删除机器人？", function () {
            $.ajax({
                    url: url + "?id=" + oid,
                    type: 'GET',
                    dataType: 'json',
                    data: {},
                    cache: false,
                })
                .done(function (res) {
                    var res = JSON.parse(res);
                    if (res.error) {
                        new PNotify({
                            title: '提示',
                            text: res.msg
                        });
                    } else {
                        $("#tr_" + oid).remove();
                        window.location.reload();
                    }
                })
                .fail(function () {
                    new PNotify({
                        title: '提示',
                        text: '网络请求失败',
                        'type': 'error'
                    });
                });
        });
    });

    // 同步通讯录
    $('.btn-sync').unbind('click').bind('click', function () {
        var _this = $(this);
        var status = _this.attr('status');
        if (status != 2) {
            new PNotify({
                title: '提示',
                text: '机器人未启动'
            });
            return;
        };
        var url = "/admin/Robot/sync";
        var oid = _this.attr('oid');
        showDialog("同步通讯录", "确定同步机器人通讯录？", function () {
            showLoading();
            $.ajax({
                    url: url + "?id=" + oid,
                    type: 'GET',
                    dataType: 'json',
                    data: {},
                    cache: false,
                })
                .done(function (res) {
                    var res = JSON.parse(res);
                    if (res.error) {
                        new PNotify({
                            title: '提示',
                            text: res.msg
                        });
                    } else {
                        window.location.reload();
                    }
                })
                .fail(function () {
                    new PNotify({
                        title: '提示',
                        text: '网络请求失败'
                    });
                })
                .always(function () {
                    hideLoading();
                });
        });
    });

    // 同步单个群用户
    $('.btn-sync-group').unbind('click').bind('click', function () {
        var _this = $(this);
        var status = _this.attr('status');
        if (status != 2) {
            new PNotify({
                title: '提示',
                text: '机器人未启动'
            });
            return;
        };
        var url = "/admin/Robot/syncGroup";
        var oid = _this.attr('oid');
        showDialog("同步群用户", "确定同步群用户？", function () {
            showLoading();
            $.ajax({
                    url: url,
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        'id': oid
                    },
                    cache: false,
                })
                .done(function (res) {
                    var res = JSON.parse(res);
                    if (res.error) {
                        new PNotify({
                            title: '提示',
                            text: res.msg
                        });
                    } else {
                        window.location.reload();
                    }
                })
                .fail(function () {
                    new PNotify({
                        title: '提示',
                        text: '网络请求失败'
                    });
                })
                .always(function () {
                    hideLoading();
                });
        });
    });

    // 同步所有群用户
    $('.btn-sync-groups').unbind('click').bind('click', function () {
        var _this = $(this);
        var status = _this.attr('status');
        if (status != 2) {
            new PNotify({
                title: '提示',
                text: '机器人未启动'
            });
            return;
        };
        var url = "/admin/Robot/syncGroups";
        var oid = _this.attr('oid');
        showDialog("同步群用户", "确定同步群用户？", function () {
            showLoading();
            $.ajax({
                    url: url,
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        'id': oid
                    },
                    cache: false,
                })
                .done(function (res) {
                    var res = JSON.parse(res);
                    if (res.error) {
                        new PNotify({
                            title: '提示',
                            text: res.msg
                        });
                    } else {
                        window.location.reload();
                    }
                })
                .fail(function () {
                    new PNotify({
                        title: '提示',
                        text: '网络请求失败'
                    });
                })
                .always(function () {
                    hideLoading();
                });
        });
    });

    // 导出机器人通讯录excel
    $('#btn_export').click(function(){
        var robot_id = $(this).attr("robot_id");
        window.location.href = '/admin/Robot/export_contacts/id/'+robot_id; 
        return false;
    });

    // 备注
    $('.btn-remark').unbind('click').bind('click', function () {
        var _this = $(this);
        var oid = _this.attr('oid');
        var url = "/admin/Robot/remark";
        var _modal = $('#remark-modal').modal('show');
        _modal.find('.btn-save').unbind('click').bind('click', function () {
            var _that = $(this);
            var robot_id = _that.attr('oid');
            var remark = $.trim(_modal.find('#remark').val());
            if (remark == '') {
                new PNotify({
                    title: '提示',
                    text: '请填写必要信息'
                });
                return;
            };
            var $btn = _that.button('loading');
            $.ajax({
                    url: url,
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        id: oid,
                        robot_id: robot_id,
                        remark: remark,
                    },
                    cache: false,
                })
                .done(function (res) {
                    var res = JSON.parse(res);
                    if (res.error) {
                        new PNotify({
                            title: '提示',
                            text: res.msg
                        });
                    } else {
                        window.location.reload();
                    }
                })
                .fail(function (res) {
                    new PNotify({
                        title: '提示',
                        text: '网络请求失败'
                    });
                })
                .always(function () {
                    _modal.modal('hide');
                    $btn.button('reset');
                });
        });
    });

    $('.btn-delete-repeat').unbind('click').bind('click', function (event) {
        event.preventDefault();
        var url = "/admin/Robot/deleteRepeat";
        var oid = $(this).attr('oid');
        showDialog("删除重复好友", "确定删除通讯录中重复的好友？", function () {
            $.ajax({
                    url: url + "/id/" + oid,
                    type: 'GET',
                    dataType: 'json',
                    data: {},
                    cache: false,
                })
                .done(function (res) {
                    var res = JSON.parse(res);
                    if (res.error) {
                        new PNotify({
                            title: '提示',
                            text: res.msg
                        });
                    } else {
                        $("#tr_rp_" + oid).remove();
                        window.location.reload();
                    }
                })
                .fail(function () {
                    new PNotify({
                        title: '提示',
                        text: '网络请求失败',
                        'type': 'error'
                    });
                });
        });
    });
    
    // 删除通讯录
    $('.btn-delete-contact').unbind('click').bind('click', function (event) {
        var url = "/admin/Robot/delete_contact";
        var oid = $(this).attr('oid');
        showDialog("删除通讯录", "确定通讯录联系人，如果该联系人是群，则会删除该微信群相关的所有信息？", function () {
            $.ajax({
                    url: url + "?id=" + oid,
                    type: 'GET',
                    dataType: 'json',
                    data: {},
                    cache: false,
                })
                .done(function (res) {
                    var res = JSON.parse(res);
                    if (res.error) {
                        new PNotify({
                            title: '提示',
                            text: res.msg
                        });
                    } else {
                        $("#tr_" + oid).remove();
                        window.location.reload();
                    }
                })
                .fail(function () {
                    new PNotify({
                        title: '提示',
                        text: '网络请求失败',
                        'type': 'error'
                    });
                });
        });
    });

    // 配置用户业务
    $(".btn-config-contact").bind('click', function (event) {
        event.preventDefault();
        var _this = $(this);
        var url = "/admin/Sbusiness/config_excepts";
        var oid = _this.attr('oid');
        var nickname = _this.find('span').text();

        var _modal = $('#config-modal').modal('show');
        getauthitem(oid,nickname);

        // 按钮
        _modal.find('.btn-save').unbind('click').bind('click', function () {
            var values = $('#values').val();
            var values_str = JSON.stringify(exceptsvalues);
            $.post(url, {nickname:nickname,values:values,last_values:values_str}, function(res){
                res = JSON.parse(res);
                if (res.error==1) {
                    new PNotify({
                        title: '提示',
                        text: res.msg,
                        'type': 'error'
                    });
                    _modal.modal('hide');
                } else {
                    new PNotify({
                        title: '提示',
                        text: res.msg
                    });
                    window.location.href = "/admin/Robot/contacts/id/"+oid;
                }
              
            });
        });
    });

    $("#add_tags").change(function(){
        var selected = [];
        $('#add_tags option:selected').each(function () {
            selected.push($(this).val());
        });
        $("#values").val(selected);
    });

});