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.education.base.BaseResponse;
import com.ym.mec.education.base.PageResponse;
import com.ym.mec.education.entity.*;
import com.ym.mec.education.enums.*;
import com.ym.mec.education.mapper.MusicGroupMapper;
import com.ym.mec.education.req.ClassGroupReq;
import com.ym.mec.education.req.MusicGroupReq;
import com.ym.mec.education.resp.ClassGroupResp;
import com.ym.mec.education.resp.ClassStudentResp;
import com.ym.mec.education.resp.ClassTeacherResp;
import com.ym.mec.education.resp.MusicGroupResp;
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 org.springframework.util.StringUtils;

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

/**
 * <p>
 * 乐团表 服务实现类
 * </p>
 *
 * @author lemeng
 * @since 2019-09-25
 */
@Service("IMusicGroupService")
public class MusicGroupServiceImpl extends ServiceImpl<MusicGroupMapper, MusicGroup> implements IMusicGroupService {

    @Autowired
    private IClassGroupService classGroupService;

    @Autowired
    private IClassGroupTeacherMapperService classGroupTeacherMapperService;

    @Autowired
    private ICourseScheduleTeacherSalaryService courseScheduleTeacherSalaryService;

    @Autowired
    private ITeacherService teacherService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IClassGroupStudentMapperService classGroupStudentMapperService;

    @Autowired
    private IStudentAttendanceService studentAttendanceService;

    @Autowired
    private ISubjectService subjectService;


    @Override
    public PageResponse groupList(MusicGroupReq req) {
        PageResponse response = new PageResponse();
        IPage page = new Page(req.getPageNo() == null ? 0 : req.getPageNo(), req.getPageSize() == null ? 10 : req.getPageSize());
        QueryWrapper<MusicGroup> queryWrapper = new QueryWrapper<>();
        if (req != null && !StringUtils.isEmpty(req.getName())) {
            queryWrapper.eq("name_", req.getName());
        }

        IPage<MusicGroup> queryPage = this.page(page, queryWrapper);
        if (queryPage.getRecords() == null && queryPage.getRecords().isEmpty()) {
            response.setReturnCode(ReturnCodeEnum.CODE_206.getCode());
            return response;
        }

        List<MusicGroup> musicGroupList = queryPage.getRecords();
        List<MusicGroupResp> musicGroupResps = Lists.newArrayList();
        musicGroupList.forEach(g -> {
            MusicGroupResp musicGroupResp = new MusicGroupResp();
            BeanUtils.copyProperties(g, musicGroupResp);
            QueryWrapper<ClassGroup> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("music_group_id_", g.getId());
            List<ClassGroup> classGroups = classGroupService.list(queryWrapper1);
            if (!CollectionUtils.isEmpty(classGroups)) {
                int studNum = classGroups.stream().mapToInt(ClassGroup::getStudentNum).sum();
                musicGroupResp.setStudentNum(studNum);
            } else {
                musicGroupResp.setStudentNum(0);
            }

            QueryWrapper<ClassGroupTeacherMapper> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("music_group_id_", g.getId());
            List<ClassGroupTeacherMapper> classGroupTeacherMappers = classGroupTeacherMapperService.list(queryWrapper2);

            if (!CollectionUtils.isEmpty(classGroupTeacherMappers)) {
                int teachNum = classGroupTeacherMappers.size();
                musicGroupResp.setTeacherNum(teachNum);
            } else {
                musicGroupResp.setTeacherNum(0);
            }

            //老师
            SysUser sysUser1 = sysUserService.getById(g.getTeamTeacherId());

            SysUser sysUser2 = sysUserService.getById(g.getTeamTeacherId());
            if (sysUser1 != null) {
                musicGroupResp.setTeamTeacherName(sysUser1.getRealName());
            }
            if (sysUser2 != null) {
                musicGroupResp.setEduTeacherName(sysUser2.getRealName());
            }
            musicGroupResps.add(musicGroupResp);
        });
        response.setRecords(musicGroupResps);
        response.setReturnCode(ReturnCodeEnum.CODE_200.getCode());
        response.setMessage(ReturnCodeEnum.CODE_200.getValue());
        response.setTotal(Math.toIntExact(page.getTotal()));
        return response;
    }

    @Override
    public BaseResponse groupDetail(Integer groupId) {
        BaseResponse baseResponse = new BaseResponse();

        MusicGroup musicGroup = this.getById(groupId);
        if (musicGroup == null) {
            baseResponse.setReturnCode(ReturnCodeEnum.CODE_207.getCode());
            baseResponse.setMessage(ReturnCodeEnum.CODE_207.getValue());
            return baseResponse;
        }
        MusicGroupResp musicGroupResp = new MusicGroupResp();
        BeanUtils.copyProperties(musicGroup, musicGroupResp);
        QueryWrapper<ClassGroup> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("music_group_id_", groupId);
        List<ClassGroup> classGroups = classGroupService.list(queryWrapper1);
        if (!CollectionUtils.isEmpty(classGroups)) {
            int studNum = classGroups.stream().mapToInt(ClassGroup::getStudentNum).sum();
            musicGroupResp.setStudentNum(studNum);

            Long mergeNum = classGroups.stream().filter(e -> ClassGroupTypeEnum.MIX.getCode().equalsIgnoreCase(e.getType())).count();

            Long unitClassNum = classGroups.stream().filter(e -> ClassGroupTypeEnum.NORMAL.getCode().equalsIgnoreCase(e.getType())).count();
            musicGroupResp.setMergeClassNum(Optional.ofNullable(mergeNum).orElse(0L).intValue());
            musicGroupResp.setUnitClassNum(Optional.ofNullable(unitClassNum).orElse(0L).intValue());


            List<Integer> classId = classGroups.stream().map(e -> e.getId()).collect(Collectors.toList());
            QueryWrapper<ClassGroupStudentMapper> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.in("class_group_id_", classId);

            List<ClassGroupStudentMapper> classGroupStudentMappers = classGroupStudentMapperService.list(queryWrapper2);

            if (!CollectionUtils.isEmpty(classGroupStudentMappers)) {

                Long liveNum = classGroups.stream().filter(e -> ClassGroupStudentStatusEnum.NORMAL.getCode().equalsIgnoreCase(e.getType())).count();

                Long delNum = classGroups.stream().filter(e -> ClassGroupStudentStatusEnum.QUIT.getCode().equalsIgnoreCase(e.getType())).count();
                musicGroupResp.setLiveStudNum(Optional.ofNullable(liveNum).orElse(0L).intValue());
                musicGroupResp.setDelStudNum(Optional.ofNullable(delNum).orElse(0L).intValue());

            }
        }
        //老师
        SysUser sysUser1 = sysUserService.getById(musicGroup.getTeamTeacherId());

        SysUser sysUser2 = sysUserService.getById(musicGroup.getTeamTeacherId());
        if (sysUser1 != null) {
            musicGroupResp.setTeamTeacherName(sysUser1.getRealName());
        }
        if (sysUser2 != null) {
            musicGroupResp.setEduTeacherName(sysUser2.getRealName());
        }
        baseResponse.setDataInfo(musicGroupResp);
        baseResponse.setReturnCode(ReturnCodeEnum.CODE_200.getCode());
        baseResponse.setMessage(ReturnCodeEnum.CODE_200.getValue());
        return baseResponse;
    }

    /**
     * 班级列表
     *
     * @param
     * @return
     */
    @Override
    public PageResponse classGroupList(ClassGroupReq req) {

        PageResponse response = new PageResponse();
        IPage<ClassGroup> page = new Page(req.getPageNo() == null ? 1 : req.getPageNo(), req.getPageSize() == null ? 10 : req.getPageSize());
        QueryWrapper<ClassGroup> queryWrapper1 = new QueryWrapper<>();
        if (req != null && req.getMusicGroupId() != null) {
            queryWrapper1.eq("music_group_id_", req.getMusicGroupId());
        }

        IPage<ClassGroup> classGroupPage = classGroupService.page(page, queryWrapper1);

        if (classGroupPage.getRecords() == null && classGroupPage.getRecords().isEmpty()) {
            response.setReturnCode(ReturnCodeEnum.CODE_206.getCode());
            return response;
        }

        List<ClassGroup> classGroups = classGroupPage.getRecords();

        if(CollectionUtils.isEmpty(classGroups)){
            return PageResponse.noDataExists();
        }

        //班级
        if (req.getType() == 0) {
            List<ClassGroupResp> groupRespList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(classGroups)) {
                classGroups.forEach(e -> {

                    ClassGroupResp classGroupResp = new ClassGroupResp();
                    //查询班级老师
                    BeanUtils.copyProperties(e, classGroupResp);
                    QueryWrapper<ClassGroupTeacherMapper> queryWrapper2 = new QueryWrapper<>();
                    queryWrapper2.eq("music_group_id_", e.getId()).eq("teacher_role_", TeachTypeEnum.BISHOP.getCode());
                    List<ClassGroupTeacherMapper> list = classGroupTeacherMapperService.list(queryWrapper2);

                    if (!CollectionUtils.isEmpty(list)) {
                        List<Integer> firstId = list.stream().map(ClassGroupTeacherMapper::getUserId).collect(Collectors.toList());
                        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
                        queryWrapper.in("id_", firstId);
                        List<SysUser> sysUserList = sysUserService.list(queryWrapper);
                        if (!CollectionUtils.isEmpty(sysUserList)) {
                            classGroupResp.setFirstTehNameList(sysUserList.stream().map(SysUser::getRealName).collect(Collectors.toList()));
                        }
                    }

                    queryWrapper2.eq("music_group_id_", e.getId()).eq("teacher_role_", TeachTypeEnum.TEACHING.getCode());
                    List<ClassGroupTeacherMapper> list2 = classGroupTeacherMapperService.list(queryWrapper2);
                    if (!CollectionUtils.isEmpty(list2)) {
                        List<Integer> secdId = list2.stream().map(ClassGroupTeacherMapper::getUserId).collect(Collectors.toList());
                        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
                        queryWrapper.in("id_", secdId);
                        List<SysUser> sysUserList = sysUserService.list(queryWrapper);
                        if (!CollectionUtils.isEmpty(sysUserList)) {
                            classGroupResp.setSecdTehNameList(sysUserList.stream().map(SysUser::getRealName).collect(Collectors.toList()));
                        }
                    }
                    groupRespList.add(classGroupResp);

                });
            }

            response.setRecords(groupRespList);
            response.setReturnCode(ReturnCodeEnum.CODE_200.getCode());
            response.setMessage(ReturnCodeEnum.CODE_200.getValue());
            response.setTotal(Math.toIntExact(classGroupPage.getTotal()));
            return response;
        }
        //学生
        if (req.getType() == 1) {
            List<ClassStudentResp> classStudentResps = new ArrayList<>();

            List<Integer> classGroupId = classGroups.stream().map(ClassGroup::getId).collect(Collectors.toList());
            QueryWrapper<ClassGroupStudentMapper> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("class_group_id_", classGroupId);
            IPage<ClassGroupStudentMapper> studentPage = new Page<>(req.getPageNo() == null ? 0 : req.getPageNo(), req.getPageSize() == null ? 10 : req.getPageSize());
            IPage<ClassGroupStudentMapper> studentMappersPage = classGroupStudentMapperService.page(studentPage, queryWrapper);
            List<ClassGroupStudentMapper> studentMappers = studentMappersPage.getRecords();

            if (!CollectionUtils.isEmpty(studentMappers)) {
                studentMappers.forEach(stud -> {


                    Optional<ClassGroup> optional = classGroups.stream().filter(e -> e.getId().equals(stud.getClassGroupId())).findFirst();

                    ClassStudentResp classStudentResp = new ClassStudentResp();
                    Set<String> set = new HashSet<>();
                    List<ClassStudentResp> removeList = classStudentResps.stream().filter(c -> c.getUserId().equals(stud.getUserId()) && c.getClassGroupId().equals(stud.getClassGroupId())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(removeList)) {
                        classStudentResp = removeList.get(0);
                        set.addAll(classStudentResp.getClassType());
                        if (optional.isPresent()) {
                            set.add(optional.get().getType());
                        }

                        classStudentResp.setClassType(new ArrayList<>(set));
                    } else {

                        SysUser sysUser = sysUserService.getById(stud.getUserId());
                        if (sysUser != null) {
                            classStudentResp.setName(sysUser.getRealName());
                            classStudentResp.setAvatar(sysUser.getAvatar());
                        }
                        classStudentResp.setUserId(stud.getUserId());
                        classStudentResp.setClassGroupId(stud.getClassGroupId());
                        QueryWrapper<StudentAttendance> truntWrapper = new QueryWrapper<>();
                        //旷课
                        truntWrapper.lambda().eq(true, StudentAttendance::getMusicGroupId, req.getMusicGroupId())
                                .eq(true, StudentAttendance::getClassGroupId, stud.getClassGroupId())
                                .eq(true, StudentAttendance::getStatus, StudentAttendanceStatusEnum.TRUANT.getCode())
                                .eq(true, StudentAttendance::getUserId, stud.getUserId());
                        Integer leaveCount = studentAttendanceService.count(truntWrapper);
                        classStudentResp.setTruantNum(leaveCount);
                        if (optional.isPresent()) {
                            set.add(optional.get().getType());
                            if (ClassGroupTypeEnum.VIP.equals(optional.get().getType())) {
                                classStudentResp.setIsVip(1);
                            }
                        }
                        classStudentResp.setClassType(new ArrayList<>(set));
                        classStudentResps.add(classStudentResp);
                    }

                });

                response.setRecords(classStudentResps);
                response.setReturnCode(ReturnCodeEnum.CODE_200.getCode());
                response.setMessage(ReturnCodeEnum.CODE_200.getValue());
                response.setTotal(Math.toIntExact(studentMappersPage.getTotal()));
                return response;

            }
            //老师

        }

        if (req.getType() == 2) {

            List<ClassTeacherResp> classTeacherResps = new ArrayList<>();
            IPage<ClassGroupTeacherMapper> teacherPage = new Page<>(req.getPageNo() == null ? 0 : req.getPageNo(), req.getPageSize() == null ? 10 : req.getPageSize());

            List<Integer> classGroupIds = classGroups.stream().map(ClassGroup::getId).collect(Collectors.toList());
            QueryWrapper<ClassGroupTeacherMapper> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.in("music_group_id_", classGroupIds);
            IPage<ClassGroupTeacherMapper> teacherMapperIPage = classGroupTeacherMapperService.page(teacherPage, queryWrapper2);
            List<ClassGroupTeacherMapper> list = teacherMapperIPage.getRecords();

            list.forEach(tech -> {
                ClassTeacherResp classTeacherResp = new ClassTeacherResp();
                List<ClassTeacherResp> removeList = classTeacherResps.stream().filter(c -> c.getUserId().equals(tech.getUserId()) && c.getClassGroupId().equals(tech.getClassGroupId())).collect(Collectors.toList());
                HashSet set = new HashSet<>();
                Optional<ClassGroup> optional = classGroups.stream().filter(e -> e.getId().equals(tech.getClassGroupId())).findFirst();
                if (!CollectionUtils.isEmpty(removeList)) {

                    classTeacherResp = removeList.get(0);
                    set.addAll(classTeacherResp.getClassName());

                    if (optional.isPresent()) {
                        set.add(optional.get().getName());
                    }

                    classTeacherResp.setClassName(new ArrayList<>(set));
                } else {
                    SysUser sysUser = sysUserService.getById(tech.getUserId());
                    if (sysUser != null) {
                        classTeacherResp.setName(sysUser.getRealName());
                        classTeacherResp.setAvatar(sysUser.getAvatar());
                    }
                    classTeacherResp.setUserId(tech.getUserId());
                    classTeacherResp.setClassGroupId(tech.getClassGroupId());
                    if (optional.isPresent()) {
                        set.add(optional.get().getName());
                    }

                    classTeacherResp.setClassName(new ArrayList<>(set));

                    //查询老师技能
                    Teacher teacher = teacherService.getById(tech.getUserId());
                    if (teacher != null && !StringUtils.isEmpty(teacher.getSubjectId())) {
                        String ids[] = teacher.getSubjectId().split(",");
                        List<String> stringB = Arrays.asList(ids);
                        QueryWrapper<Subject> queryWrapperSub = new QueryWrapper<>();
                        queryWrapperSub.in("id_", stringB);
                        List<Subject> subjectList = subjectService.list(queryWrapperSub);
                        if (!CollectionUtils.isEmpty(subjectList)) {
                            List<String> subName = subjectList.stream().map(Subject::getName).collect(Collectors.toList());
                            classTeacherResp.setTechSubject(subName);
                        }
                    }

                    classTeacherResps.add(classTeacherResp);
                }

            });

            response.setRecords(classTeacherResps);
            response.setReturnCode(ReturnCodeEnum.CODE_200.getCode());
            response.setMessage(ReturnCodeEnum.CODE_200.getValue());
            response.setTotal(Math.toIntExact(teacherPage.getTotal()));
            return response;

        }
        return response;
    }
}
