<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>数据管理</title>
    <link rel="stylesheet" href="{{ asset('CmsProUi/component/pear/css/pear.css') }}">
    <link rel="stylesheet" href="{{ asset('CmsProUi/font-awesome/4.7.0/css/font-awesome.min.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/admin.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/variables.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/reset.css') }}">
</head>
<body class="pear-container">
    <div class="layui-row">
        <div class="layui-card">
            <div class="layui-card-body">
                <table id="tableList" lay-filter="tableList"></table>
            </div>
        </div>
    </div>

    @verbatim
    <script type="text/html" id="table-toolbar">
        <button class="layui-btn layui-btn-sm" lay-event="Backup">
            <i class="fa fa-cubes"></i> 全量备份
        </button>
        <button class="layui-btn layui-btn-sm" lay-event="Recover">
            <i class="fa fa-cube"></i> 全量恢复
        </button>
        <button class="layui-btn layui-bg-orange layui-btn-sm" lay-event="Advanced" style="position:absolute!important;right:100px;top:10px;">
            <i class="layui-icon layui-icon-util"></i> 高级模式
        </button>
    </script>

    <script type="text/html" id="row-operate">
        <button class="layui-btn layui-btn-xs" lay-event="Backup">备份</button>
        <button class="layui-btn layui-btn-xs" lay-event="Recover">恢复</button>
        <button class="layui-btn layui-btn-xs" lay-event="Optimize">优化</button>
    </script>
    @endverbatim

    <script src="{{ asset('CmsProUi/component/layui/layui.js') }}"></script>
    <script src="{{ asset('CmsProUi/component/pear/pear.js') }}"></script>
    <script>
        layui.use(['table', 'form', 'jquery'], function() {
            var table = layui.table;
            var form = layui.form;
            var $ = layui.jquery;

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                statusCode: {
                    401: function() {
                        layer.msg('登录已过期，请重新登录', {icon: 2, time: 1500}, function() {
                            window.location.href = '/admin/login?redirect=' + encodeURIComponent(window.location.pathname + window.location.search);
                        });
                    }
                }
            });

            var API = '/api/admin/database';

            table.render({
                elem: '#tableList',
                url: API + '/list',
                page: false,
                cols: [[
                    { field: 'Name', title: '数据表', sort: true, width: 300 },
                    { field: 'Comment', title: '备注' },
                    { field: 'Rows', title: '行数', width: 80, align: 'center' },
                    { field: 'Index_length', title: '大小', width: 100, align: 'center', templet: function(d) { return formatSize(d.Index_length); } },
                    { field: 'Data_free', title: '冗余', width: 100, align: 'center', templet: function(d) { return formatSize(d.Data_free); } },
                    { title: '操作', toolbar: '#row-operate', align: 'center', width: 200 }
                ]],
                toolbar: '#table-toolbar',
                defaultToolbar: [{
                    title: '刷新',
                    layEvent: 'refresh',
                    icon: 'layui-icon-refresh',
                }],
                parseData: function(res) {
                    return {
                        "code": res.code,
                        "msg": res.message,
                        "data": res.data || []
                    };
                }
            });

            table.on('toolbar(tableList)', function(obj) {
                if (obj.event === 'Backup') {
                    allBackup();
                } else if (obj.event === 'Recover') {
                    allRecover();
                } else if (obj.event === 'Advanced') {
                    advancedMode();
                } else if (obj.event === 'refresh') {
                    table.reload('tableList');
                }
            });

            table.on('tool(tableList)', function(obj) {
                if (obj.event === 'Backup') {
                    backupTable(obj.data.Name);
                } else if (obj.event === 'Recover') {
                    recoverTable(obj.data.Name);
                } else if (obj.event === 'Optimize') {
                    optimizeTable(obj.data.Name);
                }
            });

            function allBackup() {
                showBackupDialog('全量备份', function(volumeSize) {
                    var loadIdx = layer.load();
                    $.ajax({
                        url: API + '/backup',
                        type: 'POST',
                        data: { volume_size: volumeSize },
                        dataType: 'json',
                        success: function(res) {
                            layer.close(loadIdx);
                            if (res.code === 0) {
                                layer.msg(res.message, { icon: 1 });
                            } else {
                                layer.msg(res.message, { icon: 2 });
                            }
                        },
                        error: function() {
                            layer.close(loadIdx);
                            layer.msg('备份失败', { icon: 2 });
                        }
                    });
                });
            }

            function allRecover() {
                layer.open({
                    type: 2,
                    maxmin: true,
                    title: '恢复 - 全部数据表',
                    shade: 0.1,
                    area: ['80%', '80%'],
                    content: '/admin/database/recover/All'
                });
            }

            function advancedMode() {
                layer.confirm('高级模式可对数据表结构进行修改，操作需谨慎。是否进入？', {
                    icon: 3,
                    title: '操作提示',
                    btn: ['确定', '取消']
                }, function(index) {
                    layer.close(index);
                    window.open('/admin/database/advanced', '_blank');
                });
            }

            function backupTable(tableName) {
                showBackupDialog('备份「' + tableName + '」', function(volumeSize) {
                    var loadIdx = layer.load();
                    $.ajax({
                        url: API + '/backup',
                        type: 'POST',
                        data: { table: tableName, volume_size: volumeSize },
                        dataType: 'json',
                        success: function(res) {
                            layer.close(loadIdx);
                            if (res.code === 0) {
                                layer.msg(res.message, { icon: 1 });
                            } else {
                                layer.msg(res.message, { icon: 2 });
                            }
                        },
                        error: function() {
                            layer.close(loadIdx);
                            layer.msg('备份失败', { icon: 2 });
                        }
                    });
                });
            }

            function showBackupDialog(title, callback) {
                layer.open({
                    type: 1,
                    title: title,
                    area: ['460px', 'auto'],
                    content: '<div style="padding:20px;">'
                        + '<div style="margin-bottom:16px;font-size:13px;color:#666;">请设置分卷大小后开始备份</div>'
                        + '<div class="layui-form-item" style="margin-bottom:16px;">'
                        + '<label style="font-size:13px;color:#333;display:block;margin-bottom:6px;">分卷大小（MB）</label>'
                        + '<input type="number" id="dlgVolumeSize" class="layui-input" value="2" min="1" max="100" style="width:120px;">'
                        + '<div style="font-size:12px;color:#999;margin-top:6px;line-height:1.6;">'
                        + '分卷越小单次操作越稳定；分卷越大效率越高。建议值：虚拟主机 1-5MB，云服务器 10-50MB。'
                        + '</div></div>'
                        + '<div style="text-align:right;padding-top:10px;border-top:1px solid #f0f0f0;">'
                        + '<button type="button" class="layui-btn layui-btn-primary" id="dlgBtnCancel">取消</button> '
                        + '<button type="button" class="layui-btn" id="dlgBtnConfirm"><i class="fa fa-database"></i> 开始备份</button>'
                        + '</div></div>',
                    success: function(layero) {
                        layero.find('#dlgBtnCancel').on('click', function() { layer.closeAll(); });
                        layero.find('#dlgBtnConfirm').on('click', function() {
                            var vs = parseInt(layero.find('#dlgVolumeSize').val()) || 2;
                            if (vs < 1) vs = 1;
                            if (vs > 100) vs = 100;
                            layer.closeAll();
                            if (callback) callback(vs);
                        });
                    }
                });
            }

            function recoverTable(tableName) {
                layer.open({
                    type: 2,
                    maxmin: true,
                    title: '恢复 - ' + tableName,
                    shade: 0.1,
                    area: ['80%', '80%'],
                    content: '/admin/database/recover/' + tableName
                });
            }

            function optimizeTable(tableName) {
                $.ajax({
                    url: API + '/optimize',
                    type: 'POST',
                    data: { table: tableName, _token: '{{ csrf_token() }}' },
                    dataType: 'json',
                    success: function(res) {
                        if (res.code === 0) {
                            layer.msg(res.message, { icon: 1 });
                            setTimeout(function() { table.reload('tableList'); }, 1000);
                        } else {
                            layer.msg(res.message, { icon: 2 });
                        }
                    }
                });
            }

            function formatSize(bytes) {
                if (!bytes || bytes === 0) return '0 B';
                var kb = bytes / 1024;
                var mb = kb / 1024;
                var gb = mb / 1024;
                if (gb >= 1) return gb.toFixed(2) + ' GB';
                if (mb >= 1) return mb.toFixed(2) + ' MB';
                if (kb >= 1) return kb.toFixed(2) + ' KB';
                return bytes + ' B';
            }
        });
    </script>
</body>
</html>
