<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, Select } from 'ant-design-vue';
import {
  getClassroomListApi,
  deleteClassroomApi,
  batchDeleteClassroomApi,
  type ClassroomApi
} from '#/api';
import { $t } from '#/locales';

defineOptions({ name: 'ClassroomList' });

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

const searchForm = reactive({
  name: '',
  building: '',
  type: undefined as 'normal' | 'multimedia' | 'lab' | undefined,
  school_id: undefined as number | undefined,
});

const selectedRowKeys = ref<number[]>([]);

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
  },
  {
    title: '教室名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '楼栋',
    dataIndex: 'building',
    key: 'building',
    customRender: ({ record }: { record: ClassroomApi.ClassroomInfo }) => {
      return record.location?.building || record.building || '-';
    },
  },
  {
    title: '楼层',
    dataIndex: 'floor',
    key: 'floor',
    customRender: ({ record }: { record: ClassroomApi.ClassroomInfo }) => {
      return record.location?.floor || record.floor || '-';
    },
  },
  {
    title: '房间号',
    dataIndex: 'room',
    key: 'room',
    customRender: ({ record }: { record: ClassroomApi.ClassroomInfo }) => {
      return record.location?.room || '-';
    },
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
    customRender: ({ text }: { text: string }) => {
      const typeMap: Record<string, string> = {
        normal: '普通教室',
        multimedia: '多媒体教室',
        lab: '实验室',
      };
      return typeMap[text] || text;
    },
  },
  {
    title: '容量',
    dataIndex: 'capacity',
    key: 'capacity',
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
  },
];

const fetchData = async () => {
  loading.value = true;
  try {
    const params: ClassroomApi.ListParams = {
      page: pagination.current,
      limit: pagination.pageSize,
      ...searchForm,
    };
    const res = await getClassroomListApi(params);
    // 根据实际返回格式，code 为 0 表示成功，返回格式为 {code, msg, count, data}
    // 使用 responseReturn: 'body' 获取完整响应体
    if (res && (res.code === 0 || res.code === 200)) {
      tableData.value = Array.isArray(res.data) ? res.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 handleReset = () => {
  searchForm.name = '';
  searchForm.building = '';
  searchForm.type = undefined;
  searchForm.school_id = undefined;
  handleSearch();
};

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

const handleEdit = (record: ClassroomApi.ClassroomInfo) => {
  router.push({ name: 'ClassroomDetail', params: { id: record.id } });
};

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

const handleBatchDelete = () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请选择要删除的教室');
    return;
  }
  Modal.confirm({
    title: '确认批量删除',
    content: `确定要删除选中的 ${selectedRowKeys.value.length} 个教室吗？`,
    onOk: async () => {
      try {
        await batchDeleteClassroomApi({ ids: selectedRowKeys.value });
        message.success('批量删除成功');
        selectedRowKeys.value = [];
        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.building"
            placeholder="楼栋/房间号"
            style="width: 200px"
            @press-enter="handleSearch"
          />
          <Select
            v-model:value="searchForm.type"
            placeholder="教室类型"
            style="width: 150px"
            allow-clear
          >
            <Select.Option value="normal">普通教室</Select.Option>
            <Select.Option value="multimedia">多媒体教室</Select.Option>
            <Select.Option value="lab">实验室</Select.Option>
          </Select>
          <Button type="primary" @click="handleSearch">搜索</Button>
          <Button @click="handleReset">重置</Button>
          <Button type="primary" @click="handleAdd">新增</Button>
          <Button danger :disabled="selectedRowKeys.length === 0" @click="handleBatchDelete">
            批量删除
          </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-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: (keys: number[]) => {
            selectedRowKeys = keys;
          },
        }"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-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>

