<template>
  <div class="store-page">
    <Breadcrumb />
    <a-card title="文档分类">
      <a-space style="margin-bottom: 12px;">
        <a-button type="primary" @click="openCreate">新增分类</a-button>
      </a-space>

      <a-table :bordered="false" :data="data" :loading="loading" :pagination="false">
        <template #columns>
          <a-table-column title="名称" data-index="name" :width="140" />
          <a-table-column title="标识 (slug)" data-index="slug" :width="120" />
          <a-table-column title="图标" :width="80">
            <template #cell="{ record }">{{ record.icon || '-' }}</template>
          </a-table-column>
          <a-table-column title="排序" data-index="sort_order" :width="80" />
          <a-table-column title="状态" :width="90">
            <template #cell="{ record }">
              <a-tag :color="record.is_active ? 'green' : 'gray'">{{ record.is_active ? '启用' : '停用' }}</a-tag>
            </template>
          </a-table-column>
          <a-table-column title="操作" :width="160">
            <template #cell="{ record }">
              <a-space>
                <a-button size="mini" @click="openEdit(record)">编辑</a-button>
                <a-button status="danger" size="mini" @click="remove(record)">删除</a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <a-modal v-model:visible="editorVisible" :title="form.id ? '编辑分类' : '新增分类'" @before-ok="submitEditor">
      <a-form :model="form" layout="vertical">
        <a-form-item label="名称" required>
          <a-input v-model="form.name" allow-clear />
        </a-form-item>
        <a-form-item label="标识 (slug)" required>
          <a-input v-model="form.slug" :readonly="!!form.id" allow-clear placeholder="如 doc、guide" />
        </a-form-item>
        <a-form-item label="图标 (emoji)">
          <a-input v-model="form.icon" allow-clear placeholder="📖" :max-length="16" />
        </a-form-item>
        <a-form-item label="排序">
          <a-input-number v-model="form.sort_order" mode="button" />
        </a-form-item>
        <a-form-item label="启用">
          <a-switch v-model="form.is_active" :checked-value="1" :unchecked-value="0" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { Modal, Notification, Message } from '@arco-design/web-vue'
import { getAdminCategoryList, saveAdminCategory, deleteAdminCategory } from '@/api/article'
import { isValidSlug } from '@/utils/slugify'

const loading = ref(false)
const data = ref([])
const editorVisible = ref(false)
const form = reactive({
  id: null,
  name: '',
  slug: '',
  icon: '',
  sort_order: 0,
  is_active: 1
})

const getList = async () => {
  loading.value = true
  try {
    const res = await getAdminCategoryList({})
    if (!res || res.code !== 0) {
      Notification.error({ title: '获取分类失败', content: res?.msg ?? '请稍后再试' })
      return
    }
    data.value = res.data || []
  } finally {
    loading.value = false
  }
}

const openCreate = () => {
  form.id = null
  form.name = ''
  form.slug = ''
  form.icon = ''
  form.sort_order = 0
  form.is_active = 1
  editorVisible.value = true
}

const openEdit = (record) => {
  form.id = record.id
  form.name = record.name
  form.slug = record.slug
  form.icon = record.icon || ''
  form.sort_order = record.sort_order || 0
  form.is_active = record.is_active ? 1 : 0
  editorVisible.value = true
}

const submitEditor = async () => {
  if (!form.name || !form.slug) {
    Message.error('请填写名称和标识')
    return false
  }
  if (!isValidSlug(form.slug) || form.slug.length > 32) {
    Message.error('标识格式无效（3-32位小写字母、数字、连字符）')
    return false
  }
  const res = await saveAdminCategory({ ...form })
  if (!res || res.code !== 0) {
    Notification.error({ title: '保存失败', content: res?.msg ?? '请稍后再试' })
    return false
  }
  Message.success('保存成功')
  getList()
  return true
}

const remove = (record) => {
  Modal.confirm({
    title: '删除分类',
    content: `确定删除「${record.name}」吗？`,
    onOk: async () => {
      const res = await deleteAdminCategory({ id: record.id })
      if (!res || res.code !== 0) {
        Notification.error({ title: '删除失败', content: res?.msg ?? '请稍后再试' })
        return
      }
      Message.success('删除成功')
      getList()
    }
  })
}

onMounted(getList)
</script>
