<template>
  <el-dialog
    v-model="visible"
    :title="dialogType === 'add' ? '新增奖励配置' : '编辑奖励配置'"
    width="600px"
    align-center
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="色子点数" prop="grid_number">
        <el-input-number v-model="formData.grid_number" placeholder="请输入色子点数" />
      </el-form-item>
      <el-form-item label="前端显示文本" prop="ui_text">
        <el-input v-model="formData.ui_text" placeholder="请输入前端显示文本" />
      </el-form-item>
      <el-form-item label="真实资金结算" prop="real_ev">
        <el-input-number v-model="formData.real_ev" placeholder="请输入真实资金结算" />
      </el-form-item>
      <el-form-item label="所属档位" prop="tier">
        <el-select
          v-model="formData.tier"
          placeholder="请选择所属档位"
          clearable
          style="width: 100%"
        >
          <el-option label="T1" value="T1" />
          <el-option label="T2" value="T2" />
          <el-option label="T3" value="T3" />
          <el-option label="T4" value="T4" />
          <el-option label="T5" value="T5" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import api from '../../../api/reward_config/index'
  import { ElMessage } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'

  interface Props {
    modelValue: boolean
    dialogType: string
    data?: Record<string, any>
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    dialogType: 'add',
    data: undefined
  })

  const emit = defineEmits<Emits>()

  const formRef = ref<FormInstance>()

  /**
   * 弹窗显示状态双向绑定
   */
  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

  /**
   * 表单验证规则
   */
  const rules = reactive<FormRules>({
    grid_number: [{ required: true, message: '色子点数必需填写', trigger: 'blur' }],
    ui_text: [{ required: true, message: '前端显示文本必需填写', trigger: 'blur' }],
    real_ev: [{ required: true, message: '真实资金结算必需填写', trigger: 'blur' }],
    tier: [{ required: true, message: '所属档位必需填写', trigger: 'blur' }]
  })

  /**
   * 初始数据
   */
  const initialFormData = {
    id: null,
    grid_number: null,
    ui_text: '',
    real_ev: '',
    tier: '',
    remark: ''
  }

  /**
   * 表单数据
   */
  const formData = reactive({ ...initialFormData })

  /**
   * 监听弹窗打开，初始化表单数据
   */
  watch(
    () => props.modelValue,
    (newVal) => {
      if (newVal) {
        initPage()
      }
    }
  )

  /**
   * 初始化页面数据
   */
  const initPage = async () => {
    // 先重置为初始值
    Object.assign(formData, initialFormData)
    // 如果有数据，则填充数据
    if (props.data) {
      await nextTick()
      initForm()
    }
  }

  /**
   * 初始化表单数据
   */
  const initForm = () => {
    if (props.data) {
      for (const key in formData) {
        if (props.data[key] != null && props.data[key] != undefined) {
          ;(formData as any)[key] = props.data[key]
        }
      }
    }
  }

  /**
   * 关闭弹窗并重置表单
   */
  const handleClose = () => {
    visible.value = false
    formRef.value?.resetFields()
  }

  /**
   * 提交表单
   */
  const handleSubmit = async () => {
    if (!formRef.value) return
    try {
      await formRef.value.validate()
      if (props.dialogType === 'add') {
        await api.save(formData)
        ElMessage.success('新增成功')
      } else {
        await api.update(formData)
        ElMessage.success('修改成功')
      }
      emit('success')
      handleClose()
    } catch (error) {
      console.log('表单验证失败:', error)
    }
  }
</script>
