<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 === 'action'">
          <a-button type="link" danger @click="remove(record)">删除</a-button>
        </template>
      </template>
    </a-table>
  </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 uploadUrl = 'http://localhost:8080/api/admin/upload'
const headers = { Authorization: `Bearer ${localStorage.getItem('token') || ''}` }
const columns = [
  { title: '图片', dataIndex: 'imageUrl' },
  { 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 = res.data
    }
  }
}

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

onMounted(load)
</script>
