<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-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') }}">
    <style>
    .log-tabs { margin-bottom: 15px; }
    .log-tab-item {
        display: inline-block;
        padding: 8px 20px;
        margin-right: 5px;
        cursor: pointer;
        border-radius: 4px 4px 0 0;
        background: #f0f0f0;
        color: #666;
        font-size: 14px;
        transition: all 0.3s;
    }
    .log-tab-item.active {
        background: #16b777;
        color: #fff;
    }
    .log-tab-item:hover { opacity: 0.8; }
    .stats-cards { display: flex; gap: 15px; margin-bottom: 20px; flex-wrap: wrap; }
    .stat-card {
        flex: 1;
        min-width: 200px;
        background: #fff;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    }
    .stat-card .stat-title { font-size: 14px; color: #666; margin-bottom: 10px; }
    .stat-card .stat-value { font-size: 28px; font-weight: bold; }
    .stat-card.error .stat-value { color: #cf1322; }
    .stat-card.warning .stat-value { color: #fa8c16; }
    .stat-card.info .stat-value { color: #1890ff; }
    .log-filter-bar {
        display: flex;
        gap: 10px;
        margin-bottom: 15px;
        align-items: center;
        flex-wrap: wrap;
    }
    .log-filter-bar .layui-input { width: 200px; }
    .log-filter-bar select { width: 150px; }
    .log-content-wrapper {
        background: #1e1e1e;
        border-radius: 4px;
        padding: 15px;
        max-height: 500px;
        overflow-y: auto;
        font-family: Consolas, Monaco, monospace;
        font-size: 12px;
        line-height: 1.6;
    }
    .log-line {
        padding: 3px 0;
        border-bottom: 1px solid #333;
        display: flex;
        flex-wrap: wrap;
    }
    .log-line:last-child { border-bottom: none; }
    .log-datetime { color: #888; margin-right: 12px; white-space: nowrap; }
    .log-level-badge {
        padding: 1px 8px;
        border-radius: 3px;
        margin-right: 12px;
        font-weight: bold;
        white-space: nowrap;
        font-size: 11px;
    }
    .level-debug { background: #666; color: #fff; }
    .level-info { background: #1890ff; color: #fff; }
    .level-notice { background: #52c41a; color: #fff; }
    .level-warning { background: #fa8c16; color: #fff; }
    .level-error { background: #f5222d; color: #fff; }
    .level-critical { background: #a8071a; color: #fff; }
    .level-alert { background: #722ed1; color: #fff; }
    .level-emergency { background: #eb2f96; color: #fff; }
    .log-text { color: #d4d4d4; word-break: break-all; flex: 1; }
    .log-empty { text-align: center; color: #666; padding: 40px; }
    .layui-tag-red { background: #cf1322; color: #fff; padding: 2px 8px; border-radius: 3px; font-size: 12px; }
    .layui-tag-orange { background: #fa8c16; color: #fff; padding: 2px 8px; border-radius: 3px; font-size: 12px; }
</style>
    @include('admin.partials.permission-script')
</head>
<body>
<div class="pear-container">
    <div class="layui-card">
        <div class="layui-card-body">
            <div class="log-tabs">
                <span class="log-tab-item active" data-tab="files">日志文件</span>
                <span class="log-tab-item" data-tab="stats">统计概览</span>
            </div>

            <div id="tab-files" class="tab-content">
                <table class="layui-hide" id="log-table" lay-filter="log-table"></table>
            </div>

            <div id="tab-stats" class="tab-content" style="display: none;">
                <div class="stats-cards">
                    <div class="stat-card error">
                        <div class="stat-title"><i class="fa fa-times-circle"></i> 总错误数（7天）</div>
                        <div class="stat-value" id="total-errors">0</div>
                    </div>
                    <div class="stat-card warning">
                        <div class="stat-title"><i class="fa fa-exclamation-triangle"></i> 总警告数（7天）</div>
                        <div class="stat-value" id="total-warnings">0</div>
                    </div>
                    <div class="stat-card info">
                        <div class="stat-title"><i class="fa fa-file"></i> 日志文件数</div>
                        <div class="stat-value" id="total-files">0</div>
                    </div>
                </div>

                <div class="layui-card">
                    <div class="layui-card-header">每日错误趋势</div>
                    <div class="layui-card-body">
                        <table class="layui-hide" id="stats-table" lay-filter="stats-table"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    @verbatim
    <script type="text/html" id="log-toolbar">
        <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="refresh">
            <i class="layui-icon layui-icon-refresh"></i> 刷新
        </button>
    </script>

    <script type="text/html" id="log-bar">
        <a class="layui-btn layui-btn-xs" lay-event="view">查看</a>
        <a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="download" data-permission="admin.log.download">下载</a>
        <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete" data-permission="admin.log.destroy">删除</a>
    </script>
    @endverbatim
</div>
<script src="{{ asset('CmsProUi/component/layui/layui.js') }}"></script>
<script src="{{ asset('CmsProUi/component/pear/pear.js') }}"></script>
<script>
    layui.use(['table', 'form', 'jquery', 'laypage', 'layer'], function() {
        var table = layui.table;
        var form = layui.form;
        var $ = layui.jquery;
        var laypage = layui.laypage;
        var layer = layui.layer;

        $.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 hidePermButtons = function() {
            $('td [data-permission]').each(function() {
                if (!window.hasPermission || !window.hasPermission($(this).data('permission'))) {
                    $(this).hide();
                }
            });
        };

        var currentLogFile = '';
        var logPagination = {
            current: 1,
            pageSize: 100,
            total: 0
        };
        var logFilter = {
            level: '',
            keyword: ''
        };

        table.render({
            elem: '#log-table',
            url: '/api/admin/logs',
            toolbar: '#log-toolbar',
            defaultToolbar: ['filter', 'print', 'exports'],
            cols: [[
                { field: 'name', title: '文件名', minWidth: 250 },
                { field: 'size', title: '大小', width: 100, align: 'center' },
                { field: 'modified', title: '修改时间', width: 180, align: 'center' },
                { fixed: 'right', title: '操作', width: 220, align: 'center', toolbar: '#log-bar' }
            ]],
            parseData: function(res) {
                return {
                    "code": res.code === 0 ? 0 : 1,
                    "msg": res.message || "",
                    "count": (res.data || []).length,
                    "data": res.data || []
                };
            },
            done: function() {
                hidePermButtons();
            },
            page: false
        });

        table.on('toolbar(log-table)', function(obj) {
            if (obj.event === 'refresh') {
                table.reload('log-table');
                loadStats();
            }
        });

        table.on('tool(log-table)', function(obj) {
            if (obj.event === 'view') {
                openLogViewer(obj.data.name);
            } else if (obj.event === 'download') {
                if (!window.hasPermission || !window.hasPermission('admin.log.download')) {
                    layer.msg('无操作权限', { icon: 2, time: 1000 });
                    return;
                }
                downloadLogFile(obj.data.name);
            } else if (obj.event === 'delete') {
                if (!window.hasPermission || !window.hasPermission('admin.log.destroy')) {
                    layer.msg('无操作权限', { icon: 2, time: 1000 });
                    return;
                }
                deleteLogFile(obj.data.name);
            }
        });

        $('.log-tab-item').on('click', function() {
            $('.log-tab-item').removeClass('active');
            $(this).addClass('active');
            var tab = $(this).data('tab');
            $('.tab-content').hide();
            $('#tab-' + tab).show();
            if (tab === 'stats') {
                loadStats();
            }
        });

        function buildViewerHtml() {
            return '<div class="layui-form" lay-filter="logViewerForm" style="padding: 15px 15px 0;">' +
                '<div class="layui-form-item">' +
                '<div class="layui-inline">' +
                '<label class="layui-form-label">级别</label>' +
                '<div class="layui-input-inline" style="width: 150px;">' +
                '<select id="log-level-filter" lay-filter="levelFilter">' +
                '<option value="">全部级别</option>' +
                '<option value="debug">Debug</option>' +
                '<option value="info">Info</option>' +
                '<option value="warning">Warning</option>' +
                '<option value="error">Error</option>' +
                '<option value="critical">Critical</option>' +
                '</select>' +
                '</div>' +
                '</div>' +
                '<div class="layui-inline">' +
                '<div class="layui-input-inline" style="width: 200px;">' +
                '<input type="text" id="log-keyword" name="keyword" placeholder="搜索关键词" class="layui-input">' +
                '</div>' +
                '</div>' +
                '<div class="layui-inline">' +
                '<button type="button" class="layui-btn layui-btn-sm layui-btn-normal" id="btn-log-search"><i class="layui-icon layui-icon-search"></i> 搜索</button>' +
                '<button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="btn-log-reset"><i class="layui-icon layui-icon-refresh"></i> 重置</button>' +
                '</div>' +
                '<div class="layui-inline" style="float: right;">' +
                '<button type="button" class="layui-btn layui-btn-sm layui-btn-danger" id="btn-clear-log"><i class="layui-icon layui-icon-delete"></i> 清空日志</button>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '<div style="padding: 0 15px;">' +
                '<div id="log-content-wrapper" class="log-content-wrapper"><div class="log-empty">加载中...</div></div>' +
                '<div id="log-pagination" style="margin-top: 15px; text-align: center;"></div>' +
                '</div>';
        }

        window.openLogViewer = function(filename) {
            currentLogFile = filename;
            logPagination.current = 1;
            logFilter.level = '';
            logFilter.keyword = '';

            layer.open({
                type: 1,
                title: '日志内容 - ' + filename,
                area: ['90%', '726px'],
                maxmin: true,
                shadeClose: false,
                content: buildViewerHtml(),
                success: function(layero, index) {
                    form.render('select');

                    layero.find('#btn-log-search').on('click', function() {
                        logFilter.level = layero.find('#log-level-filter').val();
                        logFilter.keyword = layero.find('#log-keyword').val();
                        logPagination.current = 1;
                        loadLogContent();
                    });

                    layero.find('#btn-log-reset').on('click', function() {
                        logFilter.level = '';
                        logFilter.keyword = '';
                        layero.find('#log-level-filter').val('');
                        layero.find('#log-keyword').val('');
                        form.render('select');
                        logPagination.current = 1;
                        loadLogContent();
                    });

                    layero.find('#btn-clear-log').on('click', function() {
                        if (!window.hasPermission || !window.hasPermission('admin.log.clear')) {
                            layer.msg('无操作权限', { icon: 2, time: 1000 });
                            return;
                        }
                        clearLogFile();
                    });

                    form.on('select(levelFilter)', function(data) {
                        logFilter.level = data.value;
                    });

                    loadLogContent();
                }
            });
        };

        window.loadLogContent = function() {
            $('#log-content-wrapper').html('<div class="log-empty">加载中...</div>');

            $.ajax({
                url: '/api/admin/logs/read',
                type: 'GET',
                data: {
                    filename: currentLogFile,
                    page: logPagination.current,
                    page_size: logPagination.pageSize,
                    level: logFilter.level,
                    keyword: logFilter.keyword
                },
                dataType: 'json',
                success: function(res) {
                    if (res.code === 0) {
                        renderLogContent(res.data || []);
                        renderLogPagination(res.meta && res.meta.total ? res.meta.total : 0);
                    } else {
                        $('#log-content-wrapper').html('<div class="log-empty">' + (res.message || '加载失败') + '</div>');
                        $('#log-pagination').html('');
                    }
                },
                error: function() {
                    $('#log-content-wrapper').html('<div class="log-empty">请求失败</div>');
                    $('#log-pagination').html('');
                }
            });
        };

        window.renderLogContent = function(lines) {
            if (!lines || lines.length === 0) {
                $('#log-content-wrapper').html('<div class="log-empty">暂无日志内容</div>');
                return;
            }

            var html = '';
            for (var i = 0; i < lines.length; i++) {
                var line = lines[i];
                html += '<div class="log-line">';
                html += '<span class="log-datetime">' + (line.datetime || '') + '</span>';
                html += '<span class="log-level-badge level-' + (line.level || 'info') + '">' + (line.level || 'INFO').toUpperCase() + '</span>';
                html += '<span class="log-text">' + escapeHtml(line.content || '') + '</span>';
                html += '</div>';
            }
            $('#log-content-wrapper').html(html);
            $('#log-content-wrapper').scrollTop(0);
        };

        window.renderLogPagination = function(total) {
            logPagination.total = total;
            if (total <= logPagination.pageSize) {
                $('#log-pagination').html('');
                return;
            }

            laypage.render({
                elem: 'log-pagination',
                count: total,
                limit: logPagination.pageSize,
                curr: logPagination.current,
                jump: function(obj, first) {
                    if (!first) {
                        logPagination.current = obj.curr;
                        loadLogContent();
                    }
                },
                layout: ['count', 'prev', 'page', 'next'],
                theme: '#16b777'
            });
        };

        window.downloadLogFile = function(filename) {
            var url = '/api/admin/logs/download?filename=' + encodeURIComponent(filename);
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.setRequestHeader('X-CSRF-TOKEN', '{{ csrf_token() }}');
            xhr.responseType = 'blob';
            xhr.onload = function() {
                if (xhr.status === 401) {
                    layer.msg('登录已过期，请重新登录', {icon: 2, time: 1500}, function() {
                        window.location.href = '/admin/login?redirect=' + encodeURIComponent(window.location.pathname + window.location.search);
                    });
                    return;
                }
                if (xhr.status === 200) {
                    var blob = xhr.response;
                    var link = document.createElement('a');
                    link.href = window.URL.createObjectURL(blob);
                    link.download = filename;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    window.URL.revokeObjectURL(link.href);
                    layer.msg('下载成功', { icon: 1, time: 1000 });
                } else {
                    layer.msg('下载失败', { icon: 2, time: 1500 });
                }
            };
            xhr.onerror = function() {
                layer.msg('网络错误，下载失败', { icon: 2, time: 1500 });
            };
            xhr.send();
        };

        window.deleteLogFile = function(filename) {
            layer.confirm('确定要删除日志文件 "' + filename + '" 吗？此操作不可恢复。', {
                icon: 3,
                title: '确认删除',
                btn: ['确定', '取消']
            }, function(index) {
                layer.close(index);
                var loadingIdx = layer.load(2);
                $.ajax({
                    url: '/api/admin/logs/destroy?filename=' + encodeURIComponent(filename),
                    type: 'DELETE',
                    dataType: 'json',
                    success: function(res) {
                        layer.close(loadingIdx);
                        if (res.code === 0) {
                            layer.msg('删除成功', { icon: 1, time: 1000 }, function() {
                                table.reload('log-table');
                                loadStats();
                            });
                        } else {
                            layer.msg(res.message || '删除失败', { icon: 2, time: 2000 });
                        }
                    },
                    error: function() {
                        layer.close(loadingIdx);
                        layer.msg('请求失败', { icon: 2, time: 2000 });
                    }
                });
            });
        };

        window.clearLogFile = function() {
            if (!currentLogFile) return;

            layer.confirm('确定要清空日志文件 "' + currentLogFile + '" 的内容吗？此操作不可恢复。', {
                icon: 3,
                title: '确认清空',
                btn: ['确定', '取消']
            }, function(index) {
                layer.close(index);
                var loadingIdx = layer.load(2);
                $.ajax({
                    url: '/api/admin/logs/clear',
                    type: 'POST',
                    data: { filename: currentLogFile },
                    dataType: 'json',
                    success: function(res) {
                        layer.close(loadingIdx);
                        if (res.code === 0) {
                            layer.msg('清空成功', { icon: 1, time: 1000 }, function() {
                                logPagination.current = 1;
                                loadLogContent();
                                table.reload('log-table');
                            });
                        } else {
                            layer.msg(res.message || '清空失败', { icon: 2, time: 2000 });
                        }
                    },
                    error: function() {
                        layer.close(loadingIdx);
                        layer.msg('请求失败', { icon: 2, time: 2000 });
                    }
                });
            });
        };

        window.loadStats = function() {
            $.ajax({
                url: '/api/admin/logs/stats?days=7',
                type: 'GET',
                dataType: 'json',
                success: function(res) {
                    if (res.code === 0 && res.data) {
                        var stats = res.data;
                        $('#total-errors').text(stats.total_errors || 0);
                        $('#total-warnings').text(stats.total_warnings || 0);

                        $.ajax({
                            url: '/api/admin/logs',
                            type: 'GET',
                            dataType: 'json',
                            success: function(fileRes) {
                                if (fileRes.code === 0) {
                                    $('#total-files').text((fileRes.data || []).length);
                                }
                            }
                        });

                        if (stats.days && stats.days.length > 0) {
                            table.render({
                                elem: '#stats-table',
                                data: stats.days,
                                page: false,
                                cols: [[
                                    { field: 'date', title: '日期', minWidth: 120 },
                                    {
                                        field: 'errors',
                                        title: '错误数',
                                        width: 120,
                                        align: 'center',
                                        templet: function(d) {
                                            if (d.errors > 0) {
                                                return '<span class="layui-tag-red">' + d.errors + '</span>';
                                            }
                                            return d.errors;
                                        }
                                    },
                                    {
                                        field: 'warnings',
                                        title: '警告数',
                                        width: 120,
                                        align: 'center',
                                        templet: function(d) {
                                            if (d.warnings > 0) {
                                                return '<span class="layui-tag-orange">' + d.warnings + '</span>';
                                            }
                                            return d.warnings;
                                        }
                                    },
                                    { field: 'files', title: '文件数', width: 120, align: 'center' }
                                ]]
                            });
                        }
                    }
                },
                error: function() {
                    console.error('加载统计数据失败');
                }
            });
        };

        window.escapeHtml = function(text) {
            var div = document.createElement('div');
            div.appendChild(document.createTextNode(text));
            return div.innerHTML;
        };
    });
</script>
</body>
</html>
