<template>
  <a-spin :spinning="loading">
    <a-card>
      <a-row :gutter="16">
        <a-col :span="10">
          <a-carousel>
            <div v-for="img in images" :key="img.id" class="banner">
              <img :src="previewUrl(img.url)" alt="img" />
            </div>
          </a-carousel>
        </a-col>
        <a-col :span="14">
          <h2>{{ product.name }}</h2>
          <p>{{ product.description }}</p>
          <div class="price">￥{{ product.price }}</div>
          <div>库存：{{ product.stock }}</div>
          <div>适龄：{{ product.ageRange }}</div>
          <div>安全认证：{{ product.safetyInfo }}</div>
          <a-space style="margin-top: 16px">
            <a-input-number v-model:value="quantity" :min="1" />
            <a-button type="primary" @click="addToCart">加入购物车</a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-card>
  </a-spin>
</template>

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

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const product = ref({})
const images = ref([])
const quantity = ref(1)

const baseUrl = 'http://localhost:8080'
const load = async () => {
  loading.value = true
  try {
    const res = await api.get(`/api/public/products/${route.params.id}`)
    if (res.success) {
      product.value = res.data.product
      images.value = res.data.images
    }
  } finally {
    loading.value = false
  }
}

const addToCart = async () => {
  if (!localStorage.getItem('token')) {
    router.push('/login')
    return
  }
  await api.post('/api/user/cart', { productId: product.value.id, quantity: quantity.value })
  message.success('已加入购物车')
}

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

onMounted(load)
</script>

<style scoped>
.banner { height: 260px; }
.banner img { width: 100%; height: 260px; object-fit: cover; }
.price { color: #f5222d; font-size: 20px; margin: 8px 0; }
</style>
