<template>
    <div class="read-over-contain">
        <div class="exercises-answer">
            <div class="exercises-answer-bg"></div>
            <div style="position: relative; z-index: 1">
                <div class="question-container">
                    <div class="question-stem-content">题干</div>
                    <div class="question-detail">
                        <p v-html="renderFormulas(exercisesData.question)"></p>
                        <div class="question-score">{{ exercisesData.score }}分</div>
                    </div>
                </div>
                <div class="question-container answer-container">
                    <div class="question-stem-content answer-stem-content">回答</div>
                    <div class="question-detail answer-detail" v-html="renderFormulas(exercisesData.answer)" v-if="exercisesData.answer"></div>
                    <div class="question-detail answer-detail" v-else>
                        暂无作答
                    </div>
                </div>
            </div>
        </div>
        <div class="exercises-read-over"
             v-loading="!analyzeData || Object.keys(analyzeData).length < 1"
             :element-loading-text="!analyzeData ? '无数据' : '分析中,请稍后'">
            <template v-if="analyzeData">
                <div class="score">
                    <span class="score-number">{{ analyzeData.score }}</span>分
                </div>
                <div class="type" :class="{ 'type-active': analyzeData.accepted }" @click="notyApply">应用</div>
                <div class="edit-btn" v-if="!analyzeData.accepted" @click="openEdit">
                    <i class="el-icon-edit"></i>
                    编辑
                </div>
                <div class="exercises-read-over-content">
                    <div class="list" v-for="(item, index) in analyzeData.jsonContent" :key="index">
                        <p class="title" v-if="item.title">{{ item.title }}</p>
                        <p class="content" v-html="renderFormulas(item.analysis)"></p>
                    </div>
                    <chat-tools type="error"
                                v-if="analyzeData"
                                :detail-data="analyzeData"
                                @on-reanswer="reanswer"></chat-tools>
                </div>
            </template>
        </div>

      <el-dialog :visible.sync="editVisible" width="600px" append-to-body custom-class="read-over-edit-dialog"
                 :close-on-click-modal="false" @opened="onDialogOpened">
            <div slot="title" class="edit-dialog-header">
                <div class="edit-dialog-title">
                    <i class="el-icon-edit-outline"></i>
                    编辑批阅解析
                </div>
            </div>
            <div class="edit-dialog-body">
                <div class="edit-score-field">
                    <span class="edit-score-label">得分</span>
                    <el-input-number
                        v-model="editScore"
                        :min="0"
                        :max="exercisesData.score"
                        :precision="1"
                        :step="0.5"
                        size="small"
                    />
                    <span class="edit-score-max">/ {{ exercisesData.score }} 分</span>
                </div>
                <span class="edit-label">批阅解析</span>
                <div class="edit-item" v-for="(item, index) in editList" :key="index">
                    <rich-input
                        :value="item.analysisHtml"
                        placeholder="请输入解析内容，支持公式编辑"
                        :height="120"
                        @input="(v) => $set(editList[index], 'analysisHtml', v)"
                    />
                </div>
            </div>
            <div slot="footer" class="edit-dialog-footer">
                <el-button class="edit-btn-cancel" @click="editVisible = false">取消</el-button>
                <el-button class="edit-btn-save" @click="saveEdit">
                    保存
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import ChatTools from "./chat-tools.vue";
import RichInput from "./RichInput.vue";
import katex from 'katex';
import 'katex/dist/katex.min.css';
import 'katex/contrib/mhchem/mhchem.js';
export default {
    name: 'ReadOver',
    components: {
        ChatTools,
        RichInput,
    },
    props: {
        exercisesData: {
            type: Object,
            default: () => {}
        },
        analyzeData: {
            type: Object,
            default: () => {}
        }
    },
    data() {
        return {
            editVisible: false,
            editList: [],
            editScore: 0,
        }
    },
    methods: {
        reanswer(list) {
            this.$emit('on-reanswer', list);
        },
        notyApply() {
            this.$emit('on-noty-apply', this.analyzeData, this.exercisesData);
        },
        openEdit() {
          this.editScore = this.analyzeData.score || 0;
          this.editList = (this.analyzeData.jsonContent || []).map((item) => ({
            ...item,
            analysisHtml: this.plainToHtml(item.analysis),
          }));
          this.editVisible = true;
        },
        onDialogOpened() {
          this.editList = this.editList.map((item, index) => {
            const origin = this.analyzeData.jsonContent[index];
            return {
              ...item,
              analysisHtml: this.plainToHtml(origin.analysis),
            };
          });
        },
        saveEdit() {
            const jsonContent = this.editList.map((item) => ({
                ...item,
                analysis: this.htmlToPlain(item.analysisHtml),
                analysisHtml: undefined,
            }));
            this.$emit('on-edit', { ...this.analyzeData, score: this.editScore, jsonContent });
            this.editVisible = false;
        },
        plainToHtml(text) {
            if (!text) return '';
            const escaped = text
                .replace(/\$\$([^$]+)\$\$/g, (_, latex) =>
                    `<span data-w-e-type="formula" data-w-e-is-void data-w-e-is-inline data-value="${this.escAttr(latex)}"></span>`
                )
                .replace(/\$([^$]+)\$/g, (_, latex) =>
                    `<span data-w-e-type="formula" data-w-e-is-void data-w-e-is-inline data-value="${this.escAttr(latex)}"></span>`
                );
            return escaped.split('\n').map((line) => `<p>${line || '<br>'}</p>`).join('');
        },
        htmlToPlain(html) {
            if (!html) return '';
            let result = html.replace(
                /<span[^>]+data-w-e-type="formula"[^>]+data-value="([^"]*)"[^>]*>[\s\S]*?<\/span>/g,
                (_, latex) => `$${this.unescAttr(latex)}$`
            );
            result = result.replace(/<\/p>\s*<p>/gi, '\n');
            result = result.replace(/<[^>]+>/g, '');
            return result
                .replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
                .replace(/&nbsp;/g, ' ').replace(/&#39;/g, "'").replace(/&quot;/g, '"')
                .trim();
        },
        escAttr(str) {
            return str.replace(/"/g, '&quot;').replace(/'/g, '&#39;');
        },
        unescAttr(str) {
            return str.replace(/&quot;/g, '"').replace(/&#39;/g, "'");
        },
        renderFormulas(text) {
        if (!text) return '';
        text = text.replace(/&gt;/g, '>')
            .replace(/&lt;/g, '<')
            .replace(/&amp;/g, '&')
            .replace(/&quot;/g, '"')
            .replace(/&#39;/g, "'");
        // 如果整个文本包含 LaTeX 命令且没有定界符，整体包裹
        const hasDelimiter = /\$|\\\(|\\\[/.test(text);
        if (!hasDelimiter) {
          text = text.replace(
              /(\\(?:frac|sqrt|sum|int|cdot|times|geq|leq|neq|pm|div|alpha|beta|gamma|theta|pi|sigma|omega|infty|log|sin|cos|tan|left|right|overline|hat|vec|bar|lim|in|notin|supset|subseteq|ln|Gamma|to)(?:\{[^{}]*(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^{}]*)*\}|[^\s{}，。？！、；：\u4e00-\u9fa5])*)/g,
              (match) => `\\(${match}\\)`
          );
        }
        const { renderToString } = katex;
        return text
            // $$ ... $$ 块级公式
            .replace(/\$\$([\s\S]*?)\$\$/gs, function (_, formula) {
              try {
                const trimmedFormula = formula.trim()
                return renderToString(trimmedFormula, { displayMode: true });
              } catch (error) {
                console.error('Error rendering block formula:', error);
                return _;
              }
            })
            // \(...\) 行内公式
            .replace(/\\\((.*?)\\\)/gs, function (_, formula) {
              try {
                const trimmedFormula = formula.trim()
                return renderToString(trimmedFormula, { displayMode: false });
              } catch (error) {
                console.error('Error rendering inline formula:', error);
                return _;
              }
            })
            // \[...\] 块级公式
            .replace(/\\\[(.*?)\\\]/gs, function (_, formula) {
              try {
                const trimmedFormula = formula.trim()
                return renderToString(trimmedFormula, { displayMode: true });
              } catch (error) {
                console.error('Error rendering block formula:', error);
                return _;
              }
            })
            // $...$ 行内公式
            .replace(/\$(.+?)\$/gs, function (_, formula) {
              try {
                const trimmedFormula = formula.trim()
                return renderToString(trimmedFormula, { displayMode: false });
              } catch (error) {
                console.error('Error rendering inline formula with $...$:', error);
                return _;
              }
            });
      },
    },
}
</script>
<style lang="scss" scoped>
.read-over-contain {
    width: 100%;
    height: 100%;
    overflow-y: auto;
    padding-right: 32px;
    /* 滚动条轨道样式 */
    &::-webkit-scrollbar {
        width: 8px;
        /* 设置滚动条宽度 */
        // background-color: #f1f1f1;
        border-radius: 10px;
    }

    /* 滚动条轨道 */
    &::-webkit-scrollbar-track {
        background: transparent; /* 设置轨道背景为透明 */
    }

    /* 滚动条滑块样式 */
    &::-webkit-scrollbar-thumb {
        background: rgba(96, 128, 240, 0.6); /* 设置拖动块颜色 */
        border-radius: 4px;
        -webkit-box-shadow: inset 0 0 2px transparent;
        -webkit-transition: all 0.2s linear;
        transition: all 0.2s linear;
    }

    /* 滚动条滑块hover状态样式 */
    &::-webkit-scrollbar-thumb:hover {
        background: rgba(96, 128, 240, 0.5); /* 加深颜色 */
    }
}

.exercises-answer {
    position: relative;
    overflow: hidden;
    padding: 24px 32px;
    border-radius: 12px;
    background: linear-gradient(55.6deg, rgba(255, 255, 255, 1) 41%, rgba(224, 224, 255, 1) 100%);
}
.exercises-answer-bg {
    position: absolute;
    right: 0;
    top: 0;
    width: 320px;
    height: 213px;
    background: url("../static/bg-img.svg") no-repeat;
    background-size: 100%;
    opacity: 0.8;
}
.question-container {
    display: flex;
    .question-stem-content {
        min-width: 64px;
        height: 40px;
        margin-right: 16px;
        background: linear-gradient(55.6deg, #3190f0, #6161e1);
        color: #fff;
        text-align: center;
        line-height: 40px;
        border-radius: 12px;
        border-top-left-radius: 0;
    }
    .question-detail {
        border-bottom: 1px solid #d4d5e1;
        width: calc(100% - 80px);
        p {
            margin: 0;
            font-weight: 700;
            font-size: 16px;
            color: rgb(32, 40, 64);
        }
        .question-score {
            display: inline-block;
            min-width: 48px;
            height: 24px;
            text-align: center;
            line-height: 24px;
            color: rgb(96, 96, 224);
            background-color: rgba(96, 96, 224, 0.16);
            border-radius: 16px;
            font-size: 12px;
            margin: 24px 0;
        }
    }
}
:deep(.question-detail) {
    img {
        max-width: 100% !important;
    }
}
.answer-container {
    margin: 24px 0;
    .question-detail {
        border: 0;
    }
    .answer-stem-content {
        background: linear-gradient(55.6deg, #ffffff, #dadaf7);
        color: #6060E0;
        border: 1px solid #8080e6;
        border-radius: 12px;
        border-bottom-right-radius: 0;
    }
    .answer-detail {
        p {
            font-weight: normal;
        }
    }
}
.exercises-read-over {
    position: relative;
    padding: 24px 32px;
    border-radius: 12px;
    margin-top: 32px;
    background: linear-gradient(146.92022595903043deg, rgba(255, 255, 255, 1) 23%, rgba(238, 238, 255, 1) 100%);
    min-height: 160px;
    .exercises-read-over-content {
        width: 80%;
        margin: 0 auto;
        .title{
            font-weight: 700;
            font-size: 14px;
            color: rgb(96, 96, 224);
        }
        .content {
            font-size: 16px;
            color: rgb(32, 40, 64);
            line-height: 24px;
        }
    }
    .score {
        position: absolute;
        width: 64px;
        height: 64px;
        border-radius: 20px;
        border: 1px solid rgba(204, 204, 204, 1);
        background: linear-gradient(180deg, rgba(255, 255, 255, 1) 0%, rgba(240, 242, 248, 1) 100%);
        text-align: center;
        line-height: 64px;
        color: rgba(32, 40, 64, 0.64);
        font-size: 12px;
        .score-number {
            font-size: 26px;
            color: #F03030;
        }
    }
    .type {
        position: absolute;
        right: 32px;
        width: 64px;
        height: 32px;
        color: #fff;
        text-align: center;
        line-height: 32px;
        border-radius: 20px;
        font-size: 12px;
        background: linear-gradient(90deg, rgb(0, 144, 240) 0%, rgb(144, 48, 240) 100%);
        cursor: pointer;
        &:hover {
            background: linear-gradient(90deg, rgb(48, 144, 240) 0%, rgb(48, 192, 144) 100%);
        }
    }
    .type-active {
        background: linear-gradient(90deg, rgb(48, 144, 240) 0%, rgb(48, 192, 144) 100%);
    }
    .edit-btn {
        position: absolute;
        right: 32px;
        top: 70px;
        width: 64px;
        height: 32px;
        color: rgba(96, 96, 224, 1);
        text-align: center;
        line-height: 32px;
        border-radius: 20px;
        font-size: 12px;
        border: 1px solid rgba(96, 96, 224, 0.5);
        cursor: pointer;
        i {
            font-size: 13px;
        }
        &:hover {
            background-color: rgba(96, 96, 224, 0.08);
            border-color: rgba(96, 96, 224, 0.8);
        }
    }
}
:deep(.read-over-edit-dialog) {
    border-radius: 16px;
    overflow: hidden;

    .el-dialog__header {
        padding: 24px 24px 16px;
        border-bottom: 1px solid rgba(96, 96, 224, 0.12);
        background: linear-gradient(135deg, rgba(255, 255, 255, 1) 0%, rgba(238, 238, 255, 0.6) 100%);
    }

    .el-dialog__body {
        padding: 0;
    }

    .el-dialog__footer {
        padding: 0;
        border-top: 1px solid rgba(96, 96, 224, 0.12);
    }
}

.edit-dialog-header {
    .edit-dialog-title {
        font-size: 18px;
        font-weight: 700;
        color: rgb(32, 40, 64);
        display: flex;
        align-items: center;
        gap: 8px;
        i {
            font-size: 20px;
            background: linear-gradient(90deg, rgb(0, 144, 240), rgb(144, 48, 240));
            -webkit-background-clip: text;
            background-clip: text;
            -webkit-text-fill-color: transparent;
        }
    }
    .edit-dialog-subtitle {
        font-size: 12px;
        color: rgba(32, 40, 64, 0.45);
        margin-top: 4px;
        padding-left: 28px;
    }
}

.edit-dialog-body {
    max-height: 480px;
    overflow-y: auto;
    padding: 20px 24px;
    display: flex;
    flex-direction: column;
    gap: 20px;

    .edit-score-field {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 12px 16px;
        background: rgba(248, 248, 255, 1);
        border: 1px solid rgba(96, 96, 224, 0.15);
        border-radius: 10px;

        .edit-score-label {
            font-size: 13px;
            font-weight: 600;
            color: rgb(32, 40, 64);
            flex-shrink: 0;
        }

        .edit-score-max {
            font-size: 13px;
            color: rgba(32, 40, 64, 0.5);
            flex-shrink: 0;
        }

        :deep(.el-input-number) {
            width: 120px;
            .el-input__inner {
                border-color: rgba(96, 96, 224, 0.3);
                border-radius: 8px;
                text-align: center;
                &:focus {
                    border-color: rgba(96, 96, 224, 0.7);
                }
            }
        }
    }

    &::-webkit-scrollbar {
        width: 6px;
    }
    &::-webkit-scrollbar-track {
        background: transparent;
    }
    &::-webkit-scrollbar-thumb {
        background: rgba(96, 96, 224, 0.3);
        border-radius: 4px;
    }

    .edit-label {
      color: #000000;
      font-weight: bold;
    }

    .edit-item {
        .edit-item-header {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 8px;
        }
        .edit-item-index {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: linear-gradient(135deg, rgb(0, 144, 240), rgb(96, 96, 224));
            color: #fff;
            font-size: 11px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }
        .edit-item-title {
            font-size: 13px;
            font-weight: 600;
            color: rgb(96, 96, 224);
        }
        .edit-item-title--default {
            color: rgba(32, 40, 64, 0.4);
            font-weight: 400;
        }
    }
}

.edit-dialog-footer {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 5px;
    padding: 16px 24px;

    .edit-btn-cancel {
        height: 36px;
        padding: 0 20px;
        border-radius: 18px;
        border: 1px solid rgba(96, 96, 224, 0.4);
        color: rgba(96, 96, 224, 1);
        background: transparent;
        font-size: 13px;
        transition: all 0.2s;

        &:hover {
            background: rgba(96, 96, 224, 0.06);
            border-color: rgba(96, 96, 224, 0.7);
        }
    }

    .edit-btn-save {
        height: 36px;
        padding: 0 24px;
        border-radius: 18px;
        border: none;
        color: #fff;
        background: linear-gradient(90deg, rgb(0, 144, 240) 0%, rgb(144, 48, 240) 100%);
        font-size: 13px;
        font-weight: 600;
        transition: all 0.2s;

        i {
            margin-right: 4px;
        }

        &:hover {
            opacity: 0.88;
            box-shadow: 0 4px 12px rgba(96, 96, 224, 0.35);
        }
    }
}
</style>