<template>
  <div class="theme-list-page">
    <a-card :bordered="false">
      <template #title>
        <span>主题字典管理</span>
      </template>
      <template #extra>
        <a-button type="primary" @click="handleCreate">
          <template #icon><PlusOutlined /></template>
          新建主题
        </a-button>
      </template>

      <!-- 表格 -->
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 'ACTIVE' ? 'success' : 'default'">
              {{ record.status === 'ACTIVE' ? '启用' : '归档' }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
              <a-popconfirm title="确定要删除吗？" @confirm="handleDelete(record)">
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 编辑弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="isEdit ? '编辑主题' : '新建主题'"
      @ok="handleSave"
      @cancel="modalVisible = false"
    >
      <a-form :model="form" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
        <a-form-item label="主题名称" required>
          <a-input v-model:value="form.name" placeholder="请输入主题名称" />
        </a-form-item>
        <a-form-item label="描述">
          <a-textarea v-model:value="form.description" placeholder="请输入主题描述" :rows="3" />
        </a-form-item>
        <a-form-item label="排序">
          <a-input-number v-model:value="form.sortOrder" :min="1" />
        </a-form-item>
      </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 {
  getThemeList,
  createTheme,
  updateTheme,
  deleteTheme,
} from '@/api/theme';
import type { Theme } from '@/api/theme';

const loading = ref(false);
const dataSource = ref<Theme[]>([]);
const modalVisible = ref(false);
const isEdit = ref(false);
const editingId = ref<number | null>(null);

const form = reactive({
  name: '',
  description: '',
  sortOrder: 1,
});

const columns = [
  { title: '排序', dataIndex: 'sortOrder', key: 'sortOrder', width: 80 },
  { title: '主题名称', dataIndex: 'name', key: 'name' },
  { title: '描述', dataIndex: 'description', key: 'description' },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '操作', key: 'action', width: 150 },
];

const fetchData = async () => {
  loading.value = true;
  try {
    const res = await getThemeList() as any;
    dataSource.value = res || [];
  } catch (error) {
    console.error('获取主题列表失败', error);
  } finally {
    loading.value = false;
  }
};

const resetForm = () => {
  form.name = '';
  form.description = '';
  form.sortOrder = 1;
};

const handleCreate = () => {
  isEdit.value = false;
  editingId.value = null;
  resetForm();
  form.sortOrder = dataSource.value.length + 1;
  modalVisible.value = true;
};

const handleEdit = (record: any) => {
  isEdit.value = true;
  editingId.value = record.id;
  form.name = record.name;
  form.description = record.description || '';
  form.sortOrder = record.sortOrder;
  modalVisible.value = true;
};

const handleSave = async () => {
  if (!form.name) {
    message.warning('请输入主题名称');
    return;
  }

  try {
    if (isEdit.value && editingId.value) {
      await updateTheme(editingId.value, {
        name: form.name,
        description: form.description,
        sortOrder: form.sortOrder,
      });
      message.success('更新成功');
    } else {
      await createTheme({
        name: form.name,
        description: form.description,
        sortOrder: form.sortOrder,
      });
      message.success('创建成功');
    }
    modalVisible.value = false;
    fetchData();
  } catch (error) {
    message.error('保存失败');
  }
};

const handleDelete = async (record: any) => {
  try {
    await deleteTheme(record.id);
    message.success('删除成功');
    fetchData();
  } catch (error: any) {
    message.error(error.response?.data?.message || '删除失败');
  }
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.theme-list-page {
  padding: 24px;
}
</style>
