<template>
    <div class="article-detail-wrapper">
        <div class="main-container" v-loading="loading" element-loading-text="正在加载..."
            element-loading-background="rgba(248, 249, 251, 0.8)">
            <!-- 左侧核心内容区 -->
            <div class="article-left-content">
                <!-- 顶部返回按钮 -->
                <div class="back-btn-box">
                    <div class="back-btn" @click="handleBack">返回列表</div>
                </div>

                <!-- 主文章卡片 -->
                <div class="article-main-card">
                    <!-- 标题 -->
                    <h1 class="article-title">{{ currentArticle.title }}</h1>

                    <!-- 发布日期与浏览量 -->
                    <div class="article-meta">
                        <div class="meta-item">
                            <img class="meta-icon" src="@/public/article/date.png" alt="日期">
                            <span>{{ currentArticle.date }}</span>
                        </div>
                        <div class="meta-item">
                            <img class="meta-icon" src="@/public/article/eye.png" alt="浏览数">
                            <span>{{ currentArticle.views }}</span>
                        </div>
                    </div>

                    <!-- 文章导读区 -->
                    <div v-if="currentArticle.intro" class="article-intro-box">
                        <div class="intro-header">
                            <img class="star-icon" src="@/public/article/start.png" />
                            <span>文章导读</span>
                        </div>
                        <p class="intro-content">{{ currentArticle.intro }}</p>
                    </div>

                    <!-- 正文区块 -->
                    <div class="article-body-content markdown-body" v-html="parsedContent">
                    </div>

                    <!-- 上一篇 / 下一篇 导航卡片 -->
                    <div class="article-nav-section">
                        <div class="nav-card prev-card" @click="handleSwitchArticle(prevArticle)">
                            <div class="nav-arrow left-arrow">
                                <img style="width:100%;height:100%;" src="@/public/article/left.png" alt="">
                            </div>
                            <div class="nav-info">
                                <span class="nav-label">上一篇</span>
                                <span class="nav-title" :title="prevArticle?.title">{{ prevArticle?.title || '没有上一篇了'
                                    }}</span>
                            </div>
                        </div>

                        <div class="nav-card next-card" @click="handleSwitchArticle(nextArticle)">
                            <div class="nav-info align-right">
                                <span class="nav-label">下一篇</span>
                                <span class="nav-title" :title="nextArticle?.title">{{ nextArticle?.title || '没有下一篇了'
                                    }}</span>
                            </div>
                            <div class="nav-arrow right-arrow">
                                <img style="width:100%;height:100%;" src="@/public/article/right.png" alt="">
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 右侧相关推荐侧边栏 -->
            <div class="recommend-sidebar">
                <div class="sidebar-card">
                    <div class="sidebar-header">
                        <img src="@/public/article/tuijian.png" class="recommend-icon" />
                        <span class="sidebar-title">相关推荐</span>
                    </div>

                    <div class="recommend-list">
                        <div v-for="(rec, index) in recommendList" :key="rec.id" class="recommend-item"
                            @click="handleSwitchArticle(rec)">
                            <div class="rec-rank" :class="{ 'top-rank': index < 3, 'four-rank': index == 3 }">{{ index +
                                1
                            }}</div>
                            <div class="rec-content">
                                <h4 class="rec-title" :title="rec.title">{{ rec.title }}</h4>
                                <div class="rec-meta">
                                    <div class="meta-sub">
                                        <img class="meta-sub-icon" src="@/public/article/date.png" alt="日期">
                                        <span>{{ rec.date }}</span>
                                    </div>
                                    <div class="meta-sub">
                                        <img class="meta-sub-icon" src="@/public/article/eye.png" alt="浏览">
                                        <span>{{ rec.views }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
        <!-- 底部警告组件 -->
        <WarningFooter />
    </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import WarningFooter from '@/components/common/WarningFooter.vue'
import { wechatApi } from '@/api/wechat'
import { marked } from 'marked'

const router = useRouter()
const route = useRoute()

// 当前文章 ID
const currentId = ref(route.query.id || '')
// 加载状态
const loading = ref(false)

// 数据状态
const currentArticle = ref({})
const recommendList = ref([])
const prevArticle = ref(null)
const nextArticle = ref(null)

// 计算 Markdown HTML
const parsedContent = computed(() => {
    if (!currentArticle.value.content_md) return ''
    return marked.parse(currentArticle.value.content_md)
})

// 获取文章详情
const fetchArticleDetail = async (id) => {
    if (!id) return
    try {
        let res = await wechatApi.getArticleDetail(id)
        res = typeof res === 'string' ? JSON.parse(res) : res
        currentArticle.value = {
            ...res,
            title: res.title,
            date: res.published_at ? res.published_at.split('T')[0] : '',
            views: res.views_count,
            intro: res.summary
        }

        // 动态修改页面 SEO 信息
        if (res.title) {
            document.title = `${res.title} - 装样大师`
        }
        if (res.seo_keywords) {
            const metaKeywords = document.querySelector('meta[name="keywords"]')
            if (metaKeywords) metaKeywords.setAttribute('content', res.seo_keywords)
        }
        if (res.seo_description) {
            const metaDesc = document.querySelector('meta[name="description"]')
            if (metaDesc) metaDesc.setAttribute('content', res.seo_description)
        }

        window.scrollTo({ top: 0, behavior: 'smooth' })
    } catch (error) {
        console.error('获取文章详情失败:', error)
    }
}

// 获取相关推荐列表
const fetchRecommendList = async (id) => {
    if (!id) return
    try {
        let res = await wechatApi.getRelatedArticles(id)
        res = typeof res === 'string' ? JSON.parse(res) : res
        if (Array.isArray(res)) {
            recommendList.value = res.map(item => ({
                id: item.id,
                title: item.title,
                date: item.published_at ? item.published_at.split('T')[0] : '',
                views: item.views_count
            }))
        }
    } catch (e) {
        console.error('获取相关推荐失败:', e)
    }
}

// 获取上下篇文章
const fetchPrevNextArticles = async (id) => {
    if (!id) return
    try {
        let res = await wechatApi.getArticlesList({ page: 1, per_page: 500 })
        res = typeof res === 'string' ? JSON.parse(res) : res
        if (res && res.items) {
            let list = res.items

            // 先按照 is_hot 优先，再按时间倒序
            list.sort((a, b) => {
                const aHot = !!a.is_hot
                const bHot = !!b.is_hot
                if (aHot && !bHot) return -1
                if (!aHot && bHot) return 1
                const aTime = a.published_at ? new Date(a.published_at).getTime() : 0
                const bTime = b.published_at ? new Date(b.published_at).getTime() : 0
                return bTime - aTime
            })

            const index = list.findIndex(item => item.id == id)
            if (index !== -1) {
                // 根据时间倒序排列：上一篇更近，下一篇更远
                prevArticle.value = index > 0 ? list[index - 1] : null
                nextArticle.value = index < list.length - 1 ? list[index + 1] : null
            } else {
                prevArticle.value = null
                nextArticle.value = null
            }
        }
    } catch (e) {
        console.error('获取上下篇文章失败:', e)
    }
}

onMounted(async () => {
    if (currentId.value) {
        loading.value = true
        try {
            await Promise.all([
                fetchArticleDetail(currentId.value),
                fetchRecommendList(currentId.value),
                fetchPrevNextArticles(currentId.value)
            ])
        } finally {
            loading.value = false
        }
    }
})

watch(() => route.query.id, async (newId) => {
    if (newId) {
        currentId.value = newId
        loading.value = true
        try {
            await Promise.all([
                fetchArticleDetail(newId),
                fetchRecommendList(newId),
                fetchPrevNextArticles(newId)
            ])
        } finally {
            loading.value = false
        }
    }
})

function handleBack() {
    router.push('/article')
}

function handleSwitchArticle(articleItem) {
    if (!articleItem) return
    router.push({
        path: '/article-detail',
        query: { id: articleItem.id }
    })
}
</script>

<style lang="scss" scoped>
.article-detail-wrapper {
    position: relative;
    min-height: calc(100vh - 112px);
    background-color: #F8F9FB;
    padding: 36px 20px 80px;
    box-sizing: border-box;
}

.main-container {
    width: 800px;
    position: relative;
    margin: 0 auto;
}

/* 左侧主体内容：相对于整个页面水平居中 */
.article-left-content {
    width: 800px;
}

/* 右侧侧边栏：固定在居中主卡片的右侧，且不跟随页面滚动 */
.recommend-sidebar {
    width: 310px;
    position: fixed;
    top: 201px;
    left: calc(50% + 424px);
    /* 正好定位在 800px 居中卡片右侧 24px 处 */
    z-index: 10;
}

@media (max-width: 1480px) {
    .recommend-sidebar {
        left: auto;
        right: 20px;
    }
}

@media (max-width: 1340px) {
    .recommend-sidebar {
        display: none;
        /* 屏幕过窄时隐藏侧边栏避免挡住主卡片 */
    }
}

/* 返回按钮 */
.back-btn-box {
    margin-bottom: 18px;
}

.back-btn {
    width: 116px;
    height: 36px;
    background-image: url('/src/public/article/back-bg.png');
    background-size: 100% 100%;
    border: none;
    cursor: pointer;
    transition: all 0.2s ease;
    text-align: right;
    padding-right: 18px;
    font-weight: 500;
    font-size: 16px;
    color: #FFFFFF;
    line-height: 36px;

    &:hover {
        opacity: 0.92;
        transform: translateY(-1px);
    }
}

/* 主卡片 */
.article-main-card {
    background: #FFFFFF;
    border-radius: 16px;
    padding: 34px 30px 20px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.04);
    box-sizing: border-box;
}

.article-title {
    margin: 0 0 18px 0;
    font-weight: 700;
    font-size: 18px;
    color: #1A1A1A;
    line-height: 20px;
}

.article-meta {
    display: flex;
    align-items: center;
    gap: 20px;
    margin-bottom: 16px;

    .meta-item {
        height: 20px;
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 18px;
        color: #AAAAAA;
        line-height: 18px;
        text-align: left;

        .meta-icon {
            width: 20px;
            height: 20px;
        }
    }
}

/* 导读区 */
.article-intro-box {
    background-color: #F8F6FF;
    border-radius: 12px;
    padding: 16px 16px 12px;
    margin-bottom: 12px;

    .intro-header {
        display: flex;
        align-items: center;
        font-size: 16px;
        color: #965DF8;
        line-height: 16px;
        font-weight: 700;
        margin-bottom: 6px;

        .star-icon {
            width: 16px;
            height: 16px;
            margin-right: 6px;
        }
    }

    .intro-content {
        margin: 0;
        font-size: 16px;
        color: #767676;
        line-height: 26px;
    }
}

/* 正文 */
.article-body-content {
    margin-top: 32px;
    font-size: 16px;
    color: #1A1A1A;
    line-height: 26px;
}

.article-body-content :deep(img) {
    max-width: 100%;
    border-radius: 8px;
    margin: 16px 0;
}

.article-body-content :deep(h1),
.article-body-content :deep(h2),
.article-body-content :deep(h3) {
    color: #1A1A1A;
    margin-top: 24px;
    margin-bottom: 16px;
}

.article-body-content :deep(p) {
    margin-bottom: 16px;
}

.article-body-content :deep(a) {
    color: #8B70FF;
    text-decoration: none;
}

/* 上一篇/下一篇 导航卡片 */
.article-nav-section {
    display: flex;
    gap: 20px;
    margin-top: 32px;

    .nav-card {
        flex: 1;
        flex-shrink: 0;
        display: flex;
        align-items: center;
        padding: 8px 16px;
        border-radius: 12px;
        cursor: pointer;
        transition: all 0.2s ease;
        box-sizing: border-box;
        background: #FFFFFF;
        border: 1px solid #EAEAEA;

        &.prev-card {
            &:hover {
                background: #F6F3FD;
            }
        }

        &.next-card {
            &:hover {
                background: #F0EBFF;
            }
        }

        .nav-arrow {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: rgba(139, 112, 255, 0.12);
            color: #8B70FF;
            display: flex;
            align-items: center;
            justify-content: center;

            svg {
                width: 16px;
                height: 16px;
            }
        }

        .nav-info {
            display: flex;
            flex-direction: column;
            flex: 1;
            min-width: 0;
            padding: 0 16px;

            &.align-right {
                text-align: right;
            }

            .nav-label {
                font-size: 16px;
                font-weight: 700;
                color: #1A1A1A;
            }

            .nav-title {
                font-size: 12px;
                color: #767676;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }
        }
    }
}

/* 右侧侧边栏 */
.recommend-sidebar {
    width: 230px;
    flex-shrink: 0;
}

.sidebar-card {
    background: #FFFFFF;
    border-radius: 18px;
    padding: 0;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.04);
    box-sizing: border-box;
}

.sidebar-header {
    position: relative;
    height: 46px;
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 0 12px;
    color: #8B70FF;

    &::after {
        content: '';
        position: absolute;
        width: 100%;
        left: 0;
        bottom: 0;
        height: 1px;
        background-color: #D8D8D8;
        transform: scaleY(0.5);
    }

    .recommend-icon {
        width: 22px;
        height: 22px;
    }

    .sidebar-title {
        font-weight: 700;
        font-size: 16px;
        color: #1A1A1A;
        line-height: 16px;
    }
}

.recommend-list {
    display: flex;
    flex-direction: column;
}

.recommend-item {
    height: 86px;
    padding-left: 18px;
    display: flex;
    gap: 8px;
    align-items: center;
    cursor: pointer;

    &:last-child {
        border-bottom: none;
        padding-bottom: 0;
        margin-bottom: 0;
    }

    &:hover {
        .rec-title {
            color: #8B70FF;
        }
    }

    .rec-rank {
        font-size: 18px;
        font-weight: 700;
        color: #D8D8D8;
        width: 18px;

        &.top-rank {
            color: #965DF8;
        }

        &.four-rank {
            color: #AAAAAA;
        }
    }

    .rec-content {
        display: flex;
        justify-content: center;
        height: 100%;
        flex: 1;
        min-width: 0;
        display: flex;
        flex-direction: column;
        border-bottom: 1px solid #F0F0F0;
        padding-right: 10px;
        gap: 12px;
    }

    .rec-title {
        margin: 0;
        font-size: 14px;
        font-weight: 500;
        color: #1A1A1A;
        line-height: 1.4;
        overflow: hidden;
        text-overflow: ellipsis;
        transition: color 0.2s;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
    }

    .rec-meta {
        display: flex;
        align-items: center;
        gap: 12px;

        .meta-sub {
            display: flex;
            align-items: center;
            gap: 4px;
            font-size: 12px;
            color: #AAAAAA;

            .meta-sub-icon {
                width: 12px;
                height: 12px;
            }
        }
    }
}

@media (max-width: 960px) {
    .main-container {
        flex-direction: column;
    }

    .recommend-sidebar {
        width: 100%;
    }
}

:deep(.el-loading-mask) {
    z-index: 1 !important;
}
</style>