package com.example.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.config.TokenUtils;
import com.example.common.enums.ResultCodeEnum;
import com.example.entity.Account;
import com.example.entity.DoctorPatient;
import com.example.entity.SymptomRecord;
import com.example.exception.CustomException;
import com.example.mapper.SymptomRecordMapper;
import com.github.pagehelper.PageHelper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.DoubleSummaryStatistics;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * 症状记录服务类
 */
@Service
public class SymptomRecordService {

    @Resource
    private SymptomRecordMapper symptomRecordMapper;
    
    @Resource
    private DoctorPatientService doctorPatientService;

    /**
     * 添加症状记录
     */
    public void add(SymptomRecord symptomRecord) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_INVALID_ERROR);
        }
        
        // 只有患者可以添加症状记录
        if (!"patient".equals(currentUser.getRole())) {
            throw new CustomException(ResultCodeEnum.NO_AUTH_ERROR);
        }
        
        // 设置患者ID
        symptomRecord.setPatientId(currentUser.getId());
        
        // 设置记录时间和创建时间
        if (symptomRecord.getRecordTime() == null) {
            symptomRecord.setRecordTime(new Date());
        }
        symptomRecord.setCreateTime(new Date());
        
        symptomRecordMapper.insert(symptomRecord);
    }

    /**
     * 更新症状记录
     */
    public void update(SymptomRecord symptomRecord) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_INVALID_ERROR);
        }
        
        // 检查记录是否存在
        SymptomRecord existRecord = symptomRecordMapper.selectById(symptomRecord.getId());
        if (existRecord == null) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }
        
        // 权限检查
        checkPermission(currentUser, existRecord.getPatientId());
        
        // 更新记录
        symptomRecordMapper.updateById(symptomRecord);
    }

    /**
     * 删除症状记录
     */
    public void delete(Integer id) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_INVALID_ERROR);
        }
        
        // 检查记录是否存在
        SymptomRecord existRecord = symptomRecordMapper.selectById(id);
        if (existRecord == null) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }
        
        // 权限检查：患者只能删除自己的记录，医生不能删除记录，管理员可以删除所有记录
        if ("patient".equals(currentUser.getRole())) {
            if (!currentUser.getId().equals(existRecord.getPatientId())) {
                throw new CustomException(ResultCodeEnum.NO_AUTH_ERROR);
            }
        } else if ("doctor".equals(currentUser.getRole())) {
            throw new CustomException(ResultCodeEnum.NO_AUTH_ERROR);
        }
        
        symptomRecordMapper.deleteById(id);
    }

    /**
     * 根据ID查询症状记录
     */
    public SymptomRecord getById(Integer id) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_INVALID_ERROR);
        }
        
        SymptomRecord record = symptomRecordMapper.selectById(id);
        if (record == null) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }
        
        // 权限检查
        checkPermission(currentUser, record.getPatientId());
        
        return record;
    }

    /**
     * 根据患者ID查询所有症状记录
     */
    public List<SymptomRecord> getByPatientId(Integer patientId) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_INVALID_ERROR);
        }
        
        // 根据角色处理
        if ("patient".equals(currentUser.getRole())) {
            // 患者只能查看自己的记录
            patientId = currentUser.getId();
        } else if ("doctor".equals(currentUser.getRole())) {
            // 医生只能查看自己负责的患者记录
            if (patientId != null) {
                // 检查该患者是否是该医生负责的
                checkDoctorPatientRelationship(currentUser.getId(), patientId);
            } else {
                // 获取医生负责的所有患者
                List<DoctorPatient> doctorPatients = doctorPatientService.selectByDoctorId(currentUser.getId(), null);
                List<Integer> patientIds = doctorPatients.stream()
                        .map(DoctorPatient::getPatientId)
                        .collect(Collectors.toList());
                
                if (patientIds.isEmpty()) {
                    return new ArrayList<>();
                }
                
                // 查询这些患者的所有记录
                LambdaQueryWrapper<SymptomRecord> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(SymptomRecord::getPatientId, patientIds);
                queryWrapper.orderByDesc(SymptomRecord::getRecordTime);
                return symptomRecordMapper.selectList(queryWrapper);
            }
        }
        
        // 查询记录
        return symptomRecordMapper.selectWithPatient(patientId);
    }

    /**
     * 分页查询症状记录
     */
    public Page<SymptomRecord> getPage(Integer pageNum, Integer pageSize, String startDate, String endDate) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_INVALID_ERROR);
        }
        
        // 创建查询条件
        LambdaQueryWrapper<SymptomRecord> queryWrapper = new LambdaQueryWrapper<>();
        
        // 根据角色设置查询条件
        if ("patient".equals(currentUser.getRole())) {
            // 患者只能查看自己的记录
            queryWrapper.eq(SymptomRecord::getPatientId, currentUser.getId());
        } else if ("doctor".equals(currentUser.getRole())) {
            // 医生只能查看自己负责的患者记录
            List<DoctorPatient> doctorPatients = doctorPatientService.selectByDoctorId(currentUser.getId(), null);
            List<Integer> patientIds = doctorPatients.stream()
                    .map(DoctorPatient::getPatientId)
                    .collect(Collectors.toList());
            
            if (patientIds.isEmpty()) {
                // 没有负责的患者，返回空结果
                return new Page<>(pageNum, pageSize);
            }
            
            queryWrapper.in(SymptomRecord::getPatientId, patientIds);
        }
        
        // 添加日期条件
        if (ObjectUtil.isNotEmpty(startDate) && ObjectUtil.isNotEmpty(endDate)) {
            Date start = DateUtil.parseDate(startDate);
            Date end = DateUtil.parseDate(endDate);
            queryWrapper.between(SymptomRecord::getRecordTime, start, end);
        }
        
        // 按记录时间降序排序
        queryWrapper.orderByDesc(SymptomRecord::getRecordTime);
        
        // 执行分页查询
        return symptomRecordMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper);
    }
    
    /**
     * 检查用户是否有权限操作指定患者的记录
     */
    private void checkPermission(Account currentUser, Integer patientId) {
        if ("patient".equals(currentUser.getRole())) {
            // 患者只能操作自己的记录
            if (!currentUser.getId().equals(patientId)) {
                throw new CustomException(ResultCodeEnum.NO_AUTH_ERROR);
            }
        } else if ("doctor".equals(currentUser.getRole())) {
            // 医生只能操作自己负责的患者的记录
            checkDoctorPatientRelationship(currentUser.getId(), patientId);
        }
        // 管理员可以操作所有记录
    }
    
    /**
     * 检查医生与患者是否存在关联关系
     */
    private void checkDoctorPatientRelationship(Integer doctorId, Integer patientId) {
        List<DoctorPatient> doctorPatients = doctorPatientService.selectByDoctorId(doctorId, null);
        boolean isResponsible = doctorPatients.stream()
                .anyMatch(dp -> dp.getPatientId().equals(patientId));
        
        if (!isResponsible) {
            throw new CustomException(ResultCodeEnum.NO_AUTH_ERROR);
        }
    }

    /**
     * 批量查询症状记录关联的患者信息
     */
    public List<SymptomRecord> getRecordsWithPatient(List<SymptomRecord> records) {
        if (records == null || records.isEmpty()) {
            return records;
        }
        
        // 从记录中提取所有患者ID
        List<Integer> patientIds = records.stream()
                .map(SymptomRecord::getPatientId)
                .distinct()
                .collect(Collectors.toList());
        
        // 这里利用Mapper中已有的selectWithPatient方法，查询所有关联患者信息的记录
        List<SymptomRecord> recordsWithPatient = new ArrayList<>();
        for (Integer patientId : patientIds) {
            List<SymptomRecord> patientRecords = symptomRecordMapper.selectWithPatient(patientId);
            recordsWithPatient.addAll(patientRecords);
        }
        
        // 根据原记录ID匹配，返回带患者信息的记录
        Map<Integer, SymptomRecord> recordMap = recordsWithPatient.stream()
                .collect(Collectors.toMap(SymptomRecord::getId, record -> record, (a, b) -> a));
        
        return records.stream()
                .map(record -> {
                    SymptomRecord recordWithPatient = recordMap.get(record.getId());
                    return recordWithPatient != null ? recordWithPatient : record;
                })
                .collect(Collectors.toList());
    }

    /**
     * 分页查询症状记录（使用PageHelper）
     */
    public com.github.pagehelper.PageInfo<SymptomRecord> selectPage(SymptomRecord symptomRecord, Integer pageNum, Integer pageSize, String startDate, String endDate) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_INVALID_ERROR);
        }
        
        // 构建查询条件获取所有符合条件的记录
        List<SymptomRecord> allRecords = new ArrayList<>();
        
        // 获取患者名称搜索条件
        final String patientName;
        if (symptomRecord != null && ObjectUtil.isNotEmpty(symptomRecord.getPatientName())) {
            patientName = symptomRecord.getPatientName().trim().toLowerCase();
        } else {
            patientName = "";
        }
        
        // 根据角色设置查询条件
        if ("patient".equals(currentUser.getRole())) {
            // 患者只能查看自己的记录
            symptomRecord = symptomRecord == null ? new SymptomRecord() : symptomRecord;
            symptomRecord.setPatientId(currentUser.getId());
            allRecords = symptomRecordMapper.selectWithPatient(currentUser.getId());
        } else if ("doctor".equals(currentUser.getRole())) {
            // 医生只能查看自己负责的患者记录
            List<DoctorPatient> doctorPatients = doctorPatientService.selectByDoctorId(currentUser.getId(), null);
            List<Integer> patientIds = doctorPatients.stream()
                    .map(DoctorPatient::getPatientId)
                    .collect(Collectors.toList());
            
            if (patientIds.isEmpty()) {
                // 没有负责的患者，返回空结果
                return new com.github.pagehelper.PageInfo<>(new ArrayList<>());
            }
            
            // 查询患者ID在列表中的记录，并带上患者信息
            for (Integer patientId : patientIds) {
                List<SymptomRecord> patientRecords = symptomRecordMapper.selectWithPatient(patientId);
                allRecords.addAll(patientRecords);
            }
        } else {
            // 管理员可以查看所有记录
            // 这里需要查询所有带有患者信息的记录，但由于没有查询全部的接口，我们先查询所有患者ID
            List<SymptomRecord> tempRecords = symptomRecordMapper.selectList(null);
            List<Integer> allPatientIds = tempRecords.stream()
                    .map(SymptomRecord::getPatientId)
                    .distinct()
                    .collect(Collectors.toList());
            
            // 查询每个患者的记录并带上患者信息
            for (Integer patientId : allPatientIds) {
                List<SymptomRecord> patientRecords = symptomRecordMapper.selectWithPatient(patientId);
                allRecords.addAll(patientRecords);
            }
        }
        
        // 根据患者名称过滤
        if (ObjectUtil.isNotEmpty(patientName)) {
            allRecords = allRecords.stream()
                    .filter(record -> {
                        if (record.getPatient() != null && ObjectUtil.isNotEmpty(record.getPatient().getName())) {
                            return record.getPatient().getName().toLowerCase().contains(patientName);
                        }
                        return false;
                    })
                    .collect(Collectors.toList());
        }
        
        // 根据日期过滤
        if (ObjectUtil.isNotEmpty(startDate) && ObjectUtil.isNotEmpty(endDate)) {
            Date start = DateUtil.parseDate(startDate);
            Date end = DateUtil.parseDate(endDate);
            allRecords = allRecords.stream()
                    .filter(record -> {
                        Date recordTime = record.getRecordTime();
                        return recordTime != null && !recordTime.before(start) && !recordTime.after(end);
                    })
                    .collect(Collectors.toList());
        }
        
        // 按记录时间降序排序
        allRecords.sort((a, b) -> {
            if (a.getRecordTime() == null || b.getRecordTime() == null) {
                return 0;
            }
            return b.getRecordTime().compareTo(a.getRecordTime());
        });
        
        // 在内存中执行分页
        int start = (pageNum - 1) * pageSize;
        int end = Math.min(start + pageSize, allRecords.size());
        
        List<SymptomRecord> pagedRecords;
        if (start < allRecords.size()) {
            pagedRecords = allRecords.subList(start, end);
        } else {
            pagedRecords = new ArrayList<>();
        }
        
        // 创建PageInfo对象
        com.github.pagehelper.PageInfo<SymptomRecord> pageInfo = new com.github.pagehelper.PageInfo<>(pagedRecords);
        // 手动设置分页信息
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        pageInfo.setTotal(allRecords.size());
        pageInfo.setPages((int) Math.ceil((double) allRecords.size() / pageSize));
        
        return pageInfo;
    }

    /**
     * 获取症状记录统计数据
     * @param patientId 患者ID（可选，为null表示查询所有）
     * @param startDate 开始日期（可选）
     * @param endDate 结束日期（可选）
     * @return 统计数据
     */
    public Map<String, Object> getStatisticsData(Integer patientId, Date startDate, Date endDate) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 构建查询条件
            LambdaQueryWrapper<SymptomRecord> queryWrapper = new LambdaQueryWrapper<>();
            if (patientId != null) {
                queryWrapper.eq(SymptomRecord::getPatientId, patientId);
            }
            
            if (startDate != null) {
                queryWrapper.ge(SymptomRecord::getRecordTime, startDate);
            }
            
            if (endDate != null) {
                queryWrapper.le(SymptomRecord::getRecordTime, endDate);
            }
            
            // 获取所有符合条件的记录
            List<SymptomRecord> records = symptomRecordMapper.selectList(queryWrapper);
            
            // 按日期分组的严重程度平均值
            Map<String, Double> severityByDate = new LinkedHashMap<>();
            Map<String, Double> emotionByDate = new LinkedHashMap<>();
            Map<String, Double> sleepByDate = new LinkedHashMap<>();
            
            // 过去7天的日期
            List<String> last7Days = new ArrayList<>();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar = Calendar.getInstance();
            
            for (int i = 6; i >= 0; i--) {
                calendar.setTime(new Date());
                calendar.add(Calendar.DAY_OF_MONTH, -i);
                String dateStr = dateFormat.format(calendar.getTime());
                last7Days.add(dateStr);
                
                // 初始化数据
                severityByDate.put(dateStr, 0.0);
                emotionByDate.put(dateStr, 0.0);
                sleepByDate.put(dateStr, 0.0);
            }
            
            // 记录每个日期的记录数量
            Map<String, Integer> countByDate = new HashMap<>();
            for (String date : last7Days) {
                countByDate.put(date, 0);
            }
            
            // 处理记录
            for (SymptomRecord record : records) {
                if (record.getRecordTime() != null) {
                    String recordDate = dateFormat.format(record.getRecordTime());
                    
                    // 只处理过去7天的数据
                    if (last7Days.contains(recordDate)) {
                        // 更新计数
                        countByDate.put(recordDate, countByDate.getOrDefault(recordDate, 0) + 1);
                        
                        // 更新严重程度总和
                        if (record.getSeverityLevel() != null) {
                            severityByDate.put(recordDate, severityByDate.getOrDefault(recordDate, 0.0) + record.getSeverityLevel());
                        }
                        
                        // 更新情绪评分总和
                        if (record.getEmotionScore() != null) {
                            emotionByDate.put(recordDate, emotionByDate.getOrDefault(recordDate, 0.0) + record.getEmotionScore());
                        }
                        
                        // 更新入睡时间总和
                        if (record.getSleepTime() != null) {
                            sleepByDate.put(recordDate, sleepByDate.getOrDefault(recordDate, 0.0) + record.getSleepTime());
                        }
                    }
                }
            }
            
            // 计算每日平均值
            for (String date : last7Days) {
                int count = countByDate.get(date);
                if (count > 0) {
                    severityByDate.put(date, severityByDate.get(date) / count);
                    emotionByDate.put(date, emotionByDate.get(date) / count);
                    sleepByDate.put(date, sleepByDate.get(date) / count);
                }
            }
            
            // 构建返回结果
            result.put("dates", last7Days);
            result.put("severityData", last7Days.stream().map(severityByDate::get).collect(Collectors.toList()));
            result.put("emotionData", last7Days.stream().map(emotionByDate::get).collect(Collectors.toList()));
            result.put("sleepData", last7Days.stream().map(sleepByDate::get).collect(Collectors.toList()));
            
            // 计算总体统计数据
            DoubleSummaryStatistics severityStats = records.stream()
                    .filter(r -> r.getSeverityLevel() != null)
                    .mapToDouble(SymptomRecord::getSeverityLevel)
                    .summaryStatistics();
            
            DoubleSummaryStatistics emotionStats = records.stream()
                    .filter(r -> r.getEmotionScore() != null)
                    .mapToDouble(SymptomRecord::getEmotionScore)
                    .summaryStatistics();
            
            DoubleSummaryStatistics sleepStats = records.stream()
                    .filter(r -> r.getSleepTime() != null)
                    .mapToDouble(SymptomRecord::getSleepTime)
                    .summaryStatistics();
            
            // 添加总体统计
            Map<String, Object> summaryStats = new HashMap<>();
            summaryStats.put("recordCount", records.size());
            summaryStats.put("avgSeverity", severityStats.getAverage());
            summaryStats.put("avgEmotion", emotionStats.getAverage());
            summaryStats.put("avgSleepTime", sleepStats.getAverage());
            
            result.put("summary", summaryStats);
            
            // 计算各项分布
            Map<Integer, Long> severityDistribution = records.stream()
                    .filter(r -> r.getSeverityLevel() != null)
                    .collect(Collectors.groupingBy(SymptomRecord::getSeverityLevel, Collectors.counting()));
            
            Map<Integer, Long> emotionDistribution = records.stream()
                    .filter(r -> r.getEmotionScore() != null)
                    .collect(Collectors.groupingBy(SymptomRecord::getEmotionScore, Collectors.counting()));
            
            result.put("severityDistribution", severityDistribution);
            result.put("emotionDistribution", emotionDistribution);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return result;
    }

    /**
     * 根据医生ID获取其患者的症状记录统计数据
     * @param doctorId 医生ID
     * @param startDate 开始日期（可选）
     * @param endDate 结束日期（可选）
     * @return 统计数据
     */
    public Map<String, Object> getStatisticsByDoctor(Integer doctorId, Date startDate, Date endDate) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取医生的所有患者
        List<Integer> patientIds = new ArrayList<>();
        try {
            LambdaQueryWrapper<DoctorPatient> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DoctorPatient::getDoctorId, doctorId);
            queryWrapper.eq(DoctorPatient::getStatus, "正常");
            
            List<DoctorPatient> doctorPatients = doctorPatientService.selectByDoctorId(doctorId, null);
            patientIds = doctorPatients.stream()
                    .map(DoctorPatient::getPatientId)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        
        if (patientIds.isEmpty()) {
            return result;
        }
        
        try {
            // 构建查询条件
            LambdaQueryWrapper<SymptomRecord> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(SymptomRecord::getPatientId, patientIds);
            
            if (startDate != null) {
                queryWrapper.ge(SymptomRecord::getRecordTime, startDate);
            }
            
            if (endDate != null) {
                queryWrapper.le(SymptomRecord::getRecordTime, endDate);
            }
            
            // 获取所有符合条件的记录
            List<SymptomRecord> records = symptomRecordMapper.selectList(queryWrapper);
            
            // 处理和上面的方法相同...（后续统计处理逻辑与上面的方法相同）
            // 按日期分组的严重程度平均值
            Map<String, Double> severityByDate = new LinkedHashMap<>();
            Map<String, Double> emotionByDate = new LinkedHashMap<>();
            Map<String, Double> sleepByDate = new LinkedHashMap<>();
            
            // 过去7天的日期
            List<String> last7Days = new ArrayList<>();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar = Calendar.getInstance();
            
            for (int i = 6; i >= 0; i--) {
                calendar.setTime(new Date());
                calendar.add(Calendar.DAY_OF_MONTH, -i);
                String dateStr = dateFormat.format(calendar.getTime());
                last7Days.add(dateStr);
                
                // 初始化数据
                severityByDate.put(dateStr, 0.0);
                emotionByDate.put(dateStr, 0.0);
                sleepByDate.put(dateStr, 0.0);
            }
            
            // 记录每个日期的记录数量
            Map<String, Integer> countByDate = new HashMap<>();
            for (String date : last7Days) {
                countByDate.put(date, 0);
            }
            
            // 处理记录
            for (SymptomRecord record : records) {
                if (record.getRecordTime() != null) {
                    String recordDate = dateFormat.format(record.getRecordTime());
                    
                    // 只处理过去7天的数据
                    if (last7Days.contains(recordDate)) {
                        // 更新计数
                        countByDate.put(recordDate, countByDate.getOrDefault(recordDate, 0) + 1);
                        
                        // 更新严重程度总和
                        if (record.getSeverityLevel() != null) {
                            severityByDate.put(recordDate, severityByDate.getOrDefault(recordDate, 0.0) + record.getSeverityLevel());
                        }
                        
                        // 更新情绪评分总和
                        if (record.getEmotionScore() != null) {
                            emotionByDate.put(recordDate, emotionByDate.getOrDefault(recordDate, 0.0) + record.getEmotionScore());
                        }
                        
                        // 更新入睡时间总和
                        if (record.getSleepTime() != null) {
                            sleepByDate.put(recordDate, sleepByDate.getOrDefault(recordDate, 0.0) + record.getSleepTime());
                        }
                    }
                }
            }
            
            // 计算每日平均值
            for (String date : last7Days) {
                int count = countByDate.get(date);
                if (count > 0) {
                    severityByDate.put(date, severityByDate.get(date) / count);
                    emotionByDate.put(date, emotionByDate.get(date) / count);
                    sleepByDate.put(date, sleepByDate.get(date) / count);
                }
            }
            
            // 构建返回结果
            result.put("dates", last7Days);
            result.put("severityData", last7Days.stream().map(severityByDate::get).collect(Collectors.toList()));
            result.put("emotionData", last7Days.stream().map(emotionByDate::get).collect(Collectors.toList()));
            result.put("sleepData", last7Days.stream().map(sleepByDate::get).collect(Collectors.toList()));
            
            // 计算总体统计数据
            DoubleSummaryStatistics severityStats = records.stream()
                    .filter(r -> r.getSeverityLevel() != null)
                    .mapToDouble(SymptomRecord::getSeverityLevel)
                    .summaryStatistics();
            
            DoubleSummaryStatistics emotionStats = records.stream()
                    .filter(r -> r.getEmotionScore() != null)
                    .mapToDouble(SymptomRecord::getEmotionScore)
                    .summaryStatistics();
            
            DoubleSummaryStatistics sleepStats = records.stream()
                    .filter(r -> r.getSleepTime() != null)
                    .mapToDouble(SymptomRecord::getSleepTime)
                    .summaryStatistics();
            
            // 添加总体统计
            Map<String, Object> summaryStats = new HashMap<>();
            summaryStats.put("recordCount", records.size());
            summaryStats.put("avgSeverity", severityStats.getAverage());
            summaryStats.put("avgEmotion", emotionStats.getAverage());
            summaryStats.put("avgSleepTime", sleepStats.getAverage());
            summaryStats.put("patientCount", patientIds.size());
            
            result.put("summary", summaryStats);
            
            // 计算各项分布
            Map<Integer, Long> severityDistribution = records.stream()
                    .filter(r -> r.getSeverityLevel() != null)
                    .collect(Collectors.groupingBy(SymptomRecord::getSeverityLevel, Collectors.counting()));
            
            Map<Integer, Long> emotionDistribution = records.stream()
                    .filter(r -> r.getEmotionScore() != null)
                    .collect(Collectors.groupingBy(SymptomRecord::getEmotionScore, Collectors.counting()));
            
            result.put("severityDistribution", severityDistribution);
            result.put("emotionDistribution", emotionDistribution);
            
            // 按患者分组的数据
            Map<Integer, List<SymptomRecord>> recordsByPatient = records.stream()
                    .collect(Collectors.groupingBy(SymptomRecord::getPatientId));
            
            Map<Integer, Object> patientStats = new HashMap<>();
            for (Map.Entry<Integer, List<SymptomRecord>> entry : recordsByPatient.entrySet()) {
                Integer pid = entry.getKey();
                List<SymptomRecord> patientRecords = entry.getValue();
                
                DoubleSummaryStatistics patientSeverityStats = patientRecords.stream()
                        .filter(r -> r.getSeverityLevel() != null)
                        .mapToDouble(SymptomRecord::getSeverityLevel)
                        .summaryStatistics();
                
                Map<String, Object> pStats = new HashMap<>();
                pStats.put("recordCount", patientRecords.size());
                pStats.put("avgSeverity", patientSeverityStats.getAverage());
                pStats.put("maxSeverity", patientSeverityStats.getMax());
                
                patientStats.put(pid, pStats);
            }
            
            result.put("patientStats", patientStats);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return result;
    }
} 