<template>
  <div class="schools-page">
    <a-card>
      <template #title>学校信息管理</template>
      <template #extra>
        <a-button
          v-if="!schoolInfo"
          v-permission="'school:create'"
          type="primary"
          @click="handleAdd"
        >
          新增学校信息
        </a-button>
        <a-button
          v-else
          v-permission="'school:update'"
          type="primary"
          @click="handleEdit"
        >
          编辑学校信息
        </a-button>
      </template>

      <a-spin :spinning="loading">
        <div v-if="schoolInfo" class="school-info">
          <a-descriptions :column="2" bordered>
            <a-descriptions-item label="学校名称">
              {{ schoolInfo.tenant?.name || "-" }}
            </a-descriptions-item>
            <a-descriptions-item label="学校编码">
              {{ schoolInfo.tenant?.code || "-" }}
            </a-descriptions-item>
            <a-descriptions-item label="地址">
              {{ schoolInfo.address || "-" }}
            </a-descriptions-item>
            <a-descriptions-item label="联系电话">
              {{ schoolInfo.phone || "-" }}
            </a-descriptions-item>
            <a-descriptions-item label="校长">
              {{ schoolInfo.principal || "-" }}
            </a-descriptions-item>
            <a-descriptions-item label="建校时间">
              {{ formatDate(schoolInfo.established) }}
            </a-descriptions-item>
            <a-descriptions-item label="学校网站" :span="2">
              <a
                v-if="schoolInfo.website"
                :href="schoolInfo.website"
                target="_blank"
              >
                {{ schoolInfo.website }}
              </a>
              <span v-else>-</span>
            </a-descriptions-item>
            <a-descriptions-item label="学校Logo" :span="2">
              <img
                v-if="schoolInfo.logo"
                :src="schoolInfo.logo"
                alt="学校Logo"
                style="max-width: 200px; max-height: 100px"
              />
              <span v-else>-</span>
            </a-descriptions-item>
            <a-descriptions-item label="学校描述" :span="2">
              {{ schoolInfo.description || "-" }}
            </a-descriptions-item>
          </a-descriptions>
        </div>
        <a-empty v-else description="暂无学校信息" />
      </a-spin>
    </a-card>

    <!-- 新增/编辑学校信息弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      :confirm-loading="submitLoading"
      @ok="handleSubmit"
      @cancel="handleCancel"
      width="700px"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="地址" name="address">
          <a-input
            v-model:value="form.address"
            placeholder="请输入学校地址"
            :maxlength="200"
          />
        </a-form-item>
        <a-form-item label="联系电话" name="phone">
          <a-input
            v-model:value="form.phone"
            placeholder="请输入联系电话"
            :maxlength="20"
          />
        </a-form-item>
        <a-form-item label="校长" name="principal">
          <a-input
            v-model:value="form.principal"
            placeholder="请输入校长姓名"
            :maxlength="50"
          />
        </a-form-item>
        <a-form-item label="建校时间" name="established">
          <a-date-picker
            v-model:value="form.established"
            placeholder="请选择建校时间"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </a-form-item>
        <a-form-item label="学校网站" name="website">
          <a-input
            v-model:value="form.website"
            placeholder="请输入学校网站URL"
            :maxlength="500"
          />
        </a-form-item>
        <a-form-item label="学校Logo" name="logo">
          <a-input
            v-model:value="form.logo"
            placeholder="请输入Logo URL"
            :maxlength="500"
          />
        </a-form-item>
        <a-form-item label="学校描述" name="description">
          <a-textarea
            v-model:value="form.description"
            placeholder="请输入学校描述"
            :rows="4"
            :maxlength="1000"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue"
import { message } from "ant-design-vue"
import type { FormInstance } from "ant-design-vue"
import {
  schoolsApi,
  type School,
  type CreateSchoolForm,
  type UpdateSchoolForm,
} from "@/api/schools"
import { useAuthStore } from "@/stores/auth"
import dayjs, { type Dayjs } from "dayjs"

const authStore = useAuthStore()

const loading = ref(false)
const submitLoading = ref(false)
const modalVisible = ref(false)
const modalTitle = ref("新增学校信息")
const formRef = ref<FormInstance>()
const schoolInfo = ref<School | null>(null)
const isEditing = ref(false)

const form = reactive<CreateSchoolForm & { established?: Dayjs }>({
  address: "",
  phone: "",
  principal: "",
  established: undefined,
  description: "",
  logo: "",
  website: "",
})

const rules = {
  website: [{ type: "url", message: "请输入正确的URL地址", trigger: "blur" }],
  logo: [{ type: "url", message: "请输入正确的URL地址", trigger: "blur" }],
}

// 格式化日期
const formatDate = (dateStr?: string) => {
  if (!dateStr) return "-"
  return dayjs(dateStr).format("YYYY-MM-DD")
}

// 加载学校信息
const fetchSchoolInfo = async () => {
  loading.value = true
  try {
    const result = await schoolsApi.get()
    // 后端返回 null 表示学校信息不存在，这是正常状态
    schoolInfo.value = result || null
  } catch (error: any) {
    // 如果后端仍然返回 404（向后兼容），也设置为 null
    if (error?.response?.status === 404) {
      schoolInfo.value = null
    } else {
      message.error("获取学校信息失败")
    }
  } finally {
    loading.value = false
  }
}

// 新增学校信息
const handleAdd = () => {
  if (!authStore.hasPermission("school:create")) {
    message.error("您没有创建学校信息的权限")
    return
  }

  modalTitle.value = "新增学校信息"
  isEditing.value = false
  modalVisible.value = true
  form.address = ""
  form.phone = ""
  form.principal = ""
  form.established = undefined
  form.description = ""
  form.logo = ""
  form.website = ""
  formRef.value?.resetFields()
}

// 编辑学校信息
const handleEdit = () => {
  if (!authStore.hasPermission("school:update")) {
    message.error("您没有更新学校信息的权限")
    return
  }

  if (!schoolInfo.value) return

  modalTitle.value = "编辑学校信息"
  isEditing.value = true
  modalVisible.value = true
  form.address = schoolInfo.value.address || ""
  form.phone = schoolInfo.value.phone || ""
  form.principal = schoolInfo.value.principal || ""
  form.established = schoolInfo.value.established
    ? dayjs(schoolInfo.value.established)
    : undefined
  form.description = schoolInfo.value.description || ""
  form.logo = schoolInfo.value.logo || ""
  form.website = schoolInfo.value.website || ""
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitLoading.value = true

    const data: CreateSchoolForm | UpdateSchoolForm = {
      address: form.address || undefined,
      phone: form.phone || undefined,
      principal: form.principal || undefined,
      established: form.established
        ? form.established.format("YYYY-MM-DD")
        : undefined,
      description: form.description || undefined,
      logo: form.logo || undefined,
      website: form.website || undefined,
    }

    if (isEditing.value) {
      await schoolsApi.update(data as UpdateSchoolForm)
      message.success("更新成功")
    } else {
      await schoolsApi.create(data as CreateSchoolForm)
      message.success("创建成功")
    }

    modalVisible.value = false
    fetchSchoolInfo()
  } catch (error: any) {
    if (error?.errorFields) {
      return
    }
    const errorMessage =
      error?.response?.data?.message ||
      (isEditing.value ? "更新失败" : "创建失败")
    message.error(errorMessage)
  } finally {
    submitLoading.value = false
  }
}

// 取消表单
const handleCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
}

onMounted(() => {
  fetchSchoolInfo()
})
</script>

<style scoped>
.school-info {
  margin-top: 16px;
}
</style>
