package com.lesingle.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lesingle.edu.common.enums.GenericStatus;
import com.lesingle.edu.dto.response.ChildInfoResponse;
import com.lesingle.edu.dto.response.ChildProfileResponse;
import com.lesingle.edu.entity.*;
import com.lesingle.edu.mapper.GrowthRecordMapper;
import com.lesingle.edu.mapper.ParentStudentMapper;
import com.lesingle.edu.mapper.StudentMapper;
import com.lesingle.edu.mapper.StudentRecordMapper;
import com.lesingle.edu.mapper.TaskCompletionMapper;
import com.lesingle.edu.service.ClassService;
import com.lesingle.edu.service.ParentAuthService;
import com.lesingle.edu.service.ParentChildService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * 家长端孩子信息服务实现
 */
@Service
@RequiredArgsConstructor
public class ParentChildServiceImpl implements ParentChildService {

    private final ParentStudentMapper parentStudentMapper;
    private final StudentMapper studentMapper;
    private final StudentRecordMapper studentRecordMapper;
    private final TaskCompletionMapper taskCompletionMapper;
    private final GrowthRecordMapper growthRecordMapper;
    private final ParentAuthService parentAuthService;
    private final ClassService classService;

    @Override
    public List<ChildInfoResponse> getChildrenForParent(Long parentId) {
        List<ParentStudent> parentStudents = parentStudentMapper.selectList(
                new LambdaQueryWrapper<ParentStudent>()
                        .eq(ParentStudent::getParentId, parentId)
        );
        if (parentStudents.isEmpty()) {
            return List.of();
        }

        List<Long> studentIds = parentStudents.stream()
                .map(ParentStudent::getStudentId)
                .toList();
        Map<Long, String> relationshipMap = parentStudents.stream()
                .collect(Collectors.toMap(ParentStudent::getStudentId, ps -> ps.getRelationship() != null ? ps.getRelationship() : "OTHER"));

        List<Student> students = studentMapper.selectList(
                new LambdaQueryWrapper<Student>()
                        .in(Student::getId, studentIds)
                        .eq(Student::getStatus, GenericStatus.ACTIVE.getCode())
        );

        List<ChildInfoResponse> result = new ArrayList<>();
        for (Student student : students) {
            ChildInfoResponse.ClassInfo classInfo = buildClassInfo(student.getId());
            int readingCount = countStudentRecords(student.getId());
            int lessonCount = readingCount; // student_record 即上课记录

            result.add(ChildInfoResponse.builder()
                    .id(student.getId())
                    .name(student.getName())
                    .gender(student.getGender())
                    .birthDate(student.getBirthDate())
                    .relationship(relationshipMap.getOrDefault(student.getId(), "OTHER"))
                    .classInfo(classInfo)
                    .readingCount(readingCount)
                    .lessonCount(lessonCount)
                    .build());
        }
        return result;
    }

    @Override
    public ChildProfileResponse getChildProfile(Long parentId, Long studentId) {
        parentAuthService.validateParentStudentRelation(parentId, studentId);

        Student student = studentMapper.selectById(studentId);
        if (student == null) {
            return null;
        }

        ParentStudent ps = parentStudentMapper.selectOne(
                new LambdaQueryWrapper<ParentStudent>()
                        .eq(ParentStudent::getParentId, parentId)
                        .eq(ParentStudent::getStudentId, studentId)
        );
        String relationship = ps != null && ps.getRelationship() != null ? ps.getRelationship() : "OTHER";

        ChildInfoResponse.ClassInfo classInfo = buildClassInfo(studentId);
        int readingCount = countStudentRecords(studentId);
        int lessonCount = readingCount;

        int growthRecords = growthRecordMapper.selectCount(
                new LambdaQueryWrapper<GrowthRecord>()
                        .eq(GrowthRecord::getStudentId, studentId)
        ).intValue();
        int taskCompletions = taskCompletionMapper.selectCount(
                new LambdaQueryWrapper<TaskCompletion>()
                        .eq(TaskCompletion::getStudentId, studentId)
                        .in(TaskCompletion::getStatus, "SUBMITTED", "REVIEWED")
        ).intValue();

        return ChildProfileResponse.builder()
                .id(student.getId())
                .name(student.getName())
                .gender(student.getGender())
                .birthDate(student.getBirthDate())
                .relationship(relationship)
                .classInfo(classInfo)
                .readingCount(readingCount)
                .lessonCount(lessonCount)
                .stats(ChildProfileResponse.StatsInfo.builder()
                        .lessonRecords(readingCount)
                        .growthRecords(growthRecords)
                        .taskCompletions(taskCompletions)
                        .build())
                .build();
    }

    private ChildInfoResponse.ClassInfo buildClassInfo(Long studentId) {
        Clazz clazz = classService.getPrimaryClassByStudentId(studentId);
        if (clazz == null) {
            return ChildInfoResponse.ClassInfo.builder()
                    .id(0L)
                    .name("未分班")
                    .grade("-")
                    .build();
        }
        return ChildInfoResponse.ClassInfo.builder()
                .id(clazz.getId())
                .name(clazz.getName())
                .grade(clazz.getGrade() != null ? clazz.getGrade() : "-")
                .build();
    }

    private int countStudentRecords(Long studentId) {
        return studentRecordMapper.selectCount(
                new LambdaQueryWrapper<StudentRecord>()
                        .eq(StudentRecord::getStudentId, studentId)
        ).intValue();
    }
}
