<script lang="ts" setup>
// 设置页面布局
// 导入API配置
import {getArticleApiUrl} from '~/config/api'


// 获取路由参数
const route = useRoute()
const articleId = route.params.id as string

// 文章数据
const articleData = ref({
  title: '',
  publishDate: '',
  category: '',
  content: '',
  prevArticle: {
    title: '',
    url: '#'
  },
  nextArticle: {
    title: '',
    url: '#'
  }
})

// 加载状态
const loading = ref(true)
const error = ref('')

// 获取文章详情
const fetchArticle = async (id: string) => {
  try {
    loading.value = true
    error.value = ''

    const response = await fetch(getArticleApiUrl('GET', id))

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const res = await response.json()
    const data = res.data

    console.log('api请求数据', data)

    // 分类映射配置
    const categoryMapping: Record<string, string> = {
      'solution': '解决方案',
      'developKnowledge': '开发知识',
      'industryTrend': '行业动态',
      'aboutUs': '关于我们'
    }

    data.code = categoryMapping[data.code] || '暂无分类'

    // 更新文章数据
    articleData.value = {
      title: data.title || '暂无标题',
      publishDate: data.createTime || '暂无日期',
      category: data.code || '暂无分类',
      content: data.content || '暂无内容',
      prevArticle: data.prevArticle || {
        title: '暂无上一篇',
        url: '#'
      },
      nextArticle: data.nextArticle || {
        title: '暂无下一篇',
        url: '#'
      }
    }
  } catch (err) {
    console.error('获取文章失败:', err)
    error.value = '获取文章失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取文章详情
onMounted(() => {
  if (articleId) {
    fetchArticle(articleId)
  }
})

// 监听路由变化
watch(() => route.params.id, (newId) => {
  if (newId) {
    fetchArticle(newId as string)
  }
})
</script>

<template>
  <view>
    <NewsNew :article-data="articleData" :error="error" :loading="loading"/>
  </view>
</template>

<style scoped>
</style>
