<!-- 文章列表组件 -->
<template>
  <div class="article-list-container">
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :count="5" />
    </div>
    
    <!-- 文章列表 -->
    <transition-group name="article-item" tag="div" v-else>
      <div
        class="article-card"
        v-for="article in articleList"
        :key="article.articleId"
        @click="handleArticleClick(article)"
      >
        <h6 class="article-title">{{ article.title }}</h6>
        <div v-if="article.marked" class="article-special-tag">标记文章</div>
        <p class="article-content-preview">{{ formatContentPreview(article.content, 150) }}</p>
        <div class="article-meta-info">
          <span class="article-publish-date">{{ formatDateDisplay(article.createdAt || article.createTime) }}</span>
          <span v-if="article.viewCount" class="article-views-count">{{ article.viewCount }} 阅读</span>
          <span v-if="article.categoryName" class="article-category-badge"> {{ article.categoryName }} </span>
          <span v-if="article.likes > 0" class="article-likes-count">{{ article.likes }} 点赞</span>
          <span v-if="article.commentCount > 0" class="article-comments-count">{{ article.commentCount }} 评论</span>
        </div>
      </div>
    </transition-group>
    <!-- 空状态 -->
    <div v-if="!loading && articleList.length === 0" class="empty-state-container">
      <el-empty description="暂无文章" />
    </div>
  </div>
</template>

<script setup>
import { useRouter, useRoute } from 'vue-router'
import { ref, onMounted } from 'vue'
import { formatDate, formatRelativeTime } from '@/utils/dateUtils'
import { formatContentPreview } from '@/utils/stringUtils'
import { ElMessage } from 'element-plus'
import { articleService, messageService, categoryAttributeService } from '@/services'
import { useGlobalStore } from '@/store/globalStore'

// 全局状态管理
const globalStore = useGlobalStore()

// 路由相关
const router = useRouter()
const route = useRoute()

// 响应式状态
const articleList = ref([])
const loading = ref(false)

/**
 * 获取文章列表
 */
const fetchArticles = async () => {
  try {
    loading.value = true
    let response = {} 
    
    // 检查URL参数，确定获取文章的方式
    const pathSegment = route.path.split('/')[2];
    
    // 根据不同路径获取不同文章
    if (pathSegment === 'aericletype') {
      // 按属性类型获取文章
      const attributeData = globalStore.getValue('attribute')
      response = await articleService.getArticlesByAttributeId(attributeData.id)
    } else if (pathSegment === 'aericletitle') {
      // 按标题搜索文章
      const titleData = globalStore.getValue('articleserarch')
      response = await articleService.getArticlesByTitle(titleData.name)
    } else {
      // 获取所有文章
      console.log('获取所有文章列表')
      response = await articleService.getAllArticles()
    }
    
    // 为每个文章获取留言数量和分类名称
    for (const article of response.data) {
      try {
        // 获取留言数量
        const messageResponse = await messageService.getMessagesByArticleId(article.articleid)
        // console.log(`文章ID: ${article.articleid}, 分类ID: ${article.attributeid}`)
        
        // 获取分类名称
        const categoryResponse = await categoryAttributeService.getAttributeById(article.attributeid)

        if (categoryResponse && categoryResponse.data) {
          article.categoryName = categoryResponse.data.attributename
        } else {
          article.categoryName = '未分类'
        }
        
        // 设置评论数量
        article.commentCount = messageResponse.data.length > 0 ? messageResponse.data.length : 0
        
        // 标准化ID字段名
        article.articleId = article.articleid
        
        // 标准化标记字段名
        article.marked = article.mg
      } catch (err) {
        console.error(`获取文章${article.articleid}留言数量失败:`, err)
        article.commentCount = 0
      }
    }
    
    // 更新文章列表
    // console.log(response.data)
    articleList.value = response.data || []
  } catch (error) {
    console.error('获取文章列表失败:', error)
    ElMessage.error('获取文章列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

/**
 * 处理文章点击事件
 * @param {Object} article - 文章对象
 */
const handleArticleClick = (article) => {
  
  // 存储文章信息到全局状态
  globalStore.setValue('articleInfo', article)
  
  // 跳转到文章详情页
  router.push({
    path: '/article',
  })
}

/**
 * 格式化日期显示
 * @param {string} dateString - 日期字符串
 * @returns {string} 格式化后的日期
 */
const formatDateDisplay = (dateString) => {
  if (!dateString) return ''
  try {
    // 如果是今天或昨天的文章，显示相对时间
    const date = new Date(dateString)
    const now = new Date()
    const diffDays = Math.floor((now - date) / (1000 * 60 * 60 * 24))
    
    if (diffDays < 2) {
      return formatRelativeTime(dateString)
    }
    
    // 否则显示具体日期
    return formatDate(dateString, 'YYYY-MM-DD')
  } catch (error) {
    console.error('日期格式化错误:', error)
    return dateString
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchArticles()
})
</script>

<style scoped>
/* 文章列表容器样式 */
.article-list-container {
  max-width: 100%;
  padding: 0 15px;
}

/* 加载状态容器 */
.loading-container {
  padding: 20px;
  display: flex;
  justify-content: center;
}

/* 文章卡片样式 */
.article-card {
  text-align: left;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  background-color: rgba(255, 255, 255, 0.95);
  padding: 24px;
  margin-bottom: 24px;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(0, 0, 0, 0.05);
}
/* 文章卡片悬停渐变效果 */
.article-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, 
            rgba(255, 255, 255, 0.6) 0%, 
            rgba(255, 255, 255, 0.2) 50%,
            rgba(255, 255, 255, 0.05) 100%);
  pointer-events: none;
  opacity: 0;
  transition: opacity 0.4s ease;
}

/* 文章卡片悬停效果 */
.article-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 28px rgba(0, 0, 0, 0.15),
              0 0 30px rgba(255, 255, 255, 0.2);
  border-color: rgba(52, 152, 219, 0.3);
}

.article-card:hover::before {
  opacity: 1;
}

/* 文章过渡动画 */
.article-item {
  transition: all 0.4s ease;
}

/* 文章标题样式 */
.article-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
  transition: color 0.3s ease;
  line-height: 1.4;
}

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

/* 特殊标记标签样式 */
.article-special-tag {
  display: inline-block;
  padding: 3px 10px;
  background-color: rgba(52, 152, 219, 0.15);
  color: #3498db;
  border-radius: 6px;
  font-size: 0.75rem;
  font-weight: 500;
  align-self: flex-start;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

/* 文章内容预览样式 */
.article-content-preview {
  color: #555;
  line-height: 1.6;
  margin: 0;
  font-size: 0.95rem;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 文章元信息容器 */
.article-meta-info {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  font-size: 0.875rem;
  color: #7f8c8d;
  margin-top: auto;
  padding-top: 10px;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
}

/* 发布日期样式 */
.article-publish-date {
  font-weight: 500;
  color: #95a5a6;
}

/* 阅读数量样式 */
.article-views-count {
  display: flex;
  align-items: center;
  color: #95a5a6;
}

.article-views-count::before {
  content: '|';
  margin-right: 12px;
  color: #e0e0e0;
}

/* 分类标签样式 */
.article-category-badge {
  display: flex;
  align-items: center;
  padding: 2px 10px;
  background-color: rgba(52, 152, 219, 0.1);
  color: #3498db;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: 500;
}

.article-category-badge::before {
  content: '|';
  margin-right: 12px;
  color: #e0e0e0;
}

/* 点赞数量样式 */
.article-likes-count {
  display: flex;
  align-items: center;
  color: #95a5a6;
}

.article-likes-count::before {
  content: '|';
  margin-right: 12px;
  color: #e0e0e0;
}

/* 评论数量样式 */
.article-comments-count {
  display: flex;
  align-items: center;
  color: #95a5a6;
}

.article-comments-count::before {
  content: '|';
  margin-right: 12px;
  color: #e0e0e0;
}

/* 空状态容器样式 */
.empty-state-container {
  text-align: center;
  padding: 60px 20px;
  color: #7f8c8d;
}

/* 过渡动画配置 */
.article-item-enter-active,
.article-item-leave-active {
  transition: all 0.5s ease;
}

.article-item-enter-from,
.article-item-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

/* 响应式设计 - 平板和手机 */
@media (max-width: 768px) {
  .article-list-container {
    padding: 0 10px;
  }
  
  .article-card {
    padding: 18px;
    margin-bottom: 18px;
    gap: 10px;
  }
  
  .article-title {
    font-size: 1.125rem;
  }
  
  .article-meta-info {
    font-size: 0.8rem;
    gap: 8px;
  }
  
  .article-content-preview {
    font-size: 0.9rem;
  }
  
  /* 响应式元信息分隔符 */
  .article-views-count::before,
  .article-category-badge::before,
  .article-likes-count::before,
  .article-comments-count::before {
    margin-right: 8px;
  }
}

/* 响应式设计 - 小屏幕手机 */
@media (max-width: 480px) {
  .article-card {
    padding: 16px;
    margin-bottom: 16px;
  }
  
  .article-meta-info {
    font-size: 0.75rem;
    gap: 6px;
  }
  
  .article-special-tag {
    font-size: 0.7rem;
    padding: 2px 8px;
  }
}
</style>
