package com.seer.teach.teacher.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seer.teach.teacher.common.llm.resp.GradeSubjectResult;
import com.seer.teach.teacher.common.llm.resp.SubjectResult;
import com.seer.teach.teacher.common.resp.SubjectResp;
import com.seer.teach.teacher.common.utils.TeacherUtils;
import com.seer.teach.teacher.convert.GradeSubjectConvert;
import com.seer.teach.teacher.convert.SubjectConvert;
import com.seer.teach.teacher.module.entity.GradeSubjectEntity;
import com.seer.teach.teacher.module.entity.SubjectsEntity;
import com.seer.teach.teacher.module.mapper.GradeSubjectMapper;
import com.seer.teach.teacher.module.mapper.SubjectsMapper;
import com.seer.teach.teacher.service.GradeSubjectService;
import com.seer.teach.teacher.service.SubjectsService;
import com.seer.teach.user.api.GradeServiceApi;
import com.seer.teach.user.api.UserInfoServiceApi;
import com.seer.teach.user.api.dto.GradeDTO;
import com.seer.teach.user.api.dto.UserInfoDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Sir-G
 * @since 2025-05-28
 */
@Service
@RequiredArgsConstructor
public class SubjectsServiceImpl extends ServiceImpl<SubjectsMapper, SubjectsEntity> implements SubjectsService {

    private final UserInfoServiceApi userInfoServiceApi;

    private final GradeServiceApi gradeServiceApi;

    private final GradeSubjectService gradeSubjectService;

    @Override
    public List<Map<String, Object>> getUserOwnedSubjects() {
        Integer userId = StpUtil.getLoginIdAsInt();
        UserInfoDTO user = userInfoServiceApi.getById(userId);
        List<Integer> subjectIds = gradeSubjectService.list(new LambdaQueryWrapper<GradeSubjectEntity>()
                        .eq(GradeSubjectEntity::getGradeId, user.getGradeId())).stream()
                .map(GradeSubjectEntity::getSubjectId).collect(Collectors.toList());
        List<SubjectsEntity> list = listByIds(subjectIds);
        return list.stream()
                .map(item -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("subject", item.getSubject());
                    map.put("id", item.getId());
                    return map;
                })
                .collect(Collectors.toList());
    }

    /**
     * 获取所有科目列表
     *
     * @return
     */
    @Override
    public List<SubjectsEntity> getSubjectList() {
        List<SubjectsEntity> list = list();
        if (list.isEmpty()) {
            return Collections.emptyList();
        }
        return list;
    }

    @Override
    public Map<Integer, String> getSubjectIdsByGradeStage(Integer gradeId) {
        List<Integer> subjectIds;
        LambdaQueryWrapper<GradeSubjectEntity> wrapper = new LambdaQueryWrapper<>();
        if (TeacherUtils.isPrimary(gradeId)) {
            wrapper.between(GradeSubjectEntity::getGradeId, 1, 6);
        } else if (TeacherUtils.isJunior(gradeId)) {
            wrapper.between(GradeSubjectEntity::getGradeId, 7, 9);
        } else {
            wrapper.between(GradeSubjectEntity::getGradeId, 10, 12);
        }
        wrapper.orderByAsc(GradeSubjectEntity::getSort);
        subjectIds = gradeSubjectService.list(wrapper).stream()
                .map(GradeSubjectEntity::getSubjectId)
                .distinct()
                .sorted()
                .collect(Collectors.toList());
        return listByIds(subjectIds).stream().collect(Collectors.toMap(SubjectsEntity::getId, SubjectsEntity::getSubject));
    }

    @Override
    public List<SubjectResp> getUserSubjects() {
        Integer userId = StpUtil.getLoginIdAsInt();
        Integer gradeId = userInfoServiceApi.getChildrenGradeId(userId);
        List<GradeSubjectEntity> gradeSubjects = gradeSubjectService.lambdaQuery()
                .eq(GradeSubjectEntity::getGradeId, gradeId)
                .orderByAsc(GradeSubjectEntity::getSort)
                .list();
        List<Integer> subjectIds = gradeSubjects.stream().map(GradeSubjectEntity::getSubjectId)
                .collect(Collectors.toList());
        List<SubjectsEntity> subjects = listByIds(subjectIds);
        return SubjectConvert.INSTANCE.toListSubjectResp(subjects);
    }

    @Override
    public List<GradeSubjectResult> getGradeSubjects() {
        // 获取所有年级信息
        List<GradeDTO> grades = gradeServiceApi.getGradeList();
        List<Integer> gradeIds = grades.stream().map(GradeDTO::getId).collect(Collectors.toList());

        // 获取所有科目信息并转换为Map便于后续查询
        Map<Integer, SubjectsEntity> subjectMaps = this.list().stream()
                .collect(Collectors.toMap(SubjectsEntity::getId, Function.identity()));

        // 查询年级科目关联关系
        List<GradeSubjectEntity> gradeSubjects = gradeSubjectService.list(new LambdaQueryWrapper<GradeSubjectEntity>()
                .in(GradeSubjectEntity::getGradeId, gradeIds));

        // 按年级ID分组年级科目关联关系
        Map<Integer, List<GradeSubjectEntity>> gradeToSubjectsMap = gradeSubjects.stream()
                .collect(Collectors.groupingBy(GradeSubjectEntity::getGradeId));

        // 组装返回结果：将年级信息与对应的科目信息合并
        return grades.stream().map(grade -> {
            List<GradeSubjectEntity> relationList = gradeToSubjectsMap.getOrDefault(grade.getId(), Collections.emptyList());
            List<SubjectResult> subjectResult = relationList.stream()
                    .map(relation ->
                            SubjectConvert.INSTANCE.toSubjectResult(subjectMaps.get(relation.getSubjectId())))
                    .collect(Collectors.toList());
            return GradeSubjectConvert.INSTANCE.toGradeSubjectResp(grade, subjectResult);
        }).collect(Collectors.toList());
    }


}
