<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>{{ totalWinCoin }}</strong>
          </span>
          <!--          <ElSpace wrap>-->
          <!--            <ElButton-->
          <!--              v-permission="'dice:play_record:index:save'"-->
          <!--              @click="showDialog('add')"-->
          <!--              v-ripple-->
          <!--            >-->
          <!--              <template #icon>-->
          <!--                <ArtSvgIcon icon="ri:add-fill" />-->
          <!--              </template>-->
          <!--              新增-->
          <!--            </ElButton>-->
          <!--            <ElButton-->
          <!--              v-permission="'dice:play_record:index:destroy'"-->
          <!--              :disabled="selectedRows.length === 0"-->
          <!--              @click="deleteSelectedRows(api.delete, refreshData)"-->
          <!--              v-ripple-->
          <!--            >-->
          <!--              <template #icon>-->
          <!--                <ArtSvgIcon icon="ri:delete-bin-5-line" />-->
          <!--              </template>-->
          <!--              删除-->
          <!--            </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"
      >
        <!-- 彩金池配置 tag -->
        <template #lottery_config_id="{ row }">
          <ElTag size="small">{{ lotteryConfigNameFormatter(row) }}</ElTag>
        </template>
        <!-- 抽奖类型 tag -->
        <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>
        <!-- 是否中大奖 tag -->
        <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>
        <!-- 方向 tag -->
        <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 #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 #paid_amount="{ row }">
          <span>{{ formatPlatformCoin(row?.paid_amount) }}</span>
        </template>
        <!-- 摇取点数 tag -->
        <template #roll_array="{ row }">
          <ElTag size="small">
            {{ formatRollArray(row.roll_array) }}
          </ElTag>
        </template>
        <!-- 操作列 -->
        <template #operation="{ row }">
          <div class="flex gap-2">
            <SaButton
              v-permission="'dice:play_record:index:update'"
              type="secondary"
              @click="showDialog('edit', row)"
            />
            <!--            <SaButton-->
            <!--              v-permission="'dice:play_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"
    />
  </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/index'
  import TableSearch from './modules/table-search.vue'
  import EditDialog from './modules/edit-dialog.vue'
  import { lotteryPoolRowLabel } from '@/views/plugin/dice/utils/lotteryPoolDisplay'
  const { t } = useI18n()

  // 搜索表单
  const searchForm = ref<Record<string, unknown>>({
    username: undefined,
    lottery_config_name: undefined,
    lottery_type: undefined,
    is_win: undefined,
    win_coin_min: undefined,
    win_coin_max: undefined,
    roll_number_min: undefined,
    roll_number_max: undefined,
    reward_ui_text: undefined,
    reward_tier: undefined,
    direction: 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 as any)?.total_win_coin ?? null
    return res
  }

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

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

  /** 摇取点数格式化为 1,3,4,5,6,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 {
    columns,
    columnChecks,
    data,
    loading,
    getData,
    searchParams,
    pagination,
    resetSearchParams,
    handleSortChange,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    core: {
      apiFn: listApi,
      apiParams: { limit: 100 },
      columnsFactory: () => [
        // { type: 'selection' },
        { prop: 'id', label: 'page.table.id', width: 80 },
        {
          prop: 'player_id',
          label: 'page.table.player',
          formatter: (row: Record<string, any>) => usernameFormatter(row)
        },
        {
          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: 80, align: 'center' },
        { prop: 'paid_amount', label: 'page.table.paidAmount', width: 110, align: 'center', useSlot: true },
        { prop: 'is_win', label: 'page.table.isBigWin', width: 100, useSlot: true },
        { 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,
          formatter: (row: Record<string, any>) => rewardTierFormatter(row)
        },
        {
          prop: 'remark',
          label: 'page.table.remark',
          width: 200,
          showOverflowTooltip: true,
          formatter: (row: Record<string, any>) => row?.remark || '-'
        },
        { prop: 'create_time', label: 'page.table.createTime', width: 170 },
        { prop: 'update_time', label: 'page.table.updateTime', 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);
  }
</style>
