package com.ym.mec.education.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.ym.mec.biz.dal.enums.JobTypeEnum;
import com.ym.mec.common.enums.UserGenderEnum;
import com.ym.mec.education.base.BaseResponse;
import com.ym.mec.education.base.PageResponse;
import com.ym.mec.education.entity.*;
import com.ym.mec.education.enums.TeachTypeEnum;
import com.ym.mec.education.mapper.ClassGroupStudentMapperMapper;
import com.ym.mec.education.req.ClassGroupReq;
import com.ym.mec.education.req.StudentReq;
import com.ym.mec.education.resp.ClassStudentResp;
import com.ym.mec.education.resp.StudentListResp;
import com.ym.mec.education.resp.StudentResp;
import com.ym.mec.education.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 班级、学生关系表 服务实现类
 * </p>
 *
 * @author lemeng
 * @since 2019-09-25
 */
@Service("IClassGroupStudentMapperService")
public class ClassGroupStudentMapperServiceImpl extends ServiceImpl<ClassGroupStudentMapperMapper, ClassGroupStudentMapper> implements IClassGroupStudentMapperService {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IClassGroupService classGroupService;
    @Autowired
    private IMusicGroupStudentFeeService musicGroupStudentFeeService;
    @Autowired
    private ITeacherService teacherService;
    @Autowired
    private IMusicGroupService musicGroupService;
    @Autowired
    private IClassGroupStudentMapperService classGroupStudentMapperService;
    @Autowired
    private ISubjectService subjectService;
    @Autowired
    private IClassGroupTeacherMapperService classGroupTeacherMapperService;
    @Autowired
    private IStudentRegistrationService studentRegistrationService;
    @Autowired
    private ISchoolService schoolService;

    @Override
    public PageResponse getPage(ClassGroupReq classGroupReq) {
        if (Objects.isNull(classGroupReq.getGroupId())) {
            return PageResponse.errorParam();
        }
        ClassGroup classGroup = classGroupService.getById(classGroupReq.getGroupId());
        Page<ClassGroupStudentMapper> classGroupStudentMapperPage = new Page<ClassGroupStudentMapper>(classGroupReq.getPageNo(), classGroupReq.getPageSize());
        QueryWrapper<ClassGroupStudentMapper> classGroupStudentMapperQueryWrapper = new QueryWrapper<>();
        classGroupStudentMapperQueryWrapper.lambda().eq(true, ClassGroupStudentMapper::getClassGroupId, classGroupReq.getGroupId());
        IPage<ClassGroupStudentMapper> page = page(classGroupStudentMapperPage, classGroupStudentMapperQueryWrapper);
        Page<StudentListResp> studentListRespPage = new Page<>();
        BeanUtils.copyProperties(page, studentListRespPage);
        List<StudentListResp> list = Lists.newArrayList();
        page.getRecords().forEach(item -> {
            SysUser sysUser = sysUserService.getById(item.getUserId());
            StudentListResp studentRegistrationResp = new StudentListResp()
                .setStudentName(sysUser.getRealName());
            if (Objects.nonNull(classGroup) && Objects.nonNull(classGroup.getMusicGroupId())) {
                QueryWrapper<MusicGroupStudentFee> musicGroupStudentFeeQueryWrapper = new QueryWrapper<MusicGroupStudentFee>();
                musicGroupStudentFeeQueryWrapper.lambda().eq(true, MusicGroupStudentFee::getMusicGroupId, classGroup.getMusicGroupId())
                    .eq(true, MusicGroupStudentFee::getUserId, item.getUserId());
                MusicGroupStudentFee musicGroupStudentFee = musicGroupStudentFeeService.getOne(musicGroupStudentFeeQueryWrapper);
                if (Objects.nonNull(musicGroupStudentFee) && Objects.nonNull(musicGroupStudentFee.getContinuousAbsenteeismTimes())) {
                    studentRegistrationResp.setStudentAttendance("连续缺到" + musicGroupStudentFee.getContinuousAbsenteeismTimes() + "次");
                }
            }
            list.add(studentRegistrationResp);
        });
        studentListRespPage.setRecords(list);
        return PageResponse.success(studentListRespPage);
    }

    @Override
    public List<ClassStudentResp> selectStudentPage(ClassGroupReq classGroupReq) {
        IPage page = new Page(classGroupReq.getPageNo() == null ? 1 : classGroupReq.getPageNo(), classGroupReq.getPageSize() == null ? 10 : classGroupReq.getPageSize());

        List<ClassStudentResp> classStudentResps = this.baseMapper.selectStudentPage(page, classGroupReq);

        return classStudentResps;
    }

    @Override
    public int selectStudentPageCount(ClassGroupReq classGroupReq) {
        return 0;
    }

    @Override
    public Page<ClassGroupStudentMapper> selectPageByCondition(ClassGroupReq classGroupReq) {
        Page<ClassGroupStudentMapper> classGroupStudentMapperPage = new Page(classGroupReq.getPageNo(), classGroupReq.getPageSize());
        return baseMapper.selectPageByCondition(classGroupStudentMapperPage, classGroupReq);
    }

    @Override
    public PageResponse getPageByTeacher(StudentReq studentReq) {
        if (Objects.isNull(studentReq.getTeacherId())) {
            return PageResponse.errorParam();
        }
        Teacher teacher = teacherService.getById(studentReq.getTeacherId());
        if (Objects.nonNull(teacher)) {
            //教学主管
            QueryWrapper<MusicGroup> musicGroupQueryWrapper = new QueryWrapper<>();
            if (JobTypeEnum.TEACHING.getCode().equals(teacher.getJobType())) {
                musicGroupQueryWrapper.lambda().eq(MusicGroup::getOrganId, teacher.getOrganId())
                    .eq(MusicGroup::getEducationalTeacherId, teacher.getId());
            } else if (JobTypeEnum.ACADEMIC.getCode().equals(teacher.getJobType())) {
                //教务老师
                musicGroupQueryWrapper.lambda().eq(MusicGroup::getOrganId, teacher.getOrganId())
                    .eq(MusicGroup::getTeamTeacherId, teacher.getId());
            }
            List<MusicGroup> musicGroupList = musicGroupService.list(musicGroupQueryWrapper);
            if (!CollectionUtils.isEmpty(musicGroupList)) {
                QueryWrapper<ClassGroup> classGroupQueryWrapper = new QueryWrapper<>();
                classGroupQueryWrapper.lambda().in(ClassGroup::getMusicGroupId,
                    musicGroupList.stream().map(MusicGroup::getId).collect(Collectors.toList()));
                List<ClassGroup> classGroupList = classGroupService.list(classGroupQueryWrapper);
                if (!CollectionUtils.isEmpty(classGroupList)) {
                    return PageResponse.success(getPage(classGroupList, studentReq, musicGroupList));
                }
            }
            //指导老师 助教老师
            QueryWrapper<ClassGroupTeacherMapper> classGroupTeacherMapperQueryWrapper = new QueryWrapper<>();
            if (JobTypeEnum.ADVISER.getCode().equals(teacher.getJobType())) {
                classGroupTeacherMapperQueryWrapper.lambda().eq(ClassGroupTeacherMapper::getTeacherRole, TeachTypeEnum.BISHOP.getCode())
                    .eq(ClassGroupTeacherMapper::getUserId, teacher.getId());
            } else if (JobTypeEnum.ASSISTANT.getCode().equals(teacher.getJobType())) {
                classGroupTeacherMapperQueryWrapper.lambda().eq(ClassGroupTeacherMapper::getTeacherRole, TeachTypeEnum.TEACHING.getCode())
                    .eq(ClassGroupTeacherMapper::getUserId, teacher.getId());
            }
            List<ClassGroupTeacherMapper> classGroupTeacherMapperList = classGroupTeacherMapperService.list(classGroupTeacherMapperQueryWrapper);
            if (!CollectionUtils.isEmpty(classGroupTeacherMapperList)) {
                QueryWrapper<ClassGroup> classGroupQueryWrapper = new QueryWrapper<>();
                classGroupQueryWrapper.lambda().in(ClassGroup::getMusicGroupId, classGroupTeacherMapperList.stream().
                    map(ClassGroupTeacherMapper::getMusicGroupId).collect(Collectors.toList()));
                List<ClassGroup> classGroupList = classGroupService.list(classGroupQueryWrapper);
                if (!CollectionUtils.isEmpty(classGroupList)) {
                    musicGroupQueryWrapper.lambda().in(MusicGroup::getId, classGroupList.stream().map(ClassGroup::getMusicGroupId).collect(Collectors.toList()));
                    musicGroupList = musicGroupService.list(musicGroupQueryWrapper);
                    return PageResponse.success(getPage(classGroupList, studentReq, musicGroupList));
                }
            }
        }
        return PageResponse.noDataExists();
    }

    @Override
    public BaseResponse getInfo(StudentReq studentReq) {
        if (Objects.isNull(studentReq.getStudentId())) {
            return BaseResponse.errorParam();
        }
        SysUser user = sysUserService.getById(studentReq.getStudentId());
        StudentResp studentResp = new StudentResp();
        List<String> subjectNameList = Lists.newArrayList();
        if (Objects.nonNull(user)) {
            studentResp.setStudentName(user.getRealName())
                .setStudentGender(UserGenderEnum.get(user.getGender()).getDescription());
        }
        QueryWrapper<StudentRegistration> studentRegistrationQueryWrapper = new QueryWrapper<>();
        studentRegistrationQueryWrapper.lambda().eq(StudentRegistration::getUserId, studentReq.getStudentId());
        studentRegistrationService.list(studentRegistrationQueryWrapper).stream().findFirst().
            ifPresent(studentRegistration -> studentResp.setParentsPhone(studentRegistration.getParentsPhone())
                .setStudentGrade(studentRegistration.getCurrentGrade())
                .setRemark(studentRegistration.getRemark()));
        QueryWrapper<ClassGroupStudentMapper> classGroupStudentMapperQueryWrapper = new QueryWrapper<>();
        classGroupStudentMapperQueryWrapper.lambda().eq(ClassGroupStudentMapper::getUserId, studentReq.getStudentId());
        List<ClassGroupStudentMapper> classGroupStudentMapperList = list(classGroupStudentMapperQueryWrapper);
        if (!CollectionUtils.isEmpty(classGroupStudentMapperList)) {
            QueryWrapper<ClassGroup> classGroupQueryWrapper = new QueryWrapper<>();
            classGroupQueryWrapper.lambda().in(ClassGroup::getId, classGroupStudentMapperList.stream().
                map(ClassGroupStudentMapper::getClassGroupId).collect(Collectors.toList()));
            List<ClassGroup> classGroupList = classGroupService.list(classGroupQueryWrapper);
            if (!CollectionUtils.isEmpty(classGroupList)) {
                classGroupList.forEach(classGroup -> {
                    List<Subject> subjectList = subjectService.getSubjectList(classGroup.getSubjectIdList());
                    if (!CollectionUtils.isEmpty(subjectList)) {
                        subjectNameList.addAll(subjectList.stream().map(Subject::getName).collect(Collectors.toList()));
                    }
                });
                //学校
                classGroupList.stream().findFirst().ifPresent(group -> {
                    MusicGroup musicGroup = musicGroupService.getById(group.getMusicGroupId());
                    if (Objects.nonNull(musicGroup) && Objects.nonNull(musicGroup.getSchoolId())) {
                        School school = schoolService.getById(musicGroup.getSchoolId());
                        if (Objects.nonNull(school)) {
                            studentResp.setStudentSchool(school.getName());
                        }
                    }
                });
            }
        }
        studentResp.setSubjectName(subjectNameList);
        return BaseResponse.success(studentResp);
    }

    private IPage<StudentListResp> getPage(List<ClassGroup> classGroupList, StudentReq studentReq, List<MusicGroup> musicGroupList) {
        Page<StudentListResp> pageResult = new Page<>();
        ArrayList<StudentListResp> resultList = Lists.newArrayList();
        QueryWrapper<ClassGroupStudentMapper> classGroupStudentMapperQueryWrapper = new QueryWrapper<>();
        classGroupStudentMapperQueryWrapper.lambda().in(ClassGroupStudentMapper::getClassGroupId,
            classGroupList.stream().map(ClassGroup::getId).collect(Collectors.toList()));
        List<ClassGroupStudentMapper> classGroupStudentMapperList = classGroupStudentMapperService.list(classGroupStudentMapperQueryWrapper);
        if (!CollectionUtils.isEmpty(classGroupStudentMapperList)) {
            QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
            sysUserQueryWrapper.lambda().in(SysUser::getId,
                classGroupStudentMapperList.stream().map(ClassGroupStudentMapper::getUserId).collect(Collectors.toList()))
                .like(SysUser::getRealName, studentReq.getStudentName());
            Page<SysUser> sysUserPage = new Page<SysUser>(studentReq.getPageNo(), studentReq.getPageSize());
            IPage<SysUser> page = sysUserService.page(sysUserPage, sysUserQueryWrapper);
            if (!CollectionUtils.isEmpty(page.getRecords())) {
                BeanUtils.copyProperties(page, pageResult);
                List<MusicGroup> finalMusicGroupList = musicGroupList;
                page.getRecords().forEach(sysUser -> {
                    StudentListResp studentListResp = new StudentListResp();
                    studentListResp.setStudentId(sysUser.getId());
                    studentListResp.setStudentName(sysUser.getRealName());
                    classGroupStudentMapperList.stream().filter
                        (classGroupStudentMapper -> classGroupStudentMapper.getUserId().
                            equals(sysUser.getId())).findFirst().ifPresent(classGroupStudentMapper -> {
                        Integer classGroupId = classGroupStudentMapper.getClassGroupId();
                        classGroupList.stream().filter(classGroup -> classGroup.getId().equals(classGroupId)).
                            findFirst().ifPresent(classGroup -> {
                            Integer musicGroupId = classGroup.getMusicGroupId();
                            //连续迟到
                            QueryWrapper<MusicGroupStudentFee> musicGroupStudentFeeQueryWrapper = new QueryWrapper<MusicGroupStudentFee>();
                            musicGroupStudentFeeQueryWrapper.lambda().eq(true, MusicGroupStudentFee::getMusicGroupId, musicGroupId)
                                .eq(true, MusicGroupStudentFee::getUserId, sysUser.getId());
                            MusicGroupStudentFee musicGroupStudentFee = musicGroupStudentFeeService.getOne(musicGroupStudentFeeQueryWrapper);
                            if (Objects.nonNull(musicGroupStudentFee)) {
                                studentListResp.setStudentAttendance("连续旷课" + musicGroupStudentFee.getContinuousAbsenteeismTimes() + "次");
                            }
                            List<Subject> subjectList = subjectService.getSubjectList(classGroup.getSubjectIdList());
                            if (!CollectionUtils.isEmpty(subjectList)) {
                                studentListResp.setSubjectName(subjectList.stream().map(Subject::getName).collect(Collectors.toList()));
                            }
                            finalMusicGroupList.stream().filter(musicGroup -> musicGroup.getId().equals(musicGroupId)).
                                findFirst().ifPresent(musicGroup -> studentListResp.setMusicGroupName(musicGroup.getName()));
                        });
                    });
                    resultList.add(studentListResp);
                });
            }
        }
        pageResult.setRecords(resultList);
        return pageResult;
    }
}
