<template>
  <a-card title="轮播图管理">
    <a-form layout="inline">
      <a-form-item label="图片">
        <a-upload :action="uploadUrl" :headers="headers" @change="onUpload" :showUploadList="false">
          <a-button>上传图片</a-button>
        </a-upload>
      </a-form-item>
      <a-form-item label="图片URL"><a-input v-model:value="form.imageUrl" /></a-form-item>
      <a-form-item label="链接"><a-input v-model:value="form.linkUrl" /></a-form-item>
      <a-form-item label="排序"><a-input-number v-model:value="form.sortOrder" /></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 :src="previewUrl(record.imageUrl)" class="thumb" />
        </template>
        <template v-if="column.key === 'action'">
          <a-button type="link" danger @click="remove(record)">删除</a-button>
        </template>
      </template>
    </a-table>
    <img v-if="form.imageUrl" :src="previewUrl(form.imageUrl)" class="preview" />
  </a-card>
</template>

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

const list = ref([])
const form = reactive({ imageUrl: '', linkUrl: '', sortOrder: 0 })
const baseUrl = 'http://localhost:8080'
const uploadUrl = `${baseUrl}/api/admin/upload`
const headers = { Authorization: `Bearer ${localStorage.getItem('token') || ''}` }
const columns = [
  { title: '图片', key: 'image' },
  { title: '链接', dataIndex: 'linkUrl' },
  { title: '排序', dataIndex: 'sortOrder' },
  { title: '操作', key: 'action' }
]

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

const create = async () => {
  await api.post('/api/admin/carousels', form)
  form.imageUrl = ''
  form.linkUrl = ''
  form.sortOrder = 0
  load()
}

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

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

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

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

onMounted(load)
</script>

<style scoped>
.thumb {
  width: 120px;
  height: 60px;
  object-fit: cover;
}
.preview {
  display: block;
  width: 240px;
  height: 120px;
  object-fit: cover;
  margin-top: 12px;
}
</style>
