<template>
  <el-drawer
    v-model="visible"
    :title="$t('page.detail.title')"
    :size="drawerSize"
    direction="rtl"
    destroy-on-close
    @close="handleClose"
  >
    <template v-if="record">
      <div class="detail-section">
        <div class="section-title">{{ $t('page.detail.sectionBasic') }}</div>
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item :label="$t('page.detail.recordId')">
            {{ record.id }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('page.detail.chainModeLabel')">
            {{ formatChainModeDetail(record) }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('page.detail.paidPlannedSpins')">
            {{ record.paid_planned_spins ?? $t('page.detail.dash') }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('page.detail.testSafetyLine')">
            {{ formatTestSafetyLineDetail(record) }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('page.table.ante')">
            {{ formatAnteDetail(record) }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('page.detail.testCount')">
            {{ formatTestCountDisplay(record) }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('page.detail.createTime')">
            {{ record.create_time || $t('page.detail.dash') }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('page.detail.admin')">
            {{ record.admin_name ?? record.admin_id ?? $t('page.detail.dash') }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('page.detail.paidPoolId')">
            {{ formatRecordPaidPoolName(record) }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('page.detail.freePoolId')">
            {{ formatRecordFreePoolName(record) }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('page.detail.bigwinSnapshot')">
            <template v-if="bigwinWeightDisplay.length">
              <span v-for="item in bigwinWeightDisplay" :key="item.grid" class="mr-2">
                {{ item.grid }}:{{ item.weight }}
              </span>
            </template>
            <template v-else>{{ $t('page.detail.dash') }}</template>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="detail-section">
        <div class="section-title">{{ $t('page.detail.sectionPaidTier') }}</div>
        <el-table
          v-if="paidTierTableData.length"
          :data="paidTierTableData"
          border
          size="small"
          class="tier-weights-table"
          max-height="160"
        >
          <el-table-column prop="tier" :label="$t('page.detail.colTier')" width="80" align="center" />
          <el-table-column prop="weight" :label="$t('page.detail.colWeight')" width="100" align="center" />
          <el-table-column prop="percent" :label="$t('page.detail.colPercent')" width="100" align="center" />
        </el-table>
        <div v-else class="empty-tip">
          {{ $t('page.detail.emptyPaidTier') }}
        </div>
      </div>

      <div class="detail-section">
        <div class="section-title">{{ $t('page.detail.sectionFreeTier') }}</div>
        <el-table
          v-if="freeTierTableData.length"
          :data="freeTierTableData"
          border
          size="small"
          class="tier-weights-table"
          max-height="160"
        >
          <el-table-column prop="tier" :label="$t('page.detail.colTier')" width="80" align="center" />
          <el-table-column prop="weight" :label="$t('page.detail.colWeight')" width="100" align="center" />
          <el-table-column prop="percent" :label="$t('page.detail.colPercent')" width="100" align="center" />
        </el-table>
        <div v-else class="empty-tip">{{ $t('page.detail.emptyFreeTier') }}</div>
      </div>

      <div class="detail-section">
        <div class="section-title">{{ $t('page.detail.sectionSnapshot') }}</div>

        <div class="snapshot-group">
          <div class="snapshot-subtitle">{{ $t('page.detail.subCw') }}</div>
          <el-table
            :data="snapshotClockwise"
            border
            size="small"
            max-height="180"
            class="snapshot-table"
          >
            <el-table-column prop="tier" :label="$t('page.detail.colTier')" width="80" align="center" />
            <el-table-column prop="grid_number" :label="$t('page.detail.colGridNumber')" width="100" align="center" />
            <el-table-column prop="weight" :label="$t('page.detail.colWeight')" width="90" align="center" />
          </el-table>
          <div v-if="!snapshotClockwise.length" class="empty-tip">{{ $t('page.detail.emptyCw') }}</div>
        </div>

        <div class="snapshot-group">
          <div class="snapshot-subtitle">{{ $t('page.detail.subCcw') }}</div>
          <el-table
            :data="snapshotCounterclockwise"
            border
            size="small"
            max-height="180"
            class="snapshot-table"
          >
            <el-table-column prop="tier" :label="$t('page.detail.colTier')" width="80" align="center" />
            <el-table-column prop="grid_number" :label="$t('page.detail.colGridNumber')" width="100" align="center" />
            <el-table-column prop="weight" :label="$t('page.detail.colWeight')" width="90" align="center" />
          </el-table>
          <div v-if="!snapshotCounterclockwise.length" class="empty-tip">{{ $t('page.detail.emptyCcw') }}</div>
        </div>

        <div class="snapshot-group">
          <div class="snapshot-subtitle">{{ $t('page.detail.subBigwin') }}</div>
          <el-table
            :data="bigwinTableData"
            border
            size="small"
            max-height="180"
            class="snapshot-table"
          >
            <el-table-column prop="grid_number" :label="$t('page.detail.colGridNumber')" width="100" align="center" />
            <el-table-column prop="weight" :label="$t('page.detail.colWeight')" width="90" align="center" />
          </el-table>
          <div v-if="!bigwinTableData.length" class="empty-tip">{{ $t('page.detail.emptyBigwinTable') }}</div>
        </div>
      </div>

      <div class="detail-section">
        <div class="section-title">{{ $t('page.detail.sectionResult') }}</div>
        <div class="chart-wrap">
          <ArtBarChart
            :x-axis-name="$t('page.detail.chartXAxis')"
            :x-axis-data="chartLabels"
            :data="chartData"
            height="280px"
          />
        </div>
        <div v-if="resultTotal === 0" class="empty-tip">{{ $t('page.detail.emptyResult') }}</div>
        <div v-else class="result-summary">{{ $t('page.detail.resultTotal', { n: resultTotal }) }}</div>
      </div>

      <div class="detail-section footer-actions">
        <el-button
          v-permission="'dice:reward_config_record:index:importFromRecord'"
          type="primary"
          :loading="importing"
          @click="openImport"
        >
          {{ $t('page.detail.btnImport') }}
        </el-button>
      </div>
    </template>

    <!-- 导入弹窗 -->
    <el-dialog
      v-model="importVisible"
      :title="$t('page.detail.importTitle')"
      width="520px"
      align-center
      :close-on-click-modal="false"
    >
      <p class="import-desc">
        {{ $t('page.detail.importDesc') }}
      </p>
      <el-form label-width="160px">
        <el-form-item :label="$t('page.detail.importPaidLabel')">
          <el-select
            v-model="importPaidLotteryConfigId"
            :placeholder="$t('page.detail.importPaidPlaceholder')"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="opt in paidLotteryOptions"
              :key="opt.id"
              :label="lotteryPoolOptionLabel(opt)"
              :value="opt.id"
            />
          </el-select>
          <div class="form-tip">{{ $t('page.detail.importPaidTip') }}</div>
        </el-form-item>
        <el-form-item :label="$t('page.detail.importFreeLabel')">
          <el-select
            v-model="importFreeLotteryConfigId"
            :placeholder="$t('page.detail.importFreePlaceholder')"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="opt in freeLotteryOptions"
              :key="opt.id"
              :label="lotteryPoolOptionLabel(opt)"
              :value="opt.id"
            />
          </el-select>
          <div class="form-tip">{{ $t('page.detail.importFreeTip') }}</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="importVisible = false">{{ $t('common.cancel') }}</el-button>
        <el-button
          v-permission="'dice:reward_config_record:index:importFromRecord'"
          type="primary"
          :loading="importing"
          @click="confirmImport"
          >{{ $t('page.detail.btnConfirmImport') }}</el-button
        >
      </template>
    </el-dialog>
  </el-drawer>
</template>

<script setup lang="ts">
  import ArtBarChart from '@/components/core/charts/art-bar-chart/index.vue'
  import recordApi from '../../../api/reward_config_record/index'
  import lotteryConfigApi from '../../../api/lottery_pool_config/index'
  import {
    lotteryPoolLabelById,
    lotteryPoolOptionLabel,
    type LotteryPoolOption
  } from '@/views/plugin/dice/utils/lotteryPoolDisplay'
  import { ElMessage } from 'element-plus'
  import { useI18n } from 'vue-i18n'

  const { t, locale } = useI18n()

  const GRID_NUMBERS = [
    5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
    30
  ]

  interface RecordRow {
    id?: number
    test_count?: number
    total_play_count?: number
    status?: number
    over_play_count?: number
    chain_free_mode?: number | boolean | string
    paid_planned_spins?: number
    ante?: number
    kill_mode_enabled?: number
    test_safety_line?: number
    create_time?: string
    admin_id?: number | null
    admin_name?: string
    lottery_config_id?: number | null
    paid_lottery_config_id?: number | null
    free_lottery_config_id?: number | null
    bigwin_weight?: Record<string, number> | Array<[number, number]> | null
    tier_weights_snapshot?:
      | {
          paid?: Record<string, number>
          free?: Record<string, number>
          [key: string]: any
        }
      | Record<string, number>
    paid_tier_weights?: Record<string, number>
    free_tier_weights?: Record<string, number>
    weight_config_snapshot?: Array<{
      id?: number
      grid_number?: number
      tier?: string
      weight?: number
    }>
    result_counts?: Record<string, number>
  }

  function formatChainModeDetail(record: RecordRow | null): string {
    if (!record) return t('page.detail.dash')
    const v = record.chain_free_mode
    if (v === 1 || v === '1' || v === true) return t('page.table.chainModeYes')
    const snap = record.tier_weights_snapshot
    if (snap && typeof snap === 'object' && (snap as { chain_free_mode?: boolean }).chain_free_mode) {
      return t('page.table.chainModeYes')
    }
    return t('page.table.chainModeNo')
  }

  function formatTestSafetyLineDetail(record: RecordRow | null): string {
    if (!record) return t('page.detail.dash')
    if (Number(record.kill_mode_enabled ?? 0) !== 1) {
      return t('page.detail.killModeOff')
    }
    const line = record.test_safety_line
    if (line === null || line === undefined) {
      return t('page.detail.dash')
    }
    return String(line)
  }

  function formatAnteDetail(record: RecordRow | null): string {
    if (!record) return t('page.detail.dash')
    const ante = record.ante
    if (ante === null || ante === undefined) {
      return t('page.detail.dash')
    }
    const snap = record.tier_weights_snapshot
    const isRandom =
      snap &&
      typeof snap === 'object' &&
      (snap as { ante_random?: boolean }).ante_random === true
    const base = String(ante)
    return isRandom ? `${base} (${t('page.table.anteRandom')})` : base
  }

  function formatTestCountDisplay(record: RecordRow | null): string {
    if (!record) return t('page.detail.dash')
    const status = Number(record.status)
    if (status === 1) {
      const n = record.test_count ?? record.total_play_count
      return `${n ?? 0}${t('page.detail.testCountSuffix')}`
    }
    if (status === -1) {
      const over = Number(record.over_play_count ?? 0)
      return over > 0 ? t('page.detail.testCountFailed', { over }) : t('page.detail.dash')
    }
    const over = Number(record.over_play_count ?? 0)
    return t('page.detail.testCountProgress', { over })
  }

  interface Props {
    modelValue: boolean
    record: RecordRow | null
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'import-done'): void
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    record: null
  })

  const emit = defineEmits<Emits>()

  const drawerSize = ref('720px')

  const importVisible = ref(false)
  const importing = ref(false)
  const importPaidLotteryConfigId = ref<number | null>(null)
  const importFreeLotteryConfigId = ref<number | null>(null)
  const lotteryConfigOptions = ref<LotteryPoolOption[]>([])

  function formatRecordPaidPoolName(record: RecordRow | null): string {
    if (!record) return t('page.detail.dash')
    const id = record.paid_lottery_config_id ?? record.lottery_config_id ?? null
    return lotteryPoolLabelById(id, lotteryConfigOptions.value)
  }

  function formatRecordFreePoolName(record: RecordRow | null): string {
    if (!record) return t('page.detail.dash')
    return lotteryPoolLabelById(record.free_lottery_config_id ?? null, lotteryConfigOptions.value)
  }

  function tierWeightsToTableData(weightsMap: Record<string, number> | null | undefined) {
    const dash = t('page.detail.dash')
    if (!weightsMap || typeof weightsMap !== 'object') return []
    const tiers = ['T1', 'T2', 'T3', 'T4', 'T5']
    const rows = tiers.map((tier) => {
      const w = weightsMap[tier] ?? weightsMap[tier.toLowerCase()] ?? 0
      return { tier, weight: w }
    })
    const total = rows.reduce((sum, r) => sum + r.weight, 0)
    return rows.map((r) => ({
      tier: r.tier,
      weight: r.weight,
      percent: total > 0 ? `${((r.weight / total) * 100).toFixed(1)}%` : dash
    }))
  }

  const paidTierTableData = computed(() => {
    locale.value
    const r = props.record
    const paidFromRecord = r?.paid_tier_weights
    const snapshot = r?.tier_weights_snapshot
    let snapshotPaid: Record<string, number> | null = null
    if (snapshot && typeof snapshot === 'object') {
      if ('paid' in snapshot || 'free' in snapshot) {
        const s: any = snapshot
        if (s.paid && typeof s.paid === 'object') {
          snapshotPaid = s.paid
        }
      } else {
        // 兼容旧结构：直接是 T1-T5
        snapshotPaid = snapshot as Record<string, number>
      }
    }
    const source =
      paidFromRecord && Object.keys(paidFromRecord).length ? paidFromRecord : snapshotPaid
    return tierWeightsToTableData(source || undefined)
  })

  const freeTierTableData = computed(() => {
    locale.value
    const r = props.record
    const freeFromRecord = r?.free_tier_weights
    const snapshot = r?.tier_weights_snapshot
    let snapshotFree: Record<string, number> | null = null
    if (snapshot && typeof snapshot === 'object') {
      if ('paid' in snapshot || 'free' in snapshot) {
        const s: any = snapshot
        if (s.free && typeof s.free === 'object') {
          snapshotFree = s.free
        }
      }
    }
    const source =
      freeFromRecord && Object.keys(freeFromRecord).length ? freeFromRecord : snapshotFree
    return tierWeightsToTableData(source || undefined)
  })

  const bigwinWeightDisplay = computed(() => {
    const raw = props.record?.bigwin_weight
    if (!raw) return []
    const entries: Array<{ grid: number; weight: number }> = []
    if (Array.isArray(raw)) {
      raw.forEach(([grid, weight]) => {
        entries.push({ grid: Number(grid), weight: Number(weight) })
      })
    } else if (typeof raw === 'object') {
      Object.keys(raw).forEach((k) => {
        const grid = Number(k)
        const w = Number((raw as Record<string, number>)[k])
        if (!Number.isNaN(grid) && !Number.isNaN(w)) {
          entries.push({ grid, weight: w })
        }
      })
    }
    return entries.sort((a, b) => a.grid - b.grid)
  })

  // 导入不限制奖池类型，两个下拉都可选任意 DiceLotteryPoolConfig
  const paidLotteryOptions = computed(() => lotteryConfigOptions.value)
  const freeLotteryOptions = computed(() => lotteryConfigOptions.value)

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

  const snapshotTableData = computed(() => {
    locale.value
    const dash = t('page.detail.dash')
    const snapshot = props.record?.weight_config_snapshot as
      | Array<{
          tier?: string
          direction?: number
          grid_number?: number
          weight?: number
        }>
      | undefined
    if (!Array.isArray(snapshot)) return []
    return snapshot.map((item) => {
      const dir = item.direction
      return {
        tier: item.tier ?? dash,
        direction: dir,
        direction_label:
          dir === 0 ? t('page.detail.dirCw') : dir === 1 ? t('page.detail.dirCcw') : dash,
        grid_number: item.grid_number ?? dash,
        weight: item.weight ?? dash
      }
    })
  })

  const snapshotClockwise = computed(() =>
    snapshotTableData.value.filter((row) => row.direction === 0 && row.tier !== 'BIGWIN')
  )
  const snapshotCounterclockwise = computed(() =>
    snapshotTableData.value.filter((row) => row.direction === 1 && row.tier !== 'BIGWIN')
  )
  const bigwinTableData = computed(() =>
    bigwinWeightDisplay.value.map((item) => ({
      grid_number: item.grid,
      weight: item.weight
    }))
  )

  const chartLabels = computed(() => GRID_NUMBERS.map((n) => String(n)))

  const chartData = computed(() => {
    const counts = props.record?.result_counts
    if (!counts) return GRID_NUMBERS.map(() => 0)

    // 兼容两种结构：对象 {5:10,...} 或数组 [10, ...]
    if (Array.isArray(counts)) {
      // 如果是数组，按顺序映射到 GRID_NUMBERS
      return GRID_NUMBERS.map((_, idx) => {
        const v = counts[idx]
        return typeof v === 'number' && !Number.isNaN(v) ? v : 0
      })
    }

    if (typeof counts === 'object') {
      return GRID_NUMBERS.map((n) => {
        const byString = (counts as Record<string, number>)[String(n)]
        const byNumber = (counts as Record<number, number>)[n]
        const v = byString ?? byNumber
        return typeof v === 'number' && !Number.isNaN(v) ? v : 0
      })
    }

    return GRID_NUMBERS.map(() => 0)
  })

  const resultTotal = computed(() => {
    const data = chartData.value
    return data.reduce((sum, n) => sum + n, 0)
  })

  function handleClose() {
    visible.value = false
    importVisible.value = false
  }

  if (typeof window !== 'undefined') {
    const updateDrawerSize = () => {
      drawerSize.value = window.innerWidth <= 768 ? '100%' : '720px'
    }
    updateDrawerSize()
    window.addEventListener('resize', updateDrawerSize)
  }

  async function loadLotteryOptions() {
    try {
      const list = await lotteryConfigApi.getOptions()
      lotteryConfigOptions.value = Array.isArray(list) ? list : []
    } catch {
      lotteryConfigOptions.value = []
    }
  }

  watch(
    () => props.modelValue,
    (open) => {
      if (open) {
        void loadLotteryOptions()
      }
    }
  )

  function openImport() {
    importPaidLotteryConfigId.value =
      props.record?.paid_lottery_config_id ?? props.record?.lottery_config_id ?? null
    importFreeLotteryConfigId.value = props.record?.free_lottery_config_id ?? null
    importVisible.value = true
    loadLotteryOptions()
  }

  async function confirmImport() {
    const id = props.record?.id
    if (!id) return
    importing.value = true
    try {
      await recordApi.importFromRecord({
        record_id: id,
        paid_lottery_config_id: importPaidLotteryConfigId.value ?? undefined,
        free_lottery_config_id: importFreeLotteryConfigId.value ?? undefined
      })
      ElMessage.success(t('page.detail.importSuccess'))
      importVisible.value = false
      emit('import-done')
    } catch (e: any) {
      ElMessage.error(e?.message ?? t('page.detail.importFail'))
    } finally {
      importing.value = false
    }
  }
</script>

<style lang="scss" scoped>
  :deep(.el-drawer__body) {
    padding: 16px;
    overflow: auto;
    max-height: calc(100vh - 60px);
  }

  .detail-section {
    margin-bottom: 24px;
  }
  .section-title {
    font-size: 14px;
    font-weight: 600;
    margin-bottom: 10px;
    color: var(--el-text-color-primary);
  }
  .snapshot-table {
    margin-bottom: 8px;
  }
  .snapshot-group {
    margin-bottom: 12px;
  }
  .snapshot-subtitle {
    font-size: 13px;
    font-weight: 500;
    margin: 4px 0;
    color: var(--el-text-color-secondary);
  }
  .chart-wrap {
    margin-bottom: 8px;
  }
  .empty-tip {
    padding: 12px;
    text-align: center;
    color: var(--el-text-color-secondary);
    font-size: 13px;
  }
  .result-summary {
    font-size: 13px;
    color: var(--el-text-color-secondary);
  }
  .tier-weights-table {
    margin-bottom: 8px;
  }
  .footer-actions {
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid var(--el-border-color-lighter);
  }
  .import-desc {
    font-size: 13px;
    color: var(--el-text-color-secondary);
    margin-bottom: 16px;
  }
  .form-tip {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    margin-top: 4px;
  }
</style>
