<template>
  <div class="admin-overview">
    <div class="stat-cards">
      <div class="stat-card">
        <div class="stat-icon users-icon">👥</div>
        <div class="stat-content">
          <h3>在线用户</h3>
          <div class="stat-value">{{ stats.onlineUsers }}</div>
          <div class="stat-description">当前在线用户数</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon posts-icon">📝</div>
        <div class="stat-content">
          <h3>帖子总数</h3>
          <div class="stat-value">{{ stats.totalPosts }}</div>
          <div class="stat-description">
            今日新增: 
            <span class="text-success">+{{ stats.todayPosts }}</span>
          </div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon comments-icon">💬</div>
        <div class="stat-content">
          <h3>评论总数</h3>
          <div class="stat-value">{{ stats.totalComments }}</div>
          <div class="stat-description">
            今日新增: 
            <span class="text-success">+{{ stats.todayComments }}</span>
          </div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon users-total-icon">👤</div>
        <div class="stat-content">
          <h3>用户总数</h3>
          <div class="stat-value">{{ stats.totalUsers }}</div>
          <div class="stat-description">
            今日注册: 
            <span class="text-success">+{{ stats.todayUsers }}</span>
          </div>
        </div>
      </div>
    </div>
    
    <div class="admin-charts">
      <div class="chart-card">
        <div class="card-header">
          <h3>过去7天活跃度</h3>
        </div>
        <div class="chart-container">
          <!-- 简单图表展示 - 实际中可以使用ECharts等库 -->
          <div class="simple-chart">
            <div 
              v-for="(value, day) in activityData" 
              :key="day" 
              class="chart-bar"
              :style="{ height: `${value * 2}px` }"
              :title="`${day}: ${value}人`"
            ></div>
          </div>
          <div class="chart-labels">
            <span v-for="day in Object.keys(activityData)" :key="day">{{ day }}</span>
          </div>
        </div>
      </div>
      
      <div class="chart-card">
        <div class="card-header">
          <h3>分类数据统计</h3>
        </div>
        <div class="category-stats">
          <table class="stats-table">
            <thead>
              <tr>
                <th>分类名称</th>
                <th>帖子数量</th>
                <th>占比</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(category, index) in categoryStats" :key="index">
                <td>{{ category.name }}</td>
                <td>{{ category.count }}</td>
                <td>
                  <div class="progress-bar">
                    <div 
                      class="progress-fill" 
                      :style="{ width: `${category.percentage}%` }"
                    ></div>
                    <span>{{ category.percentage }}%</span>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    
    <div class="admin-tables">
      <div class="table-card">
        <div class="card-header">
          <h3>最新帖子</h3>
          <router-link to="/admin/posts" class="view-all">查看全部</router-link>
        </div>
        <table class="data-table">
          <thead>
            <tr>
              <th>标题</th>
              <th>作者</th>
              <th>分类</th>
              <th>发布时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(post, index) in latestPosts" :key="index">
              <td class="title-cell">{{ post.title }}</td>
              <td>{{ post.author }}</td>
              <td>{{ post.category }}</td>
              <td>{{ formatDate(post.createTime) }}</td>
              <td>
                <button class="action-btn view-btn" @click="viewPost(post.id)">查看</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <div class="table-card">
        <div class="card-header">
          <h3>最新用户</h3>
          <router-link to="/admin/users" class="view-all">查看全部</router-link>
        </div>
        <table class="data-table">
          <thead>
            <tr>
              <th>用户名</th>
              <th>注册时间</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(user, index) in latestUsers" :key="index">
              <td>{{ user.username }}</td>
              <td>{{ formatDate(user.createTime) }}</td>
              <td>
                <span 
                  class="status-badge" 
                  :class="user.status === 1 ? 'status-active' : 'status-frozen'"
                >
                  {{ user.status === 1 ? '正常' : '冻结' }}
                </span>
              </td>
              <td>
                <button class="action-btn view-btn" @click="viewUser(user.id)">查看</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

const router = useRouter();

// 统计数据
const stats = ref({
  onlineUsers: 0,
  totalPosts: 0,
  todayPosts: 0,
  totalComments: 0,
  todayComments: 0,
  totalUsers: 0,
  todayUsers: 0
});

// 活跃度数据
const activityData = ref({
  '周一': 45,
  '周二': 32,
  '周三': 38,
  '周四': 51,
  '周五': 68,
  '周六': 82,
  '周日': 56
});

// 分类统计
const categoryStats = ref([
  { name: '学习', count: 156, percentage: 45 },
  { name: '娱乐', count: 89, percentage: 25 },
  { name: '二手交易', count: 67, percentage: 20 },
  { name: '求助', count: 34, percentage: 10 }
]);

// 最新帖子
const latestPosts = ref([]);

// 最新用户
const latestUsers = ref([]);

// 加载数据
const loadDashboardData = async () => {
  try {
    // 加载统计数据
    const statsResponse = await axios.get('/api/admin/stats');
    if (statsResponse.data.code === 0) {
      stats.value = statsResponse.data.data;
    }
    
    // 加载最新帖子
    const postsResponse = await axios.get('/api/admin/posts/latest');
    if (postsResponse.data.code === 0) {
      latestPosts.value = postsResponse.data.data;
    }
    
    // 加载最新用户
    const usersResponse = await axios.get('/api/admin/users/latest');
    if (usersResponse.data.code === 0) {
      latestUsers.value = usersResponse.data.data;
    }
    
    // 模拟数据，实际开发中替换为真实数据
    simulateData();
  } catch (error) {
    console.error('加载数据失败', error);
  }
};

// 模拟数据（开发阶段使用，实际对接API后移除）
const simulateData = () => {
  stats.value = {
    onlineUsers: 238,
    totalPosts: 1356,
    todayPosts: 24,
    totalComments: 8754,
    todayComments: 132,
    totalUsers: 4568,
    todayUsers: 15
  };
  
  latestPosts.value = [
    { id: 1, title: '武汉大学2023年度招生简章', author: '大学新闻', category: '学习', createTime: '2023-06-15T08:30:00' },
    { id: 2, title: '求推荐计算机专业课程的参考书', author: 'CS爱好者', category: '学习', createTime: '2023-06-14T16:45:00' },
    { id: 3, title: '樱花节摄影作品分享', author: '摄影达人', category: '娱乐', createTime: '2023-06-14T14:20:00' },
    { id: 4, title: '出售全新未拆封的iPhone 14', author: '数码控', category: '二手交易', createTime: '2023-06-14T10:15:00' },
    { id: 5, title: '武大食堂美食推荐', author: '吃货代表', category: '生活', createTime: '2023-06-13T19:40:00' }
  ];
  
  latestUsers.value = [
    { id: 101, username: '新同学2023', createTime: '2023-06-15T09:20:00', status: 1 },
    { id: 102, username: '学习达人', createTime: '2023-06-14T18:30:00', status: 1 },
    { id: 103, username: '校园生活家', createTime: '2023-06-14T15:45:00', status: 1 },
    { id: 104, username: '毕业季节', createTime: '2023-06-14T12:10:00', status: 2 },
    { id: 105, username: '樱花摄影', createTime: '2023-06-13T20:25:00', status: 1 }
  ];
};

// 查看帖子
const viewPost = (id) => {
  router.push(`/post/${id}`);
};

// 查看用户
const viewUser = (id) => {
  router.push(`/admin/users?id=${id}`);
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

onMounted(() => {
  loadDashboardData();
});
</script>

<style scoped>
.admin-overview {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 统计卡片样式 */
.stat-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  background-color: #e8f5e9;
  color: #54ac52;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.users-icon {
  background-color: #e3f2fd;
  color: #1976d2;
}

.posts-icon {
  background-color: #f9fbe7;
  color: #afb42b;
}

.comments-icon {
  background-color: #fff8e1;
  color: #ffb300;
}

.users-total-icon {
  background-color: #e8eaf6;
  color: #3f51b5;
}

.stat-content {
  flex: 1;
}

.stat-content h3 {
  margin: 0 0 5px 0;
  font-size: 14px;
  color: #666;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.stat-description {
  font-size: 12px;
  color: #888;
}

.text-success {
  color: #4caf50;
}

/* 图表卡片样式 */
.admin-charts {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.chart-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.chart-container {
  height: 200px;
  display: flex;
  flex-direction: column;
}

/* 简易图表样式 */
.simple-chart {
  flex: 1;
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  gap: 8px;
  padding-bottom: 10px;
}

.chart-bar {
  flex: 1;
  background-color: #54ac52;
  border-radius: 3px 3px 0 0;
  transition: height 0.5s;
}

.chart-labels {
  display: flex;
  justify-content: space-between;
}

.chart-labels span {
  flex: 1;
  text-align: center;
  font-size: 12px;
  color: #666;
}

/* 分类统计表格 */
.category-stats {
  max-height: 200px;
  overflow-y: auto;
}

.stats-table {
  width: 100%;
  border-collapse: collapse;
}

.stats-table th, .stats-table td {
  padding: 10px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.stats-table th {
  font-weight: bold;
  color: #333;
  background-color: #f9f9f9;
}

.progress-bar {
  height: 10px;
  background-color: #f1f1f1;
  border-radius: 5px;
  position: relative;
  width: 100%;
  display: flex;
  align-items: center;
}

.progress-fill {
  height: 100%;
  background-color: #54ac52;
  border-radius: 5px;
  position: absolute;
  left: 0;
  top: 0;
}

.progress-bar span {
  position: relative;
  font-size: 12px;
  margin-left: 10px;
  color: #666;
}

/* 数据表格样式 */
.admin-tables {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.table-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.view-all {
  color: #54ac52;
  font-size: 14px;
  text-decoration: none;
}

.view-all:hover {
  text-decoration: underline;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th, .data-table td {
  padding: 10px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  font-weight: bold;
  color: #333;
  background-color: #f9f9f9;
}

.title-cell {
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 10px;
  font-size: 12px;
  font-weight: bold;
}

.status-active {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.status-frozen {
  background-color: #ffebee;
  color: #c62828;
}

.action-btn {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.view-btn {
  background-color: #e3f2fd;
  color: #1976d2;
}

.view-btn:hover {
  background-color: #bbdefb;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .stat-cards, .admin-charts, .admin-tables {
    grid-template-columns: 1fr;
  }
}
</style> 