<template>
  <el-dialog
    v-model="visible"
    :title="$t('page.form.dialogTitleEdit')"
    width="600px"
    align-center
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="formData" label-width="120px">
      <el-form-item :label="$t('page.form.player')" prop="player_id">
        <el-select
          v-model="formData.player_id"
          :placeholder="$t('page.form.placeholderPlayer')"
          clearable
          filterable
          style="width: 100%"
          disabled
        >
          <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="$t('page.form.lotteryPoolConfig')" prop="lottery_config_id">
        <el-select
          v-model="formData.lottery_config_id"
          :placeholder="$t('page.form.placeholderLotteryPool')"
          clearable
          filterable
          style="width: 100%"
          disabled
        >
          <el-option
            v-for="item in lotteryConfigOptions"
            :key="item.id"
            :label="lotteryPoolOptionLabel(item)"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('page.form.drawType')" prop="lottery_type">
        <el-select
          v-model="formData.lottery_type"
          :placeholder="$t('form.placeholderSelect')"
          clearable
          style="width: 100%"
          disabled
        >
          <el-option :label="$t('page.form.paid')" :value="0" />
          <el-option :label="$t('page.form.free')" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('page.form.isBigWin')" prop="is_win">
        <el-select
          v-model="formData.is_win"
          :placeholder="$t('form.placeholderSelect')"
          clearable
          style="width: 100%"
          disabled
        >
          <el-option :label="$t('page.form.noBigWin')" :value="0" />
          <el-option :label="$t('page.form.bigWin')" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('page.form.winCoin')" prop="win_coin">
        <el-input-number
          v-model="formData.win_coin"
          :placeholder="$t('page.form.placeholderWinCoin')"
          :precision="0"
          style="width: 100%"
          disabled
        />
      </el-form-item>
      <el-form-item :label="$t('page.form.superWinCoin')" prop="super_win_coin">
        <el-input-number
          v-model="formData.super_win_coin"
          :placeholder="$t('page.form.placeholderSuperWinCoin')"
          :precision="0"
          :min="0"
          style="width: 100%"
          disabled
        />
      </el-form-item>
      <el-form-item :label="$t('page.form.rewardWinCoin')" prop="reward_win_coin">
        <el-input-number
          v-model="formData.reward_win_coin"
          :placeholder="$t('page.form.placeholderRewardWinCoin')"
          :precision="0"
          :min="0"
          style="width: 100%"
          disabled
        />
      </el-form-item>
      <el-form-item :label="$t('page.form.direction')" prop="direction">
        <el-select
          v-model="formData.direction"
          :placeholder="$t('page.form.placeholderDirection')"
          clearable
          style="width: 100%"
          disabled
        >
          <el-option :label="$t('page.form.clockwise')" :value="0" />
          <el-option :label="$t('page.form.anticlockwise')" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('page.form.startIndex')" prop="start_index">
        <el-input-number
          v-model="formData.start_index"
          :placeholder="$t('page.form.placeholderStartIndex')"
          :min="0"
          style="width: 100%"
          disabled
        />
      </el-form-item>
      <el-form-item :label="$t('page.form.targetIndex')" prop="target_index">
        <el-input-number
          v-model="formData.target_index"
          :placeholder="$t('page.form.placeholderTargetIndex')"
          :min="0"
          style="width: 100%"
          disabled
        />
      </el-form-item>
      <el-form-item :label="$t('page.form.rollArray')" prop="rollArrayItems">
        <div class="roll-array-wrap">
          <el-input-number
            v-for="(_, i) in 5"
            :key="i"
            v-model="formData.rollArrayItems[i]"
            :min="1"
            :max="6"
            :precision="0"
            controls-position="right"
            placeholder=""
            class="roll-array-input"
            disabled
          />
        </div>
        <div class="roll-array-hint">{{ $t('page.form.rollArrayHint') }}</div>
      </el-form-item>
      <el-form-item :label="$t('page.form.rollNumber')" prop="roll_number">
        <el-input-number
          v-model="formData.roll_number"
          :placeholder="$t('page.form.placeholderRollNumber')"
          :min="5"
          :max="30"
          :precision="0"
          style="width: 100%"
          disabled
        />
      </el-form-item>
      <el-form-item :label="$t('page.form.rewardTier')" prop="reward_tier">
        <el-select
          v-model="formData.reward_tier"
          :placeholder="$t('page.form.placeholderRewardTier')"
          clearable
          filterable
          style="width: 100%"
          disabled
        >
          <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="BIGWIN" value="BIGWIN" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">{{ $t('form.close') }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import api from '../../../api/play_record/index'
  import { getChannelDeptRequestParams } from '@/composables/useChannelDeptScope'
  import {
    lotteryPoolOptionLabel,
    type LotteryPoolOption
  } from '@/views/plugin/dice/utils/lotteryPoolDisplay'
  import type { FormInstance } 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: 'edit',
    data: undefined
  })

  const emit = defineEmits<Emits>()

  const formRef = ref<FormInstance>()

  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

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

  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,
    super_win_coin: null as number | null,
    reward_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,
    roll_number: null as number | null,
    reward_tier: '' as string
  }

  /** 摇取点数固定 5 位 [n0..n4]，每项 1～6 */
  const rollArrayItemsDefault = (): (number | 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 deptParams = getChannelDeptRequestParams()
          const [players, lotteryConfigs] = await Promise.all([
            api.getPlayerOptions(deptParams),
            api.getLotteryConfigOptions(deptParams)
          ])
          playerOptions.value = Array.isArray(players) ? players : ((players as any)?.data ?? [])
          lotteryConfigOptions.value = Array.isArray(lotteryConfigs)
            ? lotteryConfigs
            : ((lotteryConfigs as any)?.data ?? [])
        } catch {
          playerOptions.value = []
          lotteryConfigOptions.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',
      'super_win_coin',
      'reward_win_coin',
      'direction',
      'start_index',
      'target_index',
      'roll_array',
      'roll_number',
      'reward_tier'
    ]
    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_number，根据摇取点数计算
    if (formData.roll_number == null && formData.rollArrayItems.length === 5) {
      formData.roll_number = formData.rollArrayItems.reduce((s, n) => (s ?? 0) + (n ?? 0), 0) || null
    }
    // 点数和有值但五个点数为空或无效时，根据 roll_number 补全显示（兼容历史错误数据）
    const sum = formData.roll_number != null ? Number(formData.roll_number) : 0
    const hasNull = formData.rollArrayItems.some((n) => n == null)
    const itemsSum = formData.rollArrayItems.reduce((s, n) => (s ?? 0) + (n ?? 0), 0) ?? 0
    if (sum >= 5 && sum <= 30 && (hasNull || itemsSum !== sum)) {
      formData.rollArrayItems = defaultRollArrayItems(sum)
    }
  }

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

  /** 点数和有值但五个点数缺失时，根据点数和生成默认 5 个数（与后端 defaultRollArrayForSum 一致） */
  function defaultRollArrayItems(sum: number): (number | null)[] {
    const s = Math.max(5, Math.min(30, Math.floor(Number(sum))))
    const base = Math.floor(s / 5)
    const rem = s - 5 * base
    const arr: number[] = Array(5).fill(base)
    for (let i = 0; i < rem; i++) arr[i]++
    return arr.map((v) => Math.max(1, Math.min(6, v)))
  }

  const handleClose = () => {
    visible.value = false
    formRef.value?.resetFields()
  }
</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>
