<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, Upload } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';
import { 
  getStudentListApi, 
  deleteStudentApi,
  uploadStudentFileApi,
  importStudentDataApi,
  type StudentApi 
} from '#/api';
import { getClassListApi, type ClassApi } from '#/api';

defineOptions({ name: 'StudentList' });

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

const searchForm = reactive({
  student_id: '',
  name: '',
  phone: '',
  class_id: undefined as number | undefined,
  school_id: undefined as number | undefined,
  bind_status: undefined as string | undefined,
});

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
  },
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    width: 120,
  },
  {
    title: '性别',
    dataIndex: 'gender',
    key: 'gender',
    width: 80,
  },
  {
    title: '电话',
    dataIndex: 'phone',
    key: 'phone',
    width: 130,
  },
  {
    title: '学校',
    dataIndex: 'school_name',
    key: 'school_name',
    width: 150,
  },
  {
    title: '班级',
    dataIndex: 'class_name',
    key: 'class_name',
    width: 200,
  },
  {
    title: '绑定状态',
    dataIndex: 'bind_status',
    key: 'bind_status',
    width: 100,
  },
  {
    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: StudentApi.ListParams = {
      page: pagination.current,
      limit: pagination.pageSize,
      ...searchForm,
    };
    const res = await getStudentListApi(params);
    // 根据实际返回格式，code 为 0 表示成功
    if (res && (res.code === 0 || res.code === 200)) {
      const data = res.data;
      if (Array.isArray(data)) {
        tableData.value = data;
        total.value = res.count || data.length;
      } else {
        tableData.value = [];
        total.value = 0;
      }
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  pagination.current = 1;
  fetchData();
};

const handleReset = () => {
  searchForm.student_id = '';
  searchForm.name = '';
  searchForm.phone = '';
  searchForm.class_id = undefined;
  searchForm.school_id = undefined;
  searchForm.bind_status = undefined;
  handleSearch();
};

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

const handleEdit = (record: StudentApi.StudentInfo) => {
  router.push({ name: 'StudentDetail', params: { id: record.id } });
};

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

const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  fetchData();
};

// 导入相关
const importModalVisible = ref(false);
const importLoading = ref(false);
const uploadedFile = ref<string>('');
const selectedClassId = ref<number | undefined>(undefined);
const classList = ref<ClassApi.ClassInfo[]>([]);
const fileList = ref<any[]>([]);

// 获取班级列表
const fetchClassList = async () => {
  try {
    const res = await getClassListApi({ page: 1, limit: 1000 });
    if (res && (res.code === 0 || res.code === 200)) {
      // 根据实际返回格式，data 是数组
      const data = res.data;
      if (Array.isArray(data)) {
        classList.value = data;
      } else {
        classList.value = [];
      }
    } else {
      classList.value = [];
    }
  } catch (error) {
    classList.value = [];
  }
};

// 打开导入对话框
const handleImport = () => {
  importModalVisible.value = true;
  uploadedFile.value = '';
  selectedClassId.value = undefined;
  fileList.value = [];
  fetchClassList();
};

// 文件上传前验证
const beforeUpload = (file: File) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    || file.type === 'application/vnd.ms-excel'
    || file.name.endsWith('.xlsx')
    || file.name.endsWith('.xls');
  if (!isExcel) {
    message.error('只能上传 Excel 文件（.xlsx 或 .xls）');
    return false;
  }
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error('文件大小不能超过 10MB');
    return false;
  }
  return false; // 阻止自动上传
};

// 文件变化处理
const handleFileChange = async (info: any) => {
  const { file, fileList: newFileList } = info;
  fileList.value = newFileList;
  
  // 文件被移除
  if (file.status === 'removed') {
    uploadedFile.value = '';
    return;
  }
  
  // 文件选择后，手动上传
  if (file.status === 'ready' && file.originFileObj) {
    importLoading.value = true;
    try {
      const res = await uploadStudentFileApi(file.originFileObj);
      // 根据API，上传接口返回文件路径
      if (res && (res.code === 0 || res.code === 200)) {
        uploadedFile.value = res.data || res.file || '';
        message.success('文件上传成功');
        // 更新文件状态为已完成
        fileList.value = [{
          uid: file.uid,
          name: file.name,
          status: 'done',
        }];
      } else {
        message.error(res?.msg || '文件上传失败');
        fileList.value = [];
        uploadedFile.value = '';
      }
    } catch (error: any) {
      console.error('文件上传失败:', error);
      message.error(error?.response?.data?.msg || '文件上传失败');
      fileList.value = [];
      uploadedFile.value = '';
    } finally {
      importLoading.value = false;
    }
  }
};

// 确认导入
const handleConfirmImport = async () => {
  if (!uploadedFile.value) {
    message.warning('请先上传 Excel 文件');
    return;
  }
  if (!selectedClassId.value) {
    message.warning('请选择班级');
    return;
  }

  importLoading.value = true;
  try {
    await importStudentDataApi({
      class_id: selectedClassId.value,
      file: uploadedFile.value,
    });
    message.success('学生数据导入成功');
    importModalVisible.value = false;
    uploadedFile.value = '';
    selectedClassId.value = undefined;
    fileList.value = [];
    fetchData(); // 刷新列表
  } catch (error) {
    console.error('导入失败:', error);
    message.error('学生数据导入失败');
  } finally {
    importLoading.value = false;
  }
};

// 取消导入
const handleCancelImport = () => {
  importModalVisible.value = false;
  uploadedFile.value = '';
  selectedClassId.value = undefined;
  fileList.value = [];
};

onMounted(() => {
  fetchData();
});
</script>

<template>
  <Page title="学生列表">
    <Card>
      <div class="mb-4">
        <Space wrap>
          <Input
            v-model:value="searchForm.name"
            placeholder="姓名"
            style="width: 150px"
            allow-clear
            @press-enter="handleSearch"
          />
          <Input
            v-model:value="searchForm.phone"
            placeholder="电话"
            style="width: 150px"
            allow-clear
            @press-enter="handleSearch"
          />
          <Input
            v-model:value="searchForm.student_id"
            placeholder="学号"
            style="width: 150px"
            allow-clear
            @press-enter="handleSearch"
          />
          <Select
            v-model:value="searchForm.bind_status"
            placeholder="绑定状态"
            style="width: 120px"
            allow-clear
          >
            <Select.Option value="已绑定">已绑定</Select.Option>
            <Select.Option value="未绑定">未绑定</Select.Option>
          </Select>
          <Button type="primary" @click="handleSearch">搜索</Button>
          <Button @click="handleReset">重置</Button>
          <Button type="primary" @click="handleAdd">新增</Button>
          <Button @click="handleImport">导入学生</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 === 'bind_status'">
            <Tag :color="record.bind_status === '已绑定' ? 'green' : 'default'">
              {{ record.bind_status || '-' }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <Tag :color="record.status === 1 ? 'green' : 'red'">
              {{ record.status === 1 ? '启用' : '禁用' }}
            </Tag>
          </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>

    <!-- 导入学生对话框 -->
    <Modal
      v-model:open="importModalVisible"
      title="导入学生"
      :confirm-loading="importLoading"
      @ok="handleConfirmImport"
      @cancel="handleCancelImport"
      width="600px"
    >
      <div class="import-form">
        <div class="form-item">
          <div class="form-label">上传 Excel 文件：</div>
          <Upload
            v-model:file-list="fileList"
            :before-upload="beforeUpload"
            @change="handleFileChange"
            :max-count="1"
            accept=".xlsx,.xls"
          >
            <Button :loading="importLoading">
              <template #icon>
                <IconifyIcon icon="lucide:upload" />
              </template>
              选择文件
            </Button>
          </Upload>
          <div class="form-hint">
            支持 .xlsx 和 .xls 格式，文件大小不超过 10MB
          </div>
        </div>
        <div class="form-item">
          <div class="form-label">选择班级：</div>
          <Select
            v-model:value="selectedClassId"
            placeholder="请选择班级"
            style="width: 100%"
            :loading="importLoading"
            show-search
            :filter-option="(input, option) => {
              const label = option?.label || '';
              return label.toLowerCase().includes(input.toLowerCase());
            }"
          >
            <Select.Option
              v-for="item in classList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            >
              {{ item.name }}
            </Select.Option>
          </Select>
        </div>
        <div class="form-hint">
          <p><strong>导入说明：</strong></p>
          <p>1. 请先上传 Excel 文件，文件上传成功后再选择班级</p>
          <p>2. Excel 文件格式请参考系统要求</p>
          <p>3. 导入过程中请勿关闭此对话框</p>
        </div>
      </div>
    </Modal>
  </Page>
</template>

<style scoped>
.import-form {
  padding: 20px 0;
}

.form-item {
  margin-bottom: 24px;
}

.form-label {
  margin-bottom: 8px;
  font-weight: 500;
  color: var(--ant-color-text);
}

.form-hint {
  margin-top: 8px;
  font-size: 12px;
  color: var(--ant-color-text-secondary);
  line-height: 1.6;
}

.form-hint p {
  margin: 4px 0;
}
</style>

