<script setup lang="ts">
/**
 * 后台工作台：KPI 可跳转 + 最近文章 + 最近操作（查看全部进日志页）。
 */
import { computed, ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import AppNavbar from '@/components/layout/AppNavbar.vue'
import AppFloatingTabbar from '@/components/layout/AppFloatingTabbar.vue'
import AppPageShell from '@/components/layout/AppPageShell.vue'
import AdminLineChart from '../../components/AdminLineChart.vue'
import AdminBarChart from '../../components/AdminBarChart.vue'
import { useAuth } from '@/composables/useAuth'
import { useAppMode } from '@/composables/useAppMode'
import { useTheme } from '@/composables/useTheme'
import {
  adminList,
  getDashboardStats,
  getOperationLogs,
  normalizeAdminList,
  trendPointValue,
  type DashboardStats,
  type Post,
  type TrendPoint,
} from '@/api'

const { isAuthenticated } = useAuth()
const { canEnterAdmin } = useAppMode()
const { apply } = useTheme()

const loading = ref(false)
const stats = ref<DashboardStats>({})
const logs = ref<unknown[]>([])
const recentPosts = ref<Post[]>([])

const todayUv = computed(() => {
  const list = stats.value.uvTrend || []
  if (!list.length) return 0
  return trendPointValue(list[list.length - 1])
})

const kpiList = computed(() => [
  { key: 'posts', label: '文章', value: stats.value.posts ?? 0, url: '/subPackages/admin/pages/posts/list' },
  { key: 'works', label: '作品', value: stats.value.works ?? 0, url: '/subPackages/admin/pages/works/list' },
  { key: 'inquiry', label: '咨询', value: stats.value.inquiryCount ?? 0, url: '/subPackages/admin/pages/inquiries/list' },
  { key: 'uv', label: '今日 UV', value: todayUv.value, url: '/subPackages/admin/pages/analytics/index' },
])

const trendCategories = computed(() => {
  const posts = stats.value.postsTrend || []
  const uv = stats.value.uvTrend || []
  const set = new Set<string>()
  posts.forEach(p => set.add(p.date))
  uv.forEach(p => set.add(p.date))
  return Array.from(set).sort()
})

function mapByDate(list: TrendPoint[] | undefined, cats: string[]): number[] {
  const map = new Map((list || []).map(i => [i.date, trendPointValue(i)]))
  return cats.map(d => map.get(d) ?? 0)
}

const lineSeries = computed(() => {
  const cats = trendCategories.value
  return [
    { name: '发文', data: mapByDate(stats.value.postsTrend, cats) },
    { name: 'UV', data: mapByDate(stats.value.uvTrend, cats) },
  ]
})

const barCategories = computed(() =>
  (stats.value.topPosts || []).slice(0, 6).map(p => String(p.title || '').slice(0, 6) || '—'),
)
const barValues = computed(() =>
  (stats.value.topPosts || []).slice(0, 6).map(p => Number(p.count ?? p.readCount ?? 0)),
)

function guardAdmin() {
  if (!isAuthenticated() || !canEnterAdmin.value) {
    uni.reLaunch({ url: '/pages/mine/index' })
    return false
  }
  return true
}

function logLabel(item: unknown): string {
  if (!item || typeof item !== 'object') return String(item)
  const row = item as Record<string, unknown>
  return String(row.action || row.description || row.module || row.id || '操作记录')
}

function logTime(item: unknown): string {
  if (!item || typeof item !== 'object') return ''
  const row = item as Record<string, unknown>
  return String(row.createdAt || row.time || '')
}

async function load() {
  apply()
  if (!guardAdmin()) return
  loading.value = true
  try {
    const [s, logRes, postsRes] = await Promise.all([
      getDashboardStats().catch(() => ({}) as DashboardStats),
      getOperationLogs(1, 10).catch(() => ({ list: [] })),
      adminList('posts', { page: 1, pageSize: 5 }).catch(() => []),
    ])
    stats.value = s || {}
    const list = Array.isArray(logRes) ? logRes : (logRes as { list?: unknown[] }).list || []
    logs.value = list
    recentPosts.value = normalizeAdminList(postsRes) as Post[]
  }
  catch (e: unknown) {
    uni.showToast({ title: e instanceof Error ? e.message : '加载失败', icon: 'none' })
  }
  finally {
    loading.value = false
  }
}

onShow(load)

function go(url: string) {
  uni.navigateTo({ url })
}

function goPost(item: Post) {
  uni.navigateTo({ url: `/subPackages/admin/pages/posts/form?mode=edit&id=${item.id}` })
}
</script>

<template>
  <AppPageShell admin with-tab-pad>
    <AppNavbar title="工作台" />
    <view class="page-pad">
      <view class="hero-eyebrow">Dashboard</view>
      <view class="section-title" style="margin-bottom: 32rpx;">概览</view>

      <view class="stats-grid">
        <view
          v-for="item in kpiList"
          :key="item.key"
          class="admin-card stat"
          @click="go(item.url)"
        >
          <text class="font-mono-label text-art-muted">{{ item.label }}</text>
          <text class="num">{{ item.value }}</text>
        </view>
      </view>

      <view class="admin-card chart-card">
        <text class="chart-title">发文 / UV 趋势</text>
        <AdminLineChart
          v-if="trendCategories.length"
          :categories="trendCategories"
          :series="lineSeries"
        />
        <wd-empty v-else description="暂无趋势数据" />
      </view>

      <view class="admin-card chart-card">
        <text class="chart-title">热门文章阅读</text>
        <AdminBarChart
          v-if="barCategories.length"
          :categories="barCategories"
          :values="barValues"
        />
        <wd-empty v-else description="暂无热门数据" />
      </view>

      <view class="section-head">
        <text class="section-title" style="font-size: 34rpx;">最近文章</text>
        <text class="link text-art-accent" @click="go('/subPackages/admin/pages/posts/list')">全部</text>
      </view>
      <view
        v-for="item in recentPosts"
        :key="String(item.id)"
        class="admin-card log"
        @click="goPost(item)"
      >
        <text class="log-title">{{ item.title }}</text>
        <text class="font-mono-label text-art-muted">{{ item.categoryName || '' }} · {{ item.date || '' }}</text>
      </view>

      <view class="section-head" style="margin-top: 28rpx;">
        <text class="section-title" style="font-size: 34rpx;">最近操作</text>
        <text class="link text-art-accent" @click="go('/subPackages/admin/pages/logs/operation')">全部</text>
      </view>
      <view v-for="(item, idx) in logs" :key="idx" class="admin-card log">
        <text class="log-title">{{ logLabel(item) }}</text>
        <text class="font-mono-label text-art-muted">{{ logTime(item) }}</text>
      </view>
      <wd-empty v-if="!loading && !logs.length" description="暂无日志" />
      <wd-loading v-if="loading" />
    </view>
    <AppFloatingTabbar />
  </AppPageShell>
</template>

<style scoped lang="scss">
.page-pad { padding: 24rpx 32rpx 48rpx; }
.stats-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20rpx; margin-bottom: 28rpx; }
.stat { padding: 28rpx; display: flex; flex-direction: column; gap: 8rpx; }
.num { font-size: 44rpx; color: rgb(var(--art-accent)); font-family: monospace; }
.chart-card { padding: 24rpx; margin-bottom: 24rpx; }
.chart-title {
  display: block;
  font-size: 28rpx;
  color: rgb(var(--art-text));
  margin-bottom: 16rpx;
}
.section-head {
  border-bottom: 1px solid rgba(255, 255, 255, 0.08);
  padding-bottom: 16rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.link { font-size: 24rpx; }
.log {
  padding: 24rpx 28rpx;
  margin-bottom: 16rpx;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}
.log-title { font-size: 28rpx; color: rgb(var(--art-text)); }
</style>
