<template>
  <div class="flex-1 min-h-0 flex flex-col">
    <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>
          <ElButton
            v-permission="'dice:lottery_pool_config:index:index'"
            type="primary"
            @click="showCurrentPoolDialog"
          >
            {{ $t('page.toolbar.viewCurrentPool') }}
          </ElButton>
        </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 #safety_line="{ row }">
          <span v-if="isDefaultPoolRow(row)" class="font-mono">{{
            formatSafetyLine(row.safety_line)
          }}</span>
          <span v-else class="text-gray-400 text-xs">{{ $t('page.table.safetyLineNotUsed') }}</span>
        </template>
        <!-- 操作列 -->
        <template #operation="{ row }">
          <div class="flex gap-2">
            <SaButton
              v-permission="'dice:lottery_pool_config:index:update'"
              type="secondary"
              @click="showDialog('edit', row)"
            />
            <!--            <SaButton-->
            <!--              v-permission="'dice:lottery_pool_config: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"
    />
    <!-- 当前彩金池弹窗 -->
    <CurrentPoolDialog v-model="currentPoolVisible" @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/lottery_pool_config/index'
  import TableSearch from './modules/table-search.vue'
  import EditDialog from './modules/edit-dialog.vue'
  import CurrentPoolDialog from './modules/current-pool-dialog.vue'
  const { t } = useI18n()

  // 搜索表单
  const searchForm = ref({
    name: undefined,
    // type 字段已移除，改用 name 区分：default/killScore/up
  })

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

  const poolNameFormatter = (row: Record<string, unknown>) => {
    const remark = String(row.remark ?? '').trim()
    if (remark) return remark
    return String(row.name ?? '').trim() || '-'
  }

  // 权重列带 %
  const weightFormatter = (prop: string) => (row: Record<string, unknown>) => {
    const v = row[prop]
    return v != null && v !== '' ? `${v}%` : '-'
  }

  /** 仅 name=default（正常）奖池的安全线参与杀分判定 */
  function isDefaultPoolRow(row: Record<string, unknown>): boolean {
    return String(row.name ?? '') === 'default'
  }

  function formatSafetyLine(val: unknown): string {
    if (val === null || val === undefined || val === '') return '-'
    const n = typeof val === 'number' ? val : Number(val)
    return Number.isFinite(n) ? n.toFixed(2) : '-'
  }

  // 表格配置
  const {
    columns,
    columnChecks,
    data,
    loading,
    getData,
    searchParams,
    pagination,
    resetSearchParams,
    handleSortChange,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    core: {
      apiFn: api.list,
      columnsFactory: () => [
        { prop: 'remark', label: 'page.table.poolName', minWidth: 120, align: 'center', formatter: poolNameFormatter },
        {
          prop: 'config_note',
          label: 'page.table.configNote',
          minWidth: 140,
          align: 'center',
          showOverflowTooltip: true,
          formatter: (row: Record<string, unknown>) => {
            const v = String(row.config_note ?? '').trim()
            return v || '-'
          }
        },
        { prop: 'name', label: 'page.table.name', width: 110, align: 'center' },
        {
          prop: 'safety_line',
          label: 'page.table.safetyLine',
          minWidth: 120,
          align: 'center',
          useSlot: true
        },
        {
          prop: 't1_weight',
          label: 'page.table.t1PoolWeight',
          width: 100,
          align: 'center',
          formatter: weightFormatter('t1_weight')
        },
        {
          prop: 't2_weight',
          label: 'page.table.t2PoolWeight',
          width: 100,
          align: 'center',
          formatter: weightFormatter('t2_weight')
        },
        {
          prop: 't3_weight',
          label: 'page.table.t3PoolWeight',
          width: 100,
          align: 'center',
          formatter: weightFormatter('t3_weight')
        },
        {
          prop: 't4_weight',
          label: 'page.table.t4PoolWeight',
          width: 100,
          align: 'center',
          formatter: weightFormatter('t4_weight')
        },
        {
          prop: 't5_weight',
          label: 'page.table.t5PoolWeight',
          width: 100,
          align: 'center',
          formatter: weightFormatter('t5_weight')
        },
        {
          prop: 'operation',
          label: 'table.actions.operation',
          width: 60,
          align: 'center',
          fixed: 'right',
          useSlot: true
        }
      ]
    }
  })

  // 编辑配置
  const { dialogType, dialogVisible, dialogData, showDialog, handleSelectionChange } = useSaiAdmin()

  const currentPoolVisible = ref(false)
  function showCurrentPoolDialog() {
    currentPoolVisible.value = true
  }
</script>
