<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="dictType">
          <el-select
            v-model="form.dictType"
            placeholder="请选择或输入"
            filterable
            allow-create
            :disabled="isEdit"
            style="width: 100%"
          >
            <el-option
              v-for="t in dictTypeList"
              :key="t.dictType"
              :label="t.dictType"
              :value="t.dictType"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="dictLabel">
          <el-input v-model="form.dictLabel" placeholder="请输入标签" />
        </el-form-item>
        <el-form-item label="值" prop="dictValue">
          <el-input v-model="form.dictValue" placeholder="请输入值" />
        </el-form-item>

        <!-- 其他信息 -->
        <el-divider content-position="left">
          <span class="form-section-title">其他信息</span>
        </el-divider>

        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" :max="9999" />
        </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 DictTypeItem {
  dictType: string
}

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

const isEdit = ref(false)
const editId = ref<string>()
const submitLoading = ref(false)
const formRef = ref<FormInstance>()

/** 字典类型列表 */
const dictTypeList = ref<DictTypeItem[]>([])

/** 表单数据 */
const form = reactive({
  dictType: '',
  dictLabel: '',
  dictValue: '',
  sortOrder: 0,
  status: 1,
})

/** 校验规则 */
const rules: FormRules = {
  dictType: [{ required: true, message: '请选择或输入字典类型', trigger: 'blur' }],
  dictLabel: [{ required: true, message: '请输入标签', trigger: 'blur' }],
  dictValue: [{ required: true, message: '请输入值', trigger: 'blur' }],
  sortOrder: [{ required: true, message: '请输入排序', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
}

/** 加载字典类型列表 */
async function fetchDictTypeList() {
  try {
    const res = await request.get('/zgapi/v1/admin/dict/type/list')
    dictTypeList.value = res.data ?? []
  } catch {
    dictTypeList.value = []
  }
}

/** 加载已有数据 */
async function loadData() {
  const id = route.params.id as string
  if (!id) {
    isEdit.value = false
    // 新增模式，可从 query 预填字典类型
    const queryDictType = route.query.dictType
    if (queryDictType) {
      form.dictType = String(queryDictType)
    }
    return
  }
  isEdit.value = true
  editId.value = id
  try {
    const res = await request.get(`/zgapi/v1/admin/dict/${editId.value}`)
    const data = res.data
    if (data) {
      Object.assign(form, {
        dictType: data.dictType ?? '',
        dictLabel: data.dictLabel ?? '',
        dictValue: data.dictValue ?? '',
        sortOrder: data.sortOrder ?? 0,
        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/dict/${editId.value}`, form)
      ElMessage.success('编辑成功')
    } else {
      await request.post('/zgapi/v1/admin/dict', form)
      ElMessage.success('新增成功')
    }
    router.back()
  } catch {
    // 错误由拦截器处理
  } finally {
    submitLoading.value = false
  }
}

onMounted(async () => {
  await fetchDictTypeList()
  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>
