<template>
  <div id="article-detail-page">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state-container">
      <el-skeleton :count="1" />
      <el-skeleton :count="3" />
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-state-container">
      <el-alert :title="error" type="error" show-icon />
      <el-button type="primary" @click="fetchArticleDetail">重新加载</el-button>
    </div>

    <!-- 文章详情 -->
    <div v-else-if="article && Object.keys(article).length > 0" class="article-detail-wrapper">
      <!-- 文章头部信息 -->
      <div class="article-header-section">
        <h1 class="article-main-title">{{ article.title }}</h1>

        <div class="article-meta-info">
          <span class="meta-item">
            <i class="el-icon-date"></i>
            {{ formatDate(article.createdAt) }}
          </span>
          <span class="meta-item">
            <i class="el-icon-folder"></i>
            {{ article.categoryName || '未分类' }}
          </span>
          <span class="meta-item">
            <i class="el-icon-view"></i>
            {{ article.viewCount || 0 }} 阅读
          </span>
        </div>
      </div>

      <!-- 文章内容区域 -->
      <div class="article-content-area">
        <markdownViewer :markdownContent="article.markdownscontent" />
      </div>

      <!-- 文章底部信息 -->
      <div class="article-footer-section">
        <div class="article-tag-list">
          <!-- <span v-for="tag in article.tags || []" :key="tag" class="el-tag el-tag--primary">
            {{ tag }}
          </span> -->
        </div>

        <!-- 文章操作按钮 -->
        <div class="article-actions-group">
          <el-button type="primary" @click="goBack" plain>
            返回
          </el-button>
        </div>
      </div>

      <!-- 相关文章推荐 -->
      <div class="related-articles-section" v-if="relatedArticles.length > 0">
        <h3>相关文章</h3>
        <div class="related-articles-list">
          <div v-for="item in relatedArticles" :key="item.articleid" class="related-article-card"
            @click="handleRelatedArticleClick(item.articleid)">
            <i class="el-icon-document"></i>
            <span>{{ item.title }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 - 文章不存在 -->
    <div v-else class="empty-state-container">
      <el-empty description="文章不存在" />
    </div>

    <!-- 评论区组件 -->
    <div>
      <messageboard class="comment-section" />
    </div>
  </div>

</template>

<script setup lang="ts">
// 导入必要的依赖
import { useRoute, useRouter } from 'vue-router'
import { ref, onMounted } from 'vue'
import { articleService } from '@/services'
import { categoryAttributeService } from '@/services'
import { useGlobalStore } from '@/store/globalStore'
import { ElMessage } from 'element-plus'
import type { Article } from '@/types'
import { formatDate } from '@/utils/dateUtils'
import messageboard from './messageboard.vue'
import markdownViewer from './markdown.vue'
// 路由相关
const router = useRouter()

// 响应式状态管理
const globalStore = useGlobalStore()
const article = ref<Article | null>(null)  // 使用 null 作为初始值，避免类型不匹配问题
const loading = ref(false)
const error = ref('')
const relatedArticles = ref<Article[]>([])

/**
 * 获取文章详情数据
 */
const fetchArticleDetail = async () => {
  try {
    loading.value = true
    error.value = ''

    // 获取路由参数
    const articleId = globalStore.getValue('articleInfo')?.articleid || null
    if (!articleId) {
      throw new Error('文章不存在')
    }
    // 获取文章详情
    const response = await globalStore.getValue('articleInfo')
    // const markdowndata = await 
    if (response) {
      article.value = response
      // 获取并设置分类名称
      const categoryResponse = await categoryAttributeService.getAttributeById(Number(article.value.attributeid))
      article.value.categoryName = categoryResponse.data.attributename || '未分类'

      // 增加文章浏览量
      try {
        await articleService.incrementArticleViews(Number(articleId))
        // 更新前端显示的浏览量
        if (article.value.viewCount) {
          article.value.viewCount++
        } else {
          article.value.viewCount = 1
        }
      } catch (err) {
        console.error('增加文章浏览量失败:', err)
        // 不阻止主流程
      }
    } else {
      throw new Error('文章不存在或已被删除')
    }
  } catch (err) {
    error.value = err instanceof Error ? err.message : '获取文章详情失败，请稍后重试'
    console.error('获取文章详情失败:', err)
    ElMessage.error(error.value)
  } finally {
    loading.value = false
  }
}

/**
 * 返回上一页
 */
const goBack = () => {
  router.back()
}

/**
 * 处理相关文章点击事件
 * @param {number} id - 相关文章ID
 */
const handleRelatedArticleClick = (id: number) => {
  router.push({
    path: '/article/:url',
    query: { url: id }
  })
}

/**
 * 组件挂载时获取文章详情
 */
onMounted(() => {
  fetchArticleDetail()
})
</script>

<style scoped>
/* 文章详情容器 */
.article-detail-wrapper {
  max-width: 900px;
  margin: 0 auto;
  background-color: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(0, 0, 0, 0.05);
}

/* 加载状态容器 */
.loading-state-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 40px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 错误状态容器 */
.error-state-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 60px 40px;
  background-color: white;
  border-radius: 12px;
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.error-state-container .el-button {
  margin-top: 16px;
}

/* 空状态容器 */
.empty-state-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 80px 40px;
  background-color: white;
  border-radius: 12px;
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 文章头部区域 */
.article-header-section {
  margin-bottom: 32px;
  padding-bottom: 24px;
  border-bottom: 2px solid #ecf0f1;
}

/* 文章标题 */
.article-main-title {
  font-size: 2rem;
  color: #2c3e50;
  line-height: 1.4;
  margin-bottom: 20px;
  font-weight: 600;
}

/* 文章元信息 */
.article-meta-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  color: #7f8c8d;
  font-size: 0.95rem;
}

/* 元信息项 */
.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
}

/* 文章内容区域 */
.article-content-area {
  font-size: 1.05rem;
  line-height: 1.8;
  color: #34495e;
  margin-bottom: 32px;
}

/* 文章内容中的段落 */
.article-content-area p {
  margin-bottom: 16px;
  text-align: justify;
}

/* 文章内容中的二级标题 */
.article-content-area h2 {
  color: #2c3e50;
  font-size: 1.5rem;
  margin: 32px 0 16px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #ecf0f1;
  font-weight: 600;
}

/* 文章内容中的三级标题 */
.article-content-area h3 {
  color: #34495e;
  font-size: 1.3rem;
  margin: 24px 0 12px 0;
  font-weight: 600;
}

/* 文章内容中的图片 */
.article-content-area img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  margin: 20px auto;
  display: block;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 文章内容中的引用 */
.article-content-area blockquote {
  border-left: 4px solid #3498db;
  padding-left: 16px;
  color: #7f8c8d;
  margin: 16px 0;
  font-style: italic;
}

/* 文章底部区域 */
.article-footer-section {
  padding-top: 24px;
  border-top: 2px solid #ecf0f1;
  margin-bottom: 32px;
}

/* 标签列表 */
.article-tag-list {
  margin-bottom: 24px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

/* 文章操作按钮组 */
.article-actions-group {
  display: flex;
  justify-content: flex-start;
}

/* 相关文章区域 */
.related-articles-section {
  padding-top: 32px;
  border-top: 2px solid #ecf0f1;
}

/* 相关文章标题 */
.related-articles-section h3 {
  font-size: 1.3rem;
  color: #2c3e50;
  margin-bottom: 16px;
  font-weight: 600;
}

/* 相关文章列表容器 */
.related-articles-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 相关文章卡片 */
.related-article-card {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

/* 相关文章卡片悬停效果 */
.related-article-card:hover {
  background-color: #e9ecef;
  transform: translateX(5px);
  border-color: #3498db;
}

.related-article-card i {
  color: #3498db;
}

.related-article-card span {
  font-size: 1rem;
  color: #495057;
  transition: color 0.3s ease;
}

.related-article-card:hover span {
  color: #3498db;
}

/* 评论区样式 */
.comment-section {
  margin-top: 32px;
}

/* 响应式设计 - 平板和手机 */
@media (max-width: 768px) {
  #article-detail-page {
    padding: 20px 0;
  }

  .article-detail-wrapper,
  .loading-state-container,
  .error-state-container,
  .empty-state-container {
    padding: 20px;
    margin: 0 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .article-main-title {
    font-size: 1.5rem;
    line-height: 1.5;
  }

  .article-meta-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
    font-size: 0.9rem;
  }

  .article-content-area {
    font-size: 1rem;
    line-height: 1.7;
  }

  .article-content-area h2 {
    font-size: 1.3rem;
    margin: 24px 0 12px 0;
  }

  .article-content-area h3 {
    font-size: 1.2rem;
    margin: 20px 0 10px 0;
  }

  .related-articles-section h3 {
    font-size: 1.2rem;
  }

  .related-article-card {
    padding: 10px;
    gap: 8px;
  }

  .related-article-card span {
    font-size: 0.95rem;
  }
}

/* 响应式设计 - 小屏幕手机 */
@media (max-width: 480px) {
  .article-detail-wrapper {
    padding: 16px;
  }

  .article-main-title {
    font-size: 1.35rem;
  }

  .article-meta-info {
    font-size: 0.85rem;
  }
}
</style>
