<template>
  <a-spin :spinning="loading">
    <a-card title="轮播与公告">
      <a-carousel autoplay>
        <div v-for="item in home.carousels" :key="item.id" class="banner">
          <img :src="previewUrl(item.imageUrl)" alt="banner" />
        </div>
      </a-carousel>
      <a-list :data-source="home.notices" style="margin-top: 16px">
        <template #renderItem="{ item }">
          <a-list-item>{{ item.title }}</a-list-item>
        </template>
      </a-list>
    </a-card>

    <a-card title="热门商品" style="margin-top: 16px">
      <a-row :gutter="16">
        <a-col :span="6" v-for="item in home.hot" :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>
          </a-card>
        </a-col>
      </a-row>
    </a-card>

    <a-card title="新品上架" style="margin-top: 16px">
      <a-row :gutter="16">
        <a-col :span="6" v-for="item in home.newest" :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>
          </a-card>
        </a-col>
      </a-row>
    </a-card>
  </a-spin>
</template>

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

const loading = ref(false)
const home = reactive({ carousels: [], notices: [], hot: [], newest: [] })
const router = useRouter()

const baseUrl = 'http://localhost:8080'
const load = async () => {
  loading.value = true
  try {
    const res = await api.get('/api/public/home')
    if (res.success) Object.assign(home, res.data)
  } finally {
    loading.value = false
  }
}

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

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

onMounted(load)
</script>

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