$(function () {

    /**
     * 更改插件状态
     */
    $('#plugin #plugin-state input').click(function() {
        var obj = $(this);
        var name = obj.attr('data-name');
        var action = obj.is(":checked") ? 'enable' : 'disable';
        $.post(IM_config.pluginState,{name:name,action:action}, function(r) {
            we_im_msg(r.data);
            if (r.code == 200) {
                obj.parents('.addonsTr').attr('id', 'addons-' + (obj.is(":checked")?1:0));
                setTimeout(function() {
                    window.location.reload();
                },2000);
            }
        });
    });

    /**
     * 点击快捷回复到输入框
     */
    $('.card-header .spani').click(function() {
        var obj = $(this);
        obj.find('i').toggle2classes('icon-xiangshang', 'icon-xiangxia');
        obj.parent().parent().find('.set-lists').slideToggle('fast');
    });

    /**
     * 卸载删除插件
     */
    $('.addonsTr .detele').click(function() {
        var obj = $(this);
        var confirm = layer.confirm('确定要删除这个插件吗？', {
            btn: ['删除','取消']
        }, function(){
            var name = obj.attr('data-name');
            var action = $('#plugin-name-' + name).is(":checked") ? 'enable' : 'disable';
            if (action == 'enable') {
                return we_im_msg('需要先禁用该插件');
            }
            $.post(IM_config.pluginUninstall,{name:name}, function(r) {
                we_im_msg(r.data);
                if (r.code == 200) {
                    addons_cache_delete();//删除插件缓存
                    layer.close(confirm);
                    obj.parents('.addonsTr').remove();
                }
            });
        });
    });

    /**
     * 上传插件
     */
    $('input[name="upload_plugin"]').change(function() {
        try {
            var obj = $(this);
            var suffix = obj.get(0).files[0].name.split(".")[1];
            if (suffix == 'zip' || suffix == 'rar') {
                var upload = $('#upload-install');
                upload.attr('disabled', false);
                upload.text('上传中...');
                var formData = new FormData();
                formData.append('upload_plugin', obj.get(0).files[0]);
                obj.val('');
                var layer_load;
                $.ajax({
                    url:IM_config.pluginUpload,
                    method: 'post',
                    data: formData,
                    dataType: 'json',
                    processData: false,
                    contentType: false,
                    cache: false,
                    async: false,
                    beforeSend:function() {
                        layer_load = layer.load(1, {shade: [0.1,'#000'], time: 500});
                    },
                    success: function(r) {
                        we_im_msg(r.data);
                        if (r.code == 200) {
                            addons_cache_delete();//删除插件缓存
                            setTimeout(function() {
                                window.location.href = r.url;
                                layer.close(layer_load);
                            },2000);
                        }
                    }
                });
            } else {
                return we_im_msg('仅支持ZIP和RAR文件格式');
            }
        } catch(err) {
            return we_im_msg('仅支持ZIP和RAR文件格式');
        }
    });

    /**
     * 更改插件状态
     */
    $('#choose-plugin-lists .btn').click(function() {
        var type = $(this).attr('data-type');
        if (type == 'all') {
            $('#plugin tr').show();
        } else if (type == 'yi') {
            $('#plugin tr#addons-1').show();
            $('#plugin tr#addons-0').hide();
        } else if (type == 'wei') {
            $('#plugin tr#addons-1').hide();
            $('#plugin tr#addons-0').show();
        }
        $(this).addClass('current').siblings().removeClass('current');
    });

    /**
     * 配置弹窗
     */
    $('.addonsTr .set-default').click(function() {
        var url = $(this).attr('data-url');
        layer.open({
            type: 2,
            title: '配置',
            skin: 'custom-top',
            area: ['1100px', '620px'],
            content: url
        });
    });

    /**
     * 提交配置
     */
    $('#myform #plugin_config').click(function() {
        if (checkedInputFunction($('#plugin_config'))) {
            if ($('.editor_array .editor_array_lists').length) {
                $.each($('.editor_array .editor_array_lists'), function (index, item) {
                    $(item).val($('#content-' + $(item).attr('data-key')).find('.w-e-text').html().replace('<p><br></p>',''));
                });
            }
            $.ajax({
                type: "post",
                url: IM_config.pluginConfig,
                data: $('#myform').serialize(),
                dataType: "json",
                success : function(r) {
                    we_im_msg(r.data);
                    // console.log('father is here');
                    setTimeout(function() {
                        parent.location.reload();
                    },2000);
                }
            });
        }
    });

    /**
     * 删除配置项
     */
    $('body').on('click','.form-inline .btn-remove', function() {
        $(this).parents('.form-inline').remove();
    });

    /**
     * 添加配置项
     */
    $('body').on('click','.fieldlist .btn-append', function() {
        var obj = $(this);
        var pobj = obj.parent();
        var html = pobj.prev().html();
        var index = parseInt(obj.attr('data-index'));
        html = html.replace(/\]\[\d+\]\[/g, "]["+index+"][");
        if ($('.editor_array .editor_array_lists').length) {
            html = html.replace(/content-\d+/g, "content-" + index);
            html = html.replace(/data-key="\d+"/g, 'data-key="'+index+'"');
        }
        pobj.before('<dd class="form-inline">' + html + '</dd>');
        clearForm(obj.parent().prev());
        obj.attr('data-index', index + 1);
        $('#content-'+index).find('.w-e-text').html("");
        if ($('.editor_array .editor_array_lists').length) {
            $.each($('.editor_array .editor_array_lists'), function (index, item) {
                $(item).val($('#content-' + $(item).attr('data-key')).find('.w-e-text').html().replace('<p><br></p>',''));
            });
            we_im_msg('新增的编辑器需要加载中...');
            setTimeout(function() {
                $.ajax({
                    type: "post",
                    url: IM_config.pluginConfig,
                    data: $('#myform').serialize(),
                    dataType: "json",
                    success : function(r) {
                        location.reload();
                    }
                });
            },1000);
        }
    });

    /**
     * 上传图片
     */
    $(".plugin-config .faupload").change(function() {
        var formData = new FormData();
        var input = $('#' + $(this).attr('data-input-id')).parents('.form-inline');
        formData.append('ajaxupimg', input.find('.hidden-input').get(0).files[0]);
        formData.append('user_id', IM_config.custs_id);
        formData.append('field', 'ajaxupimg');
        formData.append('user_type', 1);
        input.find('.hidden-input').val('');
        $.ajax({
            url:IM_config.uploadimg,
            method: 'post',
            data: formData,
            dataType: 'json',
            processData: false,
            contentType: false,
            cache: false,
            async: false,
            success: function(res) {
                if (res.errno == 0) {
                    input.find('input[type="text"]').val(res.data[0]);
                    input.find('.faupload-preview').html('<li class="col-xs-3">'+
                        '<a class="thumbnail">'+
                            '<i class="iconfont icon-iconset0127 btn-remove2"></i>'+
                            '<img src="'+res.data[0]+'" class="img-responsive">'+
                        '</a>'+
                    '</li>');
                } else {
                    we_im_msg(res.msg);
                }
            }
        });
    });

    /**
     * 删除图片
     */
    $('body').on('click','.thumbnail .btn-remove2', function() {
        var obj = $(this).parents('.faupload-preview');
        obj.siblings('input[type="text"]').val("");
        obj.html("");
    });
});

/**
 * 去除某个元素下的表单值
 * @param form
 * @returns {*}
 */
function clearForm(form) {
    $(':input', form).each(function() {
        var type = this.type;
        var tag = this.tagName.toLowerCase();
        if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = "";
        else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
    return form;
};

/**
 * 检测是否是json
 * @param str
 * @returns {boolean}
 */
function isJSON(str) {
    if (typeof str == 'string') {
        try {
            var obj = JSON.parse(str);
            if (typeof obj == 'object' && obj) {
                return true;
            } else {
                return false;
            }
        } catch (e) {
            return false;
        }
    }
}

/**
 * 字符串转换成对象
 * @param encodedString
 * @returns {string}
 */
function htmlspecialchars_decode(encodedString) {
    var textArea = document.createElement('textarea');
    textArea.innerHTML = encodedString;
    return textArea.value;
}


/**
 * 配置html编辑器
 */
function we_im_load_wangEditor(editor) {
    editor.config.menus = [
        'head',
        'bold',
        'fontSize',
        'fontName',
        'italic',
        'underline',
        'strikeThrough',
        'indent',
        'lineHeight',
        'foreColor',
        'backColor',
        'link',
        'list',
        'justify',
        'quote',
        'emoticon',
        'image',
        'table',
        'code',
        'splitLine',
        'undo',
        'redo',
    ];
    editor.config.uploadImgServer  = IM_config.uploadimg;
    editor.config.uploadImgMaxSize = 2 * 1024 * 1024;
    editor.config.uploadImgAccept  = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
    editor.config.uploadImgMaxLength = 5;
    editor.config.height = 150;
    editor.create();
}