<template>
  <app-view class="news-list" flex>
    <template #header>
      <app-navbar title="市场资讯" />
    </template>
    <Tabs v-model:active="currentColumnId" @change="onClickTab">
      <template v-for="(item, index) in siteColumns" :key="index">
        <Tab :name="item.id" :title="item.columnname" />
      </template>
    </Tabs>
    <app-pull-refresh ref="pullRefreshRef" class="news-list__container" v-model:loading="loading" v-model:error="error"
      v-model:pageIndex="pageIndex" :page-count="pageCount" @refresh="onRefresh">
      <Empty v-if="!dataList.length" />
      <template v-for="(item, index) in dataList" :key="index">
        <Cell class="article-item" title-class="article-item__title" value-class="article-item__time" :title="item.title"
          :value="formatDate(item.creaedate, 'MM/DD')" :to="{ name: 'news-details', query: { id: item.id } }" />
      </template>
    </app-pull-refresh>
  </app-view>
</template>
  
<script lang="ts" setup>
import { shallowRef } from 'vue'
import { Cell, Tab, Tabs, Empty } from 'vant'
import { formatDate } from '@/filters'
import { useRequest } from '@/hooks/request'
import { querySiteColumnDetail, querySiteColumnConfig } from '@/services/api/news'
import AppPullRefresh from '@mobile/components/base/pull-refresh/index.vue'

const pullRefreshRef = shallowRef()
const dataList = shallowRef<Model.SiteColumnDetailRsp[]>([])
const siteColumns = shallowRef<Model.SiteColumnConfigRsp[]>([])
const currentColumnId = shallowRef(0)
const error = shallowRef(false)

/// 查询栏目配置
const getSiteColumnConfig = querySiteColumnConfig().then((res) => {
  siteColumns.value = res.data
  /// 默认第一个
  if (res.data.length) {
    currentColumnId.value = res.data[0].id
  }
})

const { loading, pageIndex, pageCount, run } = useRequest(querySiteColumnDetail, {
  manual: true,
  params: {
    pagesize: 20,
  },
  onBefore: () => {
    return getSiteColumnConfig
  },
  onSuccess: (res) => {
    if (pageIndex.value === 1) {
      dataList.value = []
    }
    dataList.value.push(...res.data)
  },
  onError: () => {
    error.value = true
  }
})

const onRefresh = () => {
  run({ columnid: currentColumnId.value })
}

// Tab触发
const onClickTab = () => {
  pullRefreshRef.value?.refresh()
}
</script>
  
<style lang="less">
@import './index.less';
</style>