<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Page } from '@vben/common-ui';
import { Button, Card, Table, Space, message, Modal, Input } from 'ant-design-vue';
import { 
  getClassListApi, 
  deleteClassApi,
  type ClassApi 
} from '#/api';

defineOptions({ name: 'ClassList' });

const router = useRouter();

const loading = ref(false);
const tableData = ref<ClassApi.ClassInfo[]>([]);
const total = ref(0);
const pagination = reactive({
  current: 1,
  pageSize: 10,
});

const searchForm = reactive({
  name: '',
  teacher_name: '',
  school_id: undefined as number | undefined,
});

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
  },
  {
    title: '班级名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '年级',
    dataIndex: 'grade',
    key: 'grade',
    width: 100,
  },
  {
    title: '班主任',
    key: 'teacher_name',
    width: 120,
  },
  {
    title: '教室',
    key: 'classroom_name',
    width: 150,
  },
  {
    title: '学生人数',
    dataIndex: 'student_count',
    key: 'student_count',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
  },
];

const fetchData = async () => {
  loading.value = true;
  try {
    const params: ClassApi.ListParams = {
      page: pagination.current,
      limit: pagination.pageSize,
      ...searchForm,
    };
    const res = await getClassListApi(params);
    // 根据实际返回格式，code 为 0 表示成功，返回格式为 {code, msg, count, data}
    if (res && (res.code === 0 || res.code === 200)) {
      // 处理数据，将嵌套的 teacher 和 classroom 信息映射到表格需要的字段
      const data = Array.isArray(res.data) ? res.data : [];
      tableData.value = data.map((item: ClassApi.ClassInfo) => ({
        ...item,
        // 映射 teacher_name 字段
        teacher_name: item.teacher?.name || '',
        // 映射 classroom_name 字段
        classroom_name: item.classroom?.name || '',
        // 确保 classroom_id 字段存在（使用 class_room_id）
        classroom_id: item.class_room_id || item.classroom?.id,
      }));
      total.value = res.count || 0;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取班级列表失败:', error);
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  pagination.current = 1;
  fetchData();
};

const handleAdd = () => {
  router.push({ name: 'ClassDetail' });
};

const handleEdit = (record: ClassApi.ClassInfo) => {
  router.push({ 
    name: 'ClassDetail', 
    params: { id: record.id }
  });
};

const handleDelete = (record: ClassApi.ClassInfo) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除班级"${record.name}"吗？`,
    onOk: async () => {
      try {
        await deleteClassApi({ id: record.id! });
        message.success('删除成功');
        fetchData();
      } catch (error) {
        console.error('删除失败:', error);
      }
    },
  });
};

const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  fetchData();
};

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

<template>
  <Page title="班级列表">
    <Card>
      <div class="mb-4">
        <Space>
          <Input
            v-model:value="searchForm.name"
            placeholder="班级名称"
            style="width: 200px"
            @press-enter="handleSearch"
          />
          <Input
            v-model:value="searchForm.teacher_name"
            placeholder="班主任姓名"
            style="width: 200px"
            @press-enter="handleSearch"
          />
          <Button type="primary" @click="handleSearch">搜索</Button>
          <Button type="primary" @click="handleAdd">添加班级</Button>
        </Space>
      </div>
      <Table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: total,
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条`,
        }"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'teacher_name'">
            {{ record.teacher?.name || '-' }}
          </template>
          <template v-else-if="column.key === 'classroom_name'">
            {{ record.classroom?.name || '-' }}
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="handleEdit(record)">编辑</Button>
              <Button type="link" danger size="small" @click="handleDelete(record)">删除</Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>
  </Page>
</template>

