<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="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入名称"
          :disabled="dialogType === 'edit'"
        />
      </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-item label="奖池类型" prop="type">
        <el-select
          v-model="formData.type"
          placeholder="请选择奖池类型"
          clearable
          style="width: 100%"
          :disabled="dialogType === 'edit'"
        >
          <el-option label="正常" :value="0" />
          <el-option label="强制杀猪" :value="1" />
          <el-option label="T1高倍率" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="安全线" prop="safety_line">
        <el-input-number
          v-model="formData.safety_line"
          :min="0"
          :precision="2"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="T1池权重(%)" prop="t1_weight">
        <el-slider v-model="formData.t1_weight" :min="0" :max="100" :step="0.01" show-input />
      </el-form-item>
      <el-form-item label="T2池权重(%)" prop="t2_weight">
        <el-slider v-model="formData.t2_weight" :min="0" :max="100" :step="0.01" show-input />
      </el-form-item>
      <el-form-item label="T3池权重(%)" prop="t3_weight">
        <el-slider v-model="formData.t3_weight" :min="0" :max="100" :step="0.01" show-input />
      </el-form-item>
      <el-form-item label="T4池权重(%)" prop="t4_weight">
        <el-slider v-model="formData.t4_weight" :min="0" :max="100" :step="0.01" show-input />
      </el-form-item>
      <el-form-item label="T5池权重(%)" prop="t5_weight">
        <el-slider v-model="formData.t5_weight" :min="0" :max="100" :step="0.01" show-input />
      </el-form-item>
      <el-form-item>
        <div class="text-gray-500 text-sm">
          五个池权重总和：<span :class="Math.abs(weightsSum - 100) > 0.01 ? 'text-red-500' : ''">{{
            weightsSum
          }}</span
          >% / 100%（必须为100%）
        </div>
      </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/lottery_pool_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 WEIGHT_KEYS = ['t1_weight', 't2_weight', 't3_weight', 't4_weight', 't5_weight'] as const

  /** 五个池权重总和（用于展示与校验） */
  const weightsSum = computed(() => {
    return WEIGHT_KEYS.reduce((sum, key) => sum + Number(formData[key] ?? 0), 0)
  })

  /**
   * 表单验证规则
   */
  const rules = reactive<FormRules>({
    name: [{ required: true, message: '名称必需填写', trigger: 'blur' }],
    type: [{ required: true, message: '请选择奖池类型', trigger: 'change' }],
    t1_weight: [{ required: true, message: 'T1池权重必需填写', trigger: 'blur' }],
    t2_weight: [{ required: true, message: 'T2池权重必需填写', trigger: 'blur' }],
    t3_weight: [{ required: true, message: 'T3池权重必需填写', trigger: 'blur' }],
    t4_weight: [{ required: true, message: 'T4池权重必需填写', trigger: 'blur' }],
    t5_weight: [{ required: true, message: 'T5池权重必需填写', trigger: 'blur' }]
  })

  /**
   * 初始数据（权重为数字便于输入与校验）
   */
  const initialFormData = {
    id: null as number | null,
    name: '',
    remark: '',
    type: null as number | null,
    safety_line: 0 as number,
    t1_weight: 0 as number,
    t2_weight: 0 as number,
    t3_weight: 0 as number,
    t4_weight: 0 as number,
    t5_weight: 0 as number
  }

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

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

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

  /**
   * 初始化表单数据（数值字段转为 number 便于滑块/输入框回显与校验）
   */
  const initForm = () => {
    if (!props.data) return
    const numKeys = [
      'id',
      'type',
      'safety_line',
      't1_weight',
      't2_weight',
      't3_weight',
      't4_weight',
      't5_weight'
    ]
    for (const key of Object.keys(formData)) {
      if (!(key in props.data)) continue
      const val = props.data[key]
      if (numKeys.includes(key)) {
        ;(formData as any)[key] =
          key === 'id' ? (val != null ? Number(val) || null : null) : Number(val) || 0
      } else {
        ;(formData as any)[key] = val ?? ''
      }
    }
  }

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

  /**
   * 提交表单
   */
  const handleSubmit = async () => {
    if (!formRef.value) return
    try {
      await formRef.value.validate()
      if (Math.abs(weightsSum.value - 100) > 0.01) {
        ElMessage.warning('五个池权重总和必须为100%')
        return
      }
      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>
