<template>
  <div class="form-page">
    <!-- 页面头部：返回按钮 + 标题 + 分隔线 -->
    <el-page-header @back="handleBack" :title="isEdit ? '编辑接口' : '新增接口'" />
    <el-divider />

    <!-- 表单卡片 -->
    <el-card class="form-card" shadow="never">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="所属系统" prop="systemId">
          <el-select v-model="form.systemId" placeholder="请选择系统" style="width: 100%">
            <el-option
              v-for="s in systemOptions"
              :key="s.id"
              :label="s.systemName"
              :value="s.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="接口路径" prop="apiPath">
          <el-input v-model="form.apiPath" placeholder="请输入接口路径，如 /zgapi/v1/admin/user" />
        </el-form-item>
        <el-form-item label="请求方式" prop="apiMethod">
          <el-select v-model="form.apiMethod" placeholder="请选择请求方式" style="width: 100%">
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
          </el-select>
        </el-form-item>
        <el-form-item label="接口名称" prop="apiName">
          <el-input v-model="form.apiName" placeholder="请输入接口名称" />
        </el-form-item>
        <el-form-item label="接口描述" prop="apiDesc">
          <el-input v-model="form.apiDesc" type="textarea" :rows="2" placeholder="请输入接口描述（可选）" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" active-text="启用" inactive-text="禁用" />
        </el-form-item>

        <!-- 按钮区域固定在底部 -->
        <el-divider />
        <div class="form-footer">
          <el-button @click="handleBack">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import request from '@/utils/request'

/** 系统选项 */
interface SystemOption {
  id: string
  systemName: string
}

const route = useRoute()
const router = useRouter()

/** 是否为编辑模式（有 id 参数） */
const isEdit = ref(false)
const editId = ref<string>()

const submitLoading = ref(false)
const formRef = ref<FormInstance>()
const systemOptions = ref<SystemOption[]>([])

/** 表单数据 */
const form = reactive({
  systemId: null as string | null,
  apiPath: '',
  apiMethod: '',
  apiName: '',
  apiDesc: '',
  status: 1,
})

/** 表单校验规则 */
const rules: FormRules = {
  systemId: [{ required: true, message: '请选择所属系统', trigger: 'change' }],
  apiPath: [{ required: true, message: '请输入接口路径', trigger: 'blur' }],
  apiMethod: [{ required: true, message: '请选择请求方式', trigger: 'change' }],
  apiName: [{ required: true, message: '请输入接口名称', trigger: 'blur' }],
}

/** 加载系统列表 */
async function loadSystems() {
  try {
    const res = await request.post('/zgapi/v1/admin/system/page', { page: 1, pageSize: 100, status: 1 })
    systemOptions.value = res.data?.records ?? []
  } catch {
    // 错误由拦截器处理
  }
}

/** 加载已有数据（编辑模式） */
async function loadData() {
  const id = route.params.id as string
  if (!id) {
    isEdit.value = false
    // 新增模式：从 query 参数取 systemId
    const sysId = route.query.systemId as string | undefined
    if (sysId) {
      form.systemId = sysId
    }
    return
  }
  isEdit.value = true
  editId.value = id
  try {
    const res = await request.get(`/zgapi/v1/admin/system/api/${editId.value}`)
    const data = res.data
    if (data) {
      Object.assign(form, {
        systemId: data.systemId ?? null,
        apiPath: data.apiPath ?? '',
        apiMethod: data.apiMethod ?? '',
        apiName: data.apiName ?? '',
        status: data.status ?? 1,
      })
      setTimeout(() => formRef.value?.clearValidate(), 0)
    }
  } catch {
    ElMessage.error('加载接口信息失败')
    router.back()
  }
}

/** 返回上一页 */
function handleBack() {
  router.back()
}

/** 提交表单 */
async function handleSubmit() {
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid) return

  submitLoading.value = true
  try {
    if (isEdit.value) {
      await request.put(`/zgapi/v1/admin/system/api/${editId.value}`, form)
      ElMessage.success('编辑成功')
    } else {
      await request.post('/zgapi/v1/admin/system/api', form)
      ElMessage.success('新增成功')
    }
    router.back()
  } catch {
    // 错误由拦截器处理
  } finally {
    submitLoading.value = false
  }
}

onMounted(async () => {
  await loadSystems()
  await loadData()
  setTimeout(() => formRef.value?.clearValidate(), 0)
})
</script>

<style scoped>
.form-page {
  display: flex;
  flex-direction: column;
  gap: 0;
}

/* 页头分隔线 */
:deep(.el-page-header) {
  margin-bottom: 4px;
}

:deep(.el-page-header + .el-divider) {
  margin: 0 0 20px 0;
}

.form-card {
  max-width: 700px;
  margin: 0 auto;
  width: 100%;
}

/* 按钮区域 */
.form-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .form-card { max-width: 100%; }
  .form-footer { flex-direction: column; }
  .form-footer .el-button { width: 100%; }
  :deep(.el-form-item__label) { width: 70px !important; }
}
</style>
