<template>
  <view class="tab-content">

    <!-- <view class="col-12 m-b30">
      <view class="card card-action action-elevate action-border-primary">
        <view class="row g-0">
          <view class="col-md-3">
            <view class="card-header border-0 p-0 m-2 position-relative overflow-hidden">
              <image src="/static/images/vu/news.jpg" alt="" class="img-fluid rounded" mode="widthFix" />
            </view>
          </view>
          <view class="col-md-9 py-3 d-flex flex-column">
            <view class="card-body px-3 py-2">
              <a href="-" class="badge badge-sm bg-danger mb-1">Trading</a>
              <h4><span class="text-2xs text-body"><i class="icon-calendar text-primary"></i> 2025-03-24 l
                  10:30 AM</span><br>
                <a href="-" class="text-dark">Dollar Index (ICE) Intraday:
                  caution</a>
              </h4>
              <p>We are thrilled to announce that CWG Markets has been honored
                with the prestigious title of Leading Financial Services..</p>
            </view>

          </view>
        </view>
      </view>
    </view> -->
    <!-- 列表 -->
    <view v-if="list.length > 0" class="list">
      <view v-for="item in list" :key="item.id" class="col-12 m-b30">
        <view class="card card-action action-elevate action-border-primary cursor-pointer" @click="handleItemClick(item)" :data-tooltip="t('vu.tooltip.t4',{pageName:currentTitleText})" data-placement="top">
          <view class="row g-0">
            <view class="col-md-3" v-if="item.coverImage">
              <view class="card-header border-0 p-0 m-2 position-relative overflow-hidden">
                <image v-if="item.coverImage" :src="imgUrl + item.coverImage" class="img-fluid rounded"
                  mode="widthFix" />
                <view v-else class="placeholder-image"></view>
              </view>
            </view>
            <view class="col-md-9 py-3 d-flex flex-column">
              <view class="card-body px-3 py-2">
                <!-- <a href="#" class="badge badge-sm bg-danger mb-1">Trading</a> -->
                <h5>
                  <span class="text-2xs text-body p-text"><i class="icon-calendar text-primary"></i> {{
                    formatDate(item.deliveryTime) }}</span><br>
                  <text class="text-dark h5">{{ item.title }}</text>
                </h5>
                <p class="p-text">{{ item.subTitle }}</p>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-else-if="!loading && list.length === 0" class="list-empty-state empty">
      <cwg-empty-state />
    </view>
    <view class="table-loading-mask">
      <uni-loading v-if="loading" />
    </view>
  </view>

</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import Config from '@/config/index'
const { locale } = useI18n()

const props = defineProps({
  fetchData: { type: Function, required: true },
  queryParams: { type: Object, default: () => ({}) },
  pageSize: { type: Number, default: 10 },
  type: { type: Number, default: 0 },
  immediate: { type: Boolean, default: true },
})
const imgUrl = computed(() => props.queryParams.tag !== 3 ? Config.Host80 : Config.Host05)

const list = ref([])
const page = ref(1)
const loading = ref(false)
const loadingMore = ref(false)
const finished = ref(false)
const total = ref(0)

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return dateStr.slice(0, 10).replace('T', ' ')
}
const currentTitleText = computed(() => {
  const map = {
    1: t('News.ViewAnalysis'),
    2: t('News.NewsInformation'),
    3: t('News.Announcement'),
    4: t('News.VideoCommentary'),
    5: t('News.NewsInformation'),
    6: t('News.VideoCommentary'),
    7: t('News.Notice'),
    8: t('News.TradeIdeas'),
    9: t('News.FinancialCalendar'),
    10: t('News.Ebook'),
    11: t('News.VideoCommentary')
  }
  return map[props.type] || ''
})

const load = async () => {
  list.value = []
  if (loading.value) return
  loading.value = true
  finished.value = false
  page.value = 1

  try {
    const res = await props.fetchData({
      lang: locale.value == 'vn' ? 'vi' : locale.value,
      page: { current: page.value, row: props.queryParams?.pageSize || props.pageSize },
      ...props.queryParams
    })
    if (res.code === 200) {
      list.value = res.data || []
      total.value = res.page?.rowTotal || 0
      finished.value = list.value.length >= total.value
    } else {
      throw new Error(res.msg || '请求失败')
    }
  } catch (err) {
    console.error('加载失败', err)
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

const loadMore = async () => {
  if (loadingMore.value || finished.value) return
  loadingMore.value = true
  try {
    const nextPage = page.value + 1
    const params = {
      lang: locale.value,
      page: { current: nextPage, row: props.queryParams?.pageSize || props.pageSize },
      ...props.queryParams
    }
    const res = await props.fetchData(params)
    if (res.code === 200) {
      const newList = res.data || []
      if (newList.length > 0) {
        list.value.push(...newList)
        page.value = nextPage
      }
      const totalRows = res.page?.rowTotal || total.value
      finished.value = list.value.length >= totalRows
    } else {
      throw new Error(res.msg || '请求失败')
    }
  } catch (err) {
    uni.showToast({ title: err.message || '加载更多失败', icon: 'none' })
  } finally {
    loadingMore.value = false
  }
}

const handleItemClick = (item) => {
  uni.navigateTo({ url: `/pages/analytics/detail?type=${props.type}&id=${item.id}` })
}

const lang = computed(() => uni.getLocale())
watch(lang, () => {
  load()
}, { immediate: true })

defineExpose({ load, loadMore })
</script>

<style lang="scss" scoped>
@import "@/uni.scss";
.p-text{
  font-size: px2rpx(14);
  line-height: px2rpx(20);
  color: var(--cwg-gray-color)!important;
}
</style>