<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('智能审校系统统计')" />
    <style>
        body {
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
            background-color: #f5f7fa;
            color: #333;
        }

        .statistics-container {
            padding: 20px;
            max-width: 1200px;
            margin: 0 auto;
        }

        .filter-card, .stat-card {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
            margin-bottom: 24px;
            overflow: hidden;
        }

        .filter-header, .stat-header {
            padding: 16px 24px;
            border-bottom: 1px solid #ebeef5;
            font-size: 16px;
            color: #303133;
            display: flex;
            align-items: center;
            background-color: #f8fafc;
        }

        .filter-header i, .stat-header i {
            margin-right: 10px;
            font-size: 18px;
            color: #409EFF;
        }

        .filter-body {
            padding: 20px;
            display: flex;
            align-items: center;
            flex-wrap: wrap;
        }

        .filter-item {
            margin-right: 20px;
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }

        .filter-item label {
            margin-right: 10px;
            color: #606266;
            font-size: 14px;
            white-space: nowrap;
        }

        .stat-body {
            padding: 20px;
        }

        .highlight-text {
            font-size: 16px;
            margin-bottom: 15px;
            line-height: 1.6;
        }

        .highlight-number {
            color: #409EFF;
            font-weight: bold;
            font-size: 20px;
            padding: 0 4px;
        }

        .highlight-error {
            color: #F56C6C;
            font-weight: bold;
            font-size: 20px;
            padding: 0 4px;
        }

        .highlight-percent {
            color: #E6A23C;
            font-weight: bold;
            font-size: 20px;
            padding: 0 4px;
        }

        .progress-bar {
            height: 12px;
            background-color: #ebeef5;
            border-radius: 6px;
            overflow: hidden;
            margin-top: 15px;
            width: 60%;
            max-width: 400px;
        }

        .progress {
            height: 100%;
            background: linear-gradient(to right, #409EFF, #67C23A);
            border-radius: 6px;
            transition: width 0.5s;
        }

        .summary-row {
            display: flex;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .summary-item {
            flex: 1;
            min-width: 150px;
            text-align: center;
            padding: 15px;
            border-radius: 6px;
            margin-right: 15px;
            margin-bottom: 15px;
            background-color: #f5f7fa;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }

        .summary-item:last-child {
            margin-right: 0;
        }

        .summary-item.success {
            background-color: #f0f9eb;
            border: 1px solid #e1f3d8;
        }

        .summary-item.warning {
            background-color: #fdf6ec;
            border: 1px solid #faecd8;
        }

        .summary-item.info {
            background-color: #f4f4f5;
            border: 1px solid #e9e9eb;
        }

        .summary-label {
            color: #909399;
            margin-bottom: 8px;
            font-size: 14px;
        }

        .summary-value {
            font-size: 20px;
            font-weight: bold;
            color: #303133;
        }

        .success .summary-value {
            color: #67C23A;
        }

        .warning .summary-value {
            color: #E6A23C;
        }

        .info .summary-value {
            color: #909399;
        }

        .chart-container {
            margin-top: 20px;
            height: 300px;
        }

        .table-container {
            margin-top: 20px;
        }

        .table-container table {
            width: 100%;
            border-collapse: collapse;
        }

        .table-container th, .table-container td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ebeef5;
        }

        .table-container th {
            background-color: #f8fafc;
            font-weight: 500;
            color: #606266;
        }

        .table-container tr:hover {
            background-color: #f5f7fa;
        }

        .tag {
            display: inline-block;
            padding: 0 10px;
            height: 32px;
            line-height: 30px;
            font-size: 12px;
            border-radius: 4px;
            box-sizing: border-box;
            white-space: nowrap;
            border: 1px solid;
        }

        .tag-danger {
            background-color: #fef0f0;
            border-color: #fde2e2;
            color: #f56c6c;
        }

        @media (max-width: 768px) {
            .filter-body {
                flex-direction: column;
                align-items: flex-start;
            }

            .filter-item {
                margin-right: 0;
                width: 100%;
                margin-bottom: 15px;
            }

            .summary-item {
                min-width: calc(50% - 15px);
                margin-right: 15px;
            }

            .summary-item:nth-child(2n) {
                margin-right: 0;
            }

            .progress-bar {
                width: 100%;
            }
        }

        @media (max-width: 480px) {
            .summary-item {
                min-width: 100%;
                margin-right: 0;
            }
        }
    </style>
</head>
<body class="gray-bg">
<div class="container-div statistics-container">
    <!-- 顶部筛选区域 -->
    <div class="filter-card">
        <div class="filter-header">
            <i class="fa fa-filter"></i>
            <span>筛选条件</span>
        </div>
        <div class="filter-body">
            <div class="filter-item">
                <label>站点：</label>
                <select class="form-control" name="sitename" style="width: 200px;">
                    <option value="">全部站点</option>
                    <option th:each="site : ${sites}" th:value="${site.sitename}" th:text="${site.sitename}"></option>
                </select>
            </div>
            <div class="filter-item">
                <label>时间范围：</label>
                <input type="text" class="time-input form-control" id="startTime" placeholder="开始时间" name="params[beginTime]"/>
                <span>  -  </span>
                <input type="text" class="time-input form-control" id="endTime" placeholder="结束时间" name="params[endTime]"/>            </div>
            <button type="button" class="btn btn-primary" onclick="search()" style="margin-left: auto;">
                <i class="fa fa-search"></i> 查询
            </button>
            <button type="button" class="btn btn-default" onclick="resetSearch()" style="margin-left: 10px;">
                <i class="fa fa-refresh"></i> 重置
            </button>
        </div>
    </div>

    <!-- 文本处理概况 -->
    <div class="stat-card">
        <div class="stat-header">
            <i class="fa fa-file-text"></i>
            <span>文本处理概况</span>
        </div>
        <div class="stat-body">
            <div class="highlight-text">
                智能审校系统共处理文本 <span class="highlight-number" id="totalTexts">0</span> 篇，
                其中检测出存在问题的文本共 <span class="highlight-error" id="problemTexts">0</span> 篇，
                占比 <span class="highlight-percent" id="problemRate">0%</span>
            </div>
            <!--<div class="progress-bar">
                <div class="progress" id="progressBar" style="width: 0%"></div>
            </div>-->
        </div>
    </div>

    <!-- 高频错词统计 -->
    <div class="stat-card">
        <div class="stat-header">
            <i class="fa fa-list"></i>
            <span>高频错词统计</span>
        </div>
        <div class="stat-body">
            <div class="table-container">
                <table>
                    <thead>
                    <tr>
                        <th>排名</th>
                        <th>错词</th>
                        <th>出现次数</th>
                    </tr>
                    </thead>
                    <tbody id="highFrequencyErrors">
                    <!-- 动态填充数据 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- 常见错误统计 -->
    <div class="stat-card">
        <div class="stat-header">
            <i class="fa fa-exclamation-triangle"></i>
            <span>常见错误统计</span>
        </div>
        <div class="stat-body">
            <div class="summary-row">
                <div class="summary-item">
                    <div class="summary-label">常见错误</div>
                    <div class="summary-value" id="commonTotal">0</div>
                </div>
                <div class="summary-item success">
                    <div class="summary-label">已修改</div>
                    <div class="summary-value" id="commonFixed">0</div>
                </div>
                <div class="summary-item warning">
                    <div class="summary-label">待处理</div>
                    <div class="summary-value" id="commonPending">0</div>
                </div>
                <div class="summary-item info">
                    <div class="summary-label">不必处理</div>
                    <div class="summary-value" id="commonIgnored">0</div>
                </div>
            </div>

            <div class="chart-container">
                <div id="commonErrorsChart" style="height: 100%;"></div>
            </div>
        </div>
    </div>
</div>

<th:block th:include="include :: footer" />

<!-- 引入必要的JS库 -->
<script th:src="@{/ajax/libs/report/echarts/echarts-all.min.js?v=4.2.1}"></script>
<!--<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@2.29.1/moment.min.js"></script>-->


<script th:inline="javascript">
    // 全局变量
    var prefix = ctx + "project/statistics";
    var commonErrorsChart = null;

    // 初始化函数
    $(function() {
        // 初始化图表
        initCharts();
        // 默认加载数据
        // 构建查询参数
        var params = {
            sitename: $("select[name='sitename']").val(), // 默认为空（全部站点）
            startTime: $('#startTime').val(),
            endTime: $('#endTime').val()
        };

        loadData(params);
    });

    // 初始化图表
    function initCharts() {
        commonErrorsChart = echarts.init(document.getElementById('commonErrorsChart'));

        var option = {
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                right: 10,
                top: 'center',
                data: ['字词类', '知识类', '政治类', '语法类', '格式类', '自定义类']
            },
            series: [{
                name: '错误类型',
                type: 'pie',
                radius: ['50%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '18',
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: [
                    {value: 0, name: '字词类'},
                    {value: 0, name: '知识类'},
                    {value: 0, name: '政治类'},
                    {value: 0, name: '语法类'},
                    {value: 0, name: '格式类'},
                    {value: 0, name: '自定义类'}
                ]
            }]
        };

        commonErrorsChart.setOption(option);

        // 窗口大小改变时重新调整图表大小
        $(window).resize(function() {
            commonErrorsChart.resize();
        });
    }

    // 加载数据
    function loadData(params) {

        $.ajax({
            url: prefix + "/getData",
            type: "POST",
            data: params,
            beforeSend: function() {
                $.blockUI({ message: '<h4>数据加载中...</h4>' });
            },
            success: function(res) {
                if (res.code == 0) {
                    updateUI(res.data);
                } else {
                    $.modal.alertError(res.msg);
                }
            },
            error: function() {
                $.modal.alertError("数据加载失败");
            },
            complete: function() {
                $.unblockUI();
            }
        });
    }

    // 更新UI
    function updateUI(data) {
        // 1. 文本处理概况
        $('#totalTexts').text(data.totalTexts || 0);
        $('#problemTexts').text(data.problemTexts || 0);

        var rate = 0;
        if (data.totalTexts > 0) {
            rate = (data.problemTexts / data.totalTexts * 100).toFixed(1);
        }
        $('#problemRate').text(rate + '%');

        // 高频错词表格
        var errorsHtml = '';
        if (data.highFrequencyErrors && data.highFrequencyErrors.length > 0) {
            data.highFrequencyErrors.forEach(function(item, index) {
                var safeWord = (item.word || '').replace(/'/g, "\\'");
                errorsHtml += '<tr>';
                errorsHtml += '<td>' + (index + 1) + '</td>';
                errorsHtml += '<td>' + (item.word || '') + '</td>';
                errorsHtml += '<td><span class="tag tag-danger" style="cursor: pointer" onclick="goToSensitiveResult(\'' + safeWord + '\')">' + (item.count || 0) + '</span></td>';
                errorsHtml += '</tr>';
            });
        } else {
            errorsHtml = '<tr><td colspan="3" style="text-align: center;">暂无数据</td></tr>';
        }
        $('#highFrequencyErrors').html(errorsHtml);

        // 3. 常见错误统计
        var commonErrors = data.commonErrors || {};
        $('#commonTotal').text(commonErrors.total || 0);
        $('#commonFixed').text(commonErrors.fixed || 0);
        $('#commonPending').text(commonErrors.pending || 0);
        $('#commonIgnored').text(commonErrors.ignored || 0);

        // 更新图表
        var option = {
            series: [{
                data: [
                    {value: commonErrors.wordCount || 0, name: '字词类'},
                    {value: commonErrors.knowledgeCount || 0, name: '知识类'},
                    {value: commonErrors.politicalCount || 0, name: '政治类'},
                    {value: commonErrors.grammarCount || 0, name: '语法类'},
                    {value: commonErrors.formatCount || 0, name: '格式类'},
                    {value: commonErrors.customCount || 0, name: '自定义类'}
                ]
            }]
        };
        commonErrorsChart.setOption(option);
    }

    // 搜索函数（点击查询按钮时触发）
    function search() {
        var params = {
            sitename: $("select[name='sitename']").val(),
            startTime: $('#startTime').val(),
            endTime: $('#endTime').val()
        };

        // 验证时间范围
        if (params.startTime && params.endTime && params.startTime > params.endTime) {
            $.modal.alertWarning("开始时间不能晚于结束时间");
            return;
        }

        loadData(params);
    }

    // 重置搜索条件
    function resetSearch() {
        // 重置站点选择
        $("select[name='sitename']").val('');
        $('#startTime').val(null);
        $('#endTime').val(null);

        // 重置后自动查询
        search();
    }

    // 跳转到敏感词结果页面（当前窗口）
    function goToSensitiveResult(word) {
        // 获取当前筛选条件
        var sitename = $("select[name='sitename']").val();
        var startTime = $('#startTime').val();
        var endTime = $('#endTime').val();

        // 构建URL参数对象（使用表单预期的参数名）
        var params = {
            'wrongWord': word || '',
            'sitename': sitename || '',
            'params[beginTime]': startTime || '',
            'params[endTime]': endTime || ''
        };

        // 过滤掉空参数
        var filteredParams = {};
        for (var key in params) {
            if (params[key] !== '') {
                filteredParams[key] = params[key];
            }
        }

        // 构建查询字符串
        var queryString = $.param(filteredParams);

        // 构建完整URL
        var url = ctx + 'project/sensitiveresult';
        if (queryString) {
            url += '?' + queryString;
        }

        console.log("跳转URL:", url); // 调试用，可以查看生成的URL
        $.modal.openTab("部门管理", url);
        // 在当前窗口跳转
        //window.location.href = url;
    }
</script>
</body>
</html>