{% extends "base.html" %}

{% block content %}
    <!-- 自定义操作按钮-->
    <div id="toolbar" class="form-inline pull-left">
        <div class="form-group">
            <select id="navStatus" class="form-control selectpicker">
                <option value="" selected="selected">状态</option>
                {% for status, status_display in status_list %}
                    <option value="{{ status }}">{{ status_display }}</option>
                {% endfor %}
            </select>
        </div>
        <div class="form-group">
            <select id="instance_id" class="form-control selectpicker"
                    data-live-search="true">
                <option value="" selected="selected">实例</option>
                {% for ins in instance %}
                    <option value="{{ ins.id }}">{{ ins.instance_name }}</option>
                {% endfor %}
            </select>
        </div>
        <div class="form-group">
            <select id="group_id" class="form-control selectpicker"
                    data-live-search="true">
                <option value="" selected="selected">组</option>
                {% for rgp in resource_group %}
                    <option value="{{ rgp.group_id }}">{{ rgp.group_name }}</option>
                {% endfor %}
            </select>
        </div>
        <div class='form-group'>
            <div id="reservation" class="form-control"
                 style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc; width: 100%">
                <i class="fa fa-calendar"></i>&nbsp;
                <span></span> <i class="fa fa-caret-down"></i>
            </div>
        </div>
        <div class="form-group ">
            <button id="btn_add" type="button" class="btn btn-default"
                    onclick="window.location.href='/submitsql/'">
                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
                提交SQL
            </button>
        </div>
    </div>
    <!-- 审核列表的表格-->
    <div class="table-responsive">
        <table id="sqlaudit-list" data-toggle="table" class="table table-striped table-hover"
               style="table-layout:inherit;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"></table>
    </div>
    <!-- 日志信息-->
    <div class="modal fade" id="logs">
        <div class="modal-dialog">
            <div class="modal-content message_align">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">×</span></button>
                    <h4 class="modal-title text-danger">工单日志</h4>
                </div>
                <div class="modal-body">
                    <div class="table-responsive">
                        <table id="log-list" data-toggle="table" class="table table-striped table-hover"
                               style="table-layout:inherit;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
                        </table>
                    </div>
                </div>
                <div class="modal-footer">
                </div>
            </div>
        </div>
    </div>
{% endblock content %}
{% block js %}
    {% load static %}
    <link href="{% static 'daterangepicker/css/daterangepicker.css' %}" rel="stylesheet" type="text/css"/>
    <script src="{% static 'daterangepicker/js/moment.min.js' %}"></script>
    <script src="{% static 'daterangepicker/js/daterangepicker.js' %}"></script>
    <script src="{% static 'bootstrap-table/js/bootstrap-table-export.min.js' %}"></script>
    <script src="{% static 'bootstrap-table/js/tableExport.min.js' %}"></script>
    <script>
        // 初始化时间控件
        $(function () {
            let start = moment().subtract(29, 'days');
            let end = moment();

            function cb(start, end) {
                if (start.isValid() && end.isValid() && start.dayOfYear()!=1) {
                    $('#reservation span').html(start.format('YYYY-MM-DD') + ' - ' + end.format('YYYY-MM-DD'));
                } else {
                    $('#reservation span').html('全部数据');
                }
            }

            $('#reservation').daterangepicker({
                startDate: start,
                endDate: end,
                showDropdowns: true,
                locale: {
                    format: "YYYY-MM-DD",// 显示格式
                    separator: " / ",// 两个日期之间的分割线
                    // 中文化
                    applyLabel: "确定",
                    cancelLabel: "取消",
                    fromLabel: "开始",
                    toLabel: "结束",
                    customRangeLabel: "自定义",
                    daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
                    monthNames: ["一月", "二月", "三月", "四月", "五月", "六", "七月", "八月", "九月", "十月", "十一月", "十二月"],
                    firstDay: 1
                },
                ranges: {
                    "全部": [moment({ year: 1970 }),moment()],
                    "今日": [moment().startOf('day'), moment()],
                    "昨日": [moment().subtract('days', 1).startOf('day'), moment().subtract('days', 1).endOf('day')],
                    "最近7日": [moment().subtract('days', 6), moment()],
                    "最近30日": [moment().subtract('days', 29), moment()],
                    "本月": [moment().startOf("month"), moment().endOf("month")],
                    "上个月": [moment().subtract(1, "month").startOf("month"), moment().subtract(1, "month").endOf("month")]
                }
            }, cb).on('apply.daterangepicker', function (ev, picker) {
                get_workflow_list()
            });
            cb(start, end);
        });

    </script>
    <script>
        //获取SQL工单列表
        function get_workflow_list() {
            //采取异步请求
            //初始化table
            $('#sqlaudit-list').bootstrapTable('destroy').bootstrapTable({
                escape: true,
                method: 'post',
                contentType: "application/x-www-form-urlencoded",
                url: "/sqlworkflow_list/",
                striped: true,                      //是否显示行间隔色
                cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true,                   //是否显示分页（*）
                sortable: true,                     //是否启用排序
                sortOrder: "asc",                   //排序方式
                sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
                pageSize: 20,                     //每页的记录行数（*）
                pageList: [20, 30, 50, 100],       //可供选择的每页的行数（*）
                showExport: true,                   //是否显示导出按钮
                exportOptions: {
                    fileName: 'sqlworkflow'  //文件名称设置
                },
                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) {
                        let start_date = $("#reservation").data('daterangepicker').startDate;
                        let end_date = $("#reservation").data('daterangepicker').endDate;
                        if (start_date.isValid() && end_date.isValid()) {
                            start_date = start_date.format('YYYY-MM-DD');
                            end_date = end_date.format('YYYY-MM-DD')
                        } else {
                            start_date = '';
                            end_date = ''
                        }
                        return {
                            limit: params.limit,
                            offset: params.offset,
                            navStatus: $("#navStatus").val(),
                            instance_id: $("#instance_id").val(),
                            group_id: $("#group_id").val(),
                            start_date: start_date,
                            end_date: end_date,
                            search: params.search
                        }
                    },
                columns: [{
                    title: '工单名称',
                    field: 'workflow_name',
                    formatter: function (value, row, index) {
                        var span = document.createElement('span');
                        span.setAttribute('title', value);
                        if (value.length > 20) {
                            span.innerHTML = "<a href=\"/detail/" + row.id + "/\">" + value.substr(0, 20) + '...';
                            +"</a>";
                        } else {
                            span.innerHTML = "<a href=\"/detail/" + row.id + "/\">" + value + "</a>";
                        }
                        return span.outerHTML;
                    }
                }, {
                    title: '工单完整名称',
                    field: 'workflow_name',
                    visible: false // 默认不显示
                }, {
                    title: '类型',
                    field: 'syntax_type',
                    formatter: function (value, row, index) {
                        if (String(value) === '0') {
                            return '其他'
                        } else if (String(value) === '1') {
                            return 'DDL'
                        } else if (String(value) === '2') {
                            return 'DML'
                        }
                    }
                }, {
                    title: '发起人',
                    field: 'engineer_display'
                }, {
                    title: '工单状态',
                    field: 'status',
                    formatter: function (value, row, index) {
                        return sqlworkflowStatus_formatter(value)
                    }
                }, {
                    title: '备份',
                    field: 'is_backup',
                    visible: true, // 默认显示
                    formatter: function (value, row, index) {
                        if (String(value) === 'true') {
                            return '是'
                        } else {
                            return '否'
                        }
                    }
                }, {
                    title: '发起时间',
                    field: 'create_time'
                }, {
                    title: '目标实例',
                    field: 'instance__instance_name'
                }, {
                    title: '数据库',
                    field: 'db_name'
                }, {
                    title: '组',
                    field: 'group_name'
                }, {
                    title: '操作',
                    field: 'operation',
                    formatter: function (value, row, index) {
                        return "<button class=\"btn btn-info btn-xs\" workflow_id=\"" + row.id + "\"\n" + "onclick=\"getLog(this)\" >操作日志\n" + "</button>"
                    }
                }],
                onLoadSuccess: function () {
                },
                onLoadError: onLoadErrorCallback,
                onSearch: function (e) {
                    //传搜索参数给服务器
                    queryParams(e)
                },
                responseHandler: function (res) {
                    //在ajax获取到数据，渲染表格之前，修改数据源
                    return res;
                }
            });

        }

        // 获取操作日志
        function getLog(obj) {
            var workflow_id = $(obj).attr("workflow_id");
            var workflow_type = 2;
            $.ajax({
                type: "post",
                url: "/workflow/log/",
                dataType: "json",
                data: {
                    workflow_id: workflow_id,
                    workflow_type: workflow_type,
                },
                complete: function () {
                },
                success: function (data) {
                    //初始化table
                    $('#logs').modal('show');
                    $('#log-list').bootstrapTable('destroy').bootstrapTable({
                        escape: true,
                        striped: true,                      //是否显示行间隔色
                        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                        pagination: false,                   //是否显示分页（*）
                        sortable: false,                     //是否启用排序
                        sortOrder: "asc",                   //排序方式
                        sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
                        pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
                        pageSize: 20,                     //每页的记录行数（*）
                        pageList: [20, 30, 50, 100],       //可供选择的每页的行数（*）
                        search: false,                      //是否显示表格搜索
                        strictSearch: false,                //是否全匹配搜索
                        showColumns: false,                  //是否显示所有的列（选择显示的列）
                        showRefresh: false,                  //是否显示刷新按钮
                        minimumCountColumns: 2,             //最少允许的列数
                        clickToSelect: false,                //是否启用点击选中行
                        uniqueId: "id",                     //每一行的唯一标识，一般为主键列
                        showToggle: false,                   //是否显示详细视图和列表视图的切换按钮
                        cardView: false,                    //是否显示详细视图
                        detailView: false,                  //是否显示父子表
                        locale: 'zh-CN',                    //本地化
                        data: data.rows,
                        columns: [{
                            title: '操作',
                            field: 'operation_type_desc'
                        }, {
                            title: '操作人',
                            field: 'operator_display'
                        }, {
                            title: '操作时间',
                            field: 'operation_time'
                        }, {
                            title: '操作信息',
                            field: 'operation_info'
                        }],
                        onLoadSuccess: function () {
                        },
                        onLoadError: onLoadErrorCallback
                    });
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(errorThrown);
                }
            })
        }

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

        $("#instance_id").change(function () {
            get_workflow_list();
        });

        $("#group_id").change(function () {
            get_workflow_list();
        });

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