<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="direction">
        <el-select
          v-model="formData.direction"
          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="start_index">
        <el-input-number
          v-model="formData.start_index"
          placeholder="起始索引"
          :min="0"
          style="width: 100%"
          :disabled="dialogType === 'edit'"
        />
      </el-form-item>
      <el-form-item label="终点索引" prop="target_index">
        <el-input-number
          v-model="formData.target_index"
          placeholder="终点索引"
          :min="0"
          style="width: 100%"
          :disabled="dialogType === 'edit'"
        />
      </el-form-item>
      <el-form-item label="摇取点数" prop="rollArrayItems">
        <div class="roll-array-wrap">
          <el-input-number
            v-for="(_, i) in 6"
            :key="i"
            v-model="formData.rollArrayItems[i]"
            :min="1"
            :max="6"
            :precision="0"
            controls-position="right"
            placeholder=""
            class="roll-array-input"
            :disabled="dialogType === 'edit'"
          />
        </div>
        <div class="roll-array-hint">固定 6 个数，每个 1～6</div>
      </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' }],
    rollArrayItems: [
      {
        validator: (_rule: any, value: (number | null)[], callback: (e?: Error) => void) => {
          if (!value || value.length !== 6) {
            callback(new Error('摇取点数必须为 6 个数'))
            return
          }
          const ok = value.every((n) => n != null && n >= 1 && n <= 6)
          if (!ok) {
            callback(new Error('摇取点数必须填写 6 个数，每个 1～6'))
            return
          }
          callback()
        },
        trigger: 'change'
      }
    ],
    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,
    direction: null as number | null,
    start_index: null as number | null,
    target_index: null as number | null,
    roll_array: null as string | number[] | null,
    reward_config_id: null as number | null
  }

  /** 摇取点数固定 6 位 [n0..n5]，每项 1～6 */
  const rollArrayItemsDefault = (): (number | null)[] => [null, null, null, null, null, null]

  const formData = reactive({
    ...initialFormData,
    rollArrayItems: rollArrayItemsDefault() as (number | null)[]
  })

  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, rollArrayItems: rollArrayItemsDefault() })
    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',
      'direction',
      'start_index',
      'target_index',
      'roll_array',
      'reward_config_id'
    ]
    keys.forEach((key) => {
      const val = props.data![key]
      if (val != null && val !== undefined) {
        if (key === 'roll_array') {
          formData.roll_array = val
          formData.rollArrayItems = parseRollArrayToItems(val)
        } else {
          ;(formData as Record<string, unknown>)[key] = val
        }
      }
    })
  }

  /** 将接口的 roll_array 转为固定 6 项数组，不足补 null */
  function parseRollArrayToItems(val: unknown): (number | null)[] {
    let arr: number[] = []
    if (Array.isArray(val)) {
      arr = val.map((n) => (typeof n === 'number' && !Number.isNaN(n) ? n : 0)).slice(0, 6)
    } else if (typeof val === 'string') {
      try {
        const parsed = JSON.parse(val)
        arr = Array.isArray(parsed) ? parsed.slice(0, 6).map((n: any) => Number(n) || 0) : []
      } catch {
        arr = val
          .split(',')
          .map((n) => parseInt(n, 10))
          .filter((n) => !Number.isNaN(n))
          .slice(0, 6)
      }
    }
    const items: (number | null)[] = [...arr]
    while (items.length < 6) items.push(null)
    return items.slice(0, 6)
  }

  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>
      // 将 6 个输入值拼成 [1,2,3,4,5,6] 格式，确保每项为 1～6 的整数
      const items = formData.rollArrayItems
      payload.roll_array = items.map((n) => {
        const v = n != null ? Number(n) : 1
        return Math.min(6, Math.max(1, Number.isNaN(v) ? 1 : Math.floor(v)))
      })
      delete payload.rollArrayItems
      if (props.dialogType === 'add') {
        delete payload.id
        await api.save(payload)
        ElMessage.success('新增成功')
      } else {
        await api.update(payload)
        ElMessage.success('修改成功')
      }
      emit('success')
      handleClose()
    } catch (error: any) {
      let msg = '表单验证失败，请检查必填项与格式'
      if (error?.message) {
        msg = error.message
      } else if (typeof error === 'string') {
        msg = error
      } else if (error && typeof error === 'object') {
        const first = Object.values(error).find((v: any) => v?.[0]?.message)
        if (first && Array.isArray(first)) {
          msg = (first[0] as any).message || msg
        }
      }
      ElMessage.warning(msg)
    }
  }
</script>

<style lang="scss" scoped>
  .roll-array-wrap {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
  }

  .roll-array-input {
    width: 72px;
  }

  .roll-array-hint {
    margin-top: 6px;
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }
</style>
