<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>备份管理 - {{ $table }}</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-card">
        <div class="layui-card-body">
            <table id="backupList" lay-filter="backupList"></table>
        </div>
    </div>

    @verbatim
    <script type="text/html" id="backup-toolbar">
        <button class="layui-btn layui-btn-sm" lay-event="Backup">
            <i class="fa fa-cubes"></i> 备份
        </button>
        <button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="Delete">
            <i class="layui-icon layui-icon-delete"></i> 删除
        </button>
    </script>

    <script type="text/html" id="backup-operate">
        <button class="layui-btn layui-btn-sm" lay-event="Recover"><i class="fa fa-mail-reply"></i></button>
        <button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="remove"><i class="layui-icon layui-icon-delete"></i></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 $ = 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 tableName = '{{ $table }}';
            var API = '/api/admin/database';

            table.render({
                elem: '#backupList',
                url: API + '/' + tableName + '/backup-list',
                page: false,
                cols: [[
                    { type: 'checkbox' },
                    { title: '文件名', field: 'name' },
                    { title: '大小', field: 'size', width: 120, align: 'center', templet: function(d) { return formatSize(d.size); } },
                    { title: '时间', field: 'time', width: 180, align: 'center', templet: function(d) { return layui.util.toDateString(d.time * 1000, 'yyyy-MM-dd HH:mm:ss'); } },
                    { title: '操作', toolbar: '#backup-operate', align: 'center', width: 200 }
                ]],
                toolbar: '#backup-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(backupList)', function(obj) {
                if (obj.event === 'Backup') { doBackup(); }
                else if (obj.event === 'Delete') { batchDelete(); }
                else if (obj.event === 'refresh') { table.reload('backupList'); }
            });

            table.on('tool(backupList)', function(obj) {
                if (obj.event === 'Recover') { doRecover(obj.data.name); }
                else if (obj.event === 'remove') { deleteBackup(obj.data.name); }
            });

            function doBackup() {
                var loadIdx = layer.load();
                $.post(API + '/backup', { table: tableName === 'All' ? '' : tableName, _token: '{{ csrf_token() }}' }, function(res) {
                    layer.close(loadIdx);
                    if (res.code === 0) { layer.msg(res.message, {icon:1}); setTimeout(function(){table.reload('backupList');}, 500); }
                    else { layer.msg(res.message, {icon:2}); }
                });
            }

            function doRecover(filename) {
                layer.confirm('确定要恢复此备份数据吗？当前数据将被覆盖！', {
                    icon: 3, title: '操作提示', btn: ['确定', '取消']
                }, function(index) {
                    layer.close(index);
                    layer.msg('正在恢复中……', { icon: 16, shade: 0.01 });
                    $.post(API + '/recover-backup', { table: tableName, filename: filename, _token: '{{ csrf_token() }}' }, function(res) {
                        if (res.code === 0) { layer.msg(res.message, {icon:1}); }
                        else { layer.msg(res.message, {icon:2}); }
                    });
                });
            }

            function deleteBackup(filename) {
                layer.confirm('确定要删除此备份文件吗？', {
                    icon: 3, title: '操作提示', btn: ['确定', '取消']
                }, function(index) {
                    layer.close(index);
                    $.ajax({
                        url: API + '/delete-backup',
                        type: 'POST',
                        data: JSON.stringify({ table: tableName, filenames: [filename], _token: '{{ csrf_token() }}' }),
                        contentType: 'application/json',
                        headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
                        success: function(res) {
                            if (res.code === 0) { layer.msg(res.message, {icon:1}); table.reload('backupList'); }
                            else { layer.msg(res.message, {icon:2}); }
                        }
                    });
                });
            }

            function batchDelete() {
                var checkData = table.checkStatus('backupList').data;
                if (checkData.length === 0) { layer.msg('请选择要删除的备份', {icon:3}); return; }
                var filenames = checkData.map(function(d) { return d.name; });
                layer.confirm('确定要删除选中的 <b>' + filenames.length + '</b> 个备份文件吗？', {
                    icon: 3, title: '操作提示', btn: ['确定', '取消']
                }, function(index) {
                    layer.close(index);
                    $.ajax({
                        url: API + '/delete-backup',
                        type: 'POST',
                        data: JSON.stringify({ table: tableName, filenames: filenames, _token: '{{ csrf_token() }}' }),
                        contentType: 'application/json',
                        headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
                        success: function(res) {
                            if (res.code === 0) { layer.msg(res.message, {icon:1}); table.reload('backupList'); }
                            else { layer.msg(res.message, {icon:2}); }
                        }
                    });
                });
            }

            function formatSize(bytes) {
                if (!bytes || bytes === 0) return '0 B';
                var kb = bytes / 1024, mb = kb / 1024, 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>
