<template>
  <a-card title="商品管理">
    <a-form layout="inline">
      <a-form-item label="名称"><a-input v-model:value="form.name" /></a-form-item>
      <a-form-item label="价格"><a-input-number v-model:value="form.price" /></a-form-item>
      <a-form-item label="库存"><a-input-number v-model:value="form.stock" /></a-form-item>
      <a-form-item label="分类">
        <a-select v-model:value="form.categoryId" style="width: 120px" allowClear>
          <a-select-option v-for="c in categories" :key="c.id" :value="c.id">{{ c.name }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-button type="primary" @click="create">新增</a-button>
    </a-form>
    <a-table :dataSource="list" :columns="columns" rowKey="id" style="margin-top: 16px">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'image'">
          <img v-if="record.imageUrl" :src="previewUrl(record.imageUrl)" class="thumb" />
          <span v-else>-</span>
        </template>
        <template v-if="column.key === 'action'">
          <a-button type="link" @click="edit(record)">编辑</a-button>
          <a-button type="link" @click="addImage(record)">更换图片</a-button>
          <a-button type="link" danger @click="remove(record)">删除</a-button>
        </template>
      </template>
    </a-table>
    <a-modal v-model:open="imgVisible" title="商品图片" @ok="saveImage">
      <a-upload :action="uploadUrl" :headers="headers" @change="onUpload" :showUploadList="false">
        <a-button>上传图片</a-button>
      </a-upload>
      <img v-if="imgForm.url" :src="previewUrl(imgForm.url)" class="preview" />
    </a-modal>

    <a-modal v-model:open="editVisible" title="编辑商品" @ok="saveEdit">
      <a-form layout="vertical">
        <a-form-item label="名称"><a-input v-model:value="editForm.name" /></a-form-item>
        <a-form-item label="价格"><a-input-number v-model:value="editForm.price" style="width: 100%" /></a-form-item>
        <a-form-item label="库存"><a-input-number v-model:value="editForm.stock" style="width: 100%" /></a-form-item>
        <a-form-item label="分类">
          <a-select v-model:value="editForm.categoryId" style="width: 100%" allowClear>
            <a-select-option v-for="c in categories" :key="c.id" :value="c.id">{{ c.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="适龄"><a-input v-model:value="editForm.ageRange" /></a-form-item>
        <a-form-item label="安全认证"><a-input v-model:value="editForm.safetyInfo" /></a-form-item>
        <a-form-item label="描述"><a-textarea v-model:value="editForm.description" /></a-form-item>
        <a-form-item label="上架">
          <a-switch v-model:checked="editForm.onSale" />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

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

const list = ref([])
const categories = ref([])
const form = reactive({ name: '', price: 0, stock: 0, categoryId: null })
const columns = [
  { title: '名称', dataIndex: 'name' },
  { title: '价格', dataIndex: 'price' },
  { title: '库存', dataIndex: 'stock' },
  { title: '图片', key: 'image' },
  { title: '操作', key: 'action' }
]

const imgVisible = ref(false)
const imgForm = reactive({ productId: null, url: '' })
const baseUrl = 'http://localhost:8080'
const uploadUrl = `${baseUrl}/api/admin/upload`
const headers = { Authorization: `Bearer ${localStorage.getItem('token') || ''}` }
const editVisible = ref(false)
const editForm = reactive({
  id: null,
  name: '',
  price: 0,
  stock: 0,
  categoryId: null,
  ageRange: '',
  safetyInfo: '',
  description: '',
  onSale: true
})

const load = async () => {
  const res = await api.get('/api/admin/products')
  if (res.success) list.value = res.data
  const res2 = await api.get('/api/admin/categories')
  if (res2.success) categories.value = res2.data
}

const create = async () => {
  await api.post('/api/admin/products', form)
  form.name = ''
  form.price = 0
  form.stock = 0
  form.categoryId = null
  load()
}

const remove = async (record) => {
  await api.delete(`/api/admin/products/${record.id}`)
  load()
}

const addImage = (record) => {
  imgForm.productId = record.id
  imgForm.url = record.imageUrl || ''
  imgVisible.value = true
}

const saveImage = async () => {
  await api.put(`/api/admin/products/${imgForm.productId}/image`, { url: imgForm.url })
  imgVisible.value = false
  load()
}

const onUpload = (info) => {
  if (info.file.status === 'done') {
    const res = info.file.response
    if (res && res.success) {
      imgForm.url = normalizeUrl(res.data)
    }
  }
}

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

const previewUrl = (url) => normalizeUrl(url)

const edit = (record) => {
  editForm.id = record.id
  editForm.name = record.name
  editForm.price = record.price
  editForm.stock = record.stock
  editForm.categoryId = record.category?.id || null
  editForm.ageRange = record.ageRange || ''
  editForm.safetyInfo = record.safetyInfo || ''
  editForm.description = record.description || ''
  editForm.onSale = record.onSale
  editVisible.value = true
}

const saveEdit = async () => {
  await api.put(`/api/admin/products/${editForm.id}`, editForm)
  editVisible.value = false
  load()
}

onMounted(load)
</script>

<style scoped>
.preview {
  display: block;
  width: 200px;
  height: 120px;
  object-fit: cover;
  margin-top: 8px;
}

.thumb {
  width: 60px;
  height: 40px;
  object-fit: cover;
}
</style>
