<template>
  <div class="home-container">
    <!-- 欢迎信息卡片 -->
    <el-card class="welcome-card">
      <template #header>
        <div class="welcome-header">
          <span>欢迎使用</span>
          <el-dropdown>
            <span class="el-dropdown-link">
              功能快捷入口<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-if="data.user.role === 'admin'" @click="router.push('/manager/admin')">用户管理</el-dropdown-item>
                <el-dropdown-item v-if="data.user.role === 'admin' || data.user.role === 'doctor'" @click="router.push('/manager/patient')">患者管理</el-dropdown-item>
                <el-dropdown-item v-if="data.user.role === 'patient'" @click="router.push('/manager/doctor')">医生列表</el-dropdown-item>
                <el-dropdown-item @click="router.push('/manager/password')">修改密码</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </template>
      <div class="welcome-content">
        <div class="welcome-left">
          <img 
            v-if="data.user.avatar" 
            :src="data.user.avatar" 
            alt="用户头像" 
            class="user-avatar"
          />
          <img 
            v-else 
            src="@/assets/imgs/avatar.png" 
            alt="默认头像" 
            class="user-avatar"
          />
        </div>
        <div class="welcome-right">
          <h2>您好，{{ data.user.name }}！</h2>
          <p>角色：{{ getRoleName(data.user.role) }}</p>
          <p>上次登录时间：{{ formatDate(new Date()) }}</p>
          <div class="welcome-buttons">
            <el-button type="primary" @click="router.push('/manager/password')">修改密码</el-button>
            <el-button v-if="data.user.role === 'patient'" type="success" @click="router.push('/manager/symptomRecord')">记录症状</el-button>
            <el-button v-if="data.user.role === 'doctor'" type="success" @click="router.push('/manager/symptomStatistics')">症状分析</el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 添加最新公告区域 -->
    <el-card class="announcement-card">
      <template #header>
        <div class="card-header">
          <span>最新公告</span>
          <el-button class="more-btn" text @click="router.push('/manager/announcementList')">查看更多</el-button>
        </div>
      </template>
      <div class="announcement-list">
        <el-empty v-if="data.announcements.length === 0" description="暂无公告"></el-empty>
        <el-card 
          v-for="item in data.announcements" 
          :key="item.id" 
          class="announcement-item" 
          shadow="hover"
          @click="viewAnnouncement(item)"
        >
          <div class="announcement-title">
            <el-tag v-if="item.isTop" type="danger" size="small" class="top-tag">置顶</el-tag>
            {{ item.title }}
          </div>
          <div class="announcement-info">
            <span class="publisher">发布人: {{ item.publisherName }}</span>
            <span class="time">{{ item.createTime }}</span>
          </div>
        </el-card>
      </div>
    </el-card>

    <!-- 资源使用情况统计卡片 -->
    <div class="section-title">心理资源使用情况</div>
    <div class="stat-container">
      <el-card class="stat-card" shadow="hover">
        <div class="card-header">
          <span>资源总数</span>
          <el-icon><Files /></el-icon>
        </div>
        <div class="stat-number">{{ data.stats.totalResources || 0 }}</div>
        <div class="stat-label">当前系统中的资源总数</div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="card-header">
          <span>总访问次数</span>
          <el-icon><View /></el-icon>
        </div>
        <div class="stat-number">{{ data.stats.totalVisits || 0 }}</div>
        <div class="stat-label">资源被查看的总次数</div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="card-header">
          <span>总下载次数</span>
          <el-icon><Download /></el-icon>
        </div>
        <div class="stat-number">{{ data.stats.totalDownloads || 0 }}</div>
        <div class="stat-label">资源被下载的总次数</div>
      </el-card>
    </div>

    <!-- 使用情况图表 -->
    <div class="charts-row">
      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="chart-header">
            <span>资源分类占比</span>
          </div>
        </template>
        <div ref="categoryPieRef" style="height: 300px;"></div>
      </el-card>

      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="chart-header">
            <span>访问/下载统计</span>
          </div>
        </template>
        <div ref="visitDownloadBarRef" style="height: 300px;"></div>
      </el-card>
    </div>

    <!-- 热门资源排行 -->
    <div class="charts-row">
      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="chart-header">
            <span>访问量排行TOP5</span>
          </div>
        </template>
        <div class="rank-list">
          <div v-for="(item, index) in data.stats.topVisitResources" :key="index" class="rank-item">
            <div class="rank-index">{{ index + 1 }}</div>
            <div class="rank-content">
              <div class="rank-title">{{ item.title }}</div>
              <div class="rank-count">{{ item.visitCount || 0 }} 次访问</div>
            </div>
            <div class="rank-progress">
              <el-progress :percentage="calculatePercentage(item.visitCount, data.stats.topVisitResources[0]?.visitCount)" 
                :stroke-width="8" :show-text="false" />
            </div>
          </div>
        </div>
      </el-card>

      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="chart-header">
            <span>下载量排行TOP5</span>
          </div>
        </template>
        <div class="rank-list">
          <div v-for="(item, index) in data.stats.topDownloadResources" :key="index" class="rank-item">
            <div class="rank-index">{{ index + 1 }}</div>
            <div class="rank-content">
              <div class="rank-title">{{ item.title }}</div>
              <div class="rank-count">{{ item.downloadCount || 0 }} 次下载</div>
            </div>
            <div class="rank-progress">
              <el-progress :percentage="calculatePercentage(item.downloadCount, data.stats.topDownloadResources[0]?.downloadCount)" 
                :stroke-width="8" :show-text="false" :color="'#409EFF'" />
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 公告详情对话框 -->
    <el-dialog 
      v-model="data.viewDialogVisible" 
      title="公告详情" 
      width="65%"
    >
      <h2 style="text-align: center; margin-bottom: 20px">{{ data.viewAnnouncement.title }}</h2>
      <div style="text-align: center; color: #999; margin-bottom: 20px">
        发布人: {{ data.viewAnnouncement.publisherName }} | 发布时间: {{ data.viewAnnouncement.createTime }}
      </div>
      <div class="content-container" v-html="data.viewAnnouncement.content"></div>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, onMounted, ref } from "vue";
import { Histogram, Files, View, Download, ArrowDown } from "@element-plus/icons-vue";
import * as echarts from 'echarts';
import request from '@/utils/request';
import router from '@/router';
import { ElMessage } from 'element-plus';

// ECharts引用
const categoryPieRef = ref(null);
const visitDownloadBarRef = ref(null);

// 图表实例
let categoryPieChart = null;
let visitDownloadBarChart = null;

const data = reactive({
  user: JSON.parse(localStorage.getItem("xm-user") || "{}"),
  stats: {
    totalResources: 0,
    totalVisits: 0,
    totalDownloads: 0,
    countByCategory: {},
    visitsByCategory: {},
    downloadsByCategory: {},
    topVisitResources: [],
    topDownloadResources: []
  },
  categoryNames: {},
  announcements: [],
  viewDialogVisible: false,
  viewAnnouncement: {}
});

// 获取角色标签
const getRoleName = (role) => {
  const roleMap = {
    'admin': '管理员',
    'doctor': '医生',
    'patient': '患者'
  };
  return roleMap[role] || role;
};

// 加载资源分类名称
const loadCategoryNames = async () => {
  try {
    const res = await request.get('/resourceCategory');
    if (res.code === '200') {
      const categories = res.data || [];
      categories.forEach(category => {
        data.categoryNames[category.id] = category.name;
      });
    }
  } catch (error) {
    console.error('加载资源分类失败', error);
  }
};

// 加载资源使用情况统计数据
const loadResourceStats = async () => {
  try {
    const res = await request.get('/treatmentResource/statistics');
    if (res.code === '200') {
      data.stats = res.data;
      
      // 渲染图表
      renderCategoryPie();
      renderVisitDownloadBar();
    }
  } catch (error) {
    console.error('加载资源统计数据失败', error);
  }
};

// 渲染资源分类占比饼图
const renderCategoryPie = () => {
  if (!categoryPieRef.value) return;
  
  if (!categoryPieChart) {
    categoryPieChart = echarts.init(categoryPieRef.value);
  }
  
  const pieData = [];
  for (const [categoryId, count] of Object.entries(data.stats.countByCategory)) {
    pieData.push({
      name: data.categoryNames[categoryId] || `分类${categoryId}`,
      value: count
    });
  }
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: pieData.map(item => item.name)
    },
    series: [
      {
        name: '资源分类',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: pieData
      }
    ]
  };
  
  categoryPieChart.setOption(option);
};

// 渲染访问下载统计条形图
const renderVisitDownloadBar = () => {
  if (!visitDownloadBarRef.value) return;
  
  if (!visitDownloadBarChart) {
    visitDownloadBarChart = echarts.init(visitDownloadBarRef.value);
  }
  
  const categories = [];
  const visitData = [];
  const downloadData = [];
  
  // 获取所有分类ID
  const categoryIds = new Set([
    ...Object.keys(data.stats.visitsByCategory), 
    ...Object.keys(data.stats.downloadsByCategory)
  ]);
  
  categoryIds.forEach(categoryId => {
    categories.push(data.categoryNames[categoryId] || `分类${categoryId}`);
    visitData.push(data.stats.visitsByCategory[categoryId] || 0);
    downloadData.push(data.stats.downloadsByCategory[categoryId] || 0);
  });
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['访问次数', '下载次数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: categories
    },
    series: [
      {
        name: '访问次数',
        type: 'bar',
        stack: 'total',
        label: {
          show: true
        },
        emphasis: {
          focus: 'series'
        },
        data: visitData,
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: '下载次数',
        type: 'bar',
        stack: 'total',
        label: {
          show: true
        },
        emphasis: {
          focus: 'series'
        },
        data: downloadData,
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
  };
  
  visitDownloadBarChart.setOption(option);
};

// 计算排行榜进度条百分比
const calculatePercentage = (value, maxValue) => {
  if (!value || !maxValue) return 0;
  return Math.floor((value / maxValue) * 100);
};

// 监听窗口大小变化，重绘图表
window.addEventListener('resize', () => {
  if (categoryPieChart) categoryPieChart.resize();
  if (visitDownloadBarChart) visitDownloadBarChart.resize();
});

// 加载最新公告
const loadLatestAnnouncements = async () => {
  try {
    const res = await request.get('/announcement/latest', {
      params: { limit: 5 }
    });
    
    if (res.code === '200') {
      data.announcements = res.data;
    } else {
      ElMessage.error(res.msg || '获取公告失败');
    }
  } catch (error) {
    console.error('加载公告出错', error);
  }
};

// 查看公告详情
const viewAnnouncement = (announcement) => {
  data.viewAnnouncement = announcement;
  data.viewDialogVisible = true;
};

const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

onMounted(async () => {
  await loadCategoryNames();
  await loadResourceStats();
  await loadLatestAnnouncements();
});
</script>

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

.welcome-card {
  margin-bottom: 20px;
}

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

.welcome-content {
  display: flex;
  align-items: center;
}

.welcome-left {
  margin-right: 20px;
}

.user-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.welcome-right h2 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #303133;
}

.welcome-right p {
  margin: 5px 0;
  color: #606266;
}

.welcome-buttons {
  margin-top: 15px;
}

/* 公告相关样式 */
.announcement-card {
  margin-bottom: 20px;
}

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

.announcement-list {
  max-height: 300px;
  overflow-y: auto;
}

.announcement-item {
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.announcement-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.announcement-item:last-child {
  margin-bottom: 0;
}

.announcement-title {
  display: flex;
  align-items: center;
  font-weight: bold;
  margin-bottom: 5px;
  color: #303133;
}

.top-tag {
  margin-right: 8px;
}

.announcement-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.content-container {
  padding: 0 20px;
  line-height: 1.6;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin: 20px 0;
  padding-left: 10px;
  border-left: 4px solid #2E8B57;
}

.stat-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.stat-card {
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.stat-number {
  font-size: 36px;
  font-weight: bold;
  color: #2E8B57;
  margin: 16px 0;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.charts-row {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
  margin-bottom: 24px;
}

.chart-card {
  height: 100%;
}

.chart-header {
  font-size: 16px;
  font-weight: bold;
}

.rank-list {
  padding: 0 10px;
}

.rank-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.rank-index {
  width: 24px;
  height: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f2f2f2;
  color: #606266;
  border-radius: 50%;
  margin-right: 12px;
  font-size: 14px;
}

.rank-item:nth-child(1) .rank-index {
  background-color: #f56c6c;
  color: white;
}

.rank-content {
  flex: 1;
  overflow: hidden;
}

.rank-title {
  font-size: 14px;
  color: #303133;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.rank-count {
  font-size: 12px;
  color: #909399;
}

.rank-progress {
  width: 120px;
  margin-left: 12px;
}

@media (max-width: 1200px) {
  .charts-row {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .stat-container {
    grid-template-columns: 1fr;
  }
  
  .rank-progress {
    display: none;
  }
}
</style>

