<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="totalCoinChange !== null" class="table-summary-inline">
            {{ $t('page.toolbar.coinChangeSummary') }}：<strong :class="coinSummaryClass">{{
              formatMoney2(totalCoinChange)
            }}</strong>
          </span>
<!--          <ElSpace wrap>-->
<!--            <ElButton-->
<!--              v-permission="'dice:player_wallet_record:index:save'"-->
<!--              @click="showDialog('add')"-->
<!--              v-ripple-->
<!--            >-->
<!--              <template #icon>-->
<!--                <ArtSvgIcon icon="ri:add-fill" />-->
<!--              </template>-->
<!--              新增-->
<!--            </ElButton>-->
<!--            <ElButton-->
<!--              v-permission="'dice:player_wallet_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 #type="{ row }">
          <ElTag class="wallet-type-tag" size="large" :type="typeTagType(row.type)">
            {{ typeFormatter(row) }}
          </ElTag>
        </template>
        <!-- 操作列 -->
        <template #operation="{ row }">
          <div class="flex gap-2">
            <SaButton
              v-permission="'dice:player_wallet_record:index:update'"
              type="secondary"
              @click="showDialog('edit', row)"
            />
<!--            <SaButton-->
<!--              v-permission="'dice:player_wallet_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 { defaultResponseAdapter } from '@/utils/table/tableUtils'
  import { useSaiAdmin } from '@/composables/useSaiAdmin'
  import api from '../../api/player_wallet_record/index'
  import TableSearch from './modules/table-search.vue'
  import EditDialog from './modules/edit-dialog.vue'

  // 搜索表单
  const searchForm = ref({
    type: undefined,
    username: undefined,
    coin_min: undefined,
    coin_max: undefined,
    create_time: undefined as [string, string] | undefined
  })

  /** 当前筛选条件下平台币变化合计 */
  const totalCoinChange = ref<number | null>(null)

  const coinSummaryClass = computed(() => {
    if (totalCoinChange.value === null) return ''
    if (totalCoinChange.value > 0) return 'coin-summary-positive'
    if (totalCoinChange.value < 0) return 'coin-summary-negative'
    return ''
  })

  const WALLET_SEARCH_KEYS = [
    'type',
    'username',
    'coin_min',
    'coin_max',
    'create_time_min',
    'create_time_max'
  ] as const

  let summaryRequestSeq = 0

  const listApi = async (params: Record<string, any>) => {
    const reqId = ++summaryRequestSeq
    const res = await api.list(params)
    if (reqId === summaryRequestSeq) {
      const summary = (res as Record<string, unknown> | undefined)?.total_coin_change
      totalCoinChange.value =
        summary !== undefined && summary !== null && summary !== '' ? Number(summary) : null
    }
    return res
  }

  const applySearchParams = (params: Record<string, any>) => {
    const p = { ...params }
    if (Array.isArray(p.create_time) && p.create_time.length === 2) {
      p.create_time_min = p.create_time[0]
      p.create_time_max = p.create_time[1]
    }
    delete p.create_time
    const paramsRecord = searchParams as Record<string, unknown>
    WALLET_SEARCH_KEYS.forEach((key) => {
      delete paramsRecord[key]
    })
    Object.assign(searchParams, p)
  }

  // 搜索处理：将 create_time 区间转为 create_time_min / create_time_max
  const handleSearch = (params: Record<string, any>) => {
    applySearchParams(params)
    getData()
  }

  const { t } = useI18n()
  // 类型展示：0=充值 1=提现 2=购买抽奖次数 3=管理员加点 4=管理员扣点 5=抽奖
  const typeFormatter = (row: Record<string, unknown>) => {
    const ty = row.type
    if (ty === 0) return t('page.search.typeRecharge')
    if (ty === 1) return t('page.search.typeWithdraw')
    if (ty === 2) return t('page.search.typeBuyTicket')
    if (ty === 3) return t('page.search.typeAdminAdd')
    if (ty === 4) return t('page.search.typeAdminSub')
    if (ty === 5) return t('page.table.typeDraw')
    return '-'
  }

  // 类型对应 tag 底色：0 充值 1 提现 2 购买 3 加点 4 扣点
  const typeTagType = (t: unknown): 'success' | 'warning' | 'danger' | 'info' | 'primary' => {
    if (t === 0) return 'success'
    if (t === 1) return 'warning'
    if (t === 2) return 'primary'
    if (t === 3) return 'success'
    if (t === 4) return 'danger'
    if (t === 5) return 'info'
    return 'info'
  }

  // 操作人：关联管理员用户名
  const operatorFormatter = (row: Record<string, any>) => {
    const op = row.operator ?? row.operator_id
    if (op && typeof op === 'object' && op.username) return op.username
    return row.user_id ?? '-'
  }

  // 用户列展示为 dicePlayer.username（兼容 dice_player）
  const usernameFormatter = (row: Record<string, any>) => {
    const player = row.dicePlayer ?? row.dice_player
    return player?.username ?? row.player_id ?? '-'
  }

  function formatMoney2(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 },
      excludeParams: ['create_time'],
      columnsFactory: () => [
        { type: 'selection', align: 'center' },
        { prop: 'id', label: 'page.table.id', width: 80, align: 'center' },
        {
          prop: 'player_id',
          label: 'page.table.user',
          width: 120,
          align: 'center',
          formatter: usernameFormatter
        },
        { prop: 'coin', label: 'page.table.coinChange', width: 110, align: 'center' },
        {
          prop: 'type',
          label: 'page.table.type',
          width: 140,
          align: 'center',
          useSlot: true,
          formatter: typeFormatter
        },
        {
          prop: 'user_id',
          label: 'page.table.operator',
          width: 100,
          align: 'center',
          formatter: operatorFormatter
        },
        {
          prop: 'wallet_before',
          label: 'page.table.walletBefore',
          width: 110,
          align: 'center',
          formatter: (row: Record<string, any>) => formatMoney2(row?.wallet_before)
        },
        {
          prop: 'wallet_after',
          label: 'page.table.walletAfter',
          width: 110,
          align: 'center',
          formatter: (row: Record<string, any>) => formatMoney2(row?.wallet_after)
        },
        {
          prop: 'remark',
          label: 'page.table.remark',
          width: 100,
          align: 'center',
          showOverflowTooltip: true
        },
        { prop: 'total_ticket_count', label: 'page.table.totalDrawCount', align: 'center' },
        { prop: 'paid_ticket_count', label: 'page.table.paidDrawCount', align: 'center' },
        { prop: 'free_ticket_count', label: 'page.table.freeDrawCount', align: 'center' },
        { prop: 'create_time', label: 'page.table.createTime', width: 170, align: 'center' },
        {
          prop: 'operation',
          label: 'table.actions.operation',
          width: 60,
          align: 'center',
          fixed: 'right',
          useSlot: true
        }
      ]
    },
    hooks: {
      onSuccess(_data, response) {
        const raw = response as unknown as Record<string, unknown>
        const summary = raw?.total_coin_change
        if (summary !== undefined && summary !== null && summary !== '') {
          totalCoinChange.value = Number(summary)
        }
      }
    },
    transform: {
      responseAdapter(response) {
        const raw = (response ?? {}) as Record<string, unknown>
        const base = defaultResponseAdapter(response)
        if (raw.total_coin_change !== undefined && raw.total_coin_change !== null) {
          ;(base as Record<string, unknown>).total_coin_change = raw.total_coin_change
        }
        return base
      }
    }
  })

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

<style lang="scss" scoped>
  .table-summary-inline {
    margin-right: 12px;
    font-size: 14px;
    color: var(--el-text-color-regular);
    white-space: nowrap;
  }

  .table-summary-inline strong {
    font-weight: 600;
  }

  .coin-summary-positive {
    color: var(--el-color-success);
  }

  .coin-summary-negative {
    color: var(--el-color-danger);
  }

  /* 类型 tag 放大一倍（large + scale） */
  :deep(.wallet-record-type-tag) {
    transform: scale(0.8);
    transform-origin: center;
  }
</style>
