<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="player_id">
        <el-select
          v-model="formData.player_id"
          placeholder="请选择玩家（显示用户名）"
          clearable
          filterable
          style="width: 100%"
          :disabled="dialogType === 'edit'"
        >
          <el-option
            v-for="item in playerOptions"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="彩金池配置" prop="lottery_config_id">
        <el-select
          v-model="formData.lottery_config_id"
          placeholder="请选择彩金池配置"
          clearable
          filterable
          style="width: 100%"
          :disabled="dialogType === 'edit'"
        >
          <el-option
            v-for="item in lotteryConfigOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="抽奖类型" prop="lottery_type">
        <el-select
          v-model="formData.lottery_type"
          placeholder="请选择"
          clearable
          style="width: 100%"
          :disabled="dialogType === 'edit'"
        >
          <el-option label="付费" :value="0" />
          <el-option label="赠送" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="中奖" prop="is_win">
        <el-select
          v-model="formData.is_win"
          placeholder="请选择"
          clearable
          style="width: 100%"
          :disabled="dialogType === 'edit'"
        >
          <el-option label="无" :value="0" />
          <el-option label="中奖" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="赢取平台币" prop="win_coin">
        <el-input-number
          v-model="formData.win_coin"
          placeholder="请输入赢取平台币"
          :precision="2"
          style="width: 100%"
          :disabled="dialogType === 'edit'"
        />
      </el-form-item>
      <el-form-item label="奖励配置" prop="reward_config_id">
        <el-select
          v-model="formData.reward_config_id"
          placeholder="请选择奖励配置（显示前端文本）"
          clearable
          filterable
          style="width: 100%"
          :disabled="dialogType === 'edit'"
        >
          <el-option
            v-for="item in rewardConfigOptions"
            :key="item.id"
            :label="
              item.ui_text
                ? `${item.ui_text}${item.tier ? ' (' + item.tier + ')' : ''}`
                : String(item.id)
            "
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">{{ dialogType === 'edit' ? '关闭' : '取消' }}</el-button>
      <el-button v-if="dialogType === 'add'" type="primary" @click="handleSubmit">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import api from '../../../api/play_record/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>({
    player_id: [{ required: true, message: '请选择玩家', trigger: 'change' }],
    lottery_config_id: [{ required: true, message: '请选择彩金池配置', trigger: 'change' }],
    lottery_type: [{ required: true, message: '请选择抽奖类型', trigger: 'change' }],
    is_win: [{ required: true, message: '请选择中奖', trigger: 'change' }],
    win_coin: [{ required: true, message: '赢取平台币必填', trigger: 'blur' }],
    reward_config_id: [{ required: true, message: '请选择奖励配置', trigger: 'change' }]
  })

  const playerOptions = ref<Array<{ id: number; username: string }>>([])
  const lotteryConfigOptions = ref<Array<{ id: number; name: string }>>([])
  const rewardConfigOptions = ref<Array<{ id: number; ui_text: string; tier: string }>>([])

  const initialFormData = {
    id: null as number | null,
    player_id: null as number | null,
    lottery_config_id: null as number | null,
    lottery_type: null as number | null,
    is_win: null as number | null,
    win_coin: null as number | null,
    reward_config_id: null as number | null
  }

  const formData = reactive({ ...initialFormData })

  watch(
    () => props.modelValue,
    async (open) => {
      if (open) {
        initPage()
        try {
          const [players, lotteryConfigs, rewardConfigs] = await Promise.all([
            api.getPlayerOptions(),
            api.getLotteryConfigOptions(),
            api.getRewardConfigOptions()
          ])
          playerOptions.value = Array.isArray(players) ? players : ((players as any)?.data ?? [])
          lotteryConfigOptions.value = Array.isArray(lotteryConfigs)
            ? lotteryConfigs
            : ((lotteryConfigs as any)?.data ?? [])
          rewardConfigOptions.value = Array.isArray(rewardConfigs)
            ? rewardConfigs
            : ((rewardConfigs as any)?.data ?? [])
        } catch {
          playerOptions.value = []
          lotteryConfigOptions.value = []
          rewardConfigOptions.value = []
        }
      }
    }
  )

  const initPage = async () => {
    Object.assign(formData, { ...initialFormData })
    if (props.data) {
      await nextTick()
      initForm()
    }
  }

  const initForm = () => {
    if (!props.data) return
    const keys = [
      'id',
      'player_id',
      'lottery_config_id',
      'lottery_type',
      'is_win',
      'win_coin',
      'reward_config_id'
    ]
    keys.forEach((key) => {
      const val = props.data![key]
      if (val != null && val !== undefined) {
        ;(formData as Record<string, unknown>)[key] = val
      }
    })
  }

  const handleClose = () => {
    visible.value = false
    formRef.value?.resetFields()
  }

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