<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 { 
  getSchoolListApi, 
  deleteSchoolApi,
  type SchoolApi 
} from '#/api';

defineOptions({ name: 'SchoolList' });

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

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

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
  },
  {
    title: '学校名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
  },
  {
    title: '地址',
    dataIndex: 'address',
    key: 'address',
    width: 250,
  },
  {
    title: '联系人',
    dataIndex: 'contact',
    key: 'contact',
    width: 120,
  },
  {
    title: '联系电话',
    dataIndex: 'phone',
    key: 'phone',
    width: 130,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
  },
];

const fetchData = async () => {
  loading.value = true;
  try {
    const params: SchoolApi.ListParams = {
      page: pagination.current,
      limit: pagination.pageSize,
      ...searchForm,
    };
    const res = await getSchoolListApi(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: SchoolApi.SchoolInfo) => {
  router.push({ 
    name: 'SchoolDetail', 
    params: { id: record.id }
  });
};

const handleDelete = (record: SchoolApi.SchoolInfo) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除学校"${record.name}"吗？`,
    onOk: async () => {
      try {
        await deleteSchoolApi({ 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"
          />
          <Button type="primary" @click="handleSearch">搜索</Button>
          <Button type="primary" @click="router.push({ name: 'SchoolDetail' })">新增</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 === 'address'">
            <span :title="record.address || '-'">
              {{ record.address || '-' }}
            </span>
          </template>
          <template v-else-if="column.key === 'contact'">
            {{ record.contact || '-' }}
          </template>
          <template v-else-if="column.key === 'phone'">
            {{ record.phone || '-' }}
          </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>

