<template>
  <div class="article-list">
    <!-- 骨架屏加载状态 -->
    <template v-if="loading">
      <div v-for="index in page.size" :key="`skeleton-${index}`" class="article-skeleton">
        <el-skeleton animated>
          <template #template>
            <div class="skeleton-item">
              <el-skeleton-item variant="image" class="skeleton-image" />
              <div class="skeleton-content">
                <el-skeleton-item variant="text" class="skeleton-date" />
                <el-skeleton-item variant="h3" class="skeleton-title" />
                <el-skeleton-item variant="text" class="skeleton-desc" />
                <el-skeleton-item variant="text" class="skeleton-desc" />
                <el-skeleton-item variant="text" class="skeleton-desc" />
                <el-skeleton-item variant="text" class="skeleton-desc skeleton-desc-short" />
              </div>
            </div>
          </template>
        </el-skeleton>
      </div>
    </template>

    <!-- 实际内容 -->
    <template v-else>
      <ArticleListItem v-for="(item, index) in dataList" :data="item" v-bind="$attrs" :key="index"></ArticleListItem>
    </template>

    <!-- 分页 -->
    <el-pagination
      class="article-list-pagination"
      background
      layout="prev, pager, next"
      :page-size="page.size"
      :total="page.total"
      v-model:current-page="page.currentPage"
      @current-change="fetchList"
      :hide-on-single-page="true">
    </el-pagination>
  </div>
</template>

<script setup>
const props = defineProps({
  remote: { type: Object, default: () => ({}) },
  hasPagination: { type: Boolean, default: true },
  limit: { type: Number, default: 10 },
})

const route = useRoute()
const page = ref({ total: 0, size: props.limit, currentPage: 1 })

// Generate unique key for useAsyncData based on remote config and route
// Key should be static, not include page number
const dataKey = computed(() => {
  const paramsStr = JSON.stringify(props.remote?.params || {})
  const typeTag = props.remote?.params?.type_tag || 'default'
  // Use route path and params to create unique key for each ArticleList instance
  return `article-list-${route.path}-${typeTag}-${paramsStr}`
})

// Fetch list data function
const fetchListData = async () => {
  if (!props.remote || !props.remote.httpRequest) {
    return { data: [], total: 0 }
  }

  const { httpRequest, beforeRequest, callback } = props.remote

  // Setup parameters
  let requestParams = { ...props.remote.params }

  // Add pagination params
  if (props.hasPagination) {
    requestParams.page = page.value.currentPage
    requestParams.limit = page.value.size
  }

  // Before request hook
  if (beforeRequest) {
    requestParams = beforeRequest(requestParams)
  }

  // Clean up empty params
  for (const key in requestParams) {
    if (requestParams[key] === '' || requestParams[key] === undefined || requestParams[key] === null) {
      delete requestParams[key]
    }
  }

  try {
    const res = await httpRequest(requestParams)
    const { data = [], total = 0 } = res.data || {}
    const processedData = callback ? callback(data) : data
    return { data: processedData, total }
  } catch (error) {
    console.error('Failed to fetch article list:', error)
    return { data: [], total: 0 }
  }
}

// Use useAsyncData for SSR
const {
  data: listData,
  pending,
  refresh,
} = useAsyncData(() => dataKey.value, fetchListData, {
  watch: [() => page.value.currentPage, () => props.remote?.params],
  default: () => ({ data: [], total: 0 }),
})

const dataList = computed(() => listData.value?.data || [])
const loading = computed(() => pending.value)

// Update page total when data changes
watch(
  () => listData.value?.total,
  (total) => {
    if (total !== undefined) {
      page.value.total = total
    }
  },
  { immediate: true }
)

// Fetch list function for pagination
const fetchList = async () => {
  await refresh()
}

// Watch remote params changes
watch(
  () => props.remote?.params,
  () => {
    // Reset to first page when params change
    page.value.currentPage = 1
  },
  { deep: true }
)

// Watch remote object to refetch when it changes
watch(
  () => props.remote,
  () => {
    if (props.remote?.httpRequest && props.remote?.params) {
      page.value.currentPage = 1
      refresh()
    }
  },
  { deep: true }
)
</script>

<style lang="scss">
.article-list {
  overflow: hidden;
}

.article-list-pagination {
  padding: 40px 0;
  text-align: center;
  justify-content: center;
}

.article-skeleton {
  border-bottom: 1px solid #e6e6e6;
  padding: 36px 0;
}

.skeleton-item {
  display: flex;
  gap: 30px;
}

.skeleton-image {
  width: 360px;
  height: 270px;
  flex-shrink: 0;
  border-radius: 4px;
  display: block;
}

.skeleton-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  padding-top: 0;
}

.skeleton-date {
  width: 80px;
  height: 16px;
  margin-bottom: 10px;
}

.skeleton-title {
  width: 70%;
  height: 32px;
  margin-top: 10px;
  margin-bottom: 15px;
}

.skeleton-desc {
  width: 100%;
  height: 20px;
  margin-bottom: 6px;
}

.skeleton-desc-short {
  width: 45%;
}
</style>
