<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <title>错词快照</title>
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }

        .highlighted {
            background-color: #ff4d4f;
            color: white;
            border-radius: 3px;
            padding: 2px 4px;
        }

        .container {
            display: flex;
            max-width: 100%;
            margin: 0 auto;
            gap: 20px;
        }

        .error-snapshot {
            flex: 1;
            white-space: pre-wrap; /* 保持换行符 */
            font-family: monospace; /* 使用等宽字体显示原始文本 */
            background-color: white;
            border-radius: 4px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            font-size: 16px;
            padding: 24px;
            max-width: 100%;
            overflow: auto; /* 内容超过显示区域时出现滚动条 */
        }

        .error-word {
            position: relative;
            display: inline-block;
            border: 2px solid #ff4d4f;
            border-radius: 3px;
            background-color: #fff2f0;
            padding: 0 2px;
            margin: 0 1px;
            cursor: pointer;
        }
        .error-word {
            background-color: yellow; /* 高亮背景 */
            font-weight: bold; /* 可选：加粗字体 */
        }

        .correction-tip {
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%);
            background: red;
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            white-space: nowrap;
            margin-bottom: 5px;
            z-index: 100;
        }

        .correction-tip:after {
            content: "";
            position: absolute;
            top: 100%;
            left: 50%;
            margin-left: -5px;
            border-width: 5px;
            border-style: solid;
            border-color: red transparent transparent;
        }

        .stats-floating-box {
            position: fixed;
            top: 50%;
            right: 20px;
            transform: translateY(-50%);
            background-color: white;
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
            padding: 16px;
            width: 280px;
            z-index: 1000;
        }

        .control-buttons {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
        }

        .control-buttons button {
            padding: 8px 16px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .control-buttons button:hover {
            background-color: #0056b3;
        }

        .stats-floating-box h3 {
            margin-top: 0;
            font-size: 16px;
            text-align: center;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        .error-stats-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }

        .error-stats-table th,
        .error-stats-table td {
            padding: 6px 10px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        .error-stats-table th {
            background-color: #fafafa;
        }

        .error-stats-table tr:hover {
            background-color: #f5f5f5;
            cursor: pointer;
        }

        /* 新增源码高亮样式 */
        .source-view {
            white-space: pre-wrap;
            font-family: monospace;
            margin: 0;
        }
        .highlighted-source {
            background-color: yellow; /* 淡红底 */
            border: 2px solid #ff4d4f;     /* 红色边框 */
            border-radius: 3px;
            position: relative;
            display: inline-block;
            padding: 0 2px;
            margin: 0 1px;
            cursor: pointer;
            border-radius: 3px;
            font-weight: bold;
        }

        .highlighted-source .correction-tip {
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%);
            background: red;
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            white-space: nowrap;
            margin-bottom: 5px;
            z-index: 100;
        }



        @media print {
            .stats-floating-box {
                display: none;
            }

            .error-word {
                border-style: dashed;
            }

            .container {
                margin: 0;
                padding: 0;
            }
        }
    </style>
</head>
<body>

<!-- 右侧中部悬浮错词统计 -->
<div class="stats-floating-box no-print">
    <input name="id" id="dataIdInput" th:value="${dataid}" type="hidden">
    <!-- 控制按钮 -->
    <div class="control-buttons">
<!--        <button onclick="scrollToWord(currentErrorWord)">页面定位</button>-->
        <button onclick="fetchSnapshotData()">页面定位</button>
        <button onclick="showSourcePosition(currentErrorWord)">源码定位</button>
    </div>

    <h3>错词统计</h3>
    <table class="error-stats-table">
        <thead>
        <tr>
            <th>错词</th>
            <th>建议</th>
            <th>次数</th>
        </tr>
        </thead>
        <tbody id="errorStats"></tbody>
    </table>
</div>

<!-- 错词快照内容 -->
<div class="container">
    <div id="snapshotContainer" class="error-snapshot"></div>
</div>

<script>
    let currentErrorIndex = 0;
    let currentErrorWord = "";
    let sortedByOffset = [];
    let allErrors = [];
    let originalContent = "";

    async function fetchSnapshotData() {
        const dataid = document.getElementById("dataIdInput").value;
        const res = await fetch(`/project/sensitiveresult/markData/${dataid}`);
        const snapshotData = await res.json();
        renderSnapshot(snapshotData);
    }

    function renderSnapshot(snapshotData) {
        const container = document.getElementById("snapshotContainer");
        const statsTable = document.getElementById("errorStats");
        const content = snapshotData.content;
        const errors = snapshotData.errors;
        originalContent = content;
        allErrors = errors;

        let cuowu = "";
        let zhengque = "";

        let offset = 0;
        sortedByOffset = [];
        errors.forEach((e) => {
            let idx = content.indexOf(e.word, offset);
            while (idx !== -1) {
                sortedByOffset.push({ ...e, index: idx });
                offset = idx + e.word.length;
                idx = content.indexOf(e.word, offset);
            }
            offset = 0;
        });

        sortedByOffset.sort((a, b) => a.index - b.index);
        const used = new Set();
        let currentPos = 0;
        let html = "";

        sortedByOffset.forEach(({ word, correct, index }) => {
            zhengque = correct;
            cuowu = word;
            if (used.has(index)) return;
            html += content.slice(currentPos, index);
            html += `<span class="error-word" id="${word}" onclick="scrollToWord('${word}')"><span class="correction-tip">建议: ${correct}</span>${word}</span>`;
            currentPos = index + word.length;
            used.add(index);
        });
        html += content.slice(currentPos);
        container.innerHTML = html;

        // 统计错词
        const errorElements = document.querySelectorAll('.error-word');
        const pageErrorCount = {};
        errorElements.forEach(el => {
            const word = el.textContent;
            const errorInfo = allErrors.find(e => e.word === word);
            const correct = errorInfo ? errorInfo.correct : '无建议';
            if (pageErrorCount[word]) {
                pageErrorCount[word].count++;
            } else {
                pageErrorCount[word] = { correct, count: 1 };
            }
        });

        statsTable.innerHTML = Object.entries(pageErrorCount)
            .map(([word, { correct, count }]) => {
                return `<tr onclick="scrollToNextError()">
                    <td>${cuowu}</td>
                    <td>${zhengque}</td>
                    <td>${count}</td>
                </tr>`;
            })
            .join("");

        if (sortedByOffset.length > 0) {
            currentErrorWord = sortedByOffset[0].word;
            scrollToWord(currentErrorWord);
        }
    }

    function scrollToWord(word) {
        const element = document.getElementById(word);
        if (element) {
            element.scrollIntoView({ behavior: "smooth", block: "center" });
            const errors = document.querySelectorAll(".error-word");
            for (let i = 0; i < errors.length; i++) {
                if (errors[i].id === word) {
                    currentErrorIndex = i;
                    break;
                }
            }
        }
    }

    function scrollToNextError() {
        const errors = document.querySelectorAll(".error-word");
        if (errors.length === 0) return;
        currentErrorIndex = (currentErrorIndex + 1) % errors.length;
        const nextWord = errors[currentErrorIndex];
        nextWord.scrollIntoView({ behavior: "smooth", block: "center" });
    }

    // ✅ 源码定位：高亮错词 + 显示建议词提示
    function showSourcePosition(word) {
        const container = document.getElementById("snapshotContainer");
        let sourceHtml = originalContent;
        const targetErrors = sortedByOffset.filter(e => e.word === word);

        if (targetErrors.length === 0) return;

        // 生成错误位置信息，从后往前插入，避免下标错乱
        const inserts = targetErrors.map(e => ({
            start: e.index,
            end: e.index + e.word.length,
            word: e.word,
            correct: e.correct
        })).sort((a, b) => b.start - a.start); // 倒序插入

        inserts.forEach(({ start, end, word, correct }) => {
            const before = sourceHtml.slice(0, start);
            const middle = sourceHtml.slice(start, end);
            const after = sourceHtml.slice(end);
            //html += `<span class="error-word" id="${word}" onclick="scrollToWord('${word}')"><span class="correction-tip">建议: ${correct}</span>${word}</span>`;

            const replacement = `<span class="highlighted-source"><span class="correction-tip">建议: ${correct}</span>${middle}</span>`;
            sourceHtml = before + replacement + after;
        });

        // 转义 HTML
        sourceHtml = sourceHtml
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;");

        // 还原插入的 HTML（反转义）
        sourceHtml = sourceHtml
            .replace(/&lt;span class="highlighted-source"&gt;&lt;span class="correction-tip"&gt;建议: (.*?)&lt;\/span&gt;(.*?)&lt;\/span&gt;/g,
                (_match, correct, word) =>
                    `<span class="highlighted-source"><span class="correction-tip">建议: ${correct}</span>${word}</span>`);

        container.innerHTML = `<pre class="source-view">${sourceHtml}</pre>`;

        const first = container.querySelector(".highlighted-source");
        if (first) {
            first.scrollIntoView({ behavior: "smooth", block: "center" });
        }
    }


    window.onload = fetchSnapshotData;
</script>
</body>
</html>