<template>
    <div>
        <template v-if="isTextMode">
            <template v-if="isFromXK">
                <div class="text-preview" style="color: #000 !important;" ref="previewRoot" v-html="displayHtml"></div>
            </template>
            <template v-else>
                <div style="color: #000 !important;" v-html="displayHtml"></div>
            </template>
        </template>

        <template v-if="isImageMode">
            <el-image v-if="hasImage && !imageError" class="question_img" :src="imgSrc" :preview-src-list="[imgSrc]"
                @load="onImageLoad" @error="onImageError">
            </el-image>

            <div v-else-if="imageLoading && !imageError" class="image-loading">正在加载图片...</div>

            <div v-else-if="imageError" class="image-error">图片加载失败</div>

            <div v-else class="image-empty">暂无图片</div>
        </template>
    </div>
</template>

<script>
const FORMULA_SELECTOR = 'span[data-w-e-type="formula"][data-value]';

function isWangEditorFormula(html = "") {
    return html && html.indexOf('data-w-e-type="formula"') > -1;
}

export default {
    name: "Preview",

    props: {
        content: {
            type: String,
            default: "",
        },
        type: [String, Number],
        imgBase64: {
            type: [String, Array],
            default: ''
        }
    },

    data() {
        return {
            displayHtml: "",
            isFromXK: false,
            imageLoading: false,
            imageError: false,
        };
    },

    computed: {
        isTextMode() {
            return String(this.type) === "1";
        },
        isImageMode() {
            return String(this.type) === "2";
        },
        imgSrc() {
            return this.normalizeImg(this.imgBase64);
        },
        hasImage() {
            return this.imgSrc !== '';
        },
    },

    watch: {
        content: {
            immediate: true,
            handler() {
                this.updateDisplay();
            },
        },

        type() {
            this.updateDisplay();
        },

        imgBase64: {
            immediate: true,
            handler() {
                const src = this.normalizeImg(this.imgBase64);
                this.imageLoading = !!src;
                this.imageError = false;
            }
        }
    },

    mounted() {
        // mounted 保持空，渲染由 updateDisplay 控制
    },

    methods: {
        async updateDisplay() {
            if (!this.isTextMode) {
                this.displayHtml = "";
                return;
            }

            const value = this.content || "";
            if (!value) {
                this.displayHtml = "";
                return;
            }

            if (!isWangEditorFormula(value)) {
                this.isFromXK = false;
                this.displayHtml = value;
                return;
            }

            const container = document.createElement('div');
            container.innerHTML = value;
            const spans = Array.from(container.querySelectorAll(FORMULA_SELECTOR));

            if (spans.length === 0) {
                this.isFromXK = false;
                this.displayHtml = value;
                return;
            }

            if (window.MathJax) {
                if (window.MathJax.tex2svgPromise) {
                    for (const span of spans) {
                        const latex = span.getAttribute('data-value') || '';
                        try {
                            const node = await window.MathJax.tex2svgPromise(latex, { display: false });
                            span.replaceWith(node);
                        } catch (e) {
                            console.warn('tex2svgPromise 渲染失败，保留原始公式标记', e);
                            span.textContent = `\\(${span.getAttribute('data-value')}\\)`;
                        }
                    }
                    this.displayHtml = container.innerHTML;
                } else {
                    for (const span of spans) {
                        const latex = span.getAttribute('data-value') || '';
                        const textNode = document.createTextNode(`\\(${latex}\\)`);
                        span.replaceWith(textNode);
                    }
                    this.isFromXK = true;
                    this.displayHtml = container.innerHTML;

                    this.$nextTick(async () => {
                        try {
                            if (window.MathJax.typesetPromise) {
                                await window.MathJax.typesetPromise([this.$refs.previewRoot]);
                            }
                        } catch (error) {
                            console.error('MathJax typeset 失败', error);
                        }
                    });
                }
            } else {
                this.displayHtml = value;
            }

            this.$nextTick(() => {
                this.$emit('rendered');
            });
        },

        normalizeImg(src) {
            if (Array.isArray(src)) return src[0] || '';
            if (typeof src === 'string') return src.trim();
            return '';
        },

        onImageLoad() {
            this.imageLoading = false;
            this.imageError = false;
        },

        onImageError() {
            this.imageLoading = false;
            this.imageError = true;
        }
    }
};
</script>

<style scoped>
/* MathJax CHTML 覆盖，缓解全局样式对公式的影响 */
.mjx-chtml {
    display: inline-block;
    line-height: 1;
    vertical-align: baseline;
}

.mjx-container,
.mjx-char,
.mjx-mfrac {
    line-height: 1 !important;
    display: inline-block !important;
    vertical-align: baseline !important;
}

.mjx-msqrt>.mjx-surd {
    vertical-align: -0.12em !important;
}

.el-image {
    max-width: 720px;
}
</style>

<style lang="scss">
.text-preview {
    img {
        vertical-align: middle !important;
    }

    table {
        width: 100%;
        border-collapse: collapse;
        border: 1px solid #ebeef5;
        text-align: center;
    }

    table td,
    table th {
        padding: 0 10px;
        border: 1px solid #ebeef5;
        color: #666;
        height: 30px;
    }

    // 第一行作为默认头部
    // table tbody tr:first-child {
    //     background-color: #F5F7FA;
    //     font-weight: bold;
    // }

    table thead th {
        background-color: #F5F7FA;
        width: 100px;
    }

    table tr:nth-child(odd) {
        background: #F9F9F9;
    }

    table tr:nth-child(even) {
        background: #fff;
    }
}

.question_img {
    max-width: 720px;
}
</style>
