<template>
  <div class="home-container">
    <h2>欢迎回来，{{ username }}</h2>
    
    <!-- 系统统计卡片 -->
    <div class="stats-container">
            
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon department-icon">
            <el-icon><OfficeBuilding /></el-icon>
          </div>
          <div class="stat-info">
            <h3>{{ totalUserCount }}</h3>
            <p>总用户数</p>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon user-icon">
            <el-icon><User /></el-icon>
          </div>
          <div class="stat-info">
            <h3>{{ activeUserCount }}</h3>
            <p>活跃用户</p>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon conversation-icon">
            <el-icon><Message /></el-icon>
          </div>
          <div class="stat-info">
            <h3>{{ totalConversationCount }}</h3>
            <p>会话记录</p>
          </div>
        </div>
      </el-card>

      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon today-icon">
            <el-icon><Calendar /></el-icon>
          </div>
          <div class="stat-info">
            <h3>{{ todayNewConversationCount }}</h3>
            <p>今日会话</p>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 最近会话记录 -->
    <el-card class="recent-conversations-card">
      <template #header>
        <div class="card-header">
          <span>最近会话记录</span>
          <router-link to="/conversations" class="view-all-link">
            查看全部
            <el-icon class="el-icon--right"><ArrowRight /></el-icon>
          </router-link>
        </div>
      </template>
      
      <el-table
        :data="recentConversations"
        style="width: 100%"
        stripe
        size="small"
        :empty-text="'暂无会话记录'"
        max-height="300"
      >
        <el-table-column prop="recordTime" label="时间" width="160"></el-table-column>
        <el-table-column prop="userName" label="用户名" width="70"></el-table-column>
        <el-table-column prop="conversationContent" label="内容" min-width="300" show-overflow-tooltip></el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { User, Message, OfficeBuilding, Calendar, ArrowRight } from '@element-plus/icons-vue'
import { useAuthStore } from '../store/auth'
import request from '../utils/request'
import { ElMessage } from 'element-plus'

// 认证状态管理
const authStore = useAuthStore()

// 用户名
const username = computed(() => authStore.username)

// 统计数据
const activeUserCount = ref(0)
const totalConversationCount = ref(0)
const totalUserCount = ref(0)
const todayNewConversationCount = ref(0)

// 最近会话记录
const recentConversations = ref([])


// 获取系统统计数据
const fetchStats = async () => {
  try {
    const res = await request.get('/Admin/QueryStats')
    const stats = res?.data ?? res

    activeUserCount.value = stats?.activeUsers ?? 0
    totalConversationCount.value = stats?.totalConversations ?? 0
    totalUserCount.value = stats?.totalUsers ?? 0
    todayNewConversationCount.value = stats?.todayNewConversations ?? 0
    
    // 获取最近会话记录
    await fetchRecentConversations()
  } catch (error) {
    console.error('获取系统统计数据失败：', error)
    ElMessage.error('获取系统统计数据失败')
  }
}

// 获取最近会话记录
const fetchRecentConversations = async () => {
  try {
    const params = {
      startTime: null,
      endTime: null,
      userKey: '',
      messageType: null,
      department: '',
      page: 1,
      pageSize: 8
    }

    // 调用API获取会话记录
    const data = await request.post('/Admin/QueryConversations', JSON.stringify(params))

    // 检查返回数据格式，确保是数组
    const rawData = Array.isArray(data) ? data : data.data || []
    
    // 按时间排序（最新的记录在前面），并只显示最近5条
    recentConversations.value = rawData
      .sort((a, b) => {
        return b.recordTimeUTCStamp - a.recordTimeUTCStamp
      })
      .slice(0, 10)
  } catch (error) {
    console.error('获取最近会话记录失败：', error)
    recentConversations.value = []
  }
}

// 页面初始化
onMounted(() => {
  fetchStats()
})
</script>

<style scoped>
.home-container {
  padding: 20px 0;
}

.stats-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: var(--box-shadow-light);
  }
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  color: #ffffff;
}

.user-icon {
  background-color: var(--primary-color);
}

.conversation-icon {
  background-color: var(--success-color);
}

.department-icon {
  background-color: var(--warning-color);
}

.today-icon {
  background-color: var(--danger-color);
}

.stat-info h3 {
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 4px 0;
  color: var(--text-color);
}

.stat-info p {
  font-size: 14px;
  margin: 0;
  color: var(--text-color-secondary);
}

.recent-conversations-card {
  margin-bottom: 20px;
}

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

.view-all-link {
  color: var(--primary-color);
  text-decoration: none;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 4px;
  
  &:hover {
    color: #66b1ff;
  }
}

.system-status-container {
  margin-bottom: 20px;
}

.status-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid var(--border-color-light);
  
  &:last-child {
    border-bottom: none;
  }
}

.status-label {
  color: var(--text-color-secondary);
  font-size: 14px;
}

.status-value {
  color: var(--text-color);
  font-size: 14px;
  font-weight: 500;
}

/* 响应式样式 */
@media (max-width: 767px) {
  .home-container {
    padding: 6px 0;
  }
  
  .stats-container {
    grid-template-columns: 1fr 1fr;
    gap: 16px;
  }
  
  .stat-content {
    gap: 12px;
  }
  
  .stat-icon {
    width: 50px;
    height: 50px;
    font-size: 20px;
  }
  
  .stat-info h3 {
    font-size: 24px;
  }
  
  .status-list {
    grid-template-columns: 1fr;
  }
}
</style>
