<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="彩金池配置id" prop="lottery_config_id">
        <el-input v-model="formData.lottery_config_id" placeholder="请输入彩金池配置id" />
      </el-form-item>
      <el-form-item label="抽奖类型" prop="lottery_type">
        <el-select
          v-model="formData.lottery_type"
          placeholder="请选择"
          clearable
          style="width: 100%"
        >
          <el-option label="付费" :value="0" />
          <el-option label="赠送" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="方向" prop="direction">
        <el-select v-model="formData.direction" placeholder="请选择" clearable style="width: 100%">
          <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%">
          <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"
          controls-position="right"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="中奖档位" prop="reward_tier">
        <el-select
          v-model="formData.reward_tier"
          placeholder="请选择档位(选后自动带出奖励配置ID)"
          clearable
          style="width: 100%"
          @change="onRewardTierChange"
        >
          <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="奖励配置id" prop="reward_config_id">
        <el-input
          v-model="formData.reward_config_id"
          placeholder="可选中奖档位自动带出或手动输入"
        />
      </el-form-item>
      <el-form-item label="起始索引" prop="start_index">
        <el-input v-model="formData.start_index" placeholder="请输入起始索引" />
      </el-form-item>
      <el-form-item label="结束索引" prop="target_index">
        <el-input v-model="formData.target_index" placeholder="请输入结束索引" />
      </el-form-item>
      <el-form-item label="摇取点数和" prop="roll_number">
        <el-input v-model="formData.roll_number" placeholder="请输入摇取点数和" />
      </el-form-item>
      <el-form-item label="摇取点数:[1,2,3,4,5,6]" prop="roll_array">
        <el-input v-model="formData.roll_array" placeholder="请输入摇取点数:[1,2,3,4,5,6]" />
      </el-form-item>
      <el-form-item label="状态:0=失败,1=成功" prop="status">
        <sa-radio v-model="formData.status" dict="data_status" />
      </el-form-item>
      <el-form-item label="中大奖平台币" prop="super_win_coin">
        <el-input v-model="formData.super_win_coin" placeholder="请输入中大奖平台币" />
      </el-form-item>
      <el-form-item label="摇色子中奖平台币" prop="reward_win_coin">
        <el-input v-model="formData.reward_win_coin" placeholder="请输入摇色子中奖平台币" />
      </el-form-item>
      <el-form-item label="所属管理员" prop="admin_id">
        <el-input v-model="formData.admin_id" placeholder="请输入所属管理员" />
      </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/play_record_test/index'
  import rewardConfigApi 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>({
    lottery_config_id: [{ required: true, message: '彩金池配置id必需填写', trigger: 'blur' }],
    lottery_type: [{ required: true, message: '抽奖类型:0=付费,1=赠送必需填写', trigger: 'blur' }],
    is_win: [{ required: true, message: '中大奖:0=无,1=中奖必需填写', trigger: 'blur' }],
    direction: [{ required: true, message: '方向:0=顺时针,1=逆时针必需填写', trigger: 'blur' }],
    reward_config_id: [{ required: true, message: '奖励配置id必需填写', trigger: 'blur' }],
    status: [{ required: true, message: '状态:0=失败,1=成功必需填写', trigger: 'blur' }]
  })

  /**
   * 初始数据
   */
  const initialFormData = {
    id: null,
    lottery_config_id: null,
    lottery_type: null,
    is_win: null,
    win_coin: 0,
    direction: null,
    reward_tier: undefined as string | undefined,
    reward_config_id: null,
    start_index: null,
    target_index: null,
    roll_number: null,
    roll_array: '',
    status: 1,
    super_win_coin: '0.00',
    reward_win_coin: '0.00',
    admin_id: null
  }

  /**
   * 表单数据
   */
  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 (key === 'reward_tier') continue
        if (props.data[key] != null && props.data[key] !== undefined) {
          ;(formData as Record<string, unknown>)[key] = props.data[key]
        }
      }
      if (typeof formData.win_coin === 'string') {
        formData.win_coin = parseFloat(formData.win_coin) || 0
      }
    }
  }

  /**
   * 中奖档位变更：按档位拉取奖励配置并取第一条的 id 填入 reward_config_id
   */
  async function onRewardTierChange(tier: string) {
    if (!tier) {
      formData.reward_config_id = null
      return
    }
    try {
      const res = await rewardConfigApi.list({
        saiType: 'all',
        tier: tier
      })
      const list = (res as any)?.data ?? (Array.isArray(res) ? res : [])
      const first = Array.isArray(list) ? list[0] : (list?.data?.[0] ?? list?.[0])
      if (first && first.id != null) {
        formData.reward_config_id = first.id
      } else {
        formData.reward_config_id = null
      }
    } catch {
      formData.reward_config_id = null
    }
  }

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

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