<template>
  <div class="workbench">
    <a-row :gutter="16">
      <a-col :span="6">
        <a-card :loading="loading">
          <a-statistic
            title="总用户数"
            :value="statistics.userCount"
            :value-style="{ color: '#3f8600' }"
          />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card :loading="loading">
          <a-statistic
            title="总角色数"
            :value="statistics.roleCount"
            :value-style="{ color: '#52c41a' }"
          />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card :loading="loading">
          <a-statistic
            title="总菜单数"
            :value="statistics.menuCount"
            :value-style="{ color: '#cf1322' }"
          />
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card :loading="loading">
          <a-statistic
            title="系统日志"
            :value="statistics.logCount"
            :value-style="{ color: '#722ed1' }"
          />
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue"
import { message } from "ant-design-vue"
import { usersApi } from "@/api/users"
import { rolesApi } from "@/api/roles"
import { menusApi } from "@/api/menus"
import { logsApi } from "@/api/logs"

const loading = ref(false)

const statistics = ref({
  userCount: 0,
  roleCount: 0,
  menuCount: 0,
  logCount: 0,
})

// 递归计算菜单总数（包括子菜单）
const countMenus = (menus: any[]): number => {
  let count = 0
  menus.forEach((menu) => {
    count++
    if (menu.children && menu.children.length > 0) {
      count += countMenus(menu.children)
    }
  })
  return count
}

// 获取统计数据
const fetchStatistics = async () => {
  loading.value = true
  try {
    // 并行获取所有统计数据
    const [usersRes, rolesRes, menusRes, logsRes] = await Promise.all([
      usersApi.getList({ page: 1, pageSize: 1 }).catch(() => ({ total: 0 })),
      rolesApi.getList({ page: 1, pageSize: 1 }).catch(() => ({ total: 0 })),
      menusApi.getList().catch(() => []),
      logsApi.getList({ page: 1, pageSize: 1 }).catch(() => ({ total: 0 })),
    ])

    statistics.value = {
      userCount: usersRes.total || 0,
      roleCount: rolesRes.total || 0,
      menuCount: Array.isArray(menusRes) ? countMenus(menusRes) : 0,
      logCount: logsRes.total || 0,
    }
  } catch (error) {
    console.error("获取统计数据失败:", error)
    message.error("获取统计数据失败")
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchStatistics()
})
</script>

<style scoped lang="scss">
.workbench {
  .ant-card {
    margin-bottom: 16px;
  }
}
</style>
