<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Page } from '@vben/common-ui';
import { Card, Form, Input, Button, message, Select, Radio } from 'ant-design-vue';
import {
  getStudentDetailApi,
  saveStudentApi,
  type StudentApi
} from '#/api';
import { getClassListApi, type ClassApi } from '#/api';

defineOptions({ name: 'StudentDetail' });

const route = useRoute();
const router = useRouter();
const formRef = ref();
const loading = ref(false);
const classList = ref<ClassApi.ClassInfo[]>([]);
const classListLoading = ref(false);
const formData = ref<Partial<StudentApi.SaveParams>>({
  student_id: '',
  name: '',
  gender: undefined,
  class_id: undefined,
  phone: '',
  email: '',
  avatar: null,
  remark: '',
  status: 1,
});

const isEdit = computed(() => !!route.params.id);

const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    loading.value = true;
    const data = { ...formData.value };
    if (isEdit.value) {
      data.id = Number(route.params.id);
    }
    await saveStudentApi(data);
    message.success(isEdit.value ? '更新成功' : '创建成功');
    router.back();
  } catch (error: any) {
    console.error('保存失败:', error);
    message.error(error?.response?.data?.message || error?.response?.data?.msg || '保存失败');
  } finally {
    loading.value = false;
  }
};

const fetchDetail = async () => {
  if (!isEdit.value) return;
  loading.value = true;
  try {
    const res = await getStudentDetailApi({ id: Number(route.params.id) });
    // 支持 code 为 0 或 200 的成功响应
    if (res && (res.code === 0 || res.code === 200)) {
      // 根据实际返回格式，数据在 res.data 中
      const data = res.data || res;
      formData.value = {
        student_id: (data.student_id || data.id?.toString() || '') as string,
        name: data.name || '',
        class_id: data.class_id,
        status: data.status !== undefined ? data.status : 1,
        gender: data.gender || undefined,
        phone: data.phone || '',
        email: data.email || '',
        avatar: data.avatar || null,
        remark: data.remark || '',
      };
    } else {
      message.error(res?.message || res?.msg || '获取学生详情失败');
    }
  } catch (error: any) {
    console.error('获取详情失败:', error);
    message.error(error?.response?.data?.message || error?.response?.data?.msg || '获取学生详情失败');
  } finally {
    loading.value = false;
  }
};

// 获取班级列表
const fetchClassList = async () => {
  classListLoading.value = true;
  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) {
    console.error('获取班级列表失败:', error);
    classList.value = [];
  } finally {
    classListLoading.value = false;
  }
};

onMounted(() => {
  fetchClassList();
  if (isEdit.value) {
    fetchDetail();
  }
});
</script>

<template>
  <Page :title="isEdit ? '编辑学生' : '新增学生'">
    <Card>
      <Form
        ref="formRef"
        :model="formData"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <Form.Item
          label="学员ID"
          name="student_id"
          :rules="[{ required: true, message: '请输入学员ID' }]"
        >
          <Input
            v-model:value="formData.student_id as string"
            :placeholder="isEdit ? '学员ID' : '请输入学员ID'"
            :disabled="isEdit"
          />
        </Form.Item>
        <Form.Item
          label="姓名"
          name="name"
          :rules="[{ required: true, message: '请输入姓名' }]"
        >
          <Input v-model:value="formData.name" placeholder="请输入姓名" />
        </Form.Item>
        <Form.Item label="性别" name="gender">
          <Radio.Group v-model:value="formData.gender">
            <Radio value="男">男</Radio>
            <Radio value="女">女</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item label="电话" name="phone">
          <Input v-model:value="formData.phone" placeholder="请输入电话" />
        </Form.Item>
        <Form.Item label="邮箱" name="email">
          <Input v-model:value="formData.email" placeholder="请输入邮箱" />
        </Form.Item>
        <Form.Item label="班级" name="class_id">
          <Select
            v-model:value="formData.class_id"
            placeholder="请选择班级"
            :loading="classListLoading"
            allow-clear
            show-search
            :filter-option="(input, option) => {
              const label = option?.label || '';
              return label.toLowerCase().includes(input.toLowerCase());
            }"
          >
            <template v-if="classList.length === 0 && !classListLoading">
              <Select.Option disabled value="">暂无班级数据</Select.Option>
            </template>
            <Select.Option
              v-for="item in classList"
              :key="item.id"
              :value="item.id"
              :label="item.name || ''"
            >
              {{ item.name || `班级 ${item.id}` }}
            </Select.Option>
          </Select>
          <div v-if="classList.length > 0" style="margin-top: 4px; font-size: 12px; color: #999;">
            共 {{ classList.length }} 个班级可选
          </div>
        </Form.Item>
        <Form.Item label="备注" name="remark">
          <Input.TextArea v-model:value="formData.remark" placeholder="请输入备注" :rows="3" />
        </Form.Item>
        <Form.Item label="状态" name="status">
          <Radio.Group v-model:value="formData.status">
            <Radio :value="1">启用</Radio>
            <Radio :value="0">禁用</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item :wrapper-col="{ offset: 4, span: 20 }">
          <Button type="primary" :loading="loading" @click="handleSubmit">保存</Button>
          <Button class="ml-2" @click="router.back()">取消</Button>
        </Form.Item>
      </Form>
    </Card>
  </Page>
</template>

