<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑权益等级' : '新增权益等级'"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="等级" prop="level">
        <el-input-number
          v-model="formData.level"
          :min="1"
          :precision="0"
          placeholder="请输入等级"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="等级名称" prop="title">
        <el-input
          v-model="formData.title"
          placeholder="请输入等级名称"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="所需欧气值" prop="requiredPoints">
        <el-input-number
          v-model="formData.requiredPoints"
          :min="0"
          :precision="0"
          placeholder="请输入所需欧气值"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import {
  createQyLevel,
  updateQyLevel,
  type QyLevelResponse,
  type QyLevelCreateRequest,
  type QyLevelUpdateRequest
} from '@/api/business/qylevel'

const props = defineProps<{
  modelValue: boolean
  level: QyLevelResponse | null
  isEdit: boolean
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

// 弹窗显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 表单引用
const formRef = ref<FormInstance>()
const submitLoading = ref(false)

// 表单数据
interface FormDataType {
  level: number
  title: string
  requiredPoints: number
}

const formData = reactive<FormDataType>({
  level: 1,
  title: '',
  requiredPoints: 0
})

// 正数验证器
const positiveNumberValidator = (_rule: any, value: any, callback: any) => {
  if (value === undefined || value === null || value === '') {
    callback(new Error('此字段为必填项'))
  } else if (typeof value !== 'number' || value <= 0) {
    callback(new Error('必须为大于0的正整数'))
  } else {
    callback()
  }
}

// 非负数验证器
const nonNegativeNumberValidator = (_rule: any, value: any, callback: any) => {
  if (value === undefined || value === null || value === '') {
    callback(new Error('此字段为必填项'))
  } else if (typeof value !== 'number' || value < 0) {
    callback(new Error('必须为非负整数'))
  } else {
    callback()
  }
}

// 表单验证规则
const formRules: FormRules = {
  level: [
    { required: true, validator: positiveNumberValidator, trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入等级名称', trigger: 'blur' },
    { min: 1, max: 50, message: '名称长度在1-50个字符之间', trigger: 'blur' }
  ],
  requiredPoints: [
    { required: true, validator: nonNegativeNumberValidator, trigger: 'blur' }
  ]
}

// 监听弹窗打开，初始化数据
watch(() => props.modelValue, (visible) => {
  if (visible) {
    if (props.isEdit && props.level) {
      // 编辑模式：回显数据
      Object.assign(formData, {
        level: props.level.level || 1,
        title: props.level.title || '',
        requiredPoints: props.level.requiredPoints || 0
      })
    } else {
      // 新增模式：重置数据
      resetForm()
    }
  }
})

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    level: 1,
    title: '',
    requiredPoints: 0
  })
  formRef.value?.resetFields()
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
  } catch {
    return
  }

  // 额外验证：等级必须大于0
  if (formData.level <= 0) {
    ElMessage.error('等级必须大于0')
    return
  }

  // 额外验证：所需欧气值必须大于等于0
  if (formData.requiredPoints < 0) {
    ElMessage.error('所需欧气值不能为负数')
    return
  }

  submitLoading.value = true
  try {
    if (props.isEdit) {
      // 编辑模式
      if (!props.level) {
        ElMessage.error('未选择要编辑的等级')
        return
      }
      const submitData: QyLevelUpdateRequest = {
        level: formData.level,
        title: formData.title,
        requiredPoints: formData.requiredPoints
      }
      await updateQyLevel(props.level.id, submitData)
      ElMessage.success('更新成功')
    } else {
      // 新增模式
      const submitData: QyLevelCreateRequest = {
        level: formData.level,
        title: formData.title,
        requiredPoints: formData.requiredPoints
      }
      await createQyLevel(submitData)
      ElMessage.success('创建成功')
    }

    emit('success')
    handleClose()
  } finally {
    submitLoading.value = false
  }
}
</script>

<style scoped>
</style>
