<template>
  <div class="art-full-height">
    <!-- 搜索面板 -->
    <TableSearch v-model="searchForm" @search="handleSearch" @reset="resetSearchParams" />

    <ElCard class="art-table-card" shadow="never">
      <!-- 表格头部 -->
      <ArtTableHeader v-model:columns="columnChecks" :loading="loading" @refresh="refreshData">
        <template #left>
          <ElSpace wrap>
            <ElButton
              v-permission="'dice:reward_config_record:index:destroy'"
              :disabled="selectedRows.length === 0"
              @click="deleteSelectedRows(api.delete, refreshData)"
              v-ripple
            >
              <template #icon>
                <ArtSvgIcon icon="ri:delete-bin-5-line" />
              </template>
              {{ $t('table.actions.delete') }}
            </ElButton>
          </ElSpace>
        </template>
      </ArtTableHeader>

      <!-- 表格 -->
      <ArtTable
        ref="tableRef"
        rowKey="id"
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @sort-change="handleSortChange"
        @selection-change="handleSelectionChange"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
        <!-- 状态：-1失败 0测试中 1完成 -->
        <template #status="{ row }">
          <span>{{ formatStatus(row.status) }}</span>
        </template>
        <!-- 付费抽取：顺时针、逆时针抽取次数 -->
        <template #paid_draw="{ row }">
          <span
            >{{ $t('page.table.clockwiseAbbr') }} {{ getPaidS(row) }} /
            {{ $t('page.table.counterclockwiseAbbr') }} {{ getPaidN(row) }}</span
          >
        </template>
        <template #chain_mode="{ row }">
          <span>{{ formatChainMode(row) }}</span>
        </template>
        <template #total_draw="{ row }">
          <span>{{ formatTotalDraw(row) }}</span>
        </template>
        <!-- 平台赚取金额 -->
        <template #platform_profit="{ row }">
          <span>{{ formatPlatformProfit(row.platform_profit) }}</span>
        </template>
        <!-- 操作列 -->
        <template #operation="{ row }">
          <div class="flex gap-2">
            <SaButton
              v-permission="'dice:reward_config_record:index:read'"
              type="success"
              :toolTip="$t('page.toolbar.viewDetail')"
              @click="openDetail(row)"
            />
            <SaButton
              v-permission="'dice:reward_config_record:index:destroy'"
              type="error"
              @click="deleteRow(row, api.delete, refreshData)"
            />
          </div>
        </template>
      </ArtTable>
    </ElCard>

    <!-- 编辑弹窗 -->
    <EditDialog
      v-model="dialogVisible"
      :dialog-type="dialogType"
      :data="dialogData"
      @success="refreshData"
    />
    <!-- 详情抽屉：导入成功后刷新列表 -->
    <DetailDrawer v-model="detailVisible" :record="detailRecord" @import-done="refreshData" />
  </div>
</template>

<script setup lang="ts">
  import { useI18n } from 'vue-i18n'
  import { useTable } from '@/hooks/core/useTable'
  import { useSaiAdmin } from '@/composables/useSaiAdmin'
  import api from '../../api/reward_config_record/index'
  import TableSearch from './modules/table-search.vue'
  import EditDialog from './modules/edit-dialog.vue'
  import DetailDrawer from './modules/detail-drawer.vue'

  // 搜索表单
  const searchForm = ref({})

  // 搜索处理
  const handleSearch = (params: Record<string, any>) => {
    Object.assign(searchParams, params)
    getData()
  }

  // 详情抽屉：打开时拉取完整记录（含 paid_tier_weights、free_tier_weights 等）
  const detailVisible = ref(false)
  const detailRecord = ref<Record<string, any> | null>(null)
  async function openDetail(row: Record<string, any>) {
    const id = row?.id
    if (id == null) return
    detailRecord.value = { ...row }
    detailVisible.value = true
    try {
      const res = await api.read(id)
      const data = res?.data ?? res
      if (data && typeof data === 'object') {
        detailRecord.value = data
      }
    } catch {
      // 读取失败时保留列表行数据
    }
  }

  const { t } = useI18n()
  // 状态文案：-1失败 0测试中 1完成（2=执行中也显示测试中）
  function formatStatus(status: unknown): string {
    const s = Number(status)
    if (s === -1) return t('page.table.statusFail')
    if (s === 1) return t('page.table.statusDone')
    if (s === 0 || s === 2) return t('page.table.statusTesting')
    return t('page.detail.dash')
  }

  // 付费抽取次数
  function getPaidS(row: Record<string, any>): number {
    return Number(row.paid_s_count ?? 0)
  }
  function getPaidN(row: Record<string, any>): number {
    return Number(row.paid_n_count ?? 0)
  }

  function formatTestSafetyLine(row: Record<string, unknown>): string {
    const dash = t('page.detail.dash')
    if (Number(row.kill_mode_enabled ?? 0) !== 1) {
      return dash
    }
    const line = row.test_safety_line
    if (line === null || line === undefined || line === '') {
      return dash
    }
    const n = Number(line)
    return Number.isFinite(n) ? String(n) : dash
  }

  function formatAnteCell(row: Record<string, unknown>): string {
    const ante = row.ante
    if (ante === null || ante === undefined || ante === '') {
      return t('page.detail.dash')
    }
    const snap = row.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 formatPlatformProfit(v: unknown): string {
    const dash = t('page.detail.dash')
    if (v === null || v === undefined || v === '') return dash
    const n = Number(v)
    if (Number.isNaN(n)) return dash
    return n.toFixed(2)
  }

  /** 链式再来一次：1=是（新库字段），JSON 旧数据用 tier_weights_snapshot.chain_free_mode */
  function formatChainMode(row: Record<string, any>): string {
    const v = row.chain_free_mode
    if (v === 1 || v === '1' || v === true) return t('page.table.chainModeYes')
    const snap = row.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 formatTotalDraw(row: Record<string, any>): string {
    const status = Number(row.status)
    const done = Number(row.total_play_count ?? 0)
    const over = Number(row.over_play_count ?? 0)
    if (status === 1) {
      return String(done)
    }
    if (status === -1) {
      return over > 0 ? t('page.table.progressFailed', { over }) : t('page.detail.dash')
    }
    return t('page.table.progressDraws', { over })
  }

  // 表格配置
  const {
    columns,
    columnChecks,
    data,
    loading,
    getData,
    searchParams,
    pagination,
    resetSearchParams,
    handleSortChange,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    core: {
      apiFn: api.list,
      apiParams: { limit: 100 },
      columnsFactory: () => [
        { type: 'selection' },
        { prop: 'id', label: 'page.table.id', width: 80, align: 'center' },
        {
          prop: 'status',
          label: 'page.table.status',
          width: 90,
          align: 'center',
          useSlot: true
        },
        {
          prop: 'paid_draw',
          label: 'page.table.paidDraw',
          width: 160,
          align: 'center',
          useSlot: true
        },
        {
          prop: 'chain_mode',
          label: 'page.table.chainMode',
          width: 110,
          align: 'center',
          useSlot: true
        },
        {
          prop: 'paid_planned_spins',
          label: 'page.table.paidPlannedSpins',
          width: 120,
          align: 'center'
        },
        {
          prop: 'ante',
          label: 'page.table.ante',
          width: 100,
          align: 'center',
          formatter: (row: Record<string, unknown>) => formatAnteCell(row)
        },
        {
          prop: 'test_safety_line',
          label: 'page.table.testSafetyLine',
          width: 100,
          align: 'center',
          formatter: (row: Record<string, unknown>) => formatTestSafetyLine(row)
        },
        {
          prop: 'play_again_count',
          label: 'page.table.playAgainCount',
          width: 120,
          align: 'center'
        },
        {
          prop: 'platform_profit',
          label: 'page.table.platformProfit',
          width: 120,
          align: 'center',
          useSlot: true
        },
        {
          prop: 'total_draw',
          label: 'page.table.totalDrawCount',
          width: 140,
          align: 'center',
          useSlot: true
        },
        {
          prop: 'admin_name',
          label: 'page.table.createdBy',
          width: 120,
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'remark',
          label: 'page.table.remark',
          width: 220,
          align: 'center',
          showOverflowTooltip: true
        },
        { prop: 'create_time', label: 'page.table.createTime', width: 170, align: 'center' },
        {
          prop: 'operation',
          label: 'table.actions.operation',
          width: 100,
          align: 'center',
          fixed: 'right',
          useSlot: true
        }
      ]
    }
  })

  // 编辑配置
  const {
    dialogType,
    dialogVisible,
    dialogData,
    deleteRow,
    deleteSelectedRows,
    handleSelectionChange,
    selectedRows
  } = useSaiAdmin()
</script>
