<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4">
        <el-card class="kpi-card"><div class="kpi-title">用户数</div><div class="kpi-value">{{ kpi.users }}</div></el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="kpi-card"><div class="kpi-title">藏品数</div><div class="kpi-value">{{ kpi.relics }}</div></el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="kpi-card"><div class="kpi-title">公告数</div><div class="kpi-value">{{ kpi.announcements }}</div></el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="kpi-card"><div class="kpi-title">预约数</div><div class="kpi-value">{{ kpi.reservations }}</div></el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="kpi-card"><div class="kpi-title">游客数</div><div class="kpi-value">{{ kpi.visitors }}</div></el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="kpi-card"><div class="kpi-title">时段数</div><div class="kpi-value">{{ kpi.timeSlots }}</div></el-card>
      </el-col>
    </el-row>

    <br>

    <el-row :gutter="20">
      <el-col :span="12"><el-card><div ref="userRoleChart" class="chart"></div></el-card></el-col>
      <el-col :span="12"><el-card><div ref="reservationStatusChart" class="chart"></div></el-card></el-col>
    </el-row>

    <br>

    <el-row :gutter="20">
      <el-col :span="12"><el-card><div ref="relicHotStatusChart" class="chart"></div></el-card></el-col>
      <el-col :span="12"><el-card><div ref="visitorVerifyChart" class="chart"></div></el-card></el-col>
    </el-row>

    <br>

    <el-row :gutter="20">
      <el-col :span="12"><el-card><div ref="timeSlotDayChart" class="chart"></div></el-card></el-col>
      <el-col :span="12"><el-card><div ref="reservationDailyChart" class="chart"></div></el-card></el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import * as echarts from 'echarts'
import { listAllSysUser } from '@/api/sysUser'
import { listAllRelic } from '@/api/relic'
import { listAllAnnouncement } from '@/api/announcement'
import { listAllReservation } from '@/api/reservation'
import { listAllReservationVisitor } from '@/api/reservationVisitor'
import { listAllReservationTimeSlot } from '@/api/reservationTimeSlot'

const { proxy } = getCurrentInstance()

const kpi = reactive({ users: 0, relics: 0, announcements: 0, reservations: 0, visitors: 0, timeSlots: 0 })

const userRoleChart = ref(null)
const reservationStatusChart = ref(null)
const relicHotStatusChart = ref(null)
const visitorVerifyChart = ref(null)
const timeSlotDayChart = ref(null)
const reservationDailyChart = ref(null)

let charts = []

function toArray(res) {
  return Array.isArray(res) ? res : (res.list || res.data || [])
}

function formatDate(val) {
  if (!val) return ''
  const d = new Date(val)
  const yyyy = d.getFullYear()
  const MM = String(d.getMonth() + 1).padStart(2, '0')
  const DD = String(d.getDate()).padStart(2, '0')
  return `${yyyy}-${MM}-${DD}`
}

function getLastNDates(n) {
  const arr = []
  const d = new Date()
  for (let i = n - 1; i >= 0; i--) {
    const t = new Date(d)
    t.setDate(d.getDate() - i)
    arr.push(formatDate(t))
  }
  return arr
}

function renderUserRoleChart(users) {
  const roleCount = { '1': 0, '2': 0 }
  users.forEach(u => { if (u && u.role) roleCount[u.role] = (roleCount[u.role] || 0) + 1 })
  const chart = echarts.init(userRoleChart.value)
  charts.push(chart)
  chart.setOption({
    title: { text: '用户角色分布', left: 'center' },
    tooltip: { trigger: 'item' },
    legend: { bottom: 0 },
    series: [{ type: 'pie', radius: '60%', data: [
      { name: '超级管理员', value: roleCount['1'] || 0 },
      { name: '普通用户', value: roleCount['2'] || 0 }
    ] }]
  })
}

function renderReservationStatusChart(reservations) {
  const map = { 0: '待审核', 1: '已通过', 2: '已取消', 3: '已驳回' }
  const cnt = { 0: 0, 1: 0, 2: 0, 3: 0 }
  reservations.forEach(r => { const s = Number(r.status); if (s in cnt) cnt[s]++ })
  const chart = echarts.init(reservationStatusChart.value)
  charts.push(chart)
  chart.setOption({
    title: { text: '预约状态分布', left: 'center' },
    tooltip: { trigger: 'item' },
    legend: { bottom: 0 },
    series: [{ type: 'pie', radius: '60%', data: Object.keys(cnt).map(k => ({ name: map[k], value: cnt[k] })) }]
  })
}

function renderRelicHotStatusChart(relics) {
  let hot = 0, normal = 0, show = 0, hide = 0
  relics.forEach(r => {
    if (Number(r.isHot) === 1) hot++; else normal++
    if (Number(r.status) === 1) show++; else hide++
  })
  const chart = echarts.init(relicHotStatusChart.value)
  charts.push(chart)
  chart.setOption({
    title: { text: '藏品热门与状态', left: 'center' },
    tooltip: { trigger: 'axis' },
    legend: { bottom: 0 },
    xAxis: { type: 'category', data: ['热门', '普通', '显示', '隐藏'] },
    yAxis: { type: 'value' },
    series: [{ name: '数量', type: 'bar', data: [hot, normal, show, hide] }]
  })
}

function renderVisitorVerifyChart(visitors) {
  let verified = 0, unverified = 0
  visitors.forEach(v => { Number(v.verifyStatus) === 1 ? verified++ : unverified++ })
  const chart = echarts.init(visitorVerifyChart.value)
  charts.push(chart)
  chart.setOption({
    title: { text: '游客验证状态', left: 'center' },
    tooltip: { trigger: 'item' },
    legend: { bottom: 0 },
    series: [{ type: 'pie', radius: '60%', data: [
      { name: '已验证', value: verified },
      { name: '未验证', value: unverified }
    ] }]
  })
}

function renderTimeSlotDayChart(slots) {
  const byDay = {}
  slots.forEach(s => {
    const d = formatDate(s.date)
    const key = d
    if (!byDay[key]) byDay[key] = { bookable: 0, blocked: 0 }
    Number(s.status) === 1 ? byDay[key].bookable++ : byDay[key].blocked++
  })
  const days = getLastNDates(7)
  const bookable = days.map(d => (byDay[d]?.bookable || 0))
  const blocked = days.map(d => (byDay[d]?.blocked || 0))
  const chart = echarts.init(timeSlotDayChart.value)
  charts.push(chart)
  chart.setOption({
    title: { text: '近7天时段可约/不可约', left: 'center' },
    tooltip: { trigger: 'axis' },
    legend: { bottom: 0 },
    xAxis: { type: 'category', data: days },
    yAxis: { type: 'value' },
    series: [
      { name: '可约', type: 'bar', stack: 'total', data: bookable },
      { name: '不可约', type: 'bar', stack: 'total', data: blocked }
    ]
  })
}

function renderReservationDailyChart(reservations) {
  const days = getLastNDates(14)
  const cnt = days.reduce((acc, d) => (acc[d] = 0, acc), {})
  reservations.forEach(r => { const d = formatDate(r.createTime || r.create_time); if (d in cnt) cnt[d]++ })
  const chart = echarts.init(reservationDailyChart.value)
  charts.push(chart)
  chart.setOption({
    title: { text: '近14天预约趋势', left: 'center' },
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: days },
    yAxis: { type: 'value' },
    series: [{ name: '预约数', type: 'line', smooth: true, data: days.map(d => cnt[d]) }]
  })
}

function init() {
  Promise.all([
    listAllSysUser({}),
    listAllRelic({}),
    listAllAnnouncement({}),
    listAllReservation({}),
    listAllReservationVisitor({}),
    listAllReservationTimeSlot({})
  ]).then(([u, r, a, rs, rv, ts]) => {
    const users = toArray(u)
    const relics = toArray(r)
    const announcements = toArray(a)
    const reservations = toArray(rs)
    const visitors = toArray(rv)
    const timeSlots = toArray(ts)

    kpi.users = users.length
    kpi.relics = relics.length
    kpi.announcements = announcements.length
    kpi.reservations = reservations.length
    kpi.visitors = visitors.length
    kpi.timeSlots = timeSlots.length

    renderUserRoleChart(users)
    renderReservationStatusChart(reservations)
    renderRelicHotStatusChart(relics)
    renderVisitorVerifyChart(visitors)
    renderTimeSlotDayChart(timeSlots)
    renderReservationDailyChart(reservations)

    window.addEventListener('resize', () => { charts.forEach(c => c.resize()) })
  })
}

onMounted(() => { init() })
</script>

<style scoped>
.kpi-card { text-align: center; }
.kpi-title { font-size: 14px; color: #606266; }
.kpi-value { font-size: 24px; font-weight: 700; color: #303133; }
.chart { width: 100%; height: 360px; }
</style>
