<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: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 ? '付费' : row.lottery_type === 1 ? '赠送' : '-' }}
          </ElTag>
        </template>
        <!-- 中奖 tag -->
        <template #is_win="{ row }">
          <ElTag size="small" :type="row.is_win === 1 ? 'success' : 'info'">
            {{ row.is_win === 0 ? '无' : row.is_win === 1 ? '中奖' : '-' }}
          </ElTag>
        </template>
        <!-- 方向 tag -->
        <template #direction="{ row }">
          <ElTag size="small" :type="row.direction === 0 ? 'primary' : 'warning'">
            {{ row.direction === 0 ? '顺时针' : row.direction === 1 ? '逆时针' : '-' }}
          </ElTag>
        </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 { 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'

  // 搜索表单
  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,
    reward_ui_text: undefined,
    reward_tier: undefined,
    direction: undefined
  })

  // 搜索处理
  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>) =>
    row?.diceLotteryConfig?.name ?? row?.lottery_config_id ?? '-'
  const rewardTierFormatter = (row: Record<string, any>) =>
    row?.diceRewardConfig?.tier ?? row?.reward_config_id ?? '-'

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

  // 表格配置
  const {
    columns,
    columnChecks,
    data,
    loading,
    getData,
    searchParams,
    pagination,
    resetSearchParams,
    handleSortChange,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    core: {
      apiFn: api.list,
      columnsFactory: () => [
        { type: 'selection' },
        { prop: 'id', label: 'ID', width: 80 },
        {
          prop: 'player_id',
          label: '玩家',
          formatter: (row: Record<string, any>) => usernameFormatter(row)
        },
        {
          prop: 'lottery_config_id',
          label: '彩金池配置',
          width: 120,
          useSlot: true
        },
        { prop: 'lottery_type', label: '抽奖类型', width: 100, useSlot: true },
        { prop: 'is_win', label: '中奖', width: 80, useSlot: true },
        { prop: 'win_coin', label: '赢取平台币' },
        { 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: 'reward_config_id',
          label: '奖励配置',
          formatter: (row: Record<string, any>) => rewardTierFormatter(row)
        },
        { prop: 'create_time', label: '创建时间', width: 170 },
        { prop: 'update_time', label: '修改时间', width: 170 },
        { prop: 'operation', label: '操作', width: 100, fixed: 'right', useSlot: true }
      ]
    }
  })

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