<script setup lang="ts">
import { ref, onMounted, h, watch } from 'vue'
import { NButton, NDataTable, NInput, NSpace, NPagination, NDatePicker, NIcon, NTabs, NTabPane } from 'naive-ui'
import { SearchOutline, RefreshOutline } from '@vicons/ionicons5'
import { api } from '../../api/client'
import { useToast } from '../../composables/useToast'
import { toBeijingDateTime } from '../../utils/date'

const toast = useToast()
const tab = ref('registered')
const items = ref<any[]>([])
const loading = ref(false)
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)

const ipFilter = ref('')
// const locationFilter = ref('')  // 所在地 已注释
const dateRange = ref<[number, number] | null>(null)

onMounted(loadData)
watch(tab, () => { page.value = 1; loadData() })

async function loadData() {
  loading.value = true
  try {
    const params: Record<string, any> = { page: page.value, page_size: pageSize.value }
    if (ipFilter.value) params.ip = ipFilter.value
    // if (locationFilter.value) params.location = locationFilter.value  // 所在地 已注释
    if (dateRange.value) {
      params.start_date = new Date(dateRange.value[0]).toISOString().slice(0, 10)
      params.end_date = new Date(dateRange.value[1]).toISOString().slice(0, 10)
    }
    const endpoint = tab.value === 'registered' ? '/admin/page-views' : '/admin/anonymous-page-views'
    const { data } = await api.get(endpoint, { params })
    items.value = data.items || []
    total.value = data.total || 0
  } catch (e) {
    toast.apiError(e, '加载失败')
  } finally {
    loading.value = false
  }
}

function formatDuration(s: number | null | undefined): string {
  if (!s || s <= 0) return ''
  if (s < 60) return `${s}s`
  if (s < 3600) return `${Math.floor(s / 60)}m ${s % 60}s`
  return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`
}

// function formatLocation(loc: any): string {  // 已注释
//   if (!loc) return '—'
//   const parts = [loc.city, loc.regionName, loc.country].filter(Boolean)
//   return parts.join(', ') || '—'
// }

function userAgentShort(ua: string | null | undefined): string {
  if (!ua) return '—'
  if (ua.includes('Mobile')) return '📱 Mobile'
  if (ua.includes('Windows')) return '🖥 Windows'
  if (ua.includes('Mac')) return '🍎 Mac'
  if (ua.includes('Linux')) return '🐧 Linux'
  return ua.split('/')[0]?.split(' ')[0] || ua.slice(0, 12)
}

const regCols = [
  { title: '用户', key: 'display_name', width: 160, ellipsis: { tooltip: true }, render: (r: any) => r.display_name || '—' },
  { title: 'IP', key: 'ip_address', width: 130, render: (r: any) => r.ip_address ? h('span', { style: 'font-family:monospace;font-size:12px' }, r.ip_address) : '—' },
  // { title: '所在地', key: 'location', width: 150, ellipsis: { tooltip: true }, render: (r: any) => formatLocation(r.location) },  // 已注释
  { title: '页面名称', key: 'page_title', minWidth: 180, ellipsis: { tooltip: true }, render: (r: any) => r.page_title || '—' },
  { title: '页面 URL', key: 'path', width: 180, ellipsis: { tooltip: true }, render: (r: any) => r.path ? h('span', { style: 'font-family:monospace;font-size:12px' }, r.path) : '—' },
  { title: '访问时间', key: 'created_at', width: 150, render: (r: any) => toBeijingDateTime(r.created_at) || '—' },
  { title: '停留', key: 'duration_seconds', width: 70, render: (r: any) => formatDuration(r.duration_seconds) },
  { title: 'UA', key: 'user_agent', width: 90, ellipsis: { tooltip: true }, render: (r: any) => userAgentShort(r.user_agent) },
]

const anonCols = [
  { title: '匿名 ID', key: 'anonymous_id', width: 160, ellipsis: { tooltip: true }, render: (r: any) => h('span', { style: 'font-family:monospace;font-size:12px' }, r.anonymous_id?.slice(0, 8) + '…') },
  { title: 'IP', key: 'ip_address', width: 130, render: (r: any) => r.ip_address ? h('span', { style: 'font-family:monospace;font-size:12px' }, r.ip_address) : '—' },
  // { title: '所在地', key: 'location', width: 150, ellipsis: { tooltip: true }, render: (r: any) => formatLocation(r.location) },  // 已注释
  { title: '页面名称', key: 'page_title', minWidth: 180, ellipsis: { tooltip: true }, render: (r: any) => r.page_title || '—' },
  { title: '页面 URL', key: 'path', width: 180, ellipsis: { tooltip: true }, render: (r: any) => r.path ? h('span', { style: 'font-family:monospace;font-size:12px' }, r.path) : '—' },
  { title: '访问时间', key: 'created_at', width: 150, render: (r: any) => toBeijingDateTime(r.created_at) || '—' },
  { title: '停留', key: 'duration_seconds', width: 70, render: (r: any) => formatDuration(r.duration_seconds) },
  { title: 'UA', key: 'user_agent', width: 90, ellipsis: { tooltip: true }, render: (r: any) => userAgentShort(r.user_agent) },
]

const scrollX = 1110
</script>

<template>
  <div>
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;flex-wrap:wrap;gap:8px">
      <h2 style="margin:0">🌐 网站访问记录 ({{ total }})</h2>
      <NSpace wrap>
        <NInput v-model:value="ipFilter" placeholder="IP 过滤" size="small" style="width:140px" clearable @keyup.enter="loadData" />
        <!-- <NInput v-model:value="locationFilter" placeholder="所在地过滤" size="small" style="width:140px" clearable @keyup.enter="loadData" />  已注释 -->
        <NDatePicker v-model:value="dateRange" type="datetimerange" size="small" style="width:280px" clearable placeholder="选择日期范围" />
        <NButton size="small" type="primary" @click="loadData" class="sky-btn"><template #icon><NIcon size="14"><SearchOutline /></NIcon></template>查询</NButton>
        <NButton size="small" @click="ipFilter='';/*locationFilter='';*/dateRange=null;loadData()" class="sky-btn"><template #icon><NIcon size="14"><RefreshOutline /></NIcon></template>重置</NButton>
      </NSpace>
    </div>
    <NTabs v-model:value="tab" type="line">
      <NTabPane name="registered" tab="注册用户" />
      <NTabPane name="anonymous" tab="匿名用户" />
    </NTabs>
    <NDataTable :columns="tab === 'registered' ? regCols : anonCols" :data="items" :loading="loading" size="small" :bordered="false" :row-key="(r:any)=>r.id" :scroll-x="scrollX" />
    <div v-if="total > pageSize" style="display:flex;justify-content:center;margin-top:16px">
      <NPagination :page="page" :page-size="pageSize" :item-count="total" @update:page="p => { page=p; loadData() }" />
    </div>
  </div>
</template>
