<template>
  <div class="admin-categories">
    <!-- 操作栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <h3 class="page-title">栏目管理</h3>
        <span class="total-count">共 {{ total }} 个栏目</span>
      </div>
      <a-button type="primary" @click="handleAdd">
        <template #icon><PlusOutlined /></template>
        新增栏目
      </a-button>
    </div>

    <!-- 栏目树形表格 -->
    <div class="table-card">
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :expand-row-by-click="true"
        :loading="loading"
        :pagination="false"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            <span class="category-name">{{ record.name }}</span>
          </template>
          <template v-if="column.key === 'type'">
            <a-tag :color="record.isSystem ? 'blue' : 'default'">
              {{ record.isSystem ? '系统栏目' : '自定义' }}
            </a-tag>
          </template>
          <template v-if="column.key === 'status'">
            <a-switch
              :checked="record.status === 1"
              checked-children="显示"
              un-checked-children="隐藏"
              @change="(val: boolean) => handleStatusChange(record, val)"
            />
          </template>
          <template v-if="column.key === 'articleCount'">
            <a-badge :count="record.articleCount" :overflow-count="999">
              <a-button size="small" @click="goArticles(record)">查看文章</a-button>
            </a-badge>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button size="small" @click="handleEdit(record)">编辑</a-button>
              <a-button size="small" type="dashed" @click="handleAddSub(record)">添加子栏目</a-button>
              <a-popconfirm
                :title="`确定删除栏目「${record.name}」吗？此操作不可恢复！`"
                cancel-text="取消"
                ok-text="确定"
                @confirm="handleDelete(record)"
              >
                <a-button :disabled="record.isSystem" danger size="small">删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 新增/编辑弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :confirm-loading="saving"
      :title="editingRecord ? '编辑栏目' : '新增栏目'"
      width="600px"
      @ok="handleSave"
    >
      <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
        <a-form-item label="上级栏目" name="parentId">
          <a-tree-select
            v-model:value="formData.parentId"
            :field-names="{ label: 'name', value: 'id', children: 'children' }"
            :tree-data="treeSelectData"
            allow-clear
            placeholder="选择上级栏目（不选则为一级）"
            tree-default-expand-all
          />
        </a-form-item>
        <a-form-item label="栏目名称" name="name">
          <a-input v-model:value="formData.name" :maxlength="50" placeholder="请输入栏目名称" show-count />
        </a-form-item>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="栏目标识（英文）" name="slug">
              <a-input v-model:value="formData.slug" placeholder="如 news / policy" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="排序权重" name="sort">
              <a-input-number v-model:value="formData.sort" :max="9999" :min="0" style="width:100%" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="栏目描述" name="description">
          <a-textarea v-model:value="formData.description" :rows="3" placeholder="请输入栏目描述" />
        </a-form-item>
        <a-form-item label="封面图" name="cover">
          <a-input v-model:value="formData.cover" placeholder="封面图URL" />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-radio-group v-model:value="formData.status">
            <a-radio :value="1">显示</a-radio>
            <a-radio :value="0">隐藏</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="是否需要会员权限" name="memberOnly">
          <a-switch v-model:checked="formData.memberOnly" checked-children="需要" un-checked-children="不需要" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'

definePageMeta({ layout: 'admin' })
useHead({ title: '栏目管理' })

const loading = ref(false)
const saving = ref(false)
const modalVisible = ref(false)
const editingRecord = ref<any>(null)
const formRef = ref()
const total = ref(0)

const formData = reactive({
  parentId: undefined as number | undefined,
  name: '',
  slug: '',
  sort: 0,
  description: '',
  cover: '',
  status: 1,
  memberOnly: false,
})

const rules = {
  name: [{ required: true, message: '请输入栏目名称' }],
  slug: [{ required: true, message: '请输入栏目标识' }],
}

const columns = [
  { title: '栏目名称', key: 'name', dataIndex: 'name' },
  { title: '标识', dataIndex: 'slug', key: 'slug' },
  { title: '类型', key: 'type' },
  { title: '排序', dataIndex: 'sort', key: 'sort', width: 80 },
  { title: '状态', key: 'status', width: 100 },
  { title: '文章数', key: 'articleCount', width: 120 },
  { title: '操作', key: 'action', width: 220 },
]

const dataSource = ref<any[]>([
  {
    id: 1, name: '政策要闻', slug: 'news', sort: 1, status: 1, articleCount: 128, isSystem: true,
    children: [
      { id: 11, name: '党中央国务院信息', slug: 'news-central', sort: 1, status: 1, articleCount: 42, isSystem: true },
      { id: 12, name: '自治区党委政府信息', slug: 'news-region', sort: 2, status: 1, articleCount: 35, isSystem: true },
      { id: 13, name: '其他厅委办信息', slug: 'news-department', sort: 3, status: 1, articleCount: 29, isSystem: true },
      { id: 14, name: '最新发布', slug: 'news-latest', sort: 4, status: 1, articleCount: 22, isSystem: true },
    ]
  },
  {
    id: 2, name: '决策咨询', slug: 'consultation', sort: 2, status: 1, articleCount: 96, isSystem: true,
    children: [
      { id: 21, name: '市县决策', slug: 'consult-city', sort: 1, status: 1, articleCount: 18, isSystem: true },
      { id: 22, name: '前沿观察', slug: 'consult-frontier', sort: 2, status: 1, articleCount: 15, isSystem: true },
      { id: 23, name: '行业资讯', slug: 'consult-industry', sort: 3, status: 1, articleCount: 20, isSystem: true },
      { id: 24, name: '企业动态', slug: 'consult-enterprise', sort: 4, status: 1, articleCount: 12, isSystem: true },
      { id: 25, name: '研究热点', slug: 'consult-research', sort: 5, status: 1, articleCount: 14, isSystem: true },
      { id: 26, name: '学术活动', slug: 'consult-academic', sort: 6, status: 1, articleCount: 10, isSystem: true },
      { id: 27, name: '其他汇编', slug: 'consult-other', sort: 7, status: 1, articleCount: 7, isSystem: true },
    ]
  },
  {
    id: 3, name: '决策参考', slug: 'reference', sort: 3, status: 1, articleCount: 75, isSystem: true,
    children: [
      { id: 31, name: '政策原文', slug: 'ref-policy', sort: 1, status: 1, articleCount: 20, isSystem: true },
      { id: 32, name: '深度解读', slug: 'ref-analysis', sort: 2, status: 1, articleCount: 15, isSystem: true },
      { id: 33, name: '研究成果', slug: 'ref-research', sort: 3, status: 1, articleCount: 18, isSystem: true },
      { id: 34, name: '专题研究', slug: 'ref-special', sort: 4, status: 1, articleCount: 12, isSystem: true },
      { id: 35, name: '东盟研究', slug: 'ref-asean', sort: 5, status: 1, articleCount: 8, isSystem: true },
      { id: 36, name: '数据服务', slug: 'ref-data', sort: 6, status: 1, articleCount: 2, isSystem: true },
    ]
  },
  { id: 4, name: '专家资讯', slug: 'expert', sort: 4, status: 1, articleCount: 52, isSystem: true },
  {
    id: 5, name: '智库观察', slug: 'think-tank', sort: 5, status: 1, articleCount: 38, isSystem: true,
    children: [
      { id: 51, name: '智库介绍', slug: 'thinktank-intro', sort: 1, status: 1, articleCount: 16, isSystem: true },
      { id: 52, name: '智库视角', slug: 'thinktank-view', sort: 2, status: 1, articleCount: 22, isSystem: true },
    ]
  },
  { id: 6, name: '建言献策', slug: 'suggestions', sort: 6, status: 1, articleCount: 0, isSystem: true },
  { id: 7, name: '翰墨文谈', slug: 'hanmo', sort: 7, status: 1, articleCount: 24, isSystem: true },
  { id: 8, name: '关于我们', slug: 'about', sort: 8, status: 1, articleCount: 5, isSystem: true },
])

const treeSelectData = computed(() => dataSource.value.map(item => ({
  id: item.id,
  name: item.name,
  children: item.children,
})))

function handleAdd() {
  editingRecord.value = null
  Object.assign(formData, { parentId: undefined, name: '', slug: '', sort: 0, description: '', cover: '', status: 1, memberOnly: false })
  modalVisible.value = true
}

function handleAddSub(record: any) {
  editingRecord.value = null
  Object.assign(formData, { parentId: record.id, name: '', slug: '', sort: 0, description: '', cover: '', status: 1, memberOnly: false })
  modalVisible.value = true
}

function handleEdit(record: any) {
  editingRecord.value = record
  Object.assign(formData, {
    parentId: record.parentId,
    name: record.name,
    slug: record.slug,
    sort: record.sort,
    description: record.description || '',
    cover: record.cover || '',
    status: record.status,
    memberOnly: record.memberOnly || false,
  })
  modalVisible.value = true
}

async function handleSave() {
  try {
    await formRef.value?.validate()
    saving.value = true
    // TODO: 调用API
    message.success(editingRecord.value ? '栏目更新成功' : '栏目创建成功')
    modalVisible.value = false
  } catch (e: any) {
    if (e?.errorFields) return
    message.error(e?.message || '操作失败')
  } finally {
    saving.value = false
  }
}

async function handleDelete(record: any) {
  try {
    // TODO: 调用API
    message.success('栏目已删除')
    loadData()
  } catch (e: any) {
    message.error(e?.message || '删除失败')
  }
}

function handleStatusChange(record: any, val: boolean) {
  record.status = val ? 1 : 0
  message.success(`栏目"${record.name}"已${val ? '显示' : '隐藏'}`)
  // TODO: 调用API
}

function goArticles(record: any) {
  navigateTo(`/admin/articles?categoryId=${record.id}`)
}

async function loadData() {
  loading.value = true
  try {
    // TODO: 接入实际API
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  total.value = 8
  // loadData()
})
</script>

<style scoped>
.admin-categories {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  border-radius: 10px;
  padding: 14px 20px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.06);
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-title {
  font-size: 16px;
  font-weight: 700;
  color: #1f2937;
  margin: 0;
}

.total-count {
  font-size: 13px;
  color: #9ca3af;
}

.table-card {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.06);
}

.category-name {
  font-weight: 500;
  color: #1f2937;
}
</style>
