<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, InputNumber, Button, message, Radio } from 'ant-design-vue';
import { 
  getTeacherDetailApi, 
  saveTeacherApi,
  type TeacherApi 
} from '#/api';

defineOptions({ name: 'TeacherDetail' });

const route = useRoute();
const router = useRouter();
const formRef = ref();
const loading = ref(false);
const formData = ref<Partial<TeacherApi.SaveParams>>({
  teacher_id: null,
  name: '',
  gender: undefined,
  nickname: '',
  phone: '',
  email: '',
  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 saveTeacherApi(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 getTeacherDetailApi({ id: Number(route.params.id) });
    // 支持 code 为 0 或 200 的成功响应
    if (res && (res.code === 0 || res.code === 200)) {
      // 根据实际返回格式，数据在 res.data 中
      const data = res.data;
      if (data) {
        formData.value = {
          teacher_id: data.teacher_id ?? null,
          name: data.name || '',
          gender: data.gender || undefined,
          nickname: data.nickname || '',
          phone: data.phone || '',
          email: data.email || '',
          remark: data.remark || '',
          status: data.status !== undefined ? data.status : 1,
        };
      } else {
        message.error('获取教师详情失败：数据为空');
      }
    } 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;
  }
};

onMounted(() => {
  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="姓名"
          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="nickname">
          <Input v-model:value="formData.nickname" placeholder="请输入昵称" />
        </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="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>

