<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,
  type ClassroomApi
} from '#/api';
import SeatLayoutEditor from '#/components/classroom/SeatLayoutEditor.vue';


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 layoutVisible = ref(false);
const layoutLoading = ref(false);
const currentClassroomId = ref<number | null>(null);
const currentLayout = ref<ClassroomApi.ClassroomLayout | null>(null);

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: 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;
  currentClassroomName.value = record.name || '';
  seatListLoading.value = true;
  seatListData.value = [];

  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();
};

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

// 导出座位列表
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('导出成功');
};

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} 条`,
          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;">
        <Button type="primary" @click="handleExportSeatList">
          导出
        </Button>
      </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' },
        ]"
        :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>
      </Table>
    </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>

