$(function () {
    /**
     * 点击快捷回复到输入框
     */
    $('.nav-item-has-subnav .spani').click(function() {
        $(this).find('i').toggle2classes('icon-xiangshang', 'icon-xiangxia');
    });

    /**
     * 添加客服分组
     */
    $('body').on('click','#add-service-group', function() {
        var group_name = $.trim($('.add_service_group #group-name').val());
        if (!group_name) {
            return we_im_msg('不能为空');
        }
        $.ajax({
            type: "post",
            url: IM_config.addServiceGroup,
            data: {
                group_name:group_name
            },
            dataType: "json",
            success : function(r) {
                we_im_msg(r.data);
                if (r.code == 200) {
                    setTimeout(function() {
                        location.reload();
                    },2000);
                }
            }
        });
    });

    /**
     * 修改客服分组
     */
    $('.table-bordered #editdata').click(function() {
        var groupname = $(this).parent().parent().siblings('#name');
        if (groupname.find('input').length == 0) {
            var input = '<input type="text" class="form-control" value="'+groupname.text()+'"><button class="btn btn-success" type="button">保存</button>';
            groupname.html(input);
        }
    });

    /**
     * 删除客服分组
     */
    $('.table-bordered #deldata').click(function() {
        var obj = $(this);
        var source = $('.data-source-' + obj.attr('valid'));
        var data = JSON.parse(source.attr('data'));
        $.ajax({
            type: "post",
            url: data.del.url,
            data: {
                group_id: data.del.id
            },
            dataType: "json",
            success : function(r) {
                we_im_msg(r.data);
                if (r.code == 200) {
                    setTimeout(function() {
                        source.parent().fadeOut();
                    },2000);
                }
            }
        });
    });

    /**
     * 修改客服分组
     */
    $('body').on('click','.table-bordered #name button', function() {
        var obj = $(this);
        var data = JSON.parse($('.data-source-' + obj.parent().attr('valid')).attr('data'));
        var group_name = $.trim(obj.siblings('input').val());
        if (!group_name) {
            return we_im_msg('不能为空');
        }
        $.ajax({
            type: "post",
            url: data.edit.url,
            data: {
                group_id: data.edit.id,
                group_name: group_name
            },
            dataType: "json",
            success : function(r) {
                we_im_msg(r.data);
                if (r.code == 200) {
                    obj.parent().text(group_name);
                }
            }
        });
    });

    /**
     * 添加客服
     */
    $('body').on('click','#add-service', function() {
        var data = {};
        data['avatar'] = $.trim($('#mer-avatar').val());
        if (data['avatar'] == '') {
            return we_im_msg('头像不能为空');
        }
        data['uname'] = $.trim($('#mer-uname').val());
        if (data['uname'] == '') {
            $('#mer-uname').focus();
            return we_im_msg('用户名不能为空');
        }
        data['upass'] = $.trim($('#mer-upass').val());
        if (data['upass'] == '') {
            $('#mer-upass').focus();
            return we_im_msg('密码不能为空');
        }
        data['upass2'] = $.trim($('#mer-upass2').val());
        if (data['upass2'] == '') {
            $('#mer-upass2').focus();
            return we_im_msg('确认不能为空');
        }
        if (data['upass'] != data['upass2']) {
            return we_im_msg('两次密码不相同');
        }
        data['nick'] = $.trim($('#mer-nick').val());
        if (data['nick'] == '') {
            $('#mer-nick').focus();
            return we_im_msg('昵称不能为空');
        }
        data['phone'] = $.trim($('#emer-phone').val());
        data['email'] = $.trim($('#emer-email').val());
        data['group_id'] = $.trim($('#mer-group_id').val());
        if (data['group_id'] == '') {
            $('#mer-group_id').focus();
            return we_im_msg('分组不能为空');
        }

        $.ajax({
            type: "post",
            url: IM_config.addService,
            data: data,
            dataType: "json",
            success : function(r) {
                we_im_msg(r.data);
                if (r.code == 200) {
                    setTimeout(function() {
                        location.reload();
                    },2000);
                }
            }
        });
    });

    /**
     * 修改客服
     */
    $('body').on('click','#edit-service', function() {
        var data = {};
        data['avatar'] = $.trim($('#emer-avatar').val());
        if (data['avatar'] == '') {
            return we_im_msg('头像不能为空');
        }
        data['uname'] = $.trim($('#emer-uname').val());
        if (data['uname'] == '') {
            $('#emer-uname').focus();
            return we_im_msg('用户名不能为空');
        }
        data['nick'] = $.trim($('#emer-nick').val());
        if (data['nick'] == '') {
            $('#emer-nick').focus();
            return we_im_msg('昵称不能为空');
        }
        data['cu_id'] = $.trim($('#emer-id').val());
        data['phone'] = $.trim($('#emer-phone').val());
        data['email'] = $.trim($('#emer-email').val());
        data['group_id'] = $.trim($('#emer-group_id').val());
        if (data['group_id'] == '') {
            $('#emer-group_id').focus();
            return we_im_msg('分组不能为空');
        }

        $.ajax({
            type: "post",
            url: IM_config.editService,
            data: data,
            dataType: "json",
            success : function(r) {
                we_im_msg(r.data);
                if (r.code == 200) {
                    setTimeout(function() {
                        location.reload();
                    },2000);
                }
            }
        });
    });

    /**
     * 删除客服
     */
    $('body').on('click','#delservice', function() {
        var obj = $(this);
        var confirm = layer.confirm('会删除这个客服相关的所有信息！确认？', {
            btn: ['删除','取消']
        }, function(){
            var data = {
                cuid: obj.attr('data-id')
            };
            $.post(IM_config.delService, data, function (r) {
                if (r.code == 200) {
                    layer.close(confirm);
                    setTimeout(function() {
                        $('#service-' + obj.attr('data-id')).fadeOut();
                    },1000);
                }
            });
        });
    });

    /**
     * 添加修改客服数据
     */
    $('body').on('click','.btn-group #addservice', function() {
        var obj = $(this);
        var getid = obj.attr('data-id');
        var service = $('#service-' + getid);
        var edit = $('.edit_service');
        edit.find('#emer-id').val(getid);
        edit.find('.img-avatar').attr('src', obj.attr('data-avatar'));
        edit.find('#emer-avatar').val(obj.attr('data-avatar'));
        edit.find('#emer-uname').val(service.find('#ser-uname').text());
        edit.find('#emer-nick').val(service.find('#ser-nick').text());
        edit.find('#emer-phone').val(service.find('#ser-phone').text().replace(/-/,''));
        edit.find('#emer-email').val(service.find('#ser-email').text().replace(/-/,''));
        edit.find('#emer-group_id').val(service.find('#ser-name').attr('group-id'));
    });

    /**
     * 生成聊天代码聊天框样式
     */
    $('.access_code .dropdown-menu li').click(function () {
        var obj = $(this);
        var cur_text = obj.parents('.btn-group').find('.cur-text');
        var type = obj.find('a').attr('data-type');
        if (type == 2) {
            $('.access-2,.access-3').addClass('hide');
        } else {
            $('.access-2,.access-3').removeClass('hide');
        }
        cur_text.text(obj.find('a').text());
        cur_text.attr('type', type);
        $('#copyVal').html("");
        $('.access-code-lists').addClass('hide');
        $('.ajax-post').removeClass('hide');
        $('.copy-link').addClass('hide');
    });


    function removePreviewJsCode(){

        if( $('#IM_sidebar').length > 0 ){
            $("#IM_sidebar").remove();
            $("head").find('script').first().remove();
            $("head").find('link').last().remove();
        }

        if( $('#IM_sidebar_m').length > 0 ){
            $("#IM_sidebar_m").remove();
            $("head").find('script').first().remove();
            $("head").find('link').last().remove();
        }
    }

    /**
     * 生成聊天代码
     */
    $('.access_code .access-1').click(function () {
        var layer_load = layer.load(1, {shade: [0.1,'#000'], time: 500});
        var style = $('.cur-text').text() == '标准窗口' ? 1 : 2;
        $(this).addClass('btn-info').siblings().removeClass('btn-info');
        $.post(IM_config.accessCode, {style:style}, function (r) {
            if (r.code == 200) {
                var jscode = '(function() {'+
                    'var hm = document.createElement("script");'+
                    'hm.src = "'+r.domain+'/chat/js/chat.js?'+r.codes+'";'+
                    'var s = document.getElementsByTagName("script")[0];'+
                    's.parentNode.insertBefore(hm, s);'+
                    '})();';
                var jsmaStr = '&lt;script type=\'text/javascript\'&gt;'+
                    'var _hmt = _hmt || [];'+
                    jscode+
                '&lt;/script&gt;';
                $('.chat_code #copyVal-1').html(jsmaStr);
                // js代码预览
                if( $("#previewCode").length > 0 ) {
                    removePreviewJsCode();
                    $("#previewCode").remove();
                }

                var previewButton = '<button type="button" style="margin-top:10px;" id="previewCode" class="btn btn-default">js代码预览</button>';
                $('.chat_code').append(previewButton);
                $("#previewCode").on('click',function(){
                    removePreviewJsCode();
                    eval(jscode);
                })


                $('.chat_page,.chat_link').addClass('hide');
                setTimeout(function() {
                    layer.close(layer_load);
                    $('.chat_code').removeClass('hide');
                },500);
            }
        });
    });

    /**
     * 生成聊天网页
     */
    $('.access_code .access-2').click(function () {
        var layer_load = layer.load(1, {shade: [0.1,'#000'], time: 500});
        $('.chat_code,.chat_link').addClass('hide');
        $(this).addClass('btn-info').siblings().removeClass('btn-info');
        setTimeout(function() {
            layer.close(layer_load);
            $('.chat_page').removeClass('hide');
        },500);
    });

    /**
     * 生成聊天链接
     */
    $('.access_code .access-3').click(function () {
        var layer_load = layer.load(1, {shade: [0.1,'#000'], time: 500});
        $('.access-code-lists').addClass('hide');
        $(this).addClass('btn-info').siblings().removeClass('btn-info');
        setTimeout(function() {
            layer.close(layer_load);
            $('.chat_link').removeClass('hide');
        },500);
    });

    /**
     * 展示添加常见问题
     */
    $('.toolbar-btn-action #add_set_problem').click(function () {
        var obj = $(this);
        layer.open({
            type: 2,
            title: '添加常见问题',
            skin: 'custom-top',
            area: ['600px', '820px'],
            content: IM_config.addSetProblem
        });
    });

    /**
     * 展示修改常见问题
     */
    $('.btn-group #edit_set_problem').click(function () {
        var obj = $(this);
        var url = IM_config.editSetProblem;
        if (url.indexOf("?") != -1) {
            url = url + '&pro_id=' + obj.attr('data-id');
        } else {
            url = url + '?pro_id=' + obj.attr('data-id');
        }
        layer.open({
            type: 2,
            title: '修改常见问题',
            skin: 'custom-top',
            area: ['600px', '820px'],
            content: url
        });
    });

    /**
     * 删除常见问题
     */
    $('.btn-group #del_set_problem').click(function () {
        var obj = $(this);
        var confirm = layer.confirm('确定要删除这个常见问题吗？', {
            btn: ['删除','取消']
        }, function(){
            var data = {
                pro_id: obj.attr('data-id')
            };
            $.post(IM_config.delSetProblem, data, function (r) {
                if (r.code == 200) {
                    layer.close(confirm);
                    setTimeout(function() {
                        $('#problem-' + obj.attr('data-id')).fadeOut();
                    },1000);
                }
            });
        });
    });
});
