<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">
            平台总盈利：<strong>{{ 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>
              删除
            </ElButton>
            <ElButton
              v-permission="'dice:play_record_test:index:destroy'"
              type="danger"
              plain
              @click="handleClearAll"
              v-ripple
            >
              <template #icon>
                <ArtSvgIcon icon="ri:delete-bin-2-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"
      >
        <!-- 彩金池配置：显示 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 ? '付费' : row.lottery_type === 1 ? '赠送' : '-' }}
          </ElTag>
        </template>
        <!-- 是否中大奖 -->
        <template #is_win="{ row }">
          <ElTag size="small" :type="row.is_win === 1 ? 'success' : 'info'">
            {{ row.is_win === 0 ? '无' : row.is_win === 1 ? '中大奖' : '-' }}
          </ElTag>
        </template>
        <!-- 方向 -->
        <template #direction="{ row }">
          <ElTag size="small" :type="row.direction === 0 ? 'primary' : 'warning'">
            {{ row.direction === 0 ? '顺时针' : row.direction === 1 ? '逆时针' : '-' }}
          </ElTag>
        </template>
        <!-- 摇取点数 -->
        <template #roll_array="{ row }">
          <ElTag size="small">
            {{ formatRollArray(row.roll_array) }}
          </ElTag>
        </template>
        <!-- 奖励档位：显示 DiceRewardConfig.tier -->
        <template #reward_config_id="{ row }">
          <ElTag size="small">{{ rewardTierFormatter(row) }}</ElTag>
        </template>
        <!-- 状态 -->
        <template #status="{ row }">
          <ElTag size="small" :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '成功' : '失败' }}
          </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 { 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'

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

  // 当前筛选下平台总盈利（付费抽奖次数×100 - 玩家总收益）
  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 lotteryConfigNameFormatter = (row: Record<string, any>) =>
    row?.diceLotteryPoolConfig?.name ?? row?.lottery_config_id ?? '-'
  const rewardTierFormatter = (row: Record<string, any>) =>
    row?.diceRewardConfig?.tier ?? row?.reward_config_id ?? '-'

  /** 摇取点数格式化为 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)
  }

  const handleClearAll = async () => {
    try {
      await ElMessageBox.confirm('确定清空所有玩家抽奖测试数据？', '提示', {
        type: 'warning'
      })
      await api.clearAll()
      ElMessage.success('已清空所有测试数据')
      getData()
    } catch (e: any) {
      if (e !== 'cancel') {
        ElMessage.error(e?.message || '清空失败')
      }
    }
  }

  // 搜索处理
  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: 'ID', width: 80 },
        { prop: 'lottery_config_id', label: '彩金池配置', width: 120, useSlot: true },
        { prop: 'lottery_type', label: '抽奖类型', width: 100, useSlot: true },
        { prop: 'is_win', label: '是否中大奖', width: 100, useSlot: true },
        { prop: 'win_coin', label: '赢取平台币', width: 110 },
        { prop: 'super_win_coin', label: '中大奖平台币', width: 120 },
        { prop: 'reward_win_coin', label: '摇色子中奖平台币', width: 140 },
        { prop: 'direction', label: '方向', width: 90, useSlot: true },
        { prop: 'start_index', label: '起始索引', width: 90 },
        { prop: 'target_index', label: '终点索引', width: 90 },
        { prop: 'roll_array', label: '摇取点数', width: 140, useSlot: true },
        { prop: 'roll_number', label: '摇取点数和', width: 110, sortable: true },
        { prop: 'reward_config_id', label: '奖励档位', width: 100, useSlot: true },
        { prop: 'status', label: '状态', width: 80, useSlot: true },
        { prop: 'create_time', label: '创建时间', width: 170 },
        { prop: 'operation', label: '操作', 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>
