<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, Select, InputNumber, Button, message, Tabs, Radio } from 'ant-design-vue';
import {
  getClassroomDetailApi,
  saveClassroomApi,
  getSchoolListApi,
  getTeacherListApi,
  type ClassroomApi,
  type SchoolApi,
  type TeacherApi
} from '#/api';

defineOptions({ name: 'ClassroomDetail' });

const route = useRoute();
const router = useRouter();
const formRef = ref();
const loading = ref(false);
const activeTab = ref('basic');
const schoolList = ref<SchoolApi.SchoolInfo[]>([]);
const teacherList = ref<TeacherApi.TeacherInfo[]>([]);
const schoolListLoading = ref(false);
const teacherListLoading = ref(false);
const formData = ref<ClassroomApi.SaveParams>({
  name: '',
  building: '',
  floor: '',
  room: '',
  type: 'normal',
  capacity: 10, // 默认容量为10
  school_id: undefined,
  teacher_id: undefined,
  description: '',
  status: 1,
});

const isEdit = computed(() => !!route.params.id);
const classroomId = computed(() => (isEdit.value ? Number(route.params.id) : 0));

const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    loading.value = true;
    const data: any = { ...formData.value };
    if (isEdit.value) {
      data.id = Number(route.params.id);
    }
    // 将 building, floor, room 组合成 location 对象
    if (data.building || data.floor || data.room) {
      data.location = {
        building: data.building || '',
        floor: data.floor || '',
        room: data.room || '',
      };
      // 删除单独的字段，避免重复
      delete data.building;
      delete data.floor;
      delete data.room;
    }
    await saveClassroomApi(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 getClassroomDetailApi({ id: Number(route.params.id) });
    // 支持 code 为 0 或 200 的成功响应
    if (res && (res.code === 0 || res.code === 200)) {
      // 根据实际返回格式，数据在 res.data 中
      const data = res.data || res;
      // 解析 location 对象
      const location = data.location || {};
      formData.value = {
        name: data.name || '',
        building: location.building || data.building || '',
        floor: location.floor || data.floor || '',
        room: location.room || data.room || '',
        type: data.type || 'normal',
        capacity: data.capacity || 10, // 默认容量为10
        school_id: data.school_id,
        teacher_id: data.teacher_id,
        description: data.description || '',
        status: data.status !== undefined ? data.status : 1,
      };
    } 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 fetchSchoolList = async () => {
  schoolListLoading.value = true;
  try {
    const res = await getSchoolListApi({ page: 1, limit: 1000 });
    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;
  }
};

// 获取教师列表
const fetchTeacherList = async () => {
  teacherListLoading.value = true;
  try {
    const res = await getTeacherListApi({ page: 1, limit: 1000 });
    if (res && (res.code === 0 || res.code === 200)) {
      teacherList.value = Array.isArray(res.data) ? res.data : [];
    } else {
      teacherList.value = [];
    }
  } catch (error) {
    console.error('获取教师列表失败:', error);
    teacherList.value = [];
  } finally {
    teacherListLoading.value = false;
  }
};

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

<template>
  <Page :title="isEdit ? '编辑教室' : '新增教室'">
    <Card>
      <Tabs v-model:activeKey="activeTab">
        <Tabs.TabPane key="basic" tab="基本信息">
          <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="building"
              :rules="[{ required: true, message: '请输入楼栋' }]"
            >
              <Input v-model:value="formData.building" placeholder="请输入楼栋" />
            </Form.Item>
            <Form.Item label="楼层" name="floor">
              <Input v-model:value="formData.floor" placeholder="请输入楼层" />
            </Form.Item>
            <Form.Item label="房间号" name="room">
              <Input v-model:value="formData.room" placeholder="请输入房间号" />
            </Form.Item>
            <Form.Item
              label="教室类型"
              name="type"
              :rules="[{ required: true, message: '请选择教室类型' }]"
            >
              <Select v-model:value="formData.type" placeholder="请选择教室类型">
                <Select.Option value="normal">普通教室</Select.Option>
                <Select.Option value="multimedia">多媒体教室</Select.Option>
                <Select.Option value="lab">实验室</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item
              label="学校"
              name="school_id"
              :rules="[{ required: true, message: '请选择学校' }]"
            >
              <Select
                v-model:value="formData.school_id"
                placeholder="请选择学校"
                :loading="schoolListLoading"
                allow-clear
                show-search
                :filter-option="(input, option) => {
                  const label = option?.label || '';
                  return label.toLowerCase().includes(input.toLowerCase());
                }"
              >
                <template v-if="schoolList.length === 0 && !schoolListLoading">
                  <Select.Option disabled value="">暂无学校数据</Select.Option>
                </template>
                <Select.Option
                  v-for="item in schoolList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name || ''"
                >
                  {{ item.name || `学校 ${item.id}` }}
                </Select.Option>
              </Select>
            </Form.Item>
            <Form.Item
              label="负责教师"
              name="teacher_id"
              :rules="[{ required: true, message: '请选择负责教师' }]"
            >
              <Select
                v-model:value="formData.teacher_id"
                placeholder="请选择负责教师"
                :loading="teacherListLoading"
                allow-clear
                show-search
                :filter-option="(input, option) => {
                  const label = option?.label || '';
                  return label.toLowerCase().includes(input.toLowerCase());
                }"
              >
                <template v-if="teacherList.length === 0 && !teacherListLoading">
                  <Select.Option disabled value="">暂无教师数据</Select.Option>
                </template>
                <Select.Option
                  v-for="item in teacherList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name || ''"
                >
                  {{ item.name || `教师 ${item.id}` }}
                </Select.Option>
              </Select>
            </Form.Item>
            <Form.Item label="描述" name="description">
              <Input.TextArea v-model:value="formData.description" 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>
        </Tabs.TabPane>
      </Tabs>
    </Card>
  </Page>
</template>

