<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<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;
        }

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

        .summary-item {
            flex: 1;
            min-width: 200px;
            text-align: center;
            padding: 20px;
            border-radius: 6px;
            margin-right: 15px;
            margin-bottom: 15px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #fff;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }

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

        .summary-item.total {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        .summary-item.avg {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }

        .summary-item.max {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }

        .summary-label {
            font-size: 16px;
            margin-bottom: 10px;
            opacity: 0.9;
        }

        .summary-value {
            font-size: 32px;
            font-weight: bold;
        }

        .summary-unit {
            font-size: 14px;
            opacity: 0.8;
            margin-left: 5px;
        }

        .table-container {
            margin-top: 10px;
            overflow-x: auto;
        }

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

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

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

        .table-container tr:hover {
            background-color: #f5f7fa;
            transition: all 0.3s;
        }

        .rank-badge {
            display: inline-block;
            width: 24px;
            height: 24px;
            line-height: 24px;
            text-align: center;
            background-color: #f5f7fa;
            border-radius: 50%;
            font-weight: bold;
            color: #606266;
        }

        .rank-badge.top-1 {
            background-color: #f56c6c;
            color: #fff;
        }

        .rank-badge.top-2 {
            background-color: #e6a23c;
            color: #fff;
        }

        .rank-badge.top-3 {
            background-color: #67c23a;
            color: #fff;
        }

        .count-tag {
            display: inline-block;
            padding: 5px 15px;
            background-color: #fef0f0;
            border: 1px solid #fde2e2;
            color: #f56c6c;
            border-radius: 20px;
            font-weight: bold;
            font-size: 14px;
        }

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

        .count-tag.medium {
            background-color: #fdf6ec;
            border-color: #faecd8;
            color: #e6a23c;
        }

        .count-tag.low {
            background-color: #f0f9eb;
            border-color: #e1f3d8;
            color: #67c23a;
        }

        .progress-bar-container {
            display: flex;
            align-items: center;
            width: 200px;
        }

        .progress-bar {
            height: 8px;
            background-color: #ebeef5;
            border-radius: 4px;
            overflow: hidden;
            flex: 1;
        }

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

        .progress-value {
            margin-left: 10px;
            font-size: 12px;
            color: #909399;
            min-width: 45px;
        }

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

        .loading-spinner {
            text-align: center;
            padding: 50px;
            color: #909399;
        }

        .loading-spinner i {
            font-size: 30px;
            animation: spin 1s linear infinite;
            margin-bottom: 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

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

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

            .summary-item {
                min-width: 100%;
                margin-right: 0;
            }

            .progress-bar-container {
                width: 120px;
            }
        }
    </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>
                <input type="text" class="time-input form-control" id="startTime" placeholder="开始时间" name="beginTime" autocomplete="off"/>
                <span style="margin: 0 10px;">—</span>
                <input type="text" class="time-input form-control" id="endTime" placeholder="结束时间" name="endTime" autocomplete="off"/>
            </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>
            <button type="button" class="btn btn-success" onclick="exportData()" style="margin-left: 10px;">
                <i class="fa fa-download"></i> 导出
            </button>
        </div>
    </div>

    <!-- 统计概览卡片 -->
    <div class="stat-card">
        <div class="stat-header">
            <i class="fa fa-pie-chart"></i>
            <span>统计概览</span>
        </div>
        <div class="stat-body">
            <div class="summary-row">
                <div class="summary-item total">
                    <div class="summary-label">总校对次数</div>
                    <div class="summary-value" id="totalCount">0</div>
                    <div class="summary-unit">次</div>
                </div>
                <div class="summary-item avg">
                    <div class="summary-label">平均校对次数</div>
                    <div class="summary-value" id="avgCount">0</div>
                    <div class="summary-unit">次/部门</div>
                </div>
                <div class="summary-item max">
                    <div class="summary-label">最高校对次数</div>
                    <div class="summary-value" id="maxCount">0</div>
                    <div class="summary-unit">次</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 部门校对次数排名 -->
    <div class="stat-card">
        <div class="stat-header">
            <i class="fa fa-building"></i>
            <span>部门校对次数排名</span>
        </div>
        <div class="stat-body">
            <!-- 加载动画 -->
            <div id="loadingSpinner" class="loading-spinner" style="display: none;">
                <i class="fa fa-spinner fa-spin"></i>
                <div>数据加载中...</div>
            </div>

            <!-- 数据表格 -->
            <div class="table-container">
                <table id="deptTable">
                    <thead>
                    <tr>
                        <th width="80">排名</th>
                        <th>部门名称</th>
                        <th width="150">校对次数</th>
                        <th width="250">占比</th>
                    </tr>
                    </thead>
                    <tbody id="deptProofreadStats">
                    <!-- 动态填充数据 -->
                    <tr>
                        <td colspan="4" style="text-align: center; color: #909399; padding: 50px;">
                            <i class="fa fa-database" style="font-size: 40px; display: block; margin-bottom: 10px;"></i>
                            暂无数据
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- 占比图表 -->
    <div class="stat-card">
        <div class="stat-header">
            <i class="fa fa-bar-chart"></i>
            <span>部门校对次数占比</span>
        </div>
        <div class="stat-body">
            <div class="chart-container">
                <div id="deptChart" style="height: 100%; width: 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 th:src="@{/ajax/libs/laydate/laydate.js}"></script>

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

    // 初始化函数
    $(function() {
        // 初始化日期选择器
        initDatePicker();
        // 设置默认时间范围为近一个月
        setDefaultTimeRange();
        // 初始化图表
        initChart();
        // 加载数据
        search();
    });

    // 初始化日期选择器
    function initDatePicker() {
        laydate.render({
            elem: '#startTime',
            type: 'date',
            format: 'yyyy-MM-dd',
            theme: '#409EFF'
        });

        laydate.render({
            elem: '#endTime',
            type: 'date',
            format: 'yyyy-MM-dd',
            theme: '#409EFF'
        });
    }

    // 设置默认时间范围为近一个月
    function setDefaultTimeRange() {
        var now = new Date();
        var endTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);

        // 计算一个月前的日期
        var startTime = new Date(now);
        startTime.setMonth(now.getMonth() - 1);
        startTime.setHours(0, 0, 0, 0);

        // 格式化日期为 YYYY-MM-DD 格式
        var formatDate = function(date) {
            var year = date.getFullYear();
            var month = (date.getMonth() + 1).toString().padStart(2, '0');
            var day = date.getDate().toString().padStart(2, '0');
            return year + '-' + month + '-' + day;
        };

        // 设置输入框的值
        $('#startTime').val(formatDate(startTime));
        $('#endTime').val(formatDate(endTime));
    }

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

        var option = {
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c}次 ({d}%)'
            },
            legend: {
                orient: 'vertical',
                right: 10,
                top: 'center',
                type: 'scroll',
                pageIconColor: '#409EFF',
                pageTextStyle: {
                    color: '#606266'
                }
            },
            series: [{
                name: '部门校对次数',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: false
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '14',
                        fontWeight: 'bold'
                    }
                },
                data: []
            }],
            noDataLoadingOption: {
                text: '暂无数据',
                effect: 'bubble',
                effectOption: {
                    effect: {
                        n: 0
                    }
                }
            }
        };

        deptChart.setOption(option);

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

    // 加载部门校对统计
    function loadDeptProofreadStats(params) {
        // 显示加载动画
        $('#loadingSpinner').show();
        $('#deptProofreadStats').html('');

        $.ajax({
            url: prefix + "/getDeptProofreadStats",
            type: "POST",
            data: params,
            beforeSend: function() {
                // 可以在这里添加额外的加载提示
            },
            success: function(res) {
                if (res.code == 0) {
                    updateDeptProofreadStats(res.data);
                    updateSummaryStats(res.data);
                    updateChart(res.data);
                } else {
                    $.modal.alertError(res.msg);
                    showNoData();
                }
            },
            error: function() {
                $.modal.alertError("加载部门校对统计失败");
                showNoData();
            },
            complete: function() {
                $('#loadingSpinner').hide();
            }
        });
    }

    // 显示无数据状态
    function showNoData() {
        var html = '<tr><td colspan="4" style="text-align: center; color: #909399; padding: 50px;">' +
            '<i class="fa fa-database" style="font-size: 40px; display: block; margin-bottom: 10px;"></i>' +
            '暂无数据</td></tr>';
        $('#deptProofreadStats').html(html);

        // 清空图表
        if (deptChart) {
            deptChart.setOption({
                series: [{
                    data: []
                }]
            });
        }
    }

    // 更新统计概览
    function updateSummaryStats(data) {
        if (!data || data.length === 0) {
            $('#totalCount').text('0');
            $('#avgCount').text('0');
            $('#maxCount').text('0');
            return;
        }

        var total = 0;
        var max = 0;

        data.forEach(function(item) {
            var count = parseInt(item.proofreadCount) || 0;
            total += count;
            if (count > max) {
                max = count;
            }
        });

        var avg = data.length > 0 ? Math.round(total / data.length) : 0;

        $('#totalCount').text(total);
        $('#avgCount').text(avg);
        $('#maxCount').text(max);

        // 添加动画效果
        $('.summary-value').each(function() {
            $(this).addClass('animated fadeIn');
        });
    }

    // 更新部门校对统计UI
    function updateDeptProofreadStats(data) {
        if (!data || data.length === 0) {
            showNoData();
            return;
        }

        var html = '';
        var total = 0;

        // 计算总数用于占比
        data.forEach(function(item) {
            total += parseInt(item.proofreadCount) || 0;
        });

        data.forEach(function(item, index) {
            var count = parseInt(item.proofreadCount) || 0;
            var percentage = total > 0 ? ((count / total) * 100).toFixed(1) : 0;

            // 根据排名设置不同的样式
            var rankClass = '';
            if (index === 0) rankClass = 'top-1';
            else if (index === 1) rankClass = 'top-2';
            else if (index === 2) rankClass = 'top-3';

            // 根据数量设置标签样式
            var tagClass = 'high';
            if (percentage < 5) tagClass = 'low';
            else if (percentage < 10) tagClass = 'medium';

            html += '<tr>';
            html += '<td><span class="rank-badge ' + rankClass + '">' + (index + 1) + '</span></td>';
            html += '<td><strong>' + (item.deptName || '') + '</strong></td>';
            html += '<td><span class="count-tag ' + tagClass + '">' + count + ' 次</span></td>';
            html += '<td>';
            html += '<div class="progress-bar-container">';
            html += '<div class="progress-bar"><div class="progress" style="width: ' + percentage + '%"></div></div>';
            html += '<span class="progress-value">' + percentage + '%</span>';
            html += '</div>';
            html += '</td>';
            html += '</tr>';
        });

        $('#deptProofreadStats').html(html);
    }

    // 更新图表
    function updateChart(data) {
        if (!data || data.length === 0 || !deptChart) {
            return;
        }

        var chartData = [];
        var otherCount = 0;
        var otherNames = [];

        // 如果部门太多，只显示前10个，其他的合并为"其他"
        if (data.length > 10) {
            for (var i = 0; i < data.length; i++) {
                if (i < 9) {
                    chartData.push({
                        name: data[i].deptName,
                        value: parseInt(data[i].proofreadCount) || 0
                    });
                } else {
                    otherCount += parseInt(data[i].proofreadCount) || 0;
                    otherNames.push(data[i].deptName);
                }
            }
            if (otherCount > 0) {
                chartData.push({
                    name: '其他(' + (data.length - 9) + '个部门)',
                    value: otherCount
                });
            }
        } else {
            data.forEach(function(item) {
                chartData.push({
                    name: item.deptName,
                    value: parseInt(item.proofreadCount) || 0
                });
            });
        }

        deptChart.setOption({
            series: [{
                data: chartData
            }]
        });
    }

    // 搜索函数
    function search() {
        var params = {
            beginTime: $('#startTime').val(),
            endTime: $('#endTime').val()
        };

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

        loadDeptProofreadStats(params);
    }

    // 重置搜索条件
    function resetSearch() {
        $('#startTime').val('');
        $('#endTime').val('');
        search();
    }

    // 导出数据
    function exportData() {
        var params = {
            beginTime: $('#startTime').val(),
            endTime: $('#endTime').val()
        };

        // 构建导出URL
        var url = prefix + "/exportDeptProofreadStats?" + $.param(params);

        // 弹出确认框
        $.modal.confirm("确定要导出数据吗？", function() {
            window.location.href = url;
        });
    }

    // 格式化日期
    function formatDate(date, format) {
        var o = {
            "M+": date.getMonth() + 1,
            "d+": date.getDate(),
            "h+": date.getHours(),
            "m+": date.getMinutes(),
            "s+": date.getSeconds(),
            "q+": Math.floor((date.getMonth() + 3) / 3),
            "S": date.getMilliseconds()
        };
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    }
</script>
</body>
</html>