<template>
  <a-card>
    <a-space>
      <a-input v-model:value="keyword" placeholder="搜索商品" style="width: 200px" />
      <a-select v-model:value="categoryId" placeholder="分类" style="width: 160px" allowClear>
        <a-select-option v-for="c in categories" :key="c.id" :value="c.id">{{ c.name }}</a-select-option>
      </a-select>
      <a-select v-model:value="sort" placeholder="排序" style="width: 160px" allowClear>
        <a-select-option value="price">价格</a-select-option>
        <a-select-option value="sales">销量</a-select-option>
      </a-select>
      <a-button type="primary" @click="load">搜索</a-button>
    </a-space>
  </a-card>

  <a-row :gutter="16" style="margin-top: 16px">
    <a-col :span="6" v-for="item in list" :key="item.id">
      <a-card hoverable @click="goDetail(item.id)">
        <img v-if="item.imageUrl" :src="previewUrl(item.imageUrl)" class="card-img" />
        <div class="title">{{ item.name }}</div>
        <div class="price">￥{{ item.price }}</div>
        <div class="meta">销量 {{ item.sales }}</div>
      </a-card>
    </a-col>
  </a-row>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import api from '../../api'

const router = useRouter()
const baseUrl = 'http://localhost:8080'
const list = ref([])
const categories = ref([])
const keyword = ref('')
const categoryId = ref(null)
const sort = ref(null)

const load = async () => {
  const res = await api.get('/api/public/products', {
    params: { keyword: keyword.value, categoryId: categoryId.value, sort: sort.value }
  })
  if (res.success) list.value = res.data
}

const loadCategories = async () => {
  const res = await api.get('/api/public/home')
  if (res.success) categories.value = res.data.categories
}

const goDetail = (id) => router.push(`/products/${id}`)

const previewUrl = (url) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  return `${baseUrl}${url}`
}

onMounted(() => {
  load()
  loadCategories()
})
</script>

<style scoped>
.title { font-weight: 600; }
.price { color: #f5222d; }
.meta { color: #999; }
.card-img {
  width: 100%;
  height: 140px;
  object-fit: cover;
  margin-bottom: 8px;
}
</style>
