<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>
          <span v-if="totalWinCoin !== null" class="table-summary-inline">
            {{ $t('page.toolbar.platformTotalProfit') }}：<strong>{{
              formatPlatformCoin(totalWinCoin)
            }}</strong>
          </span>
          <ElSpace wrap class="table-toolbar-buttons">
            <ElButton
              v-permission="'dice:play_record_test: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>
            <ElButton
              v-permission="'dice:play_record_test:index:clearAll'"
              type="danger"
              plain
              @click="handleClearAll"
              v-ripple
            >
              <template #icon>
                <ArtSvgIcon icon="ri:delete-bin-2-line" />
              </template>
              {{ $t('page.toolbar.clearAllData') }}
            </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"
      >
        <!-- 彩金池配置：显示 DiceLotteryPoolConfig.name -->
        <template #lottery_config_id="{ row }">
          <ElTag size="small">{{ lotteryConfigNameFormatter(row) }}</ElTag>
        </template>
        <!-- 抽奖类型 -->
        <template #lottery_type="{ row }">
          <ElTag size="small" :type="row.lottery_type === 0 ? 'warning' : 'success'">
            {{
              row.lottery_type === 0
                ? t('page.search.paid')
                : row.lottery_type === 1
                  ? t('page.search.free')
                  : '-'
            }}
          </ElTag>
        </template>
        <!-- 是否中大奖 -->
        <template #is_win="{ row }">
          <ElTag size="small" :type="row.is_win === 1 ? 'success' : 'info'">
            {{
              row.is_win === 0
                ? t('page.search.noBigWin')
                : row.is_win === 1
                  ? t('page.search.bigWin')
                  : '-'
            }}
          </ElTag>
        </template>
        <!-- 方向 -->
        <template #direction="{ row }">
          <ElTag size="small" :type="row.direction === 0 ? 'primary' : 'warning'">
            {{
              row.direction === 0
                ? t('page.search.clockwise')
                : row.direction === 1
                  ? t('page.search.anticlockwise')
                  : '-'
            }}
          </ElTag>
        </template>
        <!-- 摇取点数 -->
        <template #roll_array="{ row }">
          <ElTag size="small">
            {{ formatRollArray(row.roll_array) }}
          </ElTag>
        </template>
        <!-- 奖励档位：优先显示记录自带 reward_tier -->
        <template #reward_tier="{ row }">
          <ElTag size="small">{{ rewardTierFormatter(row) }}</ElTag>
        </template>
        <!-- 平台币相关：统一整数显示 -->
        <template #win_coin="{ row }">
          <span>{{ formatPlatformCoin(row?.win_coin) }}</span>
        </template>
        <template #super_win_coin="{ row }">
          <span>{{ formatPlatformCoin(row?.super_win_coin) }}</span>
        </template>
        <template #reward_win_coin="{ row }">
          <span>{{ formatPlatformCoin(row?.reward_win_coin) }}</span>
        </template>
        <!-- 状态 -->
        <template #status="{ row }">
          <ElTag size="small" :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? t('table.searchBar.success') : t('table.searchBar.failure') }}
          </ElTag>
        </template>
        <!-- 操作列 -->
        <template #operation="{ row }">
          <div class="flex gap-2">
            <SaButton
              v-permission="'dice:play_record_test:index:update'"
              type="secondary"
              @click="showDialog('edit', row)"
            />
            <SaButton
              v-permission="'dice:play_record_test: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"
    />
  </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/play_record_test/index'
  import TableSearch from './modules/table-search.vue'
  import EditDialog from './modules/edit-dialog.vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { lotteryPoolRowLabel } from '@/views/plugin/dice/utils/lotteryPoolDisplay'
  const { t } = useI18n()

  // 搜索表单（与 play_record 对齐：方向、赢取平台币范围、是否中大奖、中奖档位、点数和）
  const searchForm = ref<Record<string, unknown>>({
    lottery_config_id: undefined,
    reward_config_record_id: undefined,
    lottery_type: undefined,
    direction: undefined,
    is_win: undefined,
    paid_amount: undefined,
    ante: undefined,
    win_coin_min: undefined,
    win_coin_max: undefined,
    reward_tier: undefined,
    roll_number: undefined
  })

  // 当前筛选下平台总盈利（付费金额 paid_amount 求和 - 玩家总收益）
  const totalWinCoin = ref<number | null>(null)

  const listApi = async (params: Record<string, any>) => {
    const res = await api.list(params)
    totalWinCoin.value = res?.total_win_coin ?? null
    return res
  }

  const lotteryConfigNameFormatter = (row: Record<string, any>) => lotteryPoolRowLabel(row)
  const rewardTierFormatter = (row: Record<string, any>) => row?.reward_tier ?? '-'

  /** 摇取点数格式化为 1,3,4,5,6 */
  function formatRollArray(val: unknown): string {
    if (val == null || val === '') return '-'
    if (Array.isArray(val)) return val.join(',')
    if (typeof val === 'string') {
      try {
        const arr = JSON.parse(val)
        return Array.isArray(arr) ? arr.join(',') : val
      } catch {
        return val
      }
    }
    return String(val)
  }

  function formatPlatformCoin(val: unknown): string {
    if (val === '' || val === null || val === undefined) return '-'
    const n = typeof val === 'number' ? val : Number(val)
    if (!Number.isFinite(n)) return '-'
    return n.toFixed(2)
  }

  const handleClearAll = async () => {
    try {
      await ElMessageBox.confirm(t('page.ui.clearAllConfirm'), t('uiMsg.titlePrompt'), {
        type: 'warning'
      })
      await api.clearAll()
      ElMessage.success(t('page.ui.clearAllSuccess'))
      getData()
    } catch (e: any) {
      if (e !== 'cancel') {
        ElMessage.error(e?.message || t('page.ui.clearAllFail'))
      }
    }
  }

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

  // 表格配置
  const {
    columns,
    columnChecks,
    data,
    loading,
    getData,
    searchParams,
    pagination,
    resetSearchParams,
    handleSortChange,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    core: {
      apiFn: listApi,
      columnsFactory: () => [
        { type: 'selection' },
        { prop: 'id', label: 'page.table.id', width: 80 },
        {
          prop: 'reward_config_record_id',
          label: 'page.table.rewardConfigRecordId',
          width: 120
        },
        {
          prop: 'lottery_config_id',
          label: 'page.table.lotteryPoolConfig',
          width: 120,
          useSlot: true
        },
        { prop: 'lottery_type', label: 'page.table.drawType', width: 100, useSlot: true },
        { prop: 'direction', label: 'page.table.direction', width: 90, useSlot: true },
        { prop: 'ante', label: 'page.table.ante', width: 90 },
        { prop: 'is_win', label: 'page.table.isBigWin', width: 100, useSlot: true },
        { prop: 'paid_amount', label: 'page.table.paidAmount', width: 130 },
        { prop: 'win_coin', label: 'page.table.winCoin', width: 110, useSlot: true },
        { prop: 'super_win_coin', label: 'page.table.superWinCoin', width: 120, useSlot: true },
        { prop: 'reward_win_coin', label: 'page.table.rewardWinCoin', width: 140, useSlot: true },
        { prop: 'start_index', label: 'page.table.startIndex', width: 90 },
        { prop: 'target_index', label: 'page.table.targetIndex', width: 90 },
        { prop: 'roll_array', label: 'page.table.rollArray', width: 140, useSlot: true },
        { prop: 'roll_number', label: 'page.table.rollNumber', width: 110, sortable: true },
        { prop: 'reward_tier', label: 'page.table.rewardTier', width: 100, useSlot: true },
        { prop: 'status', label: 'page.table.status', width: 80, useSlot: true },
        { prop: 'create_time', label: 'page.table.createTime', width: 170 },
        {
          prop: 'operation',
          label: 'table.actions.operation',
          width: 100,
          fixed: 'right',
          useSlot: true
        }
      ]
    }
  })

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

<style scoped>
  .table-summary-inline {
    margin-right: 12px;
    font-size: 14px;
    color: var(--el-text-color-regular);
    white-space: nowrap;
  }
  .table-summary-inline strong {
    color: var(--el-color-danger);
  }
  .table-toolbar-buttons {
    display: inline-flex;
  }
</style>
