{% extends "base.html" %}

{% block content %}
    <!-- 自定义操作按钮-->
    <div id="toolbar" class="form-inline pull-left">
        <div class="form-group">
            <select id="type" class="form-control selectpicker">
                <option value="" selected="selected">实例类型</option>
                <option value="master">MASTER</option>
                <option value="slave">SLAVE</option>
            </select>
        </div>
        <div class="form-group">
            <select id="db_type" class="form-control selectpicker">
                <option value="" selected="selected">数据库类型</option>
                {% for name, engine in engines.items %}
                    <option value="{{ name }}">{{ engine.name }}</option>
                {%  endfor %}
            </select>
        </div>
        <div class="form-group">
            <select id="tags" class="form-control selectpicker" data-live-search="true"
                    multiple data-selected-text-format="count > 2" data-none-selected-text="标签筛选">
                {% for tag in tags %}
                    <option value="{{ tag.id }}">{{ tag.tag_name }}</option>
                {% endfor %}
            </select>
        </div>
        <div class="form-group ">
            <button id="btn_add_master" type="button" class="btn btn-default"
                    onclick="window.open('/admin/sql/instance/add/')">
                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
                添加实例
            </button>
        </div>
    </div>
    <!-- 表格-->
    <div class="table-responsive">
        <table id="instance-list" data-toggle="table" class="table table-striped table-hover"
               style="table-layout:inherit;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
        </table>
    </div>
    <!-- 删除Binlog日志的模态框-->
    <div class="modal fade" id="deleteBinlog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">清理Binlog日志</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <input type="text" class="form-control" id="delete_instance_name" name="instance_name" readonly>
                    </div>
                    <div class="form-group">
                        <select id="binlog" name="binlog" data-live-search="true"
                                class="form-control selectpicker show-tick bs-select-hidden ">
                        </select>
                    </div>
                    <p class="text-danger">提示：该binlog前的所有binlog都会被删除！</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="cleanLogBtn">清理</button>
                </div>
            </div>
        </div>
    </div>
{% endblock content %}
{% block js %}
    {% load static %}
    <script src="{% static 'bootstrap-table/js/bootstrap-table-export.min.js' %}"></script>
    <script src="{% static 'bootstrap-table/js/tableExport.min.js' %}"></script>
    <script>
        //获取列表
        function instancelist() {
            //采取异步请求
            //初始化table
            $('#instance-list').bootstrapTable('destroy').bootstrapTable({
                escape: true,
                method: 'post',
                contentType: "application/x-www-form-urlencoded",
                url: "/instance/list/",
                striped: true,                      //是否显示行间隔色
                cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true,                   //是否显示分页（*）
                sortable: true,                     //是否启用排序
                sortOrder: "asc",                   //排序方式
                sortName: 'id',                   //排序字段
                sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
                pageSize: 20,                     //每页的记录行数（*）
                pageList: [20, 30, 50, 100],       //可供选择的每页的行数（*）
                showExport: true,                   //是否显示导出按钮
                exportOptions: {
                    fileName: 'instance'  //文件名称设置
                },
                search: true,                      //是否显示表格搜索
                strictSearch: false,                //是否全匹配搜索
                showColumns: true,                  //是否显示所有的列（选择显示的列）
                showRefresh: true,                  //是否显示刷新按钮
                minimumCountColumns: 2,             //最少允许的列数
                clickToSelect: true,                //是否启用点击选中行
                uniqueId: "id",                     //每一行的唯一标识，一般为主键列
                showToggle: true,                   //是否显示详细视图和列表视图的切换按钮
                cardView: false,                    //是否显示详细视图
                detailView: false,                  //是否显示父子表
                locale: 'zh-CN',                    //本地化
                toolbar: "#toolbar",               //指明自定义的toolbar
                queryParamsType: 'limit',
                //请求服务数据时所传参数
                queryParams:
                    function (params) {
                        return {
                            limit: params.limit,
                            offset: params.offset,
                            search: params.search,
                            type: $("#type").val(),
                            db_type: $("#db_type").val(),
                            tags: $("#tags").val(),
                            sortName: params.sort,
                            sortOrder: params.order
                        }
                    },
                columns: [
                    {
                        title: 'ID',
                        field: 'id',
                        sortable: true
                    }, {
                        title: '实例名称',
                        field: 'instance_name',
                        sortable: true,
                        formatter: function (value, row, index) {
                            return "<a target=\"_blank\" href=\"/admin/sql/instance/" + row.id + "/change/\">" + value + "</a>"
                        }
                    }, {
                        title: '实例类型',
                        field: 'type'
                    }, {
                        title: '数据库类型',
                        field: 'db_type',
                        sortable: true
                    }, {
                        title: 'HOST',
                        field: 'host',
                        sortable: true
                    }, {
                        title: 'PORT',
                        field: 'port'
                    }, {
                        title: 'USER',
                        field: 'user'
                    }, {
                        title: '操作',
                        field: '',
                        formatter: function (value, row, index) {
                            var btn_del_binLog = '';
                            var btn_user_manger = '';
                            if (row.db_type === 'mysql') {
                                btn_del_binLog = "<button class=\"btn btn-danger btn-xs\" instance_id=\"" + row.id + "\" + instance_name=\"" + row.instance_name + "\"+ onclick=\"del_binLog(this)" + "\">Binlog清理</button>\n"
                            }
                            var btn_test = "<button class=\"btn btn-warning btn-xs\" instance_id=\"" + row.id + "\" onclick=\"check_instance(this)" + "\">测试</button>\n";
                            return btn_user_manger + btn_del_binLog + btn_test
                        }
                    }],
                onLoadSuccess: function () {
                },
                onLoadError: onLoadErrorCallback,
                onSearch: function (e) {
                    //传搜索参数给服务器
                    queryParams(e)
                }
            });

        }

        // 检测邮件
        function check_instance(obj) {
            $.ajax({
                type: "post",
                url: "/check/instance/",
                dataType: "json",
                data: {
                    'instance_id': $(obj).attr("instance_id")
                },
                complete: function () {
                },
                success: function (data) {
                    if (data.status === 0) {
                        alert('连接成功')
                    } else {
                        alert(data.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(errorThrown);
                }
            });
        }

        //删除binlog
        function del_binLog(obj) {
            $("#delete_instance_name").val($(obj).attr("instance_name"));
            $("#binlog option").remove();
            $.ajax({
                type: "post",
                url: "/binlog/list/",
                dataType: "json",
                data: {
                    'instance_name': $(obj).attr("instance_name")
                },
                complete: function () {
                },
                success: function (data) {
                    if (data.status === 0) {
                        var result = data.data;
                        for (var i = 0; i < result.length; i++) {
                            var _html = "<option value='" + result[i]['Log_name'] + "'>" + result[i]['Log_name'] + " Size:" + result[i]['File_size'] + "</option>";
                            $("#binlog").append(_html);
                        }
                        $("#binlog").prepend('<option value="is-empty" disabled="" selected="selected">请选择Binlog:</option>');
                        $('#binlog').selectpicker('render');
                        $('#binlog').selectpicker('refresh');
                    } else {
                        alert(data.msg);
                    }
                }
            });
            $("#deleteBinlog").modal('show');
            $("#cleanLogBtn").unbind("click").click(function () {
                $.ajax({
                    type: "post",
                    url: "/binlog/del_log/",
                    dataType: "json",
                    data: {
                        instance_id: $(obj).attr("instance_id"),
                        binlog: $("#binlog").val()
                    },
                    complete: function () {
                    },
                    success: function (data) {
                        alert(data.msg);
                        window.location.reload(true);

                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(errorThrown);
                    }
                })
            });
        }

        //筛选变动自动刷新
        $("#type").change(function () {
            instancelist();
        });

        $("#db_type").change(function () {
            instancelist();
        });

        $("#tags").change(function () {
            instancelist();
        });

        //初始化数据
        $(document).ready(function () {
            instancelist()
        });
    </script>
{% endblock %}
