<template>
  <div class="dictionary-form">
    <h2 class="page-title">{{ isEdit ? '编辑字典' : '创建字典' }}</h2>
    
    <el-card>
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="formRef"
        label-width="120px"
        style="max-width: 600px"
      >
        <el-form-item label="字典类型" prop="dictType">
          <el-input 
            v-model="form.dictType" 
            :disabled="isEdit"
            placeholder="请输入字典类型，如：city, constellation, mbti" 
          />
        </el-form-item>
        
        <el-form-item label="字典编码" prop="dictCode">
          <el-input 
            v-model="form.dictCode" 
            :disabled="isEdit"
            placeholder="请输入字典编码" 
          />
        </el-form-item>
        
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="form.dictName" placeholder="请输入字典名称" />
        </el-form-item>
        
        <el-form-item label="字典值" prop="dictValue">
          <el-input v-model="form.dictValue" placeholder="请输入字典值" />
        </el-form-item>
        
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number 
            v-model="form.sortOrder" 
            :min="0" 
            :max="9999"
            placeholder="请输入排序值"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="备注" prop="remarks">
          <el-input 
            v-model="form.remarks" 
            type="textarea"
            :rows="4"
            placeholder="请输入备注信息"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">提交</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { getDictionaryById, createDictionary, updateDictionary } from '@/api/dictionary'
import type { DictionaryCreateRequest, DictionaryUpdateRequest } from '@/types/dictionary'

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

const formRef = ref()
const submitting = ref(false)

/**
 * 创建/编辑表单默认值
 */
const DEFAULT_FORM: DictionaryCreateRequest = {
  dictType: '',
  dictCode: '',
  dictName: '',
  dictValue: '',
  sortOrder: 0,
  status: 1,
  remarks: ''
}

/**
 * 字典表单数据
 * - 创建模式：DictionaryCreateRequest
 * - 编辑模式：DictionaryUpdateRequest（后端会要求 id）
 */
const form = reactive<DictionaryCreateRequest | DictionaryUpdateRequest>({ ...DEFAULT_FORM })

const rules = {
  dictType: [
    { required: true, message: '请输入字典类型', trigger: 'blur' },
    { min: 1, max: 50, message: '字典类型长度在1-50个字符之间', trigger: 'blur' }
  ],
  dictCode: [
    { required: true, message: '请输入字典编码', trigger: 'blur' },
    { min: 1, max: 50, message: '字典编码长度在1-50个字符之间', trigger: 'blur' }
  ],
  dictName: [
    { required: true, message: '请输入字典名称', trigger: 'blur' },
    { min: 1, max: 100, message: '字典名称长度在1-100个字符之间', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

const isEdit = computed(() => route.params.id !== undefined)

const fetchDetail = async () => {
  if (isEdit.value) {
    try {
      const res = await getDictionaryById(route.params.id as string)
      Object.assign(form, res.data)
    } catch (error) {
      console.error('获取字典详情失败:', error)
    }
  }
}

/**
 * 重置表单（用于从编辑切换到创建时清空旧数据）
 */
const resetFormToDefault = () => {
  Object.assign(form, { ...DEFAULT_FORM })
  formRef.value?.clearValidate?.()
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return
  
  submitting.value = true
  try {
    if (isEdit.value) {
      // 编辑模式
      await updateDictionary(form as DictionaryUpdateRequest)
      ElMessage.success('更新成功')
    } else {
      // 创建模式
      await createDictionary(form as DictionaryCreateRequest)
      ElMessage.success('创建成功')
    }
    router.push('/dictionary/list')
  } catch (error) {
    console.error(isEdit.value ? '更新失败:' : '创建失败:', error)
  } finally {
    submitting.value = false
  }
}

const handleCancel = () => {
  router.go(-1)
}

onMounted(() => {
  if (isEdit.value) {
    fetchDetail()
  }
})

/**
 * 监听路由模式切换：
 * - edit -> create：清空表单，避免复用组件实例导致“新增页带出旧数据”
 * - create -> edit：拉取详情
 */
watch(
  () => route.params.id,
  async (id) => {
    if (id) {
      await fetchDetail()
    } else {
      resetFormToDefault()
    }
  }
)
</script>

<style scoped lang="scss">
.dictionary-form {
  .page-title {
    margin-bottom: 20px;
    font-size: 24px;
    color: var(--ls-text);
  }
  
  .el-card {
    margin-bottom: 20px;
  }
}
</style>