<template>
    <div class="article-page-wrapper">
        <div class="main-container">
            <div class="article-list-container" v-loading="loading" style="min-height: 400px;">
                <div v-for="item in articleList" :key="item.id" class="article-card" @click="handleCardClick(item)">
                    <!-- 卡片头部信息 -->
                    <div class="card-header">
                        <div class="header-left">
                            <h1 class="article-title" :title="item.title">{{ item.title }}</h1>
                            <div v-if="item.isHot" class="hot-badge">
                                <img class="hot-icon" src="@/public/article/hot.png" alt="">
                            </div>
                        </div>

                        <div class="header-meta">
                            <div class="meta-item">
                                <img class="meta-icon" src="@/public/article/date.png" alt="">
                                <span>{{ item.date }}</span>
                            </div>
                            <div class="meta-item">
                                <img class="meta-icon" src="@/public/article/eye.png" alt="">
                                <span>{{ item.views }}</span>
                            </div>
                        </div>
                    </div>

                    <!-- 卡片主体内容 -->
                    <div class="card-body">
                        <div class="cover-thumb">
                            <img :src="item.cover || '/src/public/article/empty.png'" :alt="item.title"
                                class="cover-img" />
                        </div>

                        <div class="content-right">
                            <p class="article-desc">{{ item.description }}</p>
                            <div class="action-box">
                                <button class="detail-btn" @click.stop="handleDetail(item)">查看详情</button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 暂无数据提示 -->
                <el-empty v-if="!loading && articleList.length === 0" description="暂无文章" image-size="200"
                    image="/src/public/profile/empty.png" />

                <!-- 分页组件 -->
                <div class="pagination-container" v-if="total > queryParams.per_page">
                    <el-pagination class="custom-pagination" layout="total, prev, pager, next, jumper" prev-text="上一页"
                        next-text="下一页" :total="total" :page-size="queryParams.per_page"
                        v-model:current-page="queryParams.page" @current-change="handlePageChange"
                        hide-on-single-page />
                </div>
            </div>

            <!-- 右侧分类侧边栏 -->
            <div class="category-sidebar">
                <div class="sidebar-card">
                    <div class="sidebar-header">
                        <img src="@/public/article/tuijian.png" class="category-icon" />
                        <span class="sidebar-title">类型</span>
                    </div>
                    <div class="category-list">
                        <div v-for="cat in categoryList" :key="cat.id" class="category-item"
                            :class="{ active: currentCategory === cat.id }" @click="handleCategoryClick(cat)">
                            {{ cat.name }}
                        </div>
                    </div>
                </div>
            </div>
        </div>

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

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

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

// 状态与数据
const loading = ref(false)
const categoryList = ref([{ id: '', name: '全部文章' }])
const currentCategory = ref('')
const articleList = ref([])

// 分页与参数
const queryParams = ref({
    page: 1,
    per_page: 10,
    category_id: '',
    keyword: ''
})
const total = ref(0)

// 获取当前分类的名称
const currentCategoryName = computed(() => {
    const cat = categoryList.value.find(c => c.id === currentCategory.value)
    return cat ? cat.name : '全部文章'
})

// 监听分类名称变化，动态更新页面标题
watch(currentCategoryName, (newName) => {
    if (newName !== '全部文章') {
        document.title = `${newName}-装样大师`
    } else {
        document.title = `装样大师`
    }
}, { immediate: true })

// 获取分类数据
const fetchCategories = async () => {
    try {
        let res = await wechatApi.getArticlesCategories()
        res = typeof res === 'string' ? JSON.parse(res) : res
        if (Array.isArray(res)) {
            categoryList.value = [
                { id: '', name: '全部文章' },
                ...res
            ]
        }
    } catch (e) {
        console.error('获取分类失败:', e)
    }
}

// 获取文章列表数据
const fetchArticles = async () => {
    loading.value = true
    try {
        let res = await wechatApi.getArticlesList(queryParams.value)
        res = typeof res === 'string' ? JSON.parse(res) : res

        if (res && res.items) {
            // 设置分类 SEO 信息
            if (currentCategory.value != '' && res.items.length > 0 && res.items[0].category) {
                const categoryData = res.items[0].category
                const metaKeywords = document.querySelector('meta[name="keywords"]')
                if (metaKeywords && categoryData.seo_keywords) {
                    metaKeywords.setAttribute('content', categoryData.seo_keywords)
                }
                const metaDesc = document.querySelector('meta[name="description"]')
                if (metaDesc && categoryData.seo_description) {
                    metaDesc.setAttribute('content', categoryData.seo_description)
                }
            } else if (currentCategory.value === '') {
                // 恢复全部文章的基础 SEO 信息
                const metaKeywords = document.querySelector('meta[name="keywords"]')
                if (metaKeywords) metaKeywords.setAttribute('content', '装样大师, 模拟器')
                const metaDesc = document.querySelector('meta[name="description"]')
                if (metaDesc) metaDesc.setAttribute('content', '装样大师是一款高保真的模拟工具')
            }

            let mappedList = res.items.map(item => ({
                id: item.id,
                title: item.title,
                isHot: item.is_hot,
                date: item.published_at ? item.published_at.split('T')[0] : '',
                timestamp: item.published_at ? new Date(item.published_at).getTime() : 0,
                views: item.views_count,
                cover: item.cover_url,
                description: item.summary
            }))

            // 双重排序：优先判断 is_hot，其次按照时间倒序
            mappedList.sort((a, b) => {
                const aHot = !!a.isHot
                const bHot = !!b.isHot
                if (aHot && !bHot) return -1
                if (!aHot && bHot) return 1
                return b.timestamp - a.timestamp
            })

            articleList.value = mappedList
            total.value = res.total
        }
    } catch (e) {
        console.error('获取文章失败:', e)
    } finally {
        loading.value = false
    }
}

// 统一更新 URL 逻辑
function updateQueryToUrl() {
    const query = {}
    if (queryParams.value.category_id) query.category_id = queryParams.value.category_id
    if (queryParams.value.keyword) query.keyword = queryParams.value.keyword
    if (queryParams.value.page > 1) query.page = queryParams.value.page

    router.push({ path: route.path, query })
}

// 翻页事件
function handlePageChange(page) {
    queryParams.value.page = page
    updateQueryToUrl()
    // 翻页后平滑滚动回顶部
    window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 点击分类加载对应文章
function handleCategoryClick(cat) {
    if (currentCategory.value === cat.id) return // 避免重复点击

    currentCategory.value = cat.id
    queryParams.value.category_id = cat.id
    queryParams.value.page = 1
    updateQueryToUrl()
}

// 监听路由参数变化，同步到状态并拉取数据
watch(() => route.query, (newQuery) => {
    queryParams.value.category_id = newQuery.category_id ? Number(newQuery.category_id) : ''
    queryParams.value.keyword = newQuery.keyword || ''
    queryParams.value.page = newQuery.page ? Number(newQuery.page) : 1
    currentCategory.value = queryParams.value.category_id

    fetchArticles()
}, { immediate: true })

onMounted(() => {
    // 恢复列表页基础 SEO 信息
    const metaKeywords = document.querySelector('meta[name="keywords"]')
    if (metaKeywords) metaKeywords.setAttribute('content', '装样大师, 模拟器')
    const metaDesc = document.querySelector('meta[name="description"]')
    if (metaDesc) metaDesc.setAttribute('content', '装样大师是一款高保真的模拟工具')

    fetchCategories()
})

function handleDetail(item) {
    router.push({
        path: '/article-detail',
        query: { id: item.id }
    })
}

function handleCardClick(item) {
    handleDetail(item)
}
</script>

<style lang="scss" scoped>
.article-page-wrapper {
    min-height: calc(100vh - 112px);
    background-color: #F8F9FB;
    padding: 40px 20px 80px;
    display: flex;
    flex-direction: column;
    align-items: center;
    box-sizing: border-box;
}

.main-container {
    width: 100%;
    max-width: 1140px;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;
    gap: 30px;
}

.article-list-container {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 18px;
}

.pagination-container {
    height: 74px;
    display: flex;
    justify-content: center;
    background-color: #FFFFFF;
    box-shadow: 0px 0px 12px 0px rgba(0, 0, 0, 0.1);
    border-radius: 12px;
}

.article-card {
    width: 100%;
    background: #FFFFFF;
    border-radius: 16px;
    padding: 34px;
    cursor: pointer;
    box-sizing: border-box;
    box-shadow: 0px 0px 12px 0px rgba(0, 0, 0, 0.1);

    &:hover {
        box-shadow: 0 8px 15px rgba(0, 0, 0, 0.07);
        transform: scale(1.005);
    }
}

/* 卡片头部样式 */
.card-header {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 20px;
    gap: 16px;
    margin-bottom: 20px;

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

    }
}

.header-left {
    display: flex;
    align-items: center;
    gap: 10px;
    flex: 1;
    min-width: 0;
    /* 允许标题自适应缩减触发 ellipsis */
}

.article-title {
    max-width: 468px;
    margin: 0;
    font-weight: 700;
    font-size: 18px;
    color: #1A1A1A;
    line-height: 20px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

/* HOT 标签样式 */
.hot-badge {
    width: 41px;
    height: 18px;

    img {
        width: 100%;
        height: 100%;
    }
}

.header-meta {
    display: flex;
    align-items: center;
    gap: 16px;
    color: #999999;
    font-size: 14px;
    flex-shrink: 0;
}

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

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

/* 卡片主体内容布局 */
.card-body {
    display: flex;
    gap: 28px;
    align-items: flex-start;
}

.cover-thumb {
    width: 170px;
    height: 125px;
    flex-shrink: 0;
    border-radius: 6px;
    overflow: hidden;

    .cover-img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .cover-placeholder {
        width: 100%;
        height: 100%;
        background-color: #D8D8D8;
    }
}

.content-right {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    flex: 1;
    min-height: 125px;
}

.article-desc {
    margin: 0;
    font-weight: 400;
    font-size: 16px;
    color: #767676;
    line-height: 26px;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
}

.action-box {
    display: flex;
    justify-content: flex-end;
    margin-top: 12px;
}

.detail-btn {
    width: 100px;
    height: 36px;
    background: linear-gradient(215deg, #A679F4 7.14%, #778CF5 100%);
    color: #FFFFFF;
    border: none;
    border-radius: 8px;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s ease;
    box-shadow: 0 4px 12px rgba(120, 84, 255, 0.25);

    &:hover {
        opacity: 0.92;
        box-shadow: 0 6px 16px rgba(120, 84, 255, 0.35);
    }

    &:active {
        transform: translateY(0);
    }
}

@media (max-width: 640px) {
    .card-body {
        flex-direction: column;
    }

    .cover-thumb {
        width: 100%;
        height: 160px;
    }

    .content-right {
        min-height: auto;
    }
}

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

    .category-sidebar {
        width: 100%;
        position: static;
    }
}

/* 侧边栏分类样式 */
.category-sidebar {
    width: 230px;
    flex-shrink: 0;
    position: sticky;
    top: 152px;
    height: fit-content;
}

.sidebar-card {
    background: #FFFFFF;
    border-radius: 18px;
    padding: 0;
    box-shadow: 0px 0px 14px 0px rgba(0, 0, 0, 0.1);
    box-sizing: border-box;
    padding-bottom: 12px;
}

.sidebar-header {
    height: 60px;
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 0 12px;

    .category-icon {
        width: 18px;
        height: 18px;
    }

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

.category-list {
    padding: 0 16px;
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.category-item {
    height: 56px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 8px;
    font-size: 18px;
    color: #333333;
    cursor: pointer;
    transition: all 0.2s;

    &:hover {
        // color: #8B70FF;
        background-color: #F8F9FB;
    }

    &.active {
        color: #8B70FF;
        background-color: #EFEEFF;
        font-weight: 600;
    }
}

/* 自定义分页组件样式 */
:deep(.custom-pagination) {
    justify-content: center;
    padding: 10px 0;

    .el-pagination__total {
        margin-right: 20px;
        color: #3D3D3D;
        font-size: 16px;
    }

    .btn-prev,
    .btn-next {
        background-color: transparent !important;
        border: 1px solid #E9E9E9;
        background-color: #FAFAFA !important;
        border-radius: 4px;
        padding: 0 10px;
        color: #3D3D3D;
        font-weight: normal;
        min-width: 60px;
        margin: 0 8px;
        font-size: 16px;
        height: 37px;
        line-height: 37px;
    }

    .btn-prev:hover,
    .btn-next:hover {
        color: #8B70FF;
        border-color: #8B70FF;
    }

    .el-pager li {
        font-size: 16px;
        background-color: transparent !important;
        color: #3D3D3D;
        font-weight: normal;
        min-width: 32px;
        height: 32px;
        line-height: 32px;
        border-radius: 50%;
        margin: 0 4px;

        &.is-active {
            background: linear-gradient(215deg, #A679F4 7.14%, #778CF5 100%) !important;
            color: #fff !important;
        }

        &:hover:not(.is-active) {
            color: #8B70FF;
        }
    }

    .el-pagination__jump {
        font-size: 16px;
        margin-left: 12px;
        color: #3D3D3D;

        .el-input {
            height: 37px;
            line-height: 37px;
            font-size: 16px;

            &:focus {
                border-color: #8B70FF !important;
            }

            &:active {
                border-color: #8B70FF !important;
            }
        }
    }
}

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