<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Summernote富文本编辑器</title>
    <th:block th:include="include :: header('Summernote富文本编辑器')" />
    <th:block th:include="include :: summernote-css" />
    <style>
        .result-panel {
            border-left: 1px solid #e7eaec;
            height: 100%;
            padding: 15px;
            background-color: #f9f9f9;
        }
        .error-item {
            margin-bottom: 20px;
            padding: 15px;
            border-radius: 5px;
            background-color: #fff;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            /*border-left: 4px solid #ed5565;*/
        }
        .error-title {
            font-weight: bold;
            margin-bottom: 12px;
            font-size: 16px;
            color: #ed5565;
        }

        .common-error .error-title {
            color: #ed5565;
        }
        .political-error .error-title {
            color: #ed5565;
        }
        .suggestion-table {
            width: 100%;
            margin-bottom: 10px;
            border-collapse: collapse;
            word-break: break-all;
            word-wrap: break-word;
            white-space: normal;
        }
        .suggestion-table th, .suggestion-table td {
            padding: 8px;
            border: 1px solid #ddd;
            text-align: left;
        }
        .suggestion-table th {
            width: 80px;
            background-color: #f9f9f9;
        }
        .confidence {
            font-size: 12px;
            color: #888;
            margin-top: 5px;
        }
        .political-warning {
            font-weight: bold;
        }
        .error-highlight {
            background-color: #ffcccc;
            color: #ed5565;
            border-bottom: 1px dashed #ed5565;
            padding: 0 2px;
        }
        .error-content a {
            display: inline-block;
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            vertical-align: bottom;
        }

        /* 编辑器容器固定高度 */
        .ibox-content.no-padding {
            height: 650px; /* 固定高度 */
            display: flex;
            flex-direction: column;
            position: relative;
        }

        /* 编辑器区域自动滚动 - 针对Summernote内部结构 */
        .summernote {
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        /* Summernote编辑器包装器 */
        .note-editor {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden; /* 防止内部溢出 */
        }

        /* Summernote编辑区域 */
        .note-editable {
            flex: 1;
            overflow-y: auto !important; /* 强制显示滚动条 */
            min-height: 200px; /* 确保最小高度 */
        }

        /* 底部按钮固定在容器底部 */
        .editor-footer {
            position: sticky;
            bottom: 0;
            background-color: #fff;
            z-index: 100;
            padding: 15px;
            border-top: 1px solid #e7eaec;
            text-align: center;
        }

        /* 校对结果面板样式 */
        .col-sm-4 {
            position: fixed !important;
            right: 0px !important;
            z-index: 1000 !important;
            max-height: 80vh !important;
        }

        .col-sm-4 .ibox-content {
            max-height: calc(96vh - 50px) !important;
            overflow-y: auto !important;
        }

        /* 新增误报按钮样式 */
        .false-positive-btn {
            font-size: 12px;
            background-color: #f8f9fa;
            border: 1px solid #ddd;
            border-radius: 3px;
            color: #6c757d;
            cursor: pointer;
            transition: all 0.2s;
            display: block;
            text-align: center;
            padding: 4px 8px;
            margin-top: 8px;
        }
        .false-positive-btn:hover {
            background-color: #e9ecef;
            color: #495057;
        }
        .false-positive-btn.reported {
            color: #155724;
            border-color: #c3e6cb;
            cursor: default;
        }
        .false-positive-btn i {
            margin-right: 4px;
        }
        .error-actions {
            margin-bottom: 10px;
            text-align: right;
        }

        .error-type-divider {
            margin: 15px 0;
            border-top: 1px dashed #e7eaec;
        }

        /* 加载状态样式 */
        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }
    </style>
</head>
<body class="gray-bg">
<div class="wrapper wrapper-content">
    <div class="row">
        <div class="col-sm-8">
            <div class="ibox float-e-margins">
                <div class="ibox-content no-padding" style="position: relative;">
                    <!-- 加载遮罩层 -->
                    <div id="loadingOverlay" class="loading-overlay" style="display: none;">
                        <div style="text-align: center;">
                            <i class="fa fa-spinner fa-spin fa-3x fa-fw" style="color: #1ab394;"></i>
                            <p style="margin-top: 15px; font-size: 16px;">校对中，请稍候...</p>
                        </div>
                    </div>
                    <div class="summernote">
                    </div>
                    <div class="editor-footer">
                        <button id="checkBtn" class="btn btn-primary btn-sm">
                            <i class="fa fa-check"></i> 校对
                        </button>
                        <button id="resetBtn" class="btn btn-warning btn-sm">
                            <i class="fa fa-refresh"></i> 重置
                        </button>
                        <button id="clearBtn" class="btn btn-danger btn-sm">
                            <i class="fa fa-trash"></i> 清空
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-4">
            <div class="ibox float-e-margins fixed-result-panel">
                <div class="ibox-title">
                    <h5>校对结果</h5>
                </div>
                <div class="ibox-content result-panel">
                    <div id="checkResults">
                        <div class="text-muted" style="text-align: center; padding: 20px;">
                            <i class="fa fa-info-circle fa-2x"></i>
                            <p>点击"校对"按钮检查文档内容</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: summernote-js" />
<script>
    var initialContent = '';
    var prefix = ctx + "project/jiaodui";
    var wordResults = ctx + "project/wordresults";
    var currentErrors = [];
    var falsePositiveErrors = []; // 存储被标记为误报的错误

    $(document).ready(function () {
        $('.summernote').summernote({
            lang: 'zh-CN',
            height: 460, // 调整编辑器高度
            toolbar: [
                ['style', ['bold', 'italic', 'underline', 'clear']],
                ['font', ['strikethrough', 'superscript', 'subscript']],
                ['fontsize', ['fontsize']],
                ['color', ['color']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['height', ['height']],
                ['insert', ['picture', 'link', 'video', 'table', 'hr']],
                ['view', ['fullscreen', 'codeview', 'help']]
            ]
        });

        // 显示加载状态
        function showLoading() {
            $('#loadingOverlay').show();
            $('#checkBtn').prop('disabled', true);
        }

        // 隐藏加载状态
        function hideLoading() {
            $('#loadingOverlay').hide();
            $('#checkBtn').prop('disabled', false);
        }

        // 清除所有错误高亮
        function clearErrorHighlights() {
            $('.summernote').summernote('code', $('.summernote').summernote('code').replace(/<span class="error-highlight"[^>]*>(.*?)<\/span>/g, '$1'));
        }

        // 高亮显示错误词
        function highlightErrors(errors) {
            var content = $('.summernote').summernote('code');

            errors.forEach(function(error) {
                // 如果这个错误已被标记为误报，则不进行高亮
                if (falsePositiveErrors.includes(error.wrongWord + '-' + error.correctWord)) {
                    return;
                }

                var regex = new RegExp(error.wrongWord.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), 'g');
                content = content.replace(regex, '<span class="error-highlight" data-error-type="' + error.errorType + '">$&</span>');
            });
            content = content.replace(/<img\s+[^>]*src\s*=\s*["'][^"']*["'][^>]*>/gi, '');
            $('.summernote').summernote('code', content);
        }

        // 标记误报
        function markAsFalsePositive(id, wrongWord, correctWord, button) {
            // 添加到误报列表
            falsePositiveErrors.push(wrongWord + '-' + correctWord);

            // 更新按钮状态
            $(button).addClass('reported').html('<i class="fa fa-check"></i> 已标记').prop('disabled', true);

            // 重新高亮错误（这个误报将不再高亮）
            clearErrorHighlights();
            highlightErrors(currentErrors);

            var data = { "id": id, "res": 1 };
            $.get(wordResults + "/edit", data, function(result) {
                if (result.code == web_status.SUCCESS) {
                    let errorData = result.data;
                }
            });
        }

        // 使用事件委托处理误报按钮点击
        $(document).on('click', '.false-positive-btn', function(e) {
            e.preventDefault();

            // 如果按钮已被禁用，则不执行操作
            if ($(this).prop('disabled')) {
                return;
            }

            // 获取错误信息
            var wrongWord = $(this).data('wrong');
            var correctWord = $(this).data('correct');
            var id = $(this).data('id');
            // 调用标记函数
            markAsFalsePositive(id, wrongWord, correctWord, this);
        });

        $('#checkBtn').click(function() {
            clearErrorHighlights();
            var content = $('.summernote').summernote('code');

            // 检查内容是否为空或只有空白/换行
            if (content == '' || content == null || content == '<p><br></p>' || $.trim(content.replace(/<[^>]*>/g, '')) === '') {
                // 显示错误提示
                alert('请输入校对内容');
                return false;
            }

            // 显示加载状态
            showLoading();

            // 使用 POST 请求传输大文本
            var requestData = {
                content: content,
                title: "文本校对",
                type: "1"
            };

            $.ajax({
                url: prefix + "/jiaodui",
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(requestData),
                success: function(result) {
                    if (result.code == web_status.SUCCESS) {
                        let errorData = result.data;
                        currentErrors = errorData;

                        if (errorData.length > 0) {
                            highlightErrors(errorData);
                        }

                        let resultHtml = '';

                        // 按错误类型分组
                        const errorsByType = {};
                        errorData.forEach(error => {
                            if (!errorsByType[error.errorType]) {
                                errorsByType[error.errorType] = [];
                            }
                            errorsByType[error.errorType].push(error);
                        });

                        // 生成结果HTML
                        Object.keys(errorsByType).forEach(errorType => {
                            const errors = errorsByType[errorType];
                            let errorTypeHtml = '';

                            errors.forEach((error, index) => {
                                // 检查是否是误报
                                const isFalsePositive = falsePositiveErrors.includes(error.wrongWord + '-' + error.correctWord);

                                errorTypeHtml += `
									<div class="error-content">
										<h4>${index + 1}、${error.wrongWord}</h4>
										<table class="suggestion-table">
											<tr>
												<th>修改建议</th>
												<td>${error.correctWord}</td>
											</tr>
											${error.source ? `<tr><th>参考依据</th><td>${error.source}</td></tr>` : ''}
											${error.confidence ? `<tr><th>置信度</th><td>${error.confidence}</td></tr>` : ''}
										</table>
										<div class="error-actions">
											<button class="false-positive-btn" data-id="${error.id}" data-wrong="${error.wrongWord}" data-correct="${error.correctWord}" ${isFalsePositive ? 'disabled' : ''}>
												<i class="fa ${isFalsePositive ? 'fa-check' : 'fa-flag'}"></i> ${isFalsePositive ? '已标记' : '误报'}
											</button>
										</div>
									</div>
								`;
                            });

                            resultHtml += `
								<div class="error-item">
									<div class="error-title">${errorType}（${errors.length}）</div>
									${errorTypeHtml}
								</div>
								<div class="error-type-divider"></div>
							`;
                        });

                        if (errorData.length === 0) {
                            resultHtml = `
								<div class="text-muted" style="text-align: center; padding: 20px;">
									<i class="fa fa-check-circle fa-2x" style="color:#1ab394"></i>
									<p>未发现需要修改的内容</p>
								</div>
							`;
                        } else {
                            // 移除最后一个分隔线
                            resultHtml = resultHtml.replace(/<div class="error-type-divider"><\/div>$/, '');
                        }

                        $('#checkResults').html(resultHtml);
                    } else {
                        $.modal.alertError(result.msg);
                    }
                },
                error: function(xhr, status, error) {
                    var errorMsg = '请求失败: ';
                    if (xhr.status === 413) {
                        errorMsg = '文本内容过大，请减少内容后重试';
                    } else if (xhr.status === 0) {
                        errorMsg = '网络连接失败，请检查网络后重试';
                    } else {
                        errorMsg += error;
                    }
                    $.modal.alertError(errorMsg);
                },
                complete: function() {
                    hideLoading();
                }
            });
        });

        $('#resetBtn').click(function() {
            clearErrorHighlights();
            $('.summernote').summernote('code', initialContent);
            $('#checkResults').html('<div class="text-muted" style="text-align: center; padding: 20px;"><i class="fa fa-info-circle fa-2x"></i><p>内容已重置，请重新校对</p></div>');
            toastr.success('内容已重置为初始状态');
            currentErrors = [];
            // 重置时不清除误报列表，保持用户的选择
        });

        $('#clearBtn').click(function() {
            if(confirm('确定要清空编辑器内容吗？')) {
                clearErrorHighlights();
                $('.summernote').summernote('reset');
                $('#checkResults').html('<div class="text-muted" style="text-align: center; padding: 20px;"><i class="fa fa-info-circle fa-2x"></i><p>内容已清空，请重新校对</p></div>');
                toastr.info('编辑器内容已清空');
                currentErrors = [];
                // 清空时不清除误报列表，保持用户的选择
            }
        });
    });
</script>
</body>
</html>