<template>
    <el-row>
        <el-col :span="24">
            <el-button @click="goBack()">
                < 返回列表</el-button>
        </el-col>
    </el-row>
    <el-row>
        <el-col :span="24">
            <h1>{{ details.detail.title }}</h1>
            <p style="padding: 20px;">发布时间: {{ details.detail.published }}</p>
        </el-col>
    </el-row>
    <el-row>
        <el-col :span="24">
            <div ref="vditorPreviewRef" style="width: 100%;"></div>
            <div v-if="isLoading" style="text-align: center; padding: 40px; color: #999;">
                <el-icon class="is-loading" style="font-size: 24px;">
                    <Loading />
                </el-icon>
                <p>加载中...</p>
            </div>
        </el-col>
    </el-row>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { viewDetailsStore } from '@/store/details'
import { onMounted, ref } from 'vue'
import Vditor from 'vditor'
import 'vditor/dist/index.css'

const router = useRouter()

const details = viewDetailsStore()

const vditorPreviewRef = ref(null)
const isLoading = ref(true)

const goBack = () => {
    router.back()
}

onMounted(() => {
    const markdownContent = details.detail.content || ''
        if (vditorPreviewRef.value) {
        const renderMarkdown = () => {
            Vditor.preview(vditorPreviewRef.value, markdownContent, {
                theme: {
                    current: 'light'
                },
                // cdn: '/vditor'
            })
            isLoading.value = false
        }

        if (window.requestIdleCallback) {
            window.requestIdleCallback(renderMarkdown, { timeout: 1000 })
        } else {
            setTimeout(renderMarkdown, 100)
        }
    }
})
</script>

<style scoped>
@import 'github-markdown-css/github-markdown.css';

::v-deep(.vditor-preview) {
    padding: 20px;
}

::v-deep(.vditor-preview table) {
    width: 100%;
    border-collapse: collapse;
}

::v-deep(.vditor-preview th),
::v-deep(.vditor-preview td) {
    border: 1px solid #d0d7de;
    padding: 8px;
}

::v-deep(.vditor-preview th) {
    background-color: #f6f8fa;
    font-weight: 600;
}

::v-deep(.vditor-preview img) {
    max-width: 100%;
    height: auto;
    display: block;
    margin: 0 auto;
}
</style>