<template>
  <div>
    <div class="card" style="margin-bottom: 15px">
      <div class="filter-header">
        <div>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :clearable="false"
            style="margin-right: 15px;"
          ></el-date-picker>
          
          <el-select 
            v-if="userRole === 'doctor'" 
            v-model="selectedPatientId" 
            placeholder="选择患者" 
            clearable
            @change="loadStatistics"
            style="width: 200px; margin-right: 15px;"
          >
            <el-option value="" label="所有患者"></el-option>
            <el-option 
              v-for="patient in patientList" 
              :key="patient.id" 
              :label="patient.name" 
              :value="patient.id"
            ></el-option>
          </el-select>
          
          <el-select 
            v-if="userRole === 'admin'" 
            v-model="selectedPatientId" 
            placeholder="选择患者" 
            filterable
            clearable
            @change="loadStatistics"
            style="width: 200px; margin-right: 15px;"
          >
            <el-option value="" label="所有患者"></el-option>
            <el-option 
              v-for="patient in patientList" 
              :key="patient.id" 
              :label="patient.name" 
              :value="patient.id"
            ></el-option>
          </el-select>
        </div>
        
        <el-button type="primary" @click="loadStatistics">查询</el-button>
      </div>
    </div>
    
    <!-- 汇总数据卡片 -->
    <div class="card summary-container" v-if="data.summary">
      <div class="summary-card">
        <div class="summary-title">记录总数</div>
        <div class="summary-value">{{ data.summary.recordCount }}</div>
      </div>
      
      <div class="summary-card">
        <div class="summary-title">严重程度均值</div>
        <div class="summary-value">{{ formatNumber(data.summary.avgSeverity) }}</div>
        <div class="summary-gauge">
          <div 
            class="summary-gauge-bar" 
            :style="{ width: `${data.summary.avgSeverity * 10}%`, backgroundColor: getSeverityColor(data.summary.avgSeverity) }"
          ></div>
        </div>
      </div>
      
      <div class="summary-card">
        <div class="summary-title">情绪基线均值</div>
        <div class="summary-value">{{ formatNumber(data.summary.avgEmotion) }}</div>
        <div class="summary-gauge">
          <div 
            class="summary-gauge-bar" 
            :style="{ width: `${data.summary.avgEmotion * 10}%`, backgroundColor: getEmotionColor(data.summary.avgEmotion) }"
          ></div>
        </div>
      </div>
      
      <div class="summary-card">
        <div class="summary-title">平均入睡时间</div>
        <div class="summary-value">{{ formatNumber(data.summary.avgSleepTime) }} 分钟</div>
        <div class="summary-gauge">
          <div 
            class="summary-gauge-bar" 
            :style="{ width: `${Math.min(data.summary.avgSleepTime / 60, 100)}%`, backgroundColor: getSleepTimeColor(data.summary.avgSleepTime) }"
          ></div>
        </div>
      </div>
      
      <div class="summary-card" v-if="data.summary.patientCount">
        <div class="summary-title">患者总数</div>
        <div class="summary-value">{{ data.summary.patientCount }}</div>
      </div>
    </div>
    
    <!-- 趋势图表 -->
    <div class="card" style="margin-bottom: 15px">
      <div class="chart-title">7天趋势变化</div>
      <div class="chart-container">
        <div ref="lineChartRef" style="width: 100%; height: 350px;"></div>
      </div>
    </div>
    
    <!-- 分布图表 -->
    <div class="charts-row">
      <div class="card chart-half">
        <div class="chart-title">严重程度分布</div>
        <div class="chart-container">
          <div ref="severityChartRef" style="width: 100%; height: 300px;"></div>
        </div>
      </div>
      
      <div class="card chart-half">
        <div class="chart-title">情绪基线分布</div>
        <div class="chart-container">
          <div ref="emotionChartRef" style="width: 100%; height: 300px;"></div>
        </div>
      </div>
    </div>
    
    <!-- 患者详情表格 -->
    <div class="card" v-if="userRole === 'doctor' && !selectedPatientId && data.patientStats">
      <div class="chart-title">患者详情</div>
      <el-table :data="patientStatsTable" stripe style="width: 100%">
        <el-table-column label="患者姓名" prop="name"></el-table-column>
        <el-table-column label="记录数量" prop="recordCount"></el-table-column>
        <el-table-column label="平均严重程度" prop="avgSeverity">
          <template #default="scope">
            {{ formatNumber(scope.row.avgSeverity) }}
            <el-progress 
              :percentage="scope.row.avgSeverity * 10" 
              :stroke-width="8" 
              :color="getSeverityColor(scope.row.avgSeverity)" 
            ></el-progress>
          </template>
        </el-table-column>
        <el-table-column label="最高严重程度" prop="maxSeverity">
          <template #default="scope">
            <el-tag :type="getSeverityTag(scope.row.maxSeverity)">{{ scope.row.maxSeverity }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="viewPatientDetail(scope.row.id)"
            >查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import request from '@/utils/request';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';

// 图表引用
const lineChartRef = ref(null);
const severityChartRef = ref(null);
const emotionChartRef = ref(null);

// 图表实例
let lineChart = null;
let severityChart = null;
let emotionChart = null;

// 数据
const data = reactive({
  dates: [],
  severityData: [],
  emotionData: [],
  sleepData: [],
  summary: null,
  severityDistribution: {},
  emotionDistribution: {},
  patientStats: null
});

// 日期范围
const dateRange = ref([
  new Date(new Date().setDate(new Date().getDate() - 30)).toISOString().slice(0, 10),
  new Date().toISOString().slice(0, 10)
]);

// 当前用户信息
const userInfo = JSON.parse(localStorage.getItem('xm-user') || '{}');
const userRole = userInfo.role || '';
const userId = userInfo.id || 0;

// 选择的患者ID
const selectedPatientId = ref('');

// 患者列表（仅医生和管理员可用）
const patientList = ref([]);
const patientStatsTable = ref([]);

// 加载患者列表
const loadPatientList = async () => {
  if (userRole !== 'doctor' && userRole !== 'admin') {
    return;
  }
  
  try {
    const res = await request.get('/patient');
    if (res.code === '200') {
      patientList.value = res.data || [];
    }
  } catch (error) {
    console.error('加载患者列表失败', error);
  }
};

// 加载统计数据
const loadStatistics = async () => {
  const [startDate, endDate] = dateRange.value;
  
  try {
    const params = {
      startDate,
      endDate
    };
    
    if (selectedPatientId.value) {
      params.patientId = selectedPatientId.value;
    }
    
    const res = await request.get('/symptomStatistics', { params });
    
    if (res.code === '200') {
      // 更新数据
      Object.assign(data, res.data);
      
      // 更新图表
      renderLineChart();
      renderSeverityChart();
      renderEmotionChart();
      
      // 如果是医生且未选择特定患者，则处理患者统计数据
      if (userRole === 'doctor' && !selectedPatientId.value && data.patientStats) {
        processPatientStats();
      }
    } else {
      ElMessage.error(res.msg || '加载统计数据失败');
    }
  } catch (error) {
    console.error('加载统计数据失败', error);
    ElMessage.error('加载统计数据失败');
  }
};

// 处理患者统计数据为表格格式
const processPatientStats = () => {
  if (!data.patientStats) return;
  
  patientStatsTable.value = [];
  
  for (const [pid, stats] of Object.entries(data.patientStats)) {
    const patient = patientList.value.find(p => p.id == pid);
    
    if (patient) {
      patientStatsTable.value.push({
        id: pid,
        name: patient.name,
        recordCount: stats.recordCount,
        avgSeverity: stats.avgSeverity,
        maxSeverity: stats.maxSeverity
      });
    }
  }
  
  // 按平均严重程度降序排序
  patientStatsTable.value.sort((a, b) => b.avgSeverity - a.avgSeverity);
};

// 查看患者详情
const viewPatientDetail = (patientId) => {
  selectedPatientId.value = patientId;
  loadStatistics();
};

// 格式化数字（保留1位小数）
const formatNumber = (num) => {
  if (num === undefined || num === null) return '0';
  return parseFloat(num).toFixed(1);
};

// 获取严重程度颜色
const getSeverityColor = (value) => {
  if (value <= 3) return '#67C23A';  // 绿色
  if (value <= 6) return '#E6A23C';  // 黄色
  return '#F56C6C';  // 红色
};

// 获取情绪基线颜色
const getEmotionColor = (value) => {
  if (value <= 3) return '#F56C6C';  // 红色
  if (value <= 6) return '#E6A23C';  // 黄色
  return '#67C23A';  // 绿色
};

// 获取入睡时间颜色
const getSleepTimeColor = (value) => {
  if (value <= 15) return '#67C23A';  // 绿色
  if (value <= 30) return '#E6A23C';  // 黄色
  return '#F56C6C';  // 红色
};

// 获取严重程度标签类型
const getSeverityTag = (value) => {
  if (value <= 3) return 'success';
  if (value <= 6) return 'warning';
  return 'danger';
};

// 渲染折线图
const renderLineChart = () => {
  if (!lineChartRef.value) return;
  
  if (!lineChart) {
    lineChart = echarts.init(lineChartRef.value);
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        let result = params[0].name + '<br/>';
        params.forEach(param => {
          let value = parseFloat(param.value).toFixed(1);
          result += `${param.marker} ${param.seriesName}: ${value}<br/>`;
        });
        return result;
      }
    },
    legend: {
      data: ['严重程度', '情绪基线', '入睡时间(分钟)']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.dates
    },
    yAxis: [
      {
        type: 'value',
        name: '评分',
        min: 0,
        max: 10,
        interval: 2
      },
      {
        type: 'value',
        name: '分钟',
        min: 0,
        max: 60,
        interval: 10
      }
    ],
    series: [
      {
        name: '严重程度',
        type: 'line',
        data: data.severityData,
        yAxisIndex: 0,
        itemStyle: {
          color: '#F56C6C'
        }
      },
      {
        name: '情绪基线',
        type: 'line',
        data: data.emotionData,
        yAxisIndex: 0,
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: '入睡时间(分钟)',
        type: 'line',
        data: data.sleepData,
        yAxisIndex: 1,
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
  };
  
  lineChart.setOption(option);
};

// 渲染严重程度分布图
const renderSeverityChart = () => {
  if (!severityChartRef.value || !data.severityDistribution) return;
  
  if (!severityChart) {
    severityChart = echarts.init(severityChartRef.value);
  }
  
  const severityData = [];
  for (let i = 1; i <= 10; i++) {
    severityData.push({
      value: data.severityDistribution[i] || 0,
      name: i.toString(),
      itemStyle: {
        color: getSeverityColor(i)
      }
    });
  }
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    series: [
      {
        name: '严重程度分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {c}'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true
        },
        data: severityData
      }
    ]
  };
  
  severityChart.setOption(option);
};

// 渲染情绪基线分布图
const renderEmotionChart = () => {
  if (!emotionChartRef.value || !data.emotionDistribution) return;
  
  if (!emotionChart) {
    emotionChart = echarts.init(emotionChartRef.value);
  }
  
  const emotionData = [];
  for (let i = 1; i <= 10; i++) {
    emotionData.push({
      value: data.emotionDistribution[i] || 0,
      name: i.toString(),
      itemStyle: {
        color: getEmotionColor(i)
      }
    });
  }
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    series: [
      {
        name: '情绪基线分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {c}'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true
        },
        data: emotionData
      }
    ]
  };
  
  emotionChart.setOption(option);
};

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

// 日期范围变化时重新加载数据
watch(dateRange, () => {
  loadStatistics();
});

onMounted(async () => {
  await loadPatientList();
  await loadStatistics();
  
  // 在DOM加载完成后初始化图表
  renderLineChart();
  renderSeverityChart();
  renderEmotionChart();
});
</script>

<style scoped>
.card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

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

.summary-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.summary-card {
  flex: 1;
  min-width: 200px;
  padding: 15px;
  border-radius: 8px;
  background-color: #f8f9fa;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.summary-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.summary-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
}

.summary-gauge {
  height: 6px;
  background-color: #e4e7ed;
  border-radius: 3px;
  overflow: hidden;
}

.summary-gauge-bar {
  height: 100%;
  border-radius: 3px;
}

.chart-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.charts-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-half {
  flex: 1;
  min-width: 0;
}

@media (max-width: 768px) {
  .charts-row {
    flex-direction: column;
  }
  
  .summary-container {
    flex-direction: column;
  }
}
</style> 