<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, Tag } from 'ant-design-vue';
import {
  getClassroomListApi,
  deleteClassroomApi,
  batchDeleteClassroomApi,
  getClassroomSeatListApi,
  getClassroomDetailApi,
  getClassroomSchoolListApi,
  getClassroomStatusApi,
  cancelBookingApi,
  cancelBookingAutoApi,
  assignSeatApi,
  getUnassignedStudentsApi,
  type ClassroomApi
} from '#/api';
import SeatLayoutEditor from '#/components/classroom/SeatLayoutEditor.vue';
import * as XLSX from 'xlsx-js-style';


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 seatListVisible = ref(false);
const seatListLoading = ref(false);
const seatListData = ref<ClassroomApi.SeatInfo[]>([]);
const currentClassroomName = ref('');
const seatListPagination = reactive({
  current: 1,
  pageSize: 10,
});
const selectedSeatKeys = ref<string[]>([]);
const layoutVisible = ref(false);
const layoutLoading = ref(false);
const currentClassroomId = ref<number | null>(null);
const currentLayout = ref<ClassroomApi.ClassroomLayout | null>(null);
const schoolList = ref<Array<{ id: number; name: string }>>([]);
const schoolListLoading = ref(false);

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
  },
  {
    title: '教室名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '校区',
    dataIndex: 'school_name',
    key: 'school_name',
    customRender: ({ record }: { record: ClassroomApi.ClassroomInfo }) => {
      return (record as any).school_name || '-';
    },
  },
  {
    title: '地址',
    dataIndex: 'address',
    key: 'address',
    customRender: ({ record }: { record: ClassroomApi.ClassroomInfo }) => {
      const building = record.location?.building || record.building || '';
      const floor = record.location?.floor || record.floor || '';
      const room = record.location?.room || '';
      const addressParts: string[] = [];
      if (building && building.trim() !== '') {
        addressParts.push(building);
      }
      if (floor && floor.trim() !== '') {
        addressParts.push(`${floor}层`);
      }
      if (room && room.trim() !== '') {
        addressParts.push(`${room}号`);
      }
      return addressParts.length > 0 ? addressParts.join('') : '-';
    },
  },
  {
    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: 300,
  },
];

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) => {
  if (pag) {
    pagination.current = pag.current || pagination.current;
    pagination.pageSize = pag.pageSize || pagination.pageSize;
    fetchData();
  }
};

// 处理行选择变化
const handleRowSelectionChange = (keys: (string | number)[]) => {
  selectedRowKeys.value = keys.map(key => typeof key === 'string' ? Number(key) : key);
};

// 查看使用状态
const handleViewStatus = async (record: ClassroomApi.ClassroomInfo) => {
  if (!record.id) {
    message.error('教室ID不存在');
    return;
  }

  seatListVisible.value = true;
  currentClassroomId.value = record.id;
  currentClassroomName.value = record.name || '';
  seatListLoading.value = true;
  seatListData.value = [];

  // 同时加载布局数据，以便导出布局
  currentLayout.value = null;
  try {
    const layoutRes = await getClassroomDetailApi({ id: record.id });
    if (layoutRes && (layoutRes.code === 0 || layoutRes.code === 200)) {
      const data = layoutRes.data || layoutRes;
      currentLayout.value = data.layout || null;
    }
  } catch (error) {
    console.warn('获取教室布局失败:', error);
  }

  try {
    const res = await getClassroomSeatListApi({ id: record.id });
    if (res && (res.code === 0 || res.code === 200)) {
      seatListData.value = Array.isArray(res.data) ? res.data : [];
    } else {
      message.error(res?.message || res?.msg || '获取座位列表失败');
      seatListData.value = [];
    }
  } catch (error: any) {
    console.error('获取座位列表失败:', error);
    message.error(error?.response?.data?.message || error?.message || '获取座位列表失败');
    seatListData.value = [];
  } finally {
    seatListLoading.value = false;
  }
};

// 关闭使用状态弹窗
const handleCloseSeatList = () => {
  seatListVisible.value = false;
  seatListData.value = [];
  currentClassroomName.value = '';
  seatListPagination.current = 1;
  seatListPagination.pageSize = 10;
};

// 查看座位布局
const handleViewLayout = async (record: ClassroomApi.ClassroomInfo) => {
  if (!record.id) {
    message.error('教室ID不存在');
    return;
  }

  layoutVisible.value = true;
  currentClassroomId.value = record.id;
  currentClassroomName.value = record.name || '';
  layoutLoading.value = true;
  currentLayout.value = null;

  try {
    const res = await getClassroomDetailApi({ id: record.id });
    if (res && (res.code === 0 || res.code === 200)) {
      const data = res.data || res;
      currentLayout.value = data.layout || null;
    } else {
      message.error(res?.message || res?.msg || '获取教室详情失败');
    }
  } catch (error: any) {
    console.error('获取教室详情失败:', error);
    message.error(error?.response?.data?.message || error?.message || '获取教室详情失败');
  } finally {
    layoutLoading.value = false;
  }
};

// 关闭座位布局弹窗
const handleCloseLayout = () => {
  layoutVisible.value = false;
  currentClassroomId.value = null;
  currentLayout.value = null;
  currentClassroomName.value = '';
};

// 座位布局保存成功回调
const handleLayoutSaved = (layout: ClassroomApi.ClassroomLayout) => {
  currentLayout.value = layout;
  message.success('座位布局保存成功');
  // 可以选择关闭弹窗或保持打开
  // handleCloseLayout();
};

// 导出座位布局为Excel
const handleExportLayout = async () => {
  if (!currentLayout.value || !currentClassroomId.value) {
    message.warning('没有布局数据可导出');
    return;
  }

  try {
    // 获取座位状态数据
    let seatStatusMap = new Map<string, { name: string; date: string }>();
    try {
      const statusRes = await getClassroomSeatListApi({ id: currentClassroomId.value });
      if (statusRes && (statusRes.code === 0 || statusRes.code === 200)) {
        const seatList = Array.isArray(statusRes.data) ? statusRes.data : [];
        seatList.forEach((seat: ClassroomApi.SeatInfo) => {
          if (seat.is_selected === 1 && seat.seat_number) {
            seatStatusMap.set(seat.seat_number, {
              name: seat.student_name || '',
              date: seat.select_time || '',
            });
          }
        });
      }
    } catch (error) {
      console.warn('获取座位状态失败，将只导出布局信息:', error);
    }

    const layout = currentLayout.value;
    const cols = layout.cols || 0;
    const rows = layout.rows || 0;
    const cells = layout.cells || [];

    if (cols === 0 || rows === 0) {
      message.warning('布局数据为空，无法导出');
      return;
    }

    // 创建单元格映射
    const cellMap = new Map<string, ClassroomApi.ClassroomLayoutCell>();
    cells.forEach((cell) => {
      const key = `${cell.col},${cell.row}`;
      cellMap.set(key, cell);
    });

    // 先创建数据数组
    const data: any[][] = [];
    
    // 第一行：列标题（空单元格 + A, B, C...）
    const headerRow: any[] = [''];
    for (let col = 0; col < cols; col++) {
      // 处理超过26列的情况（AA, AB, AC...）
      let colChar = '';
      if (col < 26) {
        colChar = String.fromCharCode(65 + col); // A-Z
      } else {
        const first = Math.floor(col / 26) - 1;
        const second = col % 26;
        colChar = String.fromCharCode(65 + first) + String.fromCharCode(65 + second);
      }
      headerRow.push(colChar);
    }
    data.push(headerRow);

    // 填充数据行
    for (let row = 0; row < rows; row++) {
      const dataRow: any[] = [row + 1]; // 行号
      for (let col = 0; col < cols; col++) {
        const key = `${col},${row}`;
        const cell = cellMap.get(key);

        if (!cell || cell.merged) {
          // 被合并的单元格或空白单元格
          dataRow.push('');
        } else {
          let cellValue = '';

          if (cell.type === 'seat') {
            const seatNumber = cell.number || '';
            const status = cell.status === 0 ? '不可选' : '';
            const seatStatus = seatStatusMap.get(seatNumber);

            if (seatStatus) {
              // 已预订：编号、姓名、日期
              cellValue = `${seatNumber} ${seatStatus.name} ${seatStatus.date}`;
            } else if (status === '不可选') {
              // 不可选
              cellValue = `${seatNumber} 不可选`;
            } else {
              // 空闲
              cellValue = `${seatNumber} 空闲`;
            }
          } else if (cell.type === 'aisle') {
            cellValue = '过道';
          } else if (cell.type === 'projector') {
            cellValue = '投影';
          } else if (cell.type === 'pillar') {
            cellValue = '柱子';
          } else if (cell.type === 'door') {
            cellValue = '门';
          } else {
            // empty
            cellValue = '';
          }

          dataRow.push(cellValue);
        }
      }
      data.push(dataRow);
    }

    // 使用 aoa_to_sheet 创建工作表
    const ws = XLSX.utils.aoa_to_sheet(data);

    // 设置样式
    const range = XLSX.utils.decode_range(ws['!ref'] || 'A1');
    
    // 定义边框样式（所有单元格统一使用）
    const borderStyle = {
      top: { style: 'thin', color: { rgb: '000000' } },
      bottom: { style: 'thin', color: { rgb: '000000' } },
      left: { style: 'thin', color: { rgb: '000000' } },
      right: { style: 'thin', color: { rgb: '000000' } },
    };
    
    // 设置列标题样式
    for (let c = 0; c <= range.e.c; c++) {
      const cellRef = XLSX.utils.encode_cell({ r: 0, c });
      if (!ws[cellRef]) ws[cellRef] = { v: '', t: 's' };
      if (c === 0) {
        // 行号列标题
        ws[cellRef].s = {
          fill: { fgColor: { rgb: 'F6FFED' } },
          font: { bold: true },
          alignment: { horizontal: 'center', vertical: 'center' },
          border: borderStyle,
        };
      } else {
        // 列标题
        ws[cellRef].s = {
          fill: { fgColor: { rgb: 'E6F7FF' } },
          font: { bold: true, color: { rgb: '1890FF' } },
          alignment: { horizontal: 'center', vertical: 'center' },
          border: borderStyle,
        };
      }
    }

    // 设置行号列样式
    for (let r = 1; r <= range.e.r; r++) {
      const cellRef = XLSX.utils.encode_cell({ r, c: 0 });
      if (!ws[cellRef]) ws[cellRef] = { v: r, t: 'n' };
      ws[cellRef].s = {
        fill: { fgColor: { rgb: 'F6FFED' } },
        font: { bold: true, color: { rgb: '52C41A' } },
        alignment: { horizontal: 'center', vertical: 'center' },
        border: borderStyle,
      };
    }

    // 设置数据单元格样式
    for (let r = 1; r <= range.e.r; r++) {
      for (let c = 1; c <= range.e.c; c++) {
        const cellRef = XLSX.utils.encode_cell({ r, c });
        if (!ws[cellRef]) continue;
        
        const key = `${c - 1},${r - 1}`;
        const cell = cellMap.get(key);
        
        if (!cell || cell.merged) {
          ws[cellRef].s = {
            fill: { fgColor: { rgb: 'FFFFFF' } },
            alignment: { horizontal: 'center', vertical: 'center' },
            border: borderStyle,
          };
        } else {
          let cellStyle: any = {
            alignment: { horizontal: 'center', vertical: 'center', wrapText: true },
            border: borderStyle,
          };

          if (cell.type === 'seat') {
            const seatNumber = cell.number || '';
            const status = cell.status === 0 ? '不可选' : '';
            const seatStatus = seatStatusMap.get(seatNumber);

            if (seatStatus) {
              // 已预订（蓝色背景）
              cellStyle.fill = { fgColor: { rgb: '4472C4' } };
              cellStyle.font = { color: { rgb: 'FFFFFF' }, bold: true };
            } else if (status === '不可选') {
              // 不可选（红色背景）
              cellStyle.fill = { fgColor: { rgb: 'FF0000' } };
              cellStyle.font = { color: { rgb: 'FFFFFF' }, bold: true };
            } else {
              // 空闲（绿色背景）
              cellStyle.fill = { fgColor: { rgb: '70AD47' } };
              cellStyle.font = { color: { rgb: 'FFFFFF' }, bold: true };
            }
          } else if (cell.type === 'aisle') {
            cellStyle.fill = { fgColor: { rgb: 'FFC000' } };
            cellStyle.font = { color: { rgb: 'FFFFFF' }, bold: true };
          } else if (cell.type === 'projector') {
            cellStyle.fill = { fgColor: { rgb: '00B0F0' } };
            cellStyle.font = { color: { rgb: 'FFFFFF' }, bold: true };
          } else if (cell.type === 'pillar') {
            cellStyle.fill = { fgColor: { rgb: '808080' } };
            cellStyle.font = { color: { rgb: 'FFFFFF' }, bold: true };
          } else if (cell.type === 'door') {
            cellStyle.fill = { fgColor: { rgb: '1890FF' } };
            cellStyle.font = { color: { rgb: 'FFFFFF' }, bold: true };
          } else {
            // empty
            cellStyle.fill = { fgColor: { rgb: 'FFFFFF' } };
          }

          ws[cellRef].s = cellStyle;
        }
      }
    }

    // 设置列宽（统一为10）
    ws['!cols'] = [{ wch: 10 }]; // 行号列
    for (let i = 0; i < cols; i++) {
      ws['!cols'].push({ wch: 10 });
    }

    // 设置行高（加倍高度，便于阅读）
    ws['!rows'] = [{ hpt: 40 }]; // 标题行
    for (let i = 0; i < rows; i++) {
      ws['!rows'].push({ hpt: 60 });
    }

    // 设置合并单元格（如果有）
    const merges: any[] = [];
    cells.forEach((cell) => {
      if (!cell.merged) {
        const colspan = cell.colspan || 1;
        const rowspan = cell.rowspan || 1;
        if (colspan > 1 || rowspan > 1) {
          // Excel合并单元格：结束位置 = 起始位置 + 跨度 - 1
          // 注意：Excel的行列从0开始，但我们的数据从1开始（因为有标题行）
          merges.push({
            s: { r: cell.row + 1, c: cell.col + 1 },
            e: { r: cell.row + rowspan, c: cell.col + colspan },
          });
        }
      }
    });
    if (merges.length > 0) {
      ws['!merges'] = merges;
    }

    // 创建工作簿并添加工作表
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, '座位布局');

    // 导出文件
    const fileName = `${currentClassroomName.value || '教室'}_座位布局_${new Date().toISOString().slice(0, 10)}.xlsx`;
    XLSX.writeFile(wb, fileName);

    message.success('导出成功');
  } catch (error: any) {
    console.error('导出失败:', error);
    message.error(error?.message || '导出失败');
  }
};

// 处理座位列表分页变化
const handleSeatListTableChange = (pag: any) => {
  if (pag) {
    seatListPagination.current = pag.current || seatListPagination.current;
    seatListPagination.pageSize = pag.pageSize || seatListPagination.pageSize;
  }
};

// 取消选座
const handleCancelBooking = async (record: ClassroomApi.SeatInfo) => {
  if (!currentClassroomId.value) {
    message.error('教室ID不存在');
    return;
  }

  // 如果没有booking_id，尝试通过座位号取消
  let bookingId = record.booking_id;
  
  // 如果没有booking_id，尝试通过座位状态API获取
  if (!bookingId && record.is_selected === 1) {
    try {
      const statusRes = await getClassroomStatusApi({ id: currentClassroomId.value });
      if (statusRes && (statusRes.code === 0 || statusRes.code === 200)) {
        const statusData = statusRes.data || statusRes;
        // 查找对应座位的预订ID
        if (Array.isArray(statusData)) {
          const seatStatus = statusData.find((item: any) => item.seat_number === record.seat_number);
          if (seatStatus && seatStatus.booking_id) {
            bookingId = seatStatus.booking_id;
          }
        } else if (statusData.seats && Array.isArray(statusData.seats)) {
          const seatStatus = statusData.seats.find((item: any) => item.seat_number === record.seat_number);
          if (seatStatus && seatStatus.booking_id) {
            bookingId = seatStatus.booking_id;
          }
        }
      }
    } catch (error) {
      console.warn('获取座位状态失败:', error);
    }
  }

  Modal.confirm({
    title: '确认取消选座',
    content: `确定要取消座位 ${record.seat_number} 的选座吗？`,
    onOk: async () => {
      try {
        // 优先使用booking_id，如果没有则使用seat_number
        if (bookingId) {
          await cancelBookingApi({ id: bookingId });
        } else {
          // 尝试使用座位号取消
          await cancelBookingApi({ 
            seat_number: record.seat_number,
            classroomId: currentClassroomId.value 
          });
        }
        message.success('取消选座成功');
        // 重新加载座位列表
        if (currentClassroomId.value) {
          const res = await getClassroomSeatListApi({ id: currentClassroomId.value });
          if (res && (res.code === 0 || res.code === 200)) {
            seatListData.value = Array.isArray(res.data) ? res.data : [];
            selectedSeatKeys.value = [];
          }
        }
      } catch (error: any) {
        console.error('取消选座失败:', error);
        message.error(error?.response?.data?.message || error?.message || '取消选座失败');
      }
    },
  });
};

// 批量取消选座
const handleBatchCancelBooking = () => {
  if (selectedSeatKeys.value.length === 0) {
    message.warning('请选择要取消的座位');
    return;
  }

  // 获取选中的已选座位
  const selectedSeats = seatListData.value.filter(
    (seat) => selectedSeatKeys.value.includes(seat.seat_number) && seat.is_selected === 1 && seat.booking_id
  );

  if (selectedSeats.length === 0) {
    message.warning('请选择已选座的座位');
    return;
  }

  const bookingIds = selectedSeats.map((seat) => seat.booking_id!).filter((id) => id);

  if (bookingIds.length === 0) {
    message.warning('选中的座位中没有有效的预订ID');
    return;
  }

  Modal.confirm({
    title: '确认批量取消选座',
    content: `确定要取消 ${bookingIds.length} 个座位的选座吗？`,
    onOk: async () => {
      try {
        await cancelBookingAutoApi({ ids: bookingIds });
        message.success('批量取消选座成功');
        // 重新加载座位列表
        if (currentClassroomId.value) {
          const res = await getClassroomSeatListApi({ id: currentClassroomId.value });
          if (res && (res.code === 0 || res.code === 200)) {
            seatListData.value = Array.isArray(res.data) ? res.data : [];
            selectedSeatKeys.value = [];
          }
        }
      } catch (error: any) {
        console.error('批量取消选座失败:', error);
        message.error(error?.response?.data?.message || error?.message || '批量取消选座失败');
      }
    },
  });
};

// 分配座位相关
const assignSeatVisible = ref(false);
const assignSeatRecord = ref<ClassroomApi.SeatInfo | null>(null);
const unassignedStudents = ref<Array<{ id: number; name: string; phone?: string; student_id?: string | null }>>([]);
const unassignedStudentsLoading = ref(false);
const selectedStudentId = ref<number | undefined>(undefined);

// 打开分配座位弹窗
const handleAssignSeat = async (record: ClassroomApi.SeatInfo) => {
  if (!currentClassroomId.value) {
    message.error('教室ID不存在');
    return;
  }

  assignSeatRecord.value = record;
  assignSeatVisible.value = true;
  selectedStudentId.value = undefined;
  unassignedStudents.value = [];
  unassignedStudentsLoading.value = true;

  try {
    const res = await getUnassignedStudentsApi({ classroomId: currentClassroomId.value });
    if (res && (res.code === 0 || res.code === 200)) {
      const data = res.data || res;
      unassignedStudents.value = Array.isArray(data) ? data : [];
      if (unassignedStudents.value.length === 0) {
        message.warning('没有未分配座位的学生');
      }
    } else {
      message.error(res?.message || res?.msg || '获取学生列表失败');
      unassignedStudents.value = [];
    }
  } catch (error: any) {
    console.error('获取学生列表失败:', error);
    message.error(error?.response?.data?.message || error?.message || '获取学生列表失败');
    unassignedStudents.value = [];
  } finally {
    unassignedStudentsLoading.value = false;
  }
};

// 确认分配座位
const handleConfirmAssignSeat = async () => {
  if (!assignSeatRecord.value || !selectedStudentId.value || !currentClassroomId.value) {
    message.warning('请选择学生');
    return;
  }

  if (!currentLayout.value) {
    message.error('布局数据不存在，无法分配座位');
    return;
  }

  // 从布局数据中找到座位的row和col
  const seatNumber = assignSeatRecord.value.seat_number;
  const cells = currentLayout.value.cells || [];
  const seatCell = cells.find((cell) => cell.type === 'seat' && cell.number === seatNumber);

  if (!seatCell) {
    message.error('找不到对应的座位信息');
    return;
  }

  try {
    await assignSeatApi({
      classroomId: currentClassroomId.value,
      studentId: selectedStudentId.value,
      row: seatCell.row,
      col: seatCell.col,
      number: seatNumber,
    });
    message.success('分配座位成功');
    assignSeatVisible.value = false;
    assignSeatRecord.value = null;
    selectedStudentId.value = undefined;

    // 重新加载座位列表
    const res = await getClassroomSeatListApi({ id: currentClassroomId.value });
    if (res && (res.code === 0 || res.code === 200)) {
      seatListData.value = Array.isArray(res.data) ? res.data : [];
    }
  } catch (error: any) {
    console.error('分配座位失败:', error);
    message.error(error?.response?.data?.message || error?.message || '分配座位失败');
  }
};

// 关闭分配座位弹窗
const handleCloseAssignSeat = () => {
  assignSeatVisible.value = false;
  assignSeatRecord.value = null;
  selectedStudentId.value = undefined;
  unassignedStudents.value = [];
};

// 导出座位列表
const handleExportSeatList = () => {
  if (seatListData.value.length === 0) {
    message.warning('没有数据可导出');
    return;
  }

  // CSV表头
  const headers = ['座位号', '状态', '学员姓名', '学员手机号', '选座时间'];

  // 转换数据
  const csvData = seatListData.value.map((item) => {
    const status = item.is_selected === 1 ? '已选' : '未选';
    const studentName = item.student_name || '';
    const studentMobile = item.student_mobile || '';
    const selectTime = item.select_time || '';
    return [
      item.seat_number || '',
      status,
      studentName,
      studentMobile,
      selectTime,
    ];
  });

  // 组合CSV内容
  const csvContent = [
    headers.join(','),
    ...csvData.map((row) => row.map((cell) => `"${String(cell).replace(/"/g, '""')}"`).join(',')),
  ].join('\n');

  // 添加BOM以支持中文
  const BOM = '\uFEFF';
  const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' });

  // 创建下载链接
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  link.setAttribute('href', url);
  link.setAttribute('download', `${currentClassroomName.value || '教室'}_座位使用状态_${new Date().toISOString().slice(0, 10)}.csv`);
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);

  message.success('导出成功');
};

// 获取校区列表
const fetchSchoolList = async () => {
  schoolListLoading.value = true;
  try {
    const res = await getClassroomSchoolListApi();
    if (Array.isArray(res)) {
      schoolList.value = res;
    } else if (res && (res.code === 0 || res.code === 200)) {
      schoolList.value = Array.isArray(res.data) ? res.data : [];
    } else {
      schoolList.value = [];
    }
  } catch (error) {
    console.error('获取校区列表失败:', error);
    schoolList.value = [];
  } finally {
    schoolListLoading.value = false;
  }
};

onMounted(() => {
  fetchSchoolList();
  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.school_id"
            placeholder="校区"
            style="width: 150px"
            allow-clear
            :loading="schoolListLoading"
            show-search
            :filter-option="(input, option) => {
              const label = option?.label || '';
              return label.toLowerCase().includes(input.toLowerCase());
            }"
          >
            <Select.Option
              v-for="item in schoolList"
              :key="item.id"
              :value="item.id"
              :label="item.name || ''"
            >
              {{ item.name || `校区 ${item.id}` }}
            </Select.Option>
          </Select>
          <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} 条`,
          pageSizeOptions: ['10', '20', '50', '100'],
        }"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: handleRowSelectionChange,
        }"
        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" size="small" @click="handleViewLayout(record)">座位布局</Button>
              <Button type="link" size="small" @click="handleViewStatus(record)">使用状态</Button>
              <Button type="link" danger size="small" @click="handleDelete(record)">删除</Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 使用状态弹窗 -->
    <Modal
      v-model:open="seatListVisible"
      :title="`${currentClassroomName} - 使用状态`"
      width="800px"
      :footer="null"
      @cancel="handleCloseSeatList"
    >
      <div style="margin-bottom: 16px; text-align: right;">
        <Space>
          <Button type="primary" @click="handleExportLayout">
            导出布局
          </Button>
          <Button type="primary" @click="handleExportSeatList">
            导出
          </Button>
        </Space>
      </div>
      <Table
        :columns="[
          { title: '座位号', dataIndex: 'seat_number', key: 'seat_number', width: 100 },
          { title: '状态', key: 'status', width: 100 },
          { title: '学员姓名', dataIndex: 'student_name', key: 'student_name' },
          { title: '学员手机号', dataIndex: 'student_mobile', key: 'student_mobile' },
          { title: '选座时间', dataIndex: 'select_time', key: 'select_time' },
          { title: '操作', key: 'action', width: 120, fixed: 'right' },
        ]"
        :data-source="seatListData"
        :loading="seatListLoading"
        :pagination="{
          current: seatListPagination.current,
          pageSize: seatListPagination.pageSize,
          total: seatListData.length,
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条`,
          pageSizeOptions: ['10', '20', '50', '100'],
        }"
        row-key="seat_number"
        size="small"
        @change="handleSeatListTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <Tag :color="record.is_selected === 1 ? 'red' : 'green'">
              {{ record.is_selected === 1 ? '已选' : '未选' }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'student_name'">
            {{ record.student_name || '-' }}
          </template>
          <template v-else-if="column.key === 'student_mobile'">
            {{ record.student_mobile || '-' }}
          </template>
          <template v-else-if="column.key === 'select_time'">
            {{ record.select_time || '-' }}
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button
                v-if="record.is_selected === 1"
                type="link"
                danger
                size="small"
                @click="handleCancelBooking(record)"
              >
                取消
              </Button>
              <Button
                v-else
                type="link"
                size="small"
                @click="handleAssignSeat(record)"
              >
                分配
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Modal>

    <!-- 分配座位弹窗 -->
    <Modal
      v-model:open="assignSeatVisible"
      title="分配座位"
      :footer="null"
      @cancel="handleCloseAssignSeat"
    >
      <div style="margin-bottom: 16px;">
        <div style="margin-bottom: 8px;">
          <strong>座位号：</strong>{{ assignSeatRecord?.seat_number }}
        </div>
        <div style="margin-bottom: 16px;">
          <strong>选择学生：</strong>
        </div>
        <Select
          v-model:value="selectedStudentId"
          placeholder="请选择学生"
          style="width: 100%"
          :loading="unassignedStudentsLoading"
          show-search
          :filter-option="(input, option) => {
            const label = option?.label || '';
            return label.toLowerCase().includes(input.toLowerCase());
          }"
        >
          <Select.Option
            v-for="student in unassignedStudents"
            :key="student.id"
            :value="student.id"
            :label="`${student.name} (${student.phone || ''})`"
          >
            {{ student.name }} ({{ student.phone || '' }})
          </Select.Option>
        </Select>
      </div>
      <div style="text-align: right; margin-top: 16px;">
        <Space>
          <Button @click="handleCloseAssignSeat">取消</Button>
          <Button type="primary" :disabled="!selectedStudentId" @click="handleConfirmAssignSeat">
            确认分配
          </Button>
        </Space>
      </div>
    </Modal>

    <!-- 座位布局弹窗 -->
    <Modal
      v-model:open="layoutVisible"
      :title="`${currentClassroomName} - 座位布局`"
      width="90%"
      :footer="null"
      :mask-closable="false"
      @cancel="handleCloseLayout"
    >
      <div v-if="layoutLoading" style="text-align: center; padding: 40px;">
        <span>加载中...</span>
      </div>
      <SeatLayoutEditor
        v-else-if="currentClassroomId"
        :classroom-id="currentClassroomId"
        :layout="currentLayout"
        @saved="handleLayoutSaved"
      />
    </Modal>
  </Page>
</template>

