<template>
  <app-view class="product" flex>
    <template #header>
      <app-navbar title="产品介绍" />
    </template>
    <Tabs class="product__tabs" v-model:active="active" @change="onClickTab">
      <Tab title="已关注" :name="0" />
      <Tab title="未关注" :name="1" />
    </Tabs>
    <app-pull-refresh ref="pullRefreshRef" class="product__container" v-model:error="error"
      v-model:pageIndex="pageIndex" :page-count="pageCount" @refresh="onRefresh">
      <Empty v-if="dataList.length === 0" />
      <template v-for="(item, index) in dataList" :key="index">
        <Cell>
          <template #value>
            <img :src="getFirstImage(item.thumurls)" />
            <span>{{ item.wrstandardname }}</span>
            <Button type="primary" round size="small"
              @click="$router.push({ name: 'product-detail', query: { favorite: active, wrstandardid: item.wrstandardid } })">立即进入</Button>
          </template>
        </Cell>
      </template>
    </app-pull-refresh>
  </app-view>
</template>
  
<script lang="ts" setup>
import { shallowRef } from 'vue'
import { Cell, Tabs, Tab, Button, Empty } from 'vant'
import { getImageUrl } from '@/filters'
import { useQueryTHJProductLists } from '@/business/goods'
import AppPullRefresh from '@mobile/components/base/pull-refresh/index.vue'

const { pageIndex, pageCount, getQueryTHJProductLists, active } = useQueryTHJProductLists()
const pullRefreshRef = shallowRef()
const dataList = shallowRef<Model.THJProductRsp[]>([])
const error = shallowRef(false)

// 获取产品首图
const getFirstImage = (url: string) => {
  const images = url.split(',').map((path) => getImageUrl(path))
  return images[0] ?? ''
}

// Tab触发
const onClickTab = () => {
  pullRefreshRef.value?.refresh()
}

const onRefresh = (finish: () => void) => {
  /// 获取产品列表
  getQueryTHJProductLists().then((res) => {
    if (pageIndex.value === 1) {
      dataList.value = []
    }
    dataList.value.push(...res)
  }).catch(() => {
    error.value = true
  }).finally(() => {
    finish()
  })
}

</script>

<style lang="less">
@import './index.less';
</style>