<template>
  <div class="news-more-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 style="font-family: 'Source Han Serif CN', '思源宋体 CN', serif;">
        新闻动态<span class="en-title" style="font-family: 'Source Han Serif CN', '思源宋体 CN', serif;">News</span>
      </h2>
    </div>

    <!-- 加载状态 -->
    <el-loading v-loading="isLoading" text="加载中..." class="loading-container"></el-loading>

    <!-- 新闻列表 -->
    <div class="news-list" v-if="newsList.length > 0">
      <el-card
        class="news-item-card"
        v-for="(news, index) in newsList"
        :key="news.id"
        shadow="hover"
        :body-style="{ padding: '0px' }"
        @click="handleDetailClick(news)"
      >
        <div class="news-item">
          <div class="news-img-container">
            <img :src="news.imageUrl" :alt="news.title" class="news-img">
          </div>
          <div class="news-content">
            <div class="news-header">
              <h3 class="news-title">{{ news.title }}</h3>
              <span class="news-date">{{ news.date }}</span>
            </div>
            <p class="news-desc">{{ news.desc }}</p>
            <div class="read-more">
              阅读全文 <el-icon class="read-icon"><ArrowRight /></el-icon>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-else-if="!isLoading">
      <el-empty description="暂无新闻数据"></el-empty>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container" v-if="total > 0 && !isLoading">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { ElCard, ElLoading, ElMessage, ElEmpty, ElPagination, ElIcon } from 'element-plus';
import { ArrowRight } from '@element-plus/icons-vue';
import axios from 'axios';
import { useRouter } from 'vue-router';

// 数据结构
interface NewsItem {
  id: number;
  imageUrl: string;
  title: string;
  desc: string;
  date: string;
}

interface Article {
  id: number;
  title: string;
  cover: string;
  excerpt: string;
  create_at: string;
  content: string;
  topic: string;
}

interface ArticleResponse {
  total: number;
  total_page: number;
  Article_list: Article[];
  page: number;
  size: number;
}

// 响应式数据
const router = useRouter();
const newsList = ref<NewsItem[]>([]);
const isLoading = ref<boolean>(false);
const currentPage = ref<number>(1);
const pageSize = ref<number>(20);
const total = ref<number>(0);

// 详情跳转
const handleDetailClick = (item: NewsItem) => {
  router.push({
    path: '/detail',
    query: {
      id: item.id,
      type: 'news'
    }
  });
};

// HTML转纯文本
function stripHtml(htmlStr: string): string {
  if (!htmlStr) return '';
  const doc = new DOMParser().parseFromString(htmlStr, 'text/html');
  return doc.body.textContent || "";
}

// 格式化日期
function formatDate(dateStr: string): string {
  const date = new Date(dateStr);
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
}

// 获取新闻数据（支持分页）
const fetchNewsData = async () => {
  isLoading.value = true;
  try {
    const response = await axios.post<ArticleResponse>(
      'http://localhost:8080/api/articles/getarticle',
      {
        page: currentPage.value,
        size: pageSize.value,
        topic: '新闻'
      },
      {
        headers: { 'Content-Type': 'application/json' }
      }
    );

    const data = response.data;
    if (data && Array.isArray(data.Article_list)) {
      // 转换数据格式
      newsList.value = data.Article_list.map((article: Article) => ({
        id: article.id,
        imageUrl: article.cover || 'https://picsum.photos/800/400?random=news',
        title: article.title,
        desc: stripHtml(article.excerpt || article.content).slice(0, 150) + '...',
        date: formatDate(article.create_at)
      }));
      total.value = data.total; // 总条数
    } else {
      newsList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取新闻列表失败：', error);
    ElMessage.error('新闻数据加载失败，请重试');
    newsList.value = [];
    total.value = 0;
  } finally {
    isLoading.value = false;
  }
};

// 分页事件处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1; // 切换每页条数时重置为第一页
  fetchNewsData();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchNewsData();
};

// 页面挂载时加载数据
onMounted(() => {
  fetchNewsData();
});
</script>

<style scoped>
.news-more-container {
  max-width: 1200px;
  margin: 30px auto;
  padding: 0 20px;
}

.page-header {
  margin-bottom: 30px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.page-header h2 {
  font-size: 26px;
  margin: 0;
  font-weight: 400;
}

.en-title {
  font-size: 16px;
  color: #999;
  margin-left: 10px;
  text-transform: uppercase;
}

.loading-container {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.news-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.news-item-card {
  cursor: pointer;
  transition: all 0.3s ease;
}

.news-item-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.news-item {
  display: grid;
  grid-template-columns: 240px 1fr;
  gap: 20px;
  padding: 20px;
}

.news-img-container {
  width: 100%;
  height: 160px;
  overflow: hidden;
}

.news-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.news-item-card:hover .news-img {
  transform: scale(1.05);
}

.news-content {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.news-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.news-title {
  font-size: 20px;
  font-weight: 500;
  color: #333;
  margin: 0;
  max-width: 80%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.news-date {
  font-size: 14px;
  color: #999;
}

.news-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.7;
  margin: 0 0 15px 0;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.read-more {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #b50009;
  font-size: 14px;
  font-weight: 500;
  width: fit-content;
}

.read-icon {
  font-size: 16px;
  transition: transform 0.2s ease;
}

.news-item-card:hover .read-icon {
  transform: translateX(3px);
}

.empty-state {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pagination-container {
  margin-top: 40px;
  display: flex;
  justify-content: center;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .news-item {
    grid-template-columns: 1fr;
  }

  .news-img-container {
    height: 200px;
  }

  .news-title {
    max-width: 100%;
    white-space: normal;
    margin-bottom: 8px;
  }

  .news-header {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
