<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:player:index:save'" @click="showDialog('add')" v-ripple>
              <template #icon>
                <ArtSvgIcon icon="ri:add-fill" />
              </template>
              新增
            </ElButton>
            <ElButton
              v-permission="'dice:player: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"
      >
        <!-- 状态：开关直接修改 -->
        <template #status="{ row }">
          <ElSwitch
            v-permission="'dice:player:index:update'"
            :model-value="row.status === 1"
            :loading="row._statusLoading"
            @change="(v: string | number | boolean) => handleStatusChange(row, v ? 1 : 0)"
          />
        </template>
        <!-- 平台币：tag 展示 -->
        <template #coin="{ row }">
          <ElTag type="info" size="small">{{ row.coin ?? 0 }}</ElTag>
        </template>
        <!-- 操作列 -->
        <template #operation="{ row }">
          <div class="flex gap-2">
            <SaButton
              v-permission="'dice:player:index:update'"
              type="secondary"
              @click="showDialog('edit', row)"
            />
            <SaButton
              v-permission="'dice:player: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/player/index'
  import TableSearch from './modules/table-search.vue'
  import EditDialog from './modules/edit-dialog.vue'

  // 搜索表单
  const searchForm = ref({
    username: undefined,
    name: undefined,
    phone: undefined,
    status: undefined,
    coin: undefined,
    is_up: undefined
  })

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

  // 权重列带 % 的 formatter（ColumnOption.formatter 仅接收 row）
  const weightFormatter = (prop: string) => (row: any) => {
    const cellValue = row[prop]
    return cellValue != null && cellValue !== '' ? `${cellValue}%` : '-'
  }

  // 倍率列展示：0=正常 1=强制杀猪 2=T1高倍率
  const isUpFormatter = (row: any) => {
    const cellValue = row.is_up
    return cellValue === 0
      ? '正常'
      : cellValue === 1
        ? '强制杀猪'
        : cellValue === 2
          ? 'T1高倍率'
          : '-'
  }

  // 表格配置
  const {
    columns,
    columnChecks,
    data,
    loading,
    getData,
    searchParams,
    pagination,
    resetSearchParams,
    handleSortChange,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    core: {
      apiFn: api.list,
      columnsFactory: () => [
        { type: 'selection' },
        { prop: 'username', label: '用户名' },
        { prop: 'phone', label: '手机号' },
        { prop: 'name', label: '昵称' },
        { prop: 'status', label: '状态', width: 88, useSlot: true },
        { prop: 'coin', label: '平台币', width: 100, useSlot: true },
        { prop: 'is_up', label: '倍率', width: 80, formatter: isUpFormatter },
        { prop: 't1_wight', label: 'T1池权重', width: 100, formatter: weightFormatter('t1_wight') },
        { prop: 't2_wight', label: 'T2池权重', width: 100, formatter: weightFormatter('t2_wight') },
        { prop: 't3_wight', label: 'T3池权重', width: 100, formatter: weightFormatter('t3_wight') },
        { prop: 't4_wight', label: 'T4池权重', width: 100, formatter: weightFormatter('t4_wight') },
        { prop: 't5_wight', label: 'T5池权重', width: 100, formatter: weightFormatter('t5_wight') },
        { prop: 'total_draw_count', label: '总抽奖次数' },
        { prop: 'paid_draw_count', label: '购买抽奖次数' },
        { prop: 'free_draw_count', label: '赠送抽奖次数' },
        { prop: 'created_at', label: '创建时间' },
        { prop: 'updated_at', label: '更新时间' },
        { prop: 'operation', label: '操作', width: 120, fixed: 'right', useSlot: true }
      ]
    }
  })

  // 状态开关切换（列表内直接修改）
  const handleStatusChange = async (row: Record<string, any>, status: number) => {
    row._statusLoading = true
    try {
      await api.updateStatus({ id: row.id, status })
      row.status = status
    } catch {
      refreshData()
    } finally {
      row._statusLoading = false
    }
  }

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