package com.reading.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reading.platform.common.enums.ErrorCode;
import com.reading.platform.common.exception.BusinessException;
import com.reading.platform.common.util.PageUtils;
import com.reading.platform.entity.LessonFeedback;
import com.reading.platform.mapper.LessonFeedbackMapper;
import com.reading.platform.service.LessonFeedbackService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 课程反馈服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LessonFeedbackServiceImpl implements LessonFeedbackService {

    private final LessonFeedbackMapper lessonFeedbackMapper;

    @Override
    public Page<LessonFeedback> getFeedbacksByTeacherId(String teacherId, Integer pageNum, Integer pageSize, String lessonId) {
        Page<LessonFeedback> page = PageUtils.of(pageNum, pageSize);
        LambdaQueryWrapper<LessonFeedback> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LessonFeedback::getTeacherId, teacherId);
        if (StringUtils.hasText(lessonId)) {
            wrapper.eq(LessonFeedback::getLessonId, lessonId);
        }
        wrapper.orderByDesc(LessonFeedback::getCreatedAt);
        return lessonFeedbackMapper.selectPage(page, wrapper);
    }

    @Override
    public Page<LessonFeedback> getFeedbacksByTenantId(String tenantId, Integer pageNum, Integer pageSize, String teacherId, String lessonId) {
        Page<LessonFeedback> page = PageUtils.of(pageNum, pageSize);
        LambdaQueryWrapper<LessonFeedback> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LessonFeedback::getTenantId, tenantId);
        if (StringUtils.hasText(teacherId)) {
            wrapper.eq(LessonFeedback::getTeacherId, teacherId);
        }
        if (StringUtils.hasText(lessonId)) {
            wrapper.eq(LessonFeedback::getLessonId, lessonId);
        }
        wrapper.orderByDesc(LessonFeedback::getCreatedAt);
        return lessonFeedbackMapper.selectPage(page, wrapper);
    }

    @Override
    public Map<String, Object> getTeacherFeedbackStats(String teacherId) {
        LambdaQueryWrapper<LessonFeedback> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LessonFeedback::getTeacherId, teacherId);
        List<LessonFeedback> feedbacks = lessonFeedbackMapper.selectList(wrapper);

        Map<String, Object> stats = new HashMap<>();
        stats.put("totalFeedbacks", feedbacks.size());

        // 平均评分
        if (!feedbacks.isEmpty()) {
            double avgDesignQuality = feedbacks.stream()
                    .filter(f -> f.getDesignQuality() != null)
                    .mapToInt(LessonFeedback::getDesignQuality)
                    .average()
                    .orElse(0.0);
            double avgParticipation = feedbacks.stream()
                    .filter(f -> f.getParticipation() != null)
                    .mapToInt(LessonFeedback::getParticipation)
                    .average()
                    .orElse(0.0);
            double avgGoalAchievement = feedbacks.stream()
                    .filter(f -> f.getGoalAchievement() != null)
                    .mapToInt(LessonFeedback::getGoalAchievement)
                    .average()
                    .orElse(0.0);

            stats.put("avgDesignQuality", Math.round(avgDesignQuality * 10) / 10.0);
            stats.put("avgParticipation", Math.round(avgParticipation * 10) / 10.0);
            stats.put("avgGoalAchievement", Math.round(avgGoalAchievement * 10) / 10.0);
        } else {
            stats.put("avgDesignQuality", 0.0);
            stats.put("avgParticipation", 0.0);
            stats.put("avgGoalAchievement", 0.0);
        }

        return stats;
    }

    @Override
    public Map<String, Object> getFeedbackStats(String tenantId) {
        LambdaQueryWrapper<LessonFeedback> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LessonFeedback::getTenantId, tenantId);
        List<LessonFeedback> feedbacks = lessonFeedbackMapper.selectList(wrapper);

        Map<String, Object> stats = new HashMap<>();
        stats.put("totalFeedbacks", feedbacks.size());

        // 按教师分组统计
        Map<String, Long> byTeacher = feedbacks.stream()
                .collect(Collectors.groupingBy(LessonFeedback::getTeacherId, Collectors.counting()));

        List<Map<String, Object>> teacherStats = new ArrayList<>();
        byTeacher.forEach((teacherId, count) -> {
            Map<String, Object> item = new HashMap<>();
            item.put("teacherId", teacherId);
            item.put("count", count);
            teacherStats.add(item);
        });
        stats.put("byTeacher", teacherStats);

        return stats;
    }

    @Override
    public LessonFeedback getFeedbackById(String id) {
        LessonFeedback feedback = lessonFeedbackMapper.selectById(id);
        if (feedback == null) {
            throw new BusinessException(ErrorCode.DATA_NOT_FOUND, "课程反馈不存在");
        }
        return feedback;
    }

    @Override
    public LessonFeedback createFeedback(LessonFeedback feedback) {
        lessonFeedbackMapper.insert(feedback);
        log.info("创建课程反馈：id={}, teacherId={}, lessonId={}", feedback.getId(), feedback.getTeacherId(), feedback.getLessonId());
        return feedback;
    }

    @Override
    public LessonFeedback updateFeedback(String id, LessonFeedback feedback) {
        LessonFeedback existing = getFeedbackById(id);
        feedback.setId(id);
        lessonFeedbackMapper.updateById(feedback);
        log.info("更新课程反馈：id={}", id);
        return feedback;
    }
}
