<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>
        <!-- 付费抽取：顺时针、逆时针抽取次数（兼容旧数据用 s_count/n_count） -->
        <template #paid_draw="{ row }">
          <span>顺 {{ getPaidS(row) }} / 逆 {{ getPaidN(row) }}</span>
        </template>
        <!-- 免费抽取：顺时针、逆时针抽取次数 -->
        <template #free_draw="{ row }">
          <span>顺 {{ row.free_s_count ?? 0 }} / 逆 {{ row.free_n_count ?? 0 }}</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 '—'
  }

  // 付费抽取次数（兼容旧数据：无 paid_s_count 时用 s_count）
  function getPaidS(row: Record<string, any>): number {
    const v = row.paid_s_count
    if (v !== undefined && v !== null && (Number(v) || 0) > 0) return Number(v)
    return Number(row.s_count ?? 0)
  }
  function getPaidN(row: Record<string, any>): number {
    const v = row.paid_n_count
    if (v !== undefined && v !== null && (Number(v) || 0) > 0) return Number(v)
    return Number(row.n_count ?? 0)
  }

  // 平台赚取金额展示（未完成或空显示 —）
  function formatPlatformProfit(v: unknown): string {
    if (v === null || v === undefined || v === '') return '—'
    const n = Number(v)
    if (Number.isNaN(n)) return '—'
    return String(n)
  }

  // 表格配置
  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: 'free_draw',
          label: 'page.table.freeDraw',
          width: 160,
          align: 'center',
          useSlot: true
        },
        {
          prop: 'platform_profit',
          label: 'page.table.platformProfit',
          width: 120,
          align: 'center',
          useSlot: true
        },
        { prop: 'total_play_count', label: 'page.table.totalDrawCount', width: 110, align: 'center' },
        {
          prop: 'admin_name',
          label: 'page.table.createdBy',
          width: 120,
          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>
