<template>
  <div class="admin-data-page">
    <div class="admin-page-hero">
      <div>
        <span class="admin-eyebrow">{{ eyebrow }}</span>
        <h2>{{ title }}</h2>
        <p>{{ description }}</p>
      </div>
      <div class="admin-page-actions">
        <button class="admin-button" type="button" @click="$emit('refresh')">
          <i class="fas fa-rotate"></i>
          刷新
        </button>
        <button v-if="primaryAction" class="primary-button admin-primary-action" type="button" @click="$emit('primary')">
          <i :class="primaryIcon"></i>
          {{ primaryAction }}
        </button>
      </div>
    </div>

    <div class="admin-filter-bar">
      <label class="admin-search-field">
        <i class="fas fa-search"></i>
        <input v-model="keyword" :placeholder="`搜索${title}`" />
      </label>
      <select v-model="statusFilter" class="admin-select">
        <option value="">全部状态</option>
        <option v-for="option in statusOptions" :key="option.value" :value="option.value">{{ option.label }}</option>
      </select>
      <button class="admin-button" type="button" @click="clearFilters">清空筛选</button>
      <div class="admin-filter-meta">{{ filteredRows.length }} 条记录</div>
    </div>

    <div class="admin-table-card">
      <div v-if="loading" class="admin-loading-state">
        <i></i><i></i><i></i><i></i>
      </div>
      <div v-else-if="!filteredRows.length" class="admin-empty-state">
        <i class="fas fa-inbox"></i>
        <strong>暂无数据</strong>
        <span>可以调整筛选条件，或刷新接口后再看。</span>
      </div>
      <table v-else>
        <thead>
          <tr>
            <th v-for="col in normalizedColumns" :key="col.key">{{ col.label }}</th>
            <th class="admin-actions-col">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="row in pagedRows" :key="rowKey(row)" @click="selectRow(row)">
            <td v-for="col in normalizedColumns" :key="col.key">
              <component :is="cellComponent(col)" :value="row[col.key]" :column="col" />
            </td>
            <td class="admin-row-actions" @click.stop>
              <button type="button" @click="selectRow(row)">详情</button>
              <button type="button" @click="emit('edit', row)">编辑</button>
              <button type="button">跟进</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="admin-pagination" v-if="filteredRows.length">
      <span>第 {{ page }} / {{ totalPages }} 页</span>
      <div>
        <button class="admin-button" type="button" :disabled="page === 1" @click="page--">上一页</button>
        <button class="admin-button" type="button" :disabled="page === totalPages" @click="page++">下一页</button>
      </div>
    </div>

    <transition name="admin-drawer">
      <aside v-if="selectedRow" class="admin-detail-drawer">
        <div class="admin-detail-drawer__head">
          <div>
            <span class="admin-eyebrow">DETAIL</span>
            <h3>{{ title }}详情</h3>
          </div>
          <button class="admin-icon-btn" type="button" @click="selectedRow = null"><i class="fas fa-times"></i></button>
        </div>
        <dl>
          <template v-for="col in normalizedColumns" :key="col.key">
            <dt>{{ col.label }}</dt>
            <dd><component :is="cellComponent(col)" :value="selectedRow[col.key]" :column="col" /></dd>
          </template>
        </dl>
      </aside>
    </transition>
  </div>
</template>

<script setup>
import { computed, h, ref, watch } from 'vue'

const props = defineProps({
  eyebrow: { type: String, default: 'ADMIN' },
  title: { type: String, default: '数据列表' },
  description: { type: String, default: '查看、筛选并处理后台业务数据。' },
  columns: { type: Array, default: () => [] },
  rows: { type: Array, default: () => [] },
  loading: { type: Boolean, default: false },
  primaryAction: { type: String, default: '' },
  primaryIcon: { type: String, default: 'fas fa-plus' },
  statusOptions: { type: Array, default: () => [] },
  pageSize: { type: Number, default: 8 }
})
const emit = defineEmits(['refresh', 'primary', 'edit'])

const keyword = ref('')
const statusFilter = ref('')
const page = ref(1)
const selectedRow = ref(null)

const normalizedColumns = computed(() => props.columns.map((col) => typeof col === 'string' ? { key: col, label: col, type: 'text' } : { type: 'text', ...col }))
const searchableKeys = computed(() => normalizedColumns.value.map(col => col.key))
const filteredRows = computed(() => {
  const text = keyword.value.trim().toLowerCase()
  return props.rows.filter((row) => {
    const matchText = !text || searchableKeys.value.some(key => String(row[key] ?? '').toLowerCase().includes(text))
    const matchStatus = !statusFilter.value || String(row.status ?? row.follow_status ?? row.pay_status ?? row.recommended ?? '') === statusFilter.value
    return matchText && matchStatus
  })
})
const totalPages = computed(() => Math.max(1, Math.ceil(filteredRows.value.length / props.pageSize)))
const pagedRows = computed(() => filteredRows.value.slice((page.value - 1) * props.pageSize, page.value * props.pageSize))

watch(filteredRows, () => { page.value = 1 })

const clearFilters = () => {
  keyword.value = ''
  statusFilter.value = ''
}
const selectRow = (row) => { selectedRow.value = row }
const rowKey = (row) => row.id || row.order_no || row.code || row.phone || JSON.stringify(row)

const formatMoney = (value) => value === undefined || value === null || value === '-' ? '-' : `¥${Number(value / 100).toLocaleString('zh-CN')}`
const formatCycle = (value) => value === 'year' ? '年付' : value === 'month' ? '月付' : value || '-'
const formatBool = (value) => Number(value) === 1 || value === true ? '是' : '否'

const textCell = (props) => h('span', { class: 'admin-cell-text' }, String(props.value ?? '-'))
const moneyCell = (props) => h('strong', { class: 'admin-cell-money' }, formatMoney(props.value))
const tagCell = (props) => h('span', { class: `admin-status-badge is-${props.value || 'empty'}` }, props.column.map?.[props.value] || props.value || '-')
const cycleCell = (props) => h('span', { class: 'admin-soft-badge' }, formatCycle(props.value))
const boolCell = (props) => h('span', { class: `admin-status-badge ${props.value ? 'is-success' : 'is-empty'}` }, formatBool(props.value))

const cellComponent = (col) => {
  const cells = { money: moneyCell, tag: tagCell, cycle: cycleCell, bool: boolCell }
  return cells[col.type] || textCell
}
</script>
