<template>
  <app-view class="purchase">
    <template #header>
      <app-navbar class="purchase__header" title="采购" :show-back-button="false">
        <template #footer>
          <Search shape="round" placeholder="商品搜索" v-model="keyword" @search="pullRefreshRef.refresh()" />
        </template>
      </app-navbar>
    </template>
    <app-pull-refresh ref="pullRefreshRef" class="purchase__container" v-model:error="error"
      v-model:pageIndex="pageIndex" :page-count="pageCount" @refresh="onRefresh">
      <ul class="list">
        <li class="list-item g-block--bg" v-for="(item, index) in dataList" :key="index">
          <div class="block">
            <img :src="getFirstImage(item.thumurls)" />
            <span>{{ item.wrstandardname }}</span>
          </div>
          <div class="block">
            <Button type="primary" size="small" round
              @click="$router.push({ name: 'PurchaseDetail', query: { wrstandardid: item.wrstandardid } })">去采购</Button>
          </div>
        </li>
      </ul>
    </app-pull-refresh>
  </app-view>
</template>

<script lang="ts" setup>
import { shallowRef, onActivated } from 'vue'
import { Search, Button } from 'vant'
import { getImageUrl } from '@/filters'
import { useWrstandardList } from '@/business/goods'
import AppPullRefresh from '@mobile/components/base/pull-refresh/index.vue'

const { pageIndex, pageCount, getWrstandardList } = useWrstandardList()
const dataList = shallowRef<Model.THJWrstandardRsp[]>([])
const error = shallowRef(false)
const pullRefreshRef = shallowRef()
const keyword = shallowRef('')

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

const onRefresh = (finish: () => void) => {
  getWrstandardList({ wrstandardname: keyword.value }).then((res) => {
    if (pageIndex.value === 1) {
      dataList.value = []
    }
    dataList.value.push(...res)
  }).catch(() => {
    error.value = true
  }).finally(() => {
    finish()
  })
}

onActivated(() => {
  keyword.value = ''
  pullRefreshRef.value?.refresh()
})
</script>

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