<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-divider content-position="left">
          <span class="form-section-title">基本信息</span>
        </el-divider>

        <el-form-item label="系统编码" prop="systemCode">
          <el-input v-model="form.systemCode" placeholder="请输入系统编码" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="系统名称" prop="systemName">
          <el-input v-model="form.systemName" 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 content-position="left">
          <span class="form-section-title">其他信息</span>
        </el-divider>

        <el-form-item label="前端地址" prop="frontUrl">
          <el-input v-model="form.frontUrl" placeholder="请输入前端地址" />
        </el-form-item>
        <el-form-item label="后端地址">
          <el-input v-model="form.backendUrl" placeholder="请输入后端地址" />
        </el-form-item>
        <el-form-item label="图标">
          <IconPicker v-model="form.icon" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" :max="9999" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入描述" />
        </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'
import IconPicker from '@/components/IconPicker.vue'

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

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

const submitLoading = ref(false)
const formRef = ref<FormInstance>()

/** 表单数据 */
const form = reactive({
  systemCode: '',
  systemName: '',
  frontUrl: '',
  backendUrl: '',
  icon: '',
  sortOrder: 0,
  status: 1,
  description: '',
})

/** 表单校验规则 */
const rules: FormRules = {
  systemCode: [{ required: true, message: '请输入系统编码', trigger: 'blur' }],
  systemName: [{ required: true, message: '请输入系统名称', trigger: 'blur' }],
  frontUrl: [{ required: true, message: '请输入前端地址', trigger: 'blur' }],
  sortOrder: [{ required: true, message: '请输入排序', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
}

/** 加载已有数据（编辑模式） */
async function loadData() {
  const id = route.params.id as string
  if (!id) {
    isEdit.value = false
    return
  }
  isEdit.value = true
  editId.value = id
  try {
    const res = await request.get(`/zgapi/v1/admin/system/${editId.value}`)
    const data = res.data
    if (data) {
      Object.assign(form, {
        systemCode: data.systemCode ?? '',
        systemName: data.systemName ?? '',
        frontUrl: data.frontUrl ?? '',
        backendUrl: data.backendUrl ?? '',
        icon: data.icon ?? '',
        sortOrder: data.sortOrder ?? 0,
        status: data.status ?? 1,
        description: data.description ?? '',
      })
      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', { ...form, id: editId.value })
      ElMessage.success('编辑成功')
    } else {
      await request.post('/zgapi/v1/admin/system', form)
      ElMessage.success('新增成功')
    }
    router.back()
  } catch {
    // 错误由拦截器处理
  } finally {
    submitLoading.value = false
  }
}

onMounted(async () => {
  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-section-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

/* 按钮区域 */
.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>
