<template>
  <el-dialog
    v-model="visible"
    :title="dialogType === 'add' ? $t('page.form.titleAdd') : $t('page.form.titleEdit')"
    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="$t('page.form.labelDicePoints')" prop="grid_number">
        <el-input-number
          v-model="formData.grid_number"
          :placeholder="$t('page.form.placeholderDicePoints')"
          :disabled="dialogType === 'edit'"
        />
      </el-form-item>
      <el-form-item :label="$t('page.form.labelUiText')" prop="ui_text">
        <el-input v-model="formData.ui_text" :placeholder="$t('page.form.placeholderUiText')"/>
      </el-form-item>
      <el-form-item :label="$t('page.form.labelUiTextEn')" prop="ui_text_en">
        <el-input v-model="formData.ui_text_en" :placeholder="$t('page.form.placeholderUiTextEn')" />
      </el-form-item>
      <el-form-item :label="$t('page.form.labelRealEv')" prop="real_ev">
        <el-input-number
          v-model="formData.real_ev"
          :placeholder="$t('page.form.placeholderRealEv')"
          @change="handleRealEvChange"
        />
      </el-form-item>
      <el-form-item :label="$t('page.form.labelTier')" prop="tier">
        <el-select
          v-model="formData.tier"
          :placeholder="$t('page.form.placeholderTier')"
          clearable
          style="width: 100%"
          :disabled="dialogType === 'edit'"
        >
          <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-option :label="$t('page.form.tierBigWin')" value="BIGWIN" />
        </el-select>
      </el-form-item>
      <!-- BIGWIN 时可编辑权重：10000=100% 中奖，0=0% 中奖；点数 5、30 固定 100% 不可改 -->
      <el-form-item v-if="formData.tier === 'BIGWIN'" :label="$t('page.form.labelBigWinWeight')" prop="weight">
        <el-input-number
          v-model="formData.weight"
          :min="0"
          :max="10000"
          :step="100"
          :placeholder="$t('page.form.placeholderBigWinWeight')"
          :disabled="isBigwinWeightDisabled"
        />
        <div v-if="isBigwinWeightDisabled" class="form-tip">
          {{ $t('page.form.bigWinWeightDisabledTip') }}
        </div>
        <div v-else class="form-tip">{{ $t('page.form.bigWinWeightTip') }}</div>
      </el-form-item>
      <!-- 权重已迁移至「T1-T5 与 BIGWIN 权重配比」弹窗（dice_reward 表）；BIGWIN 时本弹窗可编辑 weight；起始索引已迁移至 dice_reward.start_index -->
      <el-form-item :label="$t('page.form.labelRemark')" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          :placeholder="$t('page.form.placeholderRemark')"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" @click="handleSubmit">{{ $t('table.form.submit') }}</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'
  import { useI18n } from 'vue-i18n'
  import { withChannelDeptParams } from '@/composables/useChannelDeptScope'

  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 { t } = useI18n()

  const formRef = ref<FormInstance>()

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

  /**
   * 表单验证规则（权重已迁移至权重配比弹窗）
   */
  const rules = computed<FormRules>(() => ({
    grid_number: [{ required: true, message: t('page.form.ruleDicePointsRequired'), trigger: 'blur' }],
    ui_text: [{ required: true, message: t('page.form.ruleUiTextRequired'), trigger: 'blur' }],
    ui_text_en: [{ max: 255, message: t('page.form.ruleUiTextEnMax'), trigger: 'blur' }],
    real_ev: [{ required: true, message: t('page.form.ruleRealEvRequired'), trigger: 'blur' }],
    tier: [{ required: true, message: t('page.form.ruleTierRequired'), trigger: 'blur' }],
    weight: [
      { type: 'number', min: 0, max: 10000, message: t('page.form.ruleBigWinWeightRange'), trigger: 'blur' }
    ]
  }))

  /** 点数 5、30 固定 100% 中大奖，权重不可改 */
  const isBigwinWeightDisabled = computed(
    () => formData.tier === 'BIGWIN' && [5, 30].includes(Number(formData.grid_number))
  )

  /**
   * 初始数据
   */
  const initialFormData = {
    id: null,
    grid_number: null,
    ui_text: '',
    ui_text_en: '',
    real_ev: '',
    tier: '',
    remark: '',
    weight: 10000 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', 'grid_number', 'real_ev', 'weight']
    for (const key of Object.keys(formData)) {
      if (!(key in props.data)) continue
      const val = props.data[key]
      if (val == null || val === undefined) continue
      if (numKeys.includes(key)) {
        const numVal = Number(val)
        ;(formData as Record<string, unknown>)[key] =
          key === 'id'
            ? numVal || null
            : Number.isNaN(numVal)
              ? key === 'weight'
                ? 10000
                : 0
              : numVal
      } else {
        ;(formData as Record<string, unknown>)[key] = val ?? ''
      }
    }
    if (formData.tier === 'BIGWIN' && (formData.weight === undefined || formData.weight === null)) {
      formData.weight = [5, 30].includes(Number(formData.grid_number)) ? 10000 : 0
    }
  }

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

  /**
   * 提交表单
   */
  const handleSubmit = async () => {
    if (!formRef.value) return
    try {
      await formRef.value.validate()
      const payload = { ...formData } as Record<string, unknown>
      if (formData.tier === 'BIGWIN') {
        const w = Number(formData.weight)
        payload.weight = isBigwinWeightDisabled.value ? 10000 : Number.isNaN(w) ? 10000 : w
      } else {
        delete payload.weight
      }
      if (props.dialogType === 'add') {
        await api.save(withChannelDeptParams(payload))
        ElMessage.success(t('page.form.addSuccess'))
      } else {
        await api.update(withChannelDeptParams(payload))
        ElMessage.success(t('page.form.editSuccess'))
      }
      emit('success')
      handleClose()
    } catch (error) {
      console.log('表单验证失败:', error)
    }
  }

  const handleRealEvChange = () => {
    const n =
      typeof formData.real_ev === 'number' && !Number.isNaN(formData.real_ev)
        ? formData.real_ev
        : Number(formData.real_ev)
    const text = Number.isNaN(n) ? '' : String(n)
    formData.ui_text = text
    formData.ui_text_en = text
  }
</script>

<style lang="scss" scoped>
  .form-tip {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    margin-top: 4px;
  }
</style>
