<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 { 
  getTeacherListApi, 
  deleteTeacherApi,
  type TeacherApi 
} from '#/api';

defineOptions({ name: 'TeacherList' });

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

const searchForm = reactive({
  teacher_id: '',
  name: '',
  nickname: '',
});

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
  },
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    width: 120,
  },
  {
    title: '性别',
    dataIndex: 'gender',
    key: 'gender',
    width: 80,
  },
  {
    title: '昵称',
    dataIndex: 'nickname',
    key: 'nickname',
    width: 120,
  },
  {
    title: '电话',
    dataIndex: 'phone',
    key: 'phone',
    width: 130,
  },
  {
    title: '管理的教室',
    key: 'classroom_names',
    width: 200,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
  },
];

const fetchData = async () => {
  loading.value = true;
  try {
    const params: TeacherApi.ListParams = {
      page: pagination.current,
      limit: pagination.pageSize,
      ...searchForm,
    };
    const res = await getTeacherListApi(params);
    // 根据实际返回格式，code 为 0 表示成功，返回格式为 {code, msg, count, data}
    if (res && (res.code === 0 || res.code === 200)) {
      const data = Array.isArray(res.data) ? res.data : [];
      tableData.value = data;
      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 handleEdit = (record: TeacherApi.TeacherInfo) => {
  router.push({ 
    name: 'TeacherDetail', 
    params: { id: record.id }
  });
};

const handleDelete = (record: TeacherApi.TeacherInfo) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除教师"${record.name}"吗？`,
    onOk: async () => {
      try {
        await deleteTeacherApi({ 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.teacher_id"
            placeholder="工号"
            style="width: 200px"
            @press-enter="handleSearch"
          />
          <Input
            v-model:value="searchForm.name"
            placeholder="姓名"
            style="width: 200px"
            @press-enter="handleSearch"
          />
          <Button type="primary" @click="handleSearch">搜索</Button>
          <Button type="primary" @click="router.push({ name: 'TeacherDetail' })">新增</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 === 'classroom_names'">
            <span v-if="record.classroom_names && record.classroom_names.length > 0">
              {{ record.classroom_names.join('、') }}
            </span>
            <span v-else style="color: #999;">-</span>
          </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>

