<template>
  <div class="dashboard-container">
    <!-- 数据概览卡片区域 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col 
        v-for="card in overviewCards" 
        :key="card.key" 
        :xs="24" 
        :sm="12" 
        :md="6"
      >
        <div 
          class="overview-card" 
          :style="{ background: card.gradient }"
          v-loading="overviewLoading"
        >
          <div class="overview-card-icon">
            <el-icon size="40"><component :is="card.icon" /></el-icon>
          </div>
          <div class="overview-card-content">
            <div class="overview-card-value">
              {{ card.isCurrency ? formatCurrency(getOverviewValue(card.key)) : getOverviewValue(card.key) }}
            </div>
            <div class="overview-card-label">{{ card.label }}</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 系统统计卡片区域 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-icon stat-icon-primary">
            <el-icon size="32"><User /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats.userCount }}</div>
            <div class="stat-label">管理员数量</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-icon stat-icon-success">
            <el-icon size="32"><UserFilled /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats.roleCount }}</div>
            <div class="stat-label">角色数量</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-icon stat-icon-warning">
            <el-icon size="32"><Menu /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats.menuCount }}</div>
            <div class="stat-label">菜单数量</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-icon stat-icon-danger">
            <el-icon size="32"><OfficeBuilding /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats.departmentCount }}</div>
            <div class="stat-label">部门数量</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>欢迎使用</span>
          </template>
          <div class="welcome-content">
            <h2>HoneyBox 后台管理系统</h2>
            <p>当前登录用户：{{ userStore.userInfo?.realName || userStore.userInfo?.username }}</p>
            <p>登录时间：{{ loginTime }}</p>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>系统信息</span>
          </template>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="系统版本">1.0.0</el-descriptions-item>
            <el-descriptions-item label="框架版本">.NET 10 + Vue 3</el-descriptions-item>
            <el-descriptions-item label="数据库">SQL Server</el-descriptions-item>
            <el-descriptions-item label="缓存">Memory Cache</el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="24">
        <el-card>
          <template #header>
            <span>快捷操作</span>
          </template>
          <div class="quick-actions">
            <el-button type="primary" @click="$router.push('/system/user')">
              <el-icon><User /></el-icon>管理员管理
            </el-button>
            <el-button type="success" @click="$router.push('/system/role')">
              <el-icon><UserFilled /></el-icon>角色管理
            </el-button>
            <el-button type="warning" @click="$router.push('/system/menu')">
              <el-icon><Menu /></el-icon>菜单管理
            </el-button>
            <el-button type="info" @click="$router.push('/system/department')">
              <el-icon><OfficeBuilding /></el-icon>部门管理
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, type Component } from 'vue'
import { User, UserFilled, Menu, OfficeBuilding, ShoppingCart, Money, Wallet } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import { getDashboardOverview, type DashboardOverview } from '@/api/business/dashboard'
import { formatCurrency } from '@/utils/format'

const userStore = useUserStore()

// ==================== 数据概览卡片配置 ====================

interface OverviewCardConfig {
  key: keyof DashboardOverview
  label: string
  icon: Component
  gradient: string
  isCurrency: boolean
}

const overviewCards: OverviewCardConfig[] = [
  {
    key: 'todayRegistrations',
    label: '今日注册用户',
    icon: UserFilled,
    gradient: 'linear-gradient(-125deg, #57bdbf, #2f9de2)',
    isCurrency: false
  },
  {
    key: 'todayNewConsumers',
    label: '今日消费用户',
    icon: ShoppingCart,
    gradient: 'linear-gradient(-125deg, #e91dab, #ffd026)',
    isCurrency: false
  },
  {
    key: 'todayConsumption',
    label: '当日消费总金额',
    icon: Money,
    gradient: 'linear-gradient(-125deg, #ff7d7d, #fb2c95)',
    isCurrency: true
  },
  {
    key: 'totalConsumption',
    label: '总消费金额',
    icon: Wallet,
    gradient: 'linear-gradient(-125deg, #999, #999)',
    isCurrency: true
  }
]

// ==================== 数据概览状态 ====================

const overviewLoading = ref(false)
const overviewData = ref<DashboardOverview | null>(null)

/**
 * 获取概览数据值
 * @param key 数据字段名
 * @returns 对应的数值，如果数据未加载则返回0
 */
function getOverviewValue(key: keyof DashboardOverview): number {
  return overviewData.value?.[key] ?? 0
}

/**
 * 加载仪表盘概览数据
 */
async function loadOverviewData() {
  overviewLoading.value = true
  try {
    const response = await getDashboardOverview()
    if (response.code === 0 && response.data) {
      overviewData.value = response.data
    } else {
      ElMessage.warning(response.message || '获取概览数据失败')
      // 降级展示默认值
      overviewData.value = null
    }
  } catch (error: unknown) {
    console.error('加载概览数据失败:', error)
    // 根据错误类型显示不同提示
    if (error instanceof Error) {
      if (error.message.includes('403') || error.message.includes('权限')) {
        ElMessage.error('无权限访问此页面')
      } else if (error.message.includes('network') || error.message.includes('Network')) {
        ElMessage.error('网络连接失败，请检查网络')
      } else {
        ElMessage.error('服务器繁忙，请稍后重试')
      }
    } else {
      ElMessage.error('获取概览数据失败')
    }
    // 降级展示默认值
    overviewData.value = null
  } finally {
    overviewLoading.value = false
  }
}

// ==================== 系统统计数据 ====================

const stats = ref({
  userCount: 0,
  roleCount: 0,
  menuCount: 0,
  departmentCount: 0
})

const loginTime = ref(new Date().toLocaleString())

onMounted(() => {
  // 加载业务概览数据
  loadOverviewData()
  
  // 模拟系统统计数据，实际应从 API 获取
  stats.value = {
    userCount: 1,
    roleCount: 1,
    menuCount: 5,
    departmentCount: 1
  }
})
</script>

<style scoped>
.dashboard-container {
  padding: 0;
}

/* ==================== 数据概览卡片样式 ==================== */

.overview-cards {
  margin-bottom: 20px;
}

.overview-card {
  display: flex;
  align-items: center;
  padding: 24px;
  border-radius: var(--border-radius-large, 8px);
  color: #fff;
  transition: all 0.3s ease;
  cursor: default;
  min-height: 100px;
}

.overview-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.overview-card-icon {
  width: 64px;
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  margin-right: 16px;
  flex-shrink: 0;
}

.overview-card-content {
  flex: 1;
  min-width: 0;
}

.overview-card-value {
  font-size: 28px;
  font-weight: bold;
  line-height: 1.2;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.overview-card-label {
  font-size: 14px;
  opacity: 0.9;
  margin-top: 4px;
}

/* 响应式布局调整 */
@media (max-width: 768px) {
  .overview-card {
    padding: 16px;
    min-height: 80px;
  }
  
  .overview-card-icon {
    width: 48px;
    height: 48px;
  }
  
  .overview-card-value {
    font-size: 22px;
  }
  
  .overview-card-label {
    font-size: 12px;
  }
}

/* ==================== 系统统计卡片样式 ==================== */

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  transition: all var(--transition-duration) var(--transition-timing);
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: var(--box-shadow-dark);
}

.stat-card :deep(.el-card__body) {
  display: flex;
  align-items: center;
  width: 100%;
}

.stat-icon {
  width: 64px;
  height: 64px;
  border-radius: var(--border-radius-large);
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-white);
  margin-right: 16px;
}

.stat-icon-primary {
  background: linear-gradient(135deg, var(--primary-light) 0%, var(--primary-color) 100%);
}

.stat-icon-success {
  background: linear-gradient(135deg, #95d475 0%, var(--success-color) 100%);
}

.stat-icon-warning {
  background: linear-gradient(135deg, #f0c78a 0%, var(--warning-color) 100%);
}

.stat-icon-danger {
  background: linear-gradient(135deg, #f89898 0%, var(--danger-color) 100%);
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: var(--text-primary);
}

.stat-label {
  font-size: 14px;
  color: var(--text-secondary);
  margin-top: 4px;
}

.welcome-content {
  padding: 20px 0;
}

.welcome-content h2 {
  margin: 0 0 16px 0;
  color: var(--primary-color);
}

.welcome-content p {
  margin: 8px 0;
  color: var(--text-regular);
}

.quick-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

:deep(.el-card__header) {
  background-color: var(--bg-light);
  border-bottom: 1px solid var(--border-lighter);
  font-weight: 500;
  color: var(--text-primary);
}
</style>
