<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 v-model:value="form.description" /></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({ name: '', description: '' })
const columns = [
  { title: '名称', dataIndex: 'name' },
  { title: '描述', dataIndex: 'description' },
  { title: '操作', key: 'action' }
]

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

const create = async () => {
  await api.post('/api/admin/categories', form)
  form.name = ''
  form.description = ''
  load()
}

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

onMounted(load)
</script>
