/**
 * 选择开关
 *
 * @author CaiAoLin
 * @date 2017/10/23
 * @version
 */
(function($){
    $.fn.switchBtn = function(options){
        var defaults = {
            enableText: '开启',
            disableText: '禁止',
        };

        var opts = $.extend(defaults, options);
        var switchBtn = $(this);
        var status = switchBtn.data('status');
        status = parseInt(status);
        status = isNaN(status) ? 0 : status;
        var name = switchBtn.data('name');
        name = name === '' || name === undefined ? 'switch_btn' : name;
        var html = '';
        var inputHtml = '<input type="hidden" name="'+ name +'" value="'+ status +'" />';

        if (status > 0) {
            html += '<button class="btn btn-success btn-sm disabled="disabled">已'+ opts.enableText +'</button>' + inputHtml +
                '<button class="btn btn-outline-danger btn-sm">'+ opts.disableText +'</button>';
        } else {
            html += '<button class="btn btn-outline-success btn-sm">'+ opts.enableText +'</button>' + inputHtml +
                '<button class="btn btn-danger btn-sm disabled" disabled="disabled">已'+ opts.disableText +'</button>';
        }
        switchBtn.append(html);

        // 点击事件绑定
        switchBtn.on('click', 'button', function() {
            var currentStatus = $("input[name='"+ name +"']").val();
            if (currentStatus > 0) {
                // 切换为false的状态
                $(this).siblings("button").removeClass("btn-success").removeClass("disabled")
                    .addClass("btn-outline-success").removeAttr("disabled").text(opts.enableText);
                $(this).removeClass("btn-outline-danger").addClass("btn-danger").attr("disabled", "disabled")
                    .text("已" + opts.disableText);
                $("input[name='"+ name +"']").val(0);
                switchBtn.attr("data-status", 0);
            } else {
                // 切换为true的状态
                $(this).removeClass("btn-outline-success").addClass("btn-success").addClass("disabled")
                    .attr("disabled", "disabled").text("已" + opts.enableText);
                $(this).siblings("button").removeClass("btn-danger").removeClass("disabled")
                    .addClass("btn-outline-danger").removeAttr("disabled").text(opts.disableText);
                $("input[name='"+ name +"']").val(1);
                switchBtn.attr("data-status", 1);
            }
        });
    };
})(jQuery);
