<template>
  <div class="tag-mgmt-page">
    <a-card class="title-card">
      <template #title>标签管理</template>
      <template #extra>
        <a-button type="primary" @click="openModal()">
          <template #icon><PlusOutlined /></template>
          新增标签
        </a-button>
      </template>
    </a-card>

    <a-table
      :columns="columns"
      :data-source="tags"
      :loading="loading"
      :pagination="false"
      row-key="id"
      class="data-table"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'category'">
          <a-tag v-if="record.category">{{ record.category }}</a-tag>
          <span v-else class="text-muted">-</span>
        </template>
        <template v-else-if="column.key === 'status'">
          <a-tag :color="record.status === 'enabled' ? 'green' : 'red'">
            {{ record.status === 'enabled' ? '启用' : '禁用' }}
          </a-tag>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="link" size="small" @click="openModal(record)">编辑</a-button>
            <a-button type="link" size="small" @click="handleToggle(record)">
              {{ record.status === 'enabled' ? '禁用' : '启用' }}
            </a-button>
            <a-popconfirm title="确定删除？" @confirm="handleDelete(record.id)">
              <a-button type="link" danger size="small" :disabled="record.usageCount > 0">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <a-modal v-model:open="modalVisible" :title="editingId ? '编辑标签' : '新增标签'" :footer="null" :width="400">
      <a-form :model="form" layout="vertical" @finish="handleSubmit" style="margin-top: 16px">
        <a-form-item label="标签名称" :rules="[{ required: true, message: '请输入' }]">
          <a-input v-model:value="form.name" placeholder="如：童话、科幻、自然" />
        </a-form-item>
        <a-form-item label="所属分类">
          <a-input v-model:value="form.category" placeholder="如：主题、风格、情感" />
        </a-form-item>
        <a-form-item label="排序权重">
          <a-input-number v-model:value="form.sort" :min="0" style="width: 100%" />
        </a-form-item>
        <a-button type="primary" html-type="submit" block :loading="submitting">保存</a-button>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import request from '@/utils/request'

const tags = ref<any[]>([])
const loading = ref(false)
const modalVisible = ref(false)
const submitting = ref(false)
const editingId = ref<number | null>(null)
const form = reactive({ name: '', category: '', sort: 0 })

const columns = [
  { title: '标签名称', dataIndex: 'name', key: 'name', width: 150 },
  { title: '分类', key: 'category', width: 120 },
  { title: '使用次数', dataIndex: 'usageCount', key: 'usageCount', width: 100 },
  { title: '排序', dataIndex: 'sort', key: 'sort', width: 80 },
  { title: '状态', key: 'status', width: 80 },
  { title: '操作', key: 'action', width: 180, fixed: 'right' as const },
]

const fetchTags = async () => {
  loading.value = true
  try { tags.value = await request.get('/tags') as any } catch { message.error('获取失败') }
  finally { loading.value = false }
}

const openModal = (record?: any) => {
  editingId.value = record?.id || null
  form.name = record?.name || ''
  form.category = record?.category || ''
  form.sort = record?.sort || 0
  modalVisible.value = true
}

const handleSubmit = async () => {
  submitting.value = true
  try {
    if (editingId.value) {
      await request.put(`/tags/${editingId.value}`, form)
      message.success('编辑成功')
    } else {
      await request.post('/tags', form)
      message.success('创建成功')
    }
    modalVisible.value = false
    fetchTags()
  } catch (e: any) { message.error(e?.response?.data?.message || '操作失败') }
  finally { submitting.value = false }
}

const handleToggle = async (record: any) => {
  try {
    await request.patch(`/tags/${record.id}/status`)
    message.success(record.status === 'enabled' ? '已禁用' : '已启用')
    fetchTags()
  } catch { message.error('操作失败') }
}

const handleDelete = async (id: number) => {
  try { await request.delete(`/tags/${id}`); message.success('删除成功'); fetchTags() }
  catch (e: any) { message.error(e?.response?.data?.message || '删除失败') }
}

onMounted(fetchTags)
</script>

<style scoped lang="scss">
$primary: #6366f1;
.title-card { margin-bottom: 16px; border: none; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.06);
  :deep(.ant-card-head) { border-bottom: none; .ant-card-head-title { font-size: 18px; font-weight: 600; } }
  :deep(.ant-card-body) { padding: 0; }
}
.data-table { :deep(.ant-table-wrapper) { background: #fff; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,0.06); overflow: hidden;
  .ant-table-thead > tr > th { background: #fafafa; font-weight: 600; }
  .ant-table-tbody > tr:hover > td { background: rgba($primary, 0.03); }
} }
.text-muted { color: #d1d5db; }
</style>
