<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, Card, Table, Space, message, Modal, Input, DatePicker, Select, Tag } from 'ant-design-vue';
import { 
  getBookingListApi, 
  approveBookingApi,
  rejectBookingApi,
  type BookingApi 
} from '#/api';

defineOptions({ name: 'BookingList' });

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

const searchForm = reactive({
  classroom_id: undefined as number | undefined,
  booking_date: '',
  status: undefined as number | undefined,
  student_id: undefined as number | undefined,
});

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
  },
  {
    title: '教室名称',
    dataIndex: 'classroom_name',
    key: 'classroom_name',
    width: 180,
  },
  {
    title: '座位号',
    dataIndex: 'seat_number',
    key: 'seat_number',
    width: 100,
  },
  {
    title: '学生ID',
    dataIndex: 'student_id',
    key: 'student_id',
    width: 100,
  },
  {
    title: '预订日期',
    dataIndex: 'booking_date',
    key: 'booking_date',
    width: 120,
  },
  {
    title: '时间范围',
    dataIndex: 'time_range',
    key: 'time_range',
    width: 180,
    customRender: ({ text }: { text: string }) => {
      if (!text || text === '00:00:00 - 00:00:00') {
        return '-';
      }
      return text;
    },
  },
  {
    title: '用途',
    dataIndex: 'purpose',
    key: 'purpose',
    width: 150,
    customRender: ({ text }: { text: string | null }) => {
      return text || '-';
    },
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '创建时间',
    dataIndex: 'create_time',
    key: 'create_time',
    width: 180,
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right' as const,
  },
];

const fetchData = async () => {
  loading.value = true;
  try {
    const params: BookingApi.ListParams = {
      page: pagination.current,
      limit: pagination.pageSize,
      ...searchForm,
    };
    const res = await getBookingListApi(params);
    // 根据实际返回格式，code 为 0 表示成功
    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.classroom_id = undefined;
  searchForm.booking_date = '';
  searchForm.status = undefined;
  searchForm.student_id = undefined;
  handleSearch();
};

const getStatusText = (status?: number) => {
  const statusMap: Record<number, string> = {
    0: '待审核',
    1: '已通过',
    2: '已拒绝',
  };
  return statusMap[status ?? -1] || '未知';
};

const getStatusColor = (status?: number) => {
  const colorMap: Record<number, string> = {
    0: 'orange',
    1: 'green',
    2: 'red',
  };
  return colorMap[status ?? -1] || 'default';
};

const handleApprove = (record: BookingApi.BookingInfo) => {
  Modal.confirm({
    title: '确认同意',
    content: '确定要同意这个座位变更申请吗？',
    onOk: async () => {
      try {
        await approveBookingApi({ id: record.id! });
        message.success('操作成功');
        fetchData();
      } catch (error) {
        console.error('操作失败:', error);
      }
    },
  });
};

const handleReject = (record: BookingApi.BookingInfo) => {
  Modal.confirm({
    title: '拒绝申请',
    content: '请输入拒绝原因',
    onOk: async () => {
      try {
        await rejectBookingApi({ id: record.id!, reason: '管理员拒绝' });
        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 wrap>
          <Input
            v-model:value="searchForm.classroom_id"
            placeholder="教室ID"
            style="width: 150px"
            type="number"
            allow-clear
            @press-enter="handleSearch"
          />
          <Input
            v-model:value="searchForm.student_id"
            placeholder="学生ID"
            style="width: 150px"
            type="number"
            allow-clear
            @press-enter="handleSearch"
          />
          <DatePicker
            v-model:value="searchForm.booking_date"
            placeholder="预订日期"
            style="width: 180px"
            format="YYYY-MM-DD"
            allow-clear
          />
          <Select
            v-model:value="searchForm.status"
            placeholder="状态"
            style="width: 120px"
            allow-clear
          >
            <Select.Option :value="0">待审核</Select.Option>
            <Select.Option :value="1">已通过</Select.Option>
            <Select.Option :value="2">已拒绝</Select.Option>
          </Select>
          <Button type="primary" @click="handleSearch">搜索</Button>
          <Button @click="handleReset">重置</Button>
        </Space>
      </div>
      <Table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :scroll="{ x: 1400 }"
        :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 === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button
                v-if="record.status === 0"
                type="link"
                size="small"
                @click="handleApprove(record)"
              >
                同意
              </Button>
              <Button
                v-if="record.status === 0"
                type="link"
                danger
                size="small"
                @click="handleReject(record)"
              >
                拒绝
              </Button>
              <span v-else class="text-gray-400">-</span>
            </Space>
          </template>
        </template>
      </Table>
    </Card>
  </Page>
</template>

