package com.lesingle.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lesingle.edu.common.enums.ErrorCode;
import com.lesingle.edu.common.exception.BusinessException;
import com.lesingle.edu.entity.LessonFeedback;
import com.lesingle.edu.entity.Teacher;
import com.lesingle.edu.mapper.LessonFeedbackMapper;
import com.lesingle.edu.mapper.TeacherMapper;
import com.lesingle.edu.service.LessonFeedbackService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 课程反馈服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LessonFeedbackServiceImpl extends ServiceImpl<LessonFeedbackMapper, LessonFeedback>
    implements LessonFeedbackService {

    private final LessonFeedbackMapper lessonFeedbackMapper;
    private final TeacherMapper teacherMapper;

    @Override
    public Page<LessonFeedback> getFeedbackPage(Long tenantId, Integer pageNum, Integer pageSize,
                                                 Long teacherId, Long courseId, String keyword) {
        log.debug("分页查询反馈列表，页码：{}，每页数量：{}，租户 ID：{}", pageNum, pageSize, tenantId);

        // 设置默认值
        int current = pageNum != null && pageNum > 0 ? pageNum : 1;
        int size = pageSize != null && pageSize > 0 ? pageSize : 10;

        // 获取当前租户下的所有教师 ID
        List<Teacher> teachers = teacherMapper.selectList(
                new LambdaQueryWrapper<Teacher>().eq(Teacher::getTenantId, tenantId)
        );
        List<Long> teacherIds = teachers.stream()
                .map(Teacher::getId)
                .collect(Collectors.toList());

        // 如果没有教师，返回空结果
        if (teacherIds.isEmpty()) {
            Page<LessonFeedback> emptyPage = new Page<>(current, size);
            emptyPage.setTotal(0);
            return emptyPage;
        }

        Page<LessonFeedback> page = new Page<>(current, size);
        LambdaQueryWrapper<LessonFeedback> wrapper = new LambdaQueryWrapper<>();

        // 租户隔离：只查询当前租户下教师的反馈
        wrapper.in(LessonFeedback::getTeacherId, teacherIds);

        if (teacherId != null) {
            // 验证请求的教师 ID 是否属于当前租户
            if (!teacherIds.contains(teacherId)) {
                Page<LessonFeedback> emptyPage = new Page<>(current, size);
                emptyPage.setTotal(0);
                return emptyPage;
            }
            wrapper.eq(LessonFeedback::getTeacherId, teacherId);
        }
        if (courseId != null) {
            wrapper.eq(LessonFeedback::getLessonId, courseId);
        }
        if (keyword != null && !keyword.isEmpty()) {
            wrapper.and(w -> w
                    .like(LessonFeedback::getContent, keyword)
                    .or()
                    .like(LessonFeedback::getPros, keyword)
                    .or()
                    .like(LessonFeedback::getSuggestions, keyword)
            );
        }

        wrapper.orderByDesc(LessonFeedback::getCreatedAt);

        return lessonFeedbackMapper.selectPage(page, wrapper);
    }

    @Override
    public Map<String, Object> getFeedbackStats(Long tenantId) {
        log.debug("查询反馈统计，租户 ID：{}", tenantId);

        // 获取当前租户下的所有教师 ID
        List<Teacher> teachers = teacherMapper.selectList(
                new LambdaQueryWrapper<Teacher>().eq(Teacher::getTenantId, tenantId)
        );
        List<Long> teacherIds = teachers.stream()
                .map(Teacher::getId)
                .collect(Collectors.toList());

        // 统计当前租户的反馈数量
        Long totalFeedbacks = 0L;
        Double avgDesignQuality = 0.0;
        Double avgParticipation = 0.0;
        Double avgGoalAchievement = 0.0;

        if (!teacherIds.isEmpty()) {
            // 查询反馈总数
            totalFeedbacks = this.count(
                    new LambdaQueryWrapper<LessonFeedback>()
                            .in(LessonFeedback::getTeacherId, teacherIds)
            );

            // 查询平均评分
            List<LessonFeedback> feedbacks = this.list(
                    new LambdaQueryWrapper<LessonFeedback>()
                            .in(LessonFeedback::getTeacherId, teacherIds)
                            .isNotNull(LessonFeedback::getDesignQuality)
            );

            if (!feedbacks.isEmpty()) {
                avgDesignQuality = feedbacks.stream()
                        .mapToDouble(f -> f.getDesignQuality() != null ? f.getDesignQuality() : 0)
                        .average()
                        .orElse(0.0);

                avgParticipation = feedbacks.stream()
                        .mapToDouble(f -> f.getParticipation() != null ? f.getParticipation() : 0)
                        .average()
                        .orElse(0.0);

                avgGoalAchievement = feedbacks.stream()
                        .mapToDouble(f -> f.getGoalAchievement() != null ? f.getGoalAchievement() : 0)
                        .average()
                        .orElse(0.0);
            }
        }

        Map<String, Object> stats = new HashMap<>();
        stats.put("totalFeedbacks", totalFeedbacks);
        stats.put("avgDesignQuality", avgDesignQuality);
        stats.put("avgParticipation", avgParticipation);
        stats.put("avgGoalAchievement", avgGoalAchievement);
        stats.put("courseStats", new HashMap<>());

        return stats;
    }

}
