<template>
  <el-drawer
    v-model="visible"
    title="测试记录详情"
    :size="drawerSize"
    direction="rtl"
    destroy-on-close
    @close="handleClose"
  >
    <template v-if="record">
      <div class="detail-section">
        <div class="section-title">基本信息</div>
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="记录ID">
            {{ record.id }}
          </el-descriptions-item>
          <el-descriptions-item label="测试次数">{{ record.test_count }} 次</el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ record.create_time || '—' }}
          </el-descriptions-item>
          <el-descriptions-item label="执行管理员">
            {{ record.admin_name ?? record.admin_id ?? '—' }}
          </el-descriptions-item>
          <el-descriptions-item label="付费奖池配置ID">
            {{ record.paid_lottery_config_id ?? record.lottery_config_id ?? '—' }}
          </el-descriptions-item>
          <el-descriptions-item label="免费奖池配置ID">
            {{ record.free_lottery_config_id ?? '—' }}
          </el-descriptions-item>
          <el-descriptions-item label="BIGWIN 权重快照">
            <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>—</template>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="detail-section">
        <div class="section-title">付费抽奖档位概率（T1-T5，测试时使用）</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="档位" width="80" align="center" />
          <el-table-column prop="weight" label="权重" width="100" align="center" />
          <el-table-column prop="percent" label="占比" width="100" align="center" />
        </el-table>
        <div v-else class="empty-tip">
          暂无付费档位数据（旧记录可能仅保存 tier_weights_snapshot）
        </div>
      </div>

      <div class="detail-section">
        <div class="section-title">免费抽奖档位概率（T1-T5，测试时使用）</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="档位" width="80" align="center" />
          <el-table-column prop="weight" label="权重" width="100" align="center" />
          <el-table-column prop="percent" label="占比" width="100" align="center" />
        </el-table>
        <div v-else class="empty-tip">暂无免费档位数据</div>
      </div>

      <div class="detail-section">
        <div class="section-title">权重配比快照（测试时使用的 T1-T5/BIGWIN 配置）</div>

        <div class="snapshot-group">
          <div class="snapshot-subtitle">顺时针（非 BIGWIN）</div>
          <el-table
            :data="snapshotClockwise"
            border
            size="small"
            max-height="180"
            class="snapshot-table"
          >
            <el-table-column prop="tier" label="档位" width="80" align="center" />
            <el-table-column prop="grid_number" label="色子点数" width="100" align="center" />
            <el-table-column prop="weight" label="权重" width="90" align="center" />
          </el-table>
          <div v-if="!snapshotClockwise.length" class="empty-tip">暂无顺时针数据</div>
        </div>

        <div class="snapshot-group">
          <div class="snapshot-subtitle">逆时针（非 BIGWIN）</div>
          <el-table
            :data="snapshotCounterclockwise"
            border
            size="small"
            max-height="180"
            class="snapshot-table"
          >
            <el-table-column prop="tier" label="档位" width="80" align="center" />
            <el-table-column prop="grid_number" label="色子点数" width="100" align="center" />
            <el-table-column prop="weight" label="权重" width="90" align="center" />
          </el-table>
          <div v-if="!snapshotCounterclockwise.length" class="empty-tip">暂无逆时针数据</div>
        </div>

        <div class="snapshot-group">
          <div class="snapshot-subtitle">BIGWIN（按 DiceRewardConfig 配置快照）</div>
          <el-table
            :data="bigwinTableData"
            border
            size="small"
            max-height="180"
            class="snapshot-table"
          >
            <el-table-column prop="grid_number" label="色子点数" width="100" align="center" />
            <el-table-column prop="weight" label="权重" width="90" align="center" />
          </el-table>
          <div v-if="!bigwinTableData.length" class="empty-tip">暂无 BIGWIN 数据</div>
        </div>
      </div>

      <div class="detail-section">
        <div class="section-title">落点统计（各 grid_number 出现次数）</div>
        <div class="chart-wrap">
          <ArtBarChart
            x-axis-name="色子点数 (grid_number)"
            :x-axis-data="chartLabels"
            :data="chartData"
            height="280px"
          />
        </div>
        <div v-if="resultTotal === 0" class="empty-tip">暂无落点数据</div>
        <div v-else class="result-summary">总落点次数：{{ resultTotal }}</div>
      </div>

      <div class="detail-section footer-actions">
        <el-button type="primary" :loading="importing" @click="openImport">
          导入到当前配置
        </el-button>
      </div>
    </template>

    <!-- 导入弹窗 -->
    <el-dialog
      v-model="importVisible"
      title="导入到正式配置"
      width="520px"
      align-center
      :close-on-click-modal="false"
    >
      <p class="import-desc">
        将本测试记录导入：<strong>DiceReward</strong>（格子权重）、
        <strong>DiceRewardConfig</strong>（BIGWIN weight）、
        <strong>DiceLotteryPoolConfig</strong>（付费/免费 T1-T5 档位概率）。请选择要写入的奖池。
      </p>
      <el-form label-width="160px">
        <el-form-item label="导入付费档位概率到奖池">
          <el-select
            v-model="importPaidLotteryConfigId"
            placeholder="选择任意奖池（建议付费池）"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="opt in paidLotteryOptions"
              :key="opt.id"
              :label="opt.name"
              :value="opt.id"
            />
          </el-select>
          <div class="form-tip">不选则使用本记录保存时的付费奖池配置 ID</div>
        </el-form-item>
        <el-form-item label="导入免费档位概率到奖池">
          <el-select
            v-model="importFreeLotteryConfigId"
            placeholder="选择任意奖池（建议免费池）"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="opt in freeLotteryOptions"
              :key="opt.id"
              :label="opt.name"
              :value="opt.id"
            />
          </el-select>
          <div class="form-tip">不选则使用本记录保存时的免费奖池配置 ID</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="importVisible = false">取消</el-button>
        <el-button type="primary" :loading="importing" @click="confirmImport">确认导入</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 { ElMessage } from 'element-plus'

  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
    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
    // 新结构：{ paid: {T1..T5}, free: {T1..T5} }，兼容旧结构直接是 {T1..T5}
    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>
  }

  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<Array<{ id: number; name: string }>>([])

  function tierWeightsToTableData(t: Record<string, number> | null | undefined) {
    if (!t || typeof t !== 'object') return []
    const tiers = ['T1', 'T2', 'T3', 'T4', 'T5']
    const rows = tiers.map((tier) => {
      const w = t[tier] ?? t[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)}%` : '—'
    }))
  }

  const paidTierTableData = computed(() => {
    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(() => {
    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(() => {
    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 ?? '—',
        direction: dir,
        direction_label: dir === 0 ? '顺时针' : dir === 1 ? '逆时针' : '—',
        grid_number: item.grid_number ?? '—',
        weight: item.weight ?? '—'
      }
    })
  })

  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 = []
    }
  }

  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('导入成功，已刷新 DiceReward、DiceRewardConfig(BIGWIN)、奖池配置')
      importVisible.value = false
      emit('import-done')
    } catch (e: any) {
      ElMessage.error(e?.message ?? '导入失败')
    } 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>
