<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, Tabs } from 'ant-design-vue';
import {
  getSchoolDetailApi,
  saveSchoolApi,
  type SchoolApi
} from '#/api';

defineOptions({ name: 'SchoolDetail' });

const route = useRoute();
const router = useRouter();
const formRef = ref();
const loading = ref(false);
const activeTab = ref('basic');
const formData = ref<Partial<SchoolApi.SaveParams>>({
  name: '',
  address: '',
  contact: '',
  phone: '',
  description: '',
});

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 saveSchoolApi(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 getSchoolDetailApi({ 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 = {
          name: data.name || '',
          address: data.address || '',
          contact: data.contact || '',
          phone: data.phone || '',
          description: data.description || '',
        };
      } 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>
      <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="address">
              <Input v-model:value="formData.address" placeholder="请输入地址" />
            </Form.Item>
            <Form.Item label="联系人" name="contact">
              <Input v-model:value="formData.contact" placeholder="请输入联系人" />
            </Form.Item>
            <Form.Item label="联系电话" name="phone">
              <Input v-model:value="formData.phone" placeholder="请输入联系电话" />
            </Form.Item>
            <Form.Item label="描述" name="description">
              <Input.TextArea v-model:value="formData.description" placeholder="请输入描述" :rows="3" />
            </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>

