<template>
  <div class="dashboard-container">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12" :md="6" v-for="(item, index) in statCards" :key="index">
        <el-card shadow="hover" class="stat-card-item">
          <div class="stat-card-content">
            <div class="stat-icon-wrapper" :style="{ background: item.color }">
              <el-icon :size="24" color="#fff"><component :is="item.icon" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-label">{{ item.label }}</div>
              <div class="stat-value">
                {{ item.value }}
              </div>
            </div>
          </div>
          <div class="stat-card-footer">
            <span>较昨日</span>
            <span :class="item.trend >= 0 ? 'trend-up' : 'trend-down'">
              {{ Math.abs(item.trend) }}%
              <el-icon><component :is="item.trend >= 0 ? 'CaretTop' : 'CaretBottom'" /></el-icon>
            </span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 中部图表和快捷入口 -->
    <el-row :gutter="20" class="mt-20">
      <el-col :xs="24" :lg="16">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>访问趋势</span>
              <el-radio-group v-model="chartPeriod" size="small">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-wrapper">
             <line-chart :chart-data="lineChartData" />
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="8">
        <el-card shadow="hover" class="quick-entry-card">
          <template #header>
            <div class="card-header">
              <span>快捷导航</span>
            </div>
          </template>
          <div class="quick-nav-grid">
            <div 
              v-for="item in quickLinks" 
              :key="item.path" 
              class="quick-nav-item"
              @click="goRoute(item.path)"
            >
              <div class="nav-icon" :style="{ background: item.bg }">
                <el-icon :size="20" :color="item.color"><component :is="item.icon" /></el-icon>
              </div>
              <span class="nav-label">{{ item.name }}</span>
            </div>
          </div>
        </el-card>
        
        <el-card shadow="hover" class="mt-20 system-info-card">
          <template #header>
            <div class="card-header">
              <span>系统概览</span>
              <el-tag size="small" effect="plain">v3.9.0</el-tag>
            </div>
          </template>
          <div class="info-list">
            <div class="info-item">
              <span class="label">Vue版本</span>
              <span class="value">3.x</span>
            </div>
            <div class="info-item">
              <span class="label">Element Plus</span>
              <span class="value">2.x</span>
            </div>
            <div class="info-item">
              <span class="label">Vite</span>
              <span class="value">5.x</span>
            </div>
            <div class="info-item">
              <span class="label">当前环境</span>
              <span class="value">{{ env }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 底部项目介绍 -->
    <el-row :gutter="20" class="mt-20">
      <el-col :span="24">
        <el-card shadow="hover" class="project-card">
          <div class="project-intro">
            <div class="project-logo">
              <img src="@/assets/logo/logo.png" alt="logo" />
            </div>
            <div class="project-desc">
              <h3>予书后台管理系统</h3>
              <p>一款基于 Vue3 + Vite + Element Plus 的现代化后台管理系统。提供丰富的组件和功能，开箱即用，助力开发者快速构建高质量的 Web 应用。</p>
              <div class="project-actions">
                <el-button type="primary" icon="Promotion" @click="goTarget('http://yushu.vip')">访问官网</el-button>
                <el-button icon="Star" @click="goTarget('https://gitee.com/y_project/yushu-Vue')">Gitee Star</el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Index">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  User, ChatDotRound, Folder, Monitor, Setting, Document, Bell, ChatLineRound,
  CaretTop, CaretBottom, Promotion, Star, DataLine, Goods, Reading
} from '@element-plus/icons-vue'
import LineChart from './dashboard/LineChart.vue'
import { getDashboardStats, getVisitsTrend } from '@/api/system/statistics'

const router = useRouter()
const env = import.meta.env.MODE
const loading = ref(false)

// 统计数据
const statCards = ref([
  { label: '用户总数', value: 0, icon: 'User', color: '#409eff', trend: 0 },
  { label: '消息数量', value: 0, icon: 'ChatDotRound', color: '#67c23a', trend: 0 },
  { label: '文件数量', value: 0, icon: 'Folder', color: '#e6a23c', trend: 0 },
  { label: '今日访问', value: 0, icon: 'Monitor', color: '#f56c6c', trend: 0 }
])

// 图表数据
const chartPeriod = ref('week')
const lineChartData = ref({
  expectedData: [0, 0, 0, 0, 0, 0, 0],
  actualData: [0, 0, 0, 0, 0, 0, 0]
})

// 快捷入口
const quickLinks = ref([
  { name: '用户管理', path: '/system/user', icon: 'User', color: '#409eff', bg: '#ecf5ff' },
  { name: '角色管理', path: '/system/role', icon: 'UserFilled', color: '#67c23a', bg: '#f0f9eb' },
  { name: '菜单管理', path: '/system/menu', icon: 'Menu', color: '#e6a23c', bg: '#fdf6ec' },
  { name: '文件管理', path: '/file', icon: 'Folder', color: '#f56c6c', bg: '#fef0f0' },
  { name: '消息中心', path: '/message', icon: 'ChatDotRound', color: '#409eff', bg: '#ecf5ff' },
  { name: '通知公告', path: '/system/notice', icon: 'Bell', color: '#e6a23c', bg: '#fdf6ec' },
  { name: '操作日志', path: '/system/log/operlog', icon: 'Document', color: '#909399', bg: '#f4f4f5' },
  { name: 'AI 对话', path: '/ai/chat', icon: 'ChatLineRound', color: '#764ba2', bg: '#f8f5fa' }
])

/** 加载统计数据 */
async function loadDashboardStats() {
  loading.value = true
  try {
    const res = await getDashboardStats()
    if (res.code === 200 && res.data) {
      const data = res.data
      const trends = data.trends || {}
      
      statCards.value[0].value = data.userCount || 0
      statCards.value[0].trend = trends.userTrend || 0
      
      statCards.value[1].value = data.messageCount || 0
      statCards.value[1].trend = trends.messageTrend || 0
      
      statCards.value[2].value = data.fileCount || 0
      statCards.value[2].trend = trends.fileTrend || 0
      
      statCards.value[3].value = data.todayVisits || 0
      statCards.value[3].trend = trends.visitTrend || 0
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  } finally {
    loading.value = false
  }
}

/** 加载访问趋势 */
async function loadVisitsTrend() {
  try {
    const res = await getVisitsTrend()
    if (res.code === 200 && res.data && res.data.data) {
      const trendData = res.data.data
      const actualData = new Array(7).fill(0)
      trendData.forEach((item, index) => {
        if (index < 7) {
          actualData[index] = item.count || 0
        }
      })
      lineChartData.value.actualData = actualData
      lineChartData.value.expectedData = actualData.map(v => Math.round(v * 1.1))
    }
  } catch (error) {
    console.error('加载访问趋势失败:', error)
  }
}

function goTarget(url) {
  window.open(url, '_blank')
}

function goRoute(path) {
  router.push(path)
}

onMounted(() => {
  loadDashboardStats()
  loadVisitsTrend()
})
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100vh;
  
  .mt-20 {
    margin-top: 20px;
  }
}

.stat-card-item {
  margin-bottom: 20px;
  border: none;
  
  :deep(.el-card__body) {
    padding: 20px;
  }

  .stat-card-content {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    
    .stat-icon-wrapper {
      width: 48px;
      height: 48px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;
      box-shadow: 0 4px 10px rgba(0,0,0,0.1);
    }
    
    .stat-info {
      .stat-label {
        font-size: 14px;
        color: #909399;
        margin-bottom: 4px;
      }
      .stat-value {
        font-size: 24px;
        font-weight: 600;
        color: #303133;
      }
    }
  }
  
  .stat-card-footer {
    border-top: 1px solid #ebeef5;
    padding-top: 12px;
    font-size: 12px;
    color: #909399;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .trend-up {
      color: #67c23a;
      display: flex;
      align-items: center;
    }
    
    .trend-down {
      color: #f56c6c;
      display: flex;
      align-items: center;
    }
  }
}

.chart-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .chart-wrapper {
    height: 350px;
  }
}

.quick-entry-card {
  .quick-nav-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    
    .quick-nav-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      cursor: pointer;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
      }
      
      .nav-icon {
        width: 40px;
        height: 40px;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 8px;
      }
      
      .nav-label {
        font-size: 12px;
        color: #606266;
      }
    }
  }
}

.system-info-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .info-list {
    .info-item {
      display: flex;
      justify-content: space-between;
      padding: 12px 0;
      border-bottom: 1px solid #f0f2f5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .label {
        color: #909399;
        font-size: 14px;
      }
      
      .value {
        color: #303133;
        font-weight: 500;
        font-size: 14px;
      }
    }
  }
}

.project-card {
  .project-intro {
    display: flex;
    align-items: center;
    gap: 32px;
    padding: 10px;
    
    .project-logo {
      img {
        width: 80px;
        height: 80px;
      }
    }
    
    .project-desc {
      h3 {
        margin: 0 0 12px 0;
        font-size: 20px;
        color: #303133;
      }
      
      p {
        margin: 0 0 20px 0;
        color: #606266;
        line-height: 1.6;
      }
      
      .project-actions {
        display: flex;
        gap: 12px;
      }
    }
  }
}

@media (max-width: 768px) {
  .project-intro {
    flex-direction: column;
    text-align: center;
    
    .project-actions {
      justify-content: center;
    }
  }
}
</style>
