<template>
  <app-view class="supply-demand">
    <template #header>
      <app-navbar class="supply-demand__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="supply-demand__container" v-model:loading="loading"
      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)" />
          </div>
          <div class="block">
            <span>{{ item.wrstandardname }}</span>
            <span>{{ item.wrfactortypename }}</span>
          </div>
          <div class="block">
            <Button type="primary" size="small" round
              @click="$router.push({ name: 'SupplyDemandDetail', query: { wrfactortypeid: item.wrfactortypeid } })">去下单</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 { getFileUrl } from '@/filters'
import { useRequest } from '@/hooks/request'
import { queryOrderQuote } from '@/services/api/goods'
import AppPullRefresh from '@mobile/components/base/pull-refresh/index.vue'

const dataList = shallowRef<Model.OrderQuoteRsp[]>([])
const error = shallowRef(false)
const pullRefreshRef = shallowRef()
const keyword = shallowRef('')

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

const onRefresh = () => {
  run({ dgitemname: keyword.value })
}

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

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

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