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

import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.*;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.dal.enums.CourseStatusEnum;
import com.ym.mec.biz.dal.enums.SporadicChargeTypeEnum;
import com.ym.mec.biz.dal.page.*;
import com.ym.mec.biz.service.SysConfigService;

import com.ym.mec.common.page.QueryInfo;
import com.ym.mec.util.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.ClassGroupDao;
import com.ym.mec.biz.dal.dao.CourseScheduleStudentPaymentDao;
import com.ym.mec.biz.dal.dao.MusicGroupDao;
import com.ym.mec.biz.dal.dao.MusicGroupPaymentCalenderDao;
import com.ym.mec.biz.dal.dao.MusicGroupQuitDao;
import com.ym.mec.biz.dal.dao.OrganizationDao;
import com.ym.mec.biz.dal.dao.StudentDao;
import com.ym.mec.biz.dal.dao.StudentExtracurricularExercisesSituationDao;
import com.ym.mec.biz.dal.dao.StudentManageDao;
import com.ym.mec.biz.dal.dao.StudentPaymentOrderDao;
import com.ym.mec.biz.dal.dao.StudentRegistrationDao;
import com.ym.mec.biz.dal.dao.SubjectChangeDao;
import com.ym.mec.biz.dal.dao.SysUserCashAccountDao;
import com.ym.mec.biz.dal.dao.TeacherDao;
import com.ym.mec.biz.dal.dao.VipGroupDao;
import com.ym.mec.biz.dal.entity.MusicGroupQuit;
import com.ym.mec.biz.dal.entity.Student;
import com.ym.mec.biz.dal.entity.StudentRegistration;
import com.ym.mec.biz.dal.entity.SubjectChange;
import com.ym.mec.biz.dal.entity.SysUserCashAccount;
import com.ym.mec.biz.dal.entity.Teacher;
import com.ym.mec.biz.dal.enums.YesOrNoEnum;
import com.ym.mec.biz.service.StudentManageService;
import com.ym.mec.biz.service.StudentService;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.common.entity.ImResult;
import com.ym.mec.common.entity.ImUserModel;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.im.ImFeignService;
import com.ym.mec.util.collection.MapUtil;

/**
 * @Author Joburgess
 * @Date 2019/9/19
 */
@Service
public class StudentManageServiceImpl implements StudentManageService {

    @Autowired
    private StudentManageDao studentManageDao;
    @Autowired
    private MusicGroupPaymentStudentCourseDetailDao musicGroupPaymentStudentCourseDetailDao;
    @Autowired
    private CourseScheduleStudentPaymentDao scheduleStudentPaymentDao;
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private StudentService studentService;
    @Autowired
    private MusicGroupDao musicGroupDao;
    @Autowired
    private StudentRegistrationDao studentRegistrationDao;
    @Autowired
    private ImFeignService imFeignService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private ClassGroupDao classGroupDao;
    @Autowired
    private StudentPaymentOrderDao studentPaymentOrderDao;
    @Autowired
    private VipGroupDao vipGroupDao;
    @Autowired
    private SysUserCashAccountDao sysUserCashAccountDao;
    @Autowired
    private StudentDao studentDao;
    @Autowired
    private StudentExtracurricularExercisesSituationDao studentExtracurricularExercisesSituationDao;
    @Autowired
    private MusicGroupQuitDao musicGroupQuitDao;
    @Autowired
    private SubjectChangeDao subjectChangeDao;
    @Autowired
    private MusicGroupPaymentCalenderDao musicGroupPaymentCalenderDao;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private CourseScheduleStudentPaymentDao courseScheduleStudentPaymentDao;
    @Autowired
    private CourseScheduleDao courseScheduleDao;

    @Override
    public PageInfo<StudentManageListDto> findStudentsByOrganId(StudentManageQueryInfo queryInfo) {
        PageInfo<StudentManageListDto> pageInfo = new PageInfo<StudentManageListDto>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<String, Object>();
        MapUtil.populateMap(params, queryInfo);

        List<StudentManageListDto> dataList = null;
        int count = studentManageDao.countStudentByOrganId(params);
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList = studentManageDao.findStudentsByOrganId(params);
        }
        if (dataList == null) {
            dataList = new ArrayList<StudentManageListDto>();
        }
        pageInfo.setRows(dataList);

        if (dataList.size() == 0) {
            return pageInfo;
        }

        Set<Integer> userIds = dataList.stream().map(StudentManageListDto::getUserId).collect(Collectors.toSet());

        List<StudentListCourseDto> studentListCourseDtoList = studentManageDao.queryStudentRemianCourse(userIds);
        Map<Integer, StudentListCourseDto> StudentListCourseDtoMap = studentListCourseDtoList.stream().collect(Collectors.toMap(StudentListCourseDto::getUserId, studentListCourseDto -> studentListCourseDto));

        StudentListCourseDto studentListCourseDto = null;
        for (StudentManageListDto dto : dataList) {
            studentListCourseDto = StudentListCourseDtoMap.get(dto.getUserId());
            if (studentListCourseDto != null) {
                if (studentListCourseDto.getRemainCourseNum() > 0) {
                    dto.setHasCourse(YesOrNoEnum.YES);
                } else {
                    dto.setHasCourse(YesOrNoEnum.NO);
                }
                if (studentListCourseDto.getRemainPracticeNum() > 0) {
                    dto.setHasPracticeCourse(YesOrNoEnum.YES);
                } else {
                    dto.setHasPracticeCourse(YesOrNoEnum.NO);
                }
            } else {
                dto.setHasCourse(YesOrNoEnum.NO);
                dto.setHasPracticeCourse(YesOrNoEnum.NO);
            }
        }

        if (queryInfo.getIsExport()) {
            if (count > 50000) {
                throw new BizException("数据集太大，不能导出.最大数据集不能超过50000");
            }
            //获取所在乐团
            Map<Integer, String> musicGroupNames = MapUtil.convertMybatisMap(musicGroupDao.queryUserMusicNames(userIds));
            //获取所在vip
            Map<Integer, String> vipGroupNames = MapUtil.convertMybatisMap(vipGroupDao.queryUserVipNames(userIds));
            //获取所在乐团状态
            Map<Integer, String> musicGroupStatus = MapUtil.convertMybatisMap(musicGroupDao.queryUserMusicStatus(userIds));
            //获取所在vip状态
            Map<Integer, String> vipGroupStatus = MapUtil.convertMybatisMap(vipGroupDao.queryUserVipStatus(userIds));

            dataList.forEach(e -> {
                e.setMusicGroupName(musicGroupNames.get(e.getUserId()));
                e.setVipGroupName(vipGroupNames.get(e.getUserId()));
                e.setMusicGroupStatus(musicGroupStatus.get(e.getUserId()));
                e.setVipGroupStatus(vipGroupStatus.get(e.getUserId()));
            });
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    public PageInfo<SimpleUserDto> queryStudentsWithTeacher(StudentManageQueryInfo queryInfo) {
        PageInfo<SimpleUserDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<String, Object>();
        MapUtil.populateMap(params, queryInfo);

        Teacher teacher = teacherDao.get(queryInfo.getTeacherId());
        if (Objects.isNull(teacher)) {
            return null;
        }
        List<Integer> organIds = new ArrayList<>();
        if (Objects.nonNull(teacher.getTeacherOrganId())) {
            organIds.add(teacher.getTeacherOrganId());
        }
        if (StringUtils.isNotBlank(teacher.getFlowOrganRange())) {
            List<Integer> flowOrganRangeIds = Arrays.stream(teacher.getFlowOrganRange().split(",")).map(e -> Integer.valueOf(e)).collect(Collectors.toList());
            organIds.addAll(flowOrganRangeIds);
        }

        if (CollectionUtils.isEmpty(organIds)) {
            return null;
        }

        params.put("organIds", organIds);

        List<SimpleUserDto> dataList = null;
        int count = studentDao.countStudentsWithOrgan(params);
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList = studentDao.getStudentsWithOrgan(params);
        }
        if (count == 0) {
            dataList = new ArrayList<>();
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    public PageInfo<StudentVipDouble11Dto> queryDouble11Students(StudentManageQueryInfo queryInfo) {
        PageInfo<StudentVipDouble11Dto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<String, Object>();
        MapUtil.populateMap(params, queryInfo);

        List<StudentVipDouble11Dto> dataList = new ArrayList<>();
        int count = studentPaymentOrderDao.countDouble11Students(params);
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList = studentPaymentOrderDao.queryDouble11Students(params);
            SysConfig vipSpecialActivityConfig = sysConfigService.findByParamName(SysConfigService.VIP_SPECIAL_ACTIVITY_IDS);
            Map<Integer, StudentVipDouble11Dto> studentCourseTimeMap = new HashMap<>();
            if(Objects.nonNull(vipSpecialActivityConfig)&&StringUtils.isNotBlank(vipSpecialActivityConfig.getParanValue())){
                Set<Integer> studentIds = dataList.stream().map(StudentVipDouble11Dto::getUserId).collect(Collectors.toSet());
                Set<Integer> specialActivityIds = Arrays.stream(vipSpecialActivityConfig.getParanValue().split(",")).map(Integer::valueOf).collect(Collectors.toSet());
                List<StudentVipDouble11Dto> studentCourseTimeList = courseScheduleStudentPaymentDao.countStudentDouble11CourseTime(new ArrayList<>(studentIds), new ArrayList<>(specialActivityIds));
                studentCourseTimeMap = studentCourseTimeList.stream().collect(Collectors.toMap(StudentVipDouble11Dto::getUserId, s -> s));
            }
            for (StudentVipDouble11Dto studentVipDouble11Dto : dataList) {
                StudentVipDouble11Dto studentCourseTime = studentCourseTimeMap.get(studentVipDouble11Dto.getUserId());
                studentVipDouble11Dto.setCourseOneToOneTime(studentVipDouble11Dto.getPaymentOneToOneTime()*20-(Objects.isNull(studentCourseTime)?0:studentCourseTime.getCourseOneToOneTime()));
                if(studentVipDouble11Dto.getCourseOneToOneTime()<0){
                    studentVipDouble11Dto.setCourseOneToOneTime(0);
                }
                studentVipDouble11Dto.setCourseOneToTwoTime(studentVipDouble11Dto.getPaymentOneToTwoTime()*20-(Objects.isNull(studentCourseTime)?0:studentCourseTime.getCourseOneToTwoTime()));
                if(studentVipDouble11Dto.getCourseOneToTwoTime()<0){
                    studentVipDouble11Dto.setCourseOneToTwoTime(0);
                }
            }
        }
        pageInfo.setRows(dataList);

        return pageInfo;
    }

    @Override
    public List<StudentVipDouble11Dto> getStudentDouble11Info(List<Integer> studentIds) {
        List<StudentVipDouble11Dto> studentsDouble11Infos = studentPaymentOrderDao.findStudentsDouble11Infos(studentIds);
        SysConfig vipSpecialActivityConfig = sysConfigService.findByParamName(SysConfigService.VIP_SPECIAL_ACTIVITY_IDS);
        Map<Integer, StudentVipDouble11Dto> studentCourseTimeMap = new HashMap<>();
        if(Objects.nonNull(vipSpecialActivityConfig)&&StringUtils.isNotBlank(vipSpecialActivityConfig.getParanValue())){
            Set<Integer> specialActivityIds = Arrays.stream(vipSpecialActivityConfig.getParanValue().split(",")).map(Integer::valueOf).collect(Collectors.toSet());
            List<StudentVipDouble11Dto> studentCourseTimeList = courseScheduleStudentPaymentDao.countStudentDouble11CourseTime(studentIds, new ArrayList<>(specialActivityIds));
            studentCourseTimeMap = studentCourseTimeList.stream().collect(Collectors.toMap(StudentVipDouble11Dto::getUserId, s -> s));
        }
        for (StudentVipDouble11Dto studentVipDouble11Dto : studentsDouble11Infos) {
            StudentVipDouble11Dto studentCourseTime = studentCourseTimeMap.get(studentVipDouble11Dto.getUserId());
            studentVipDouble11Dto.setCourseOneToOneTime(studentVipDouble11Dto.getPaymentOneToOneTime()*20-(Objects.isNull(studentCourseTime)?0:studentCourseTime.getCourseOneToOneTime()));
            if(studentVipDouble11Dto.getCourseOneToOneTime()<0){
                studentVipDouble11Dto.setCourseOneToOneTime(0);
            }
            studentVipDouble11Dto.setCourseOneToTwoTime(studentVipDouble11Dto.getPaymentOneToTwoTime()*20-(Objects.isNull(studentCourseTime)?0:studentCourseTime.getCourseOneToTwoTime()));
            if(studentVipDouble11Dto.getCourseOneToTwoTime()<0){
                studentVipDouble11Dto.setCourseOneToTwoTime(0);
            }
        }
        return studentsDouble11Infos;
    }

    @Override
    public StudentManageListDto findStudentManageBaseInfo(Integer userId) {
        return studentManageDao.findStudentBaseInfoByUserID(userId);
    }

    @Override
    public List<StudentManageBaseInfoOfMusicGroupDto> findStudentMusicGroupsByUserId(Integer userId) {
        List<StudentManageBaseInfoOfMusicGroupDto> musicGroups = studentManageDao.findStudentMusicGroupsByUserId(userId);
        //获取学员报名时所选乐器
        if (musicGroups.size() > 0) {
            for (StudentManageBaseInfoOfMusicGroupDto e : musicGroups) {
                List<UserGoodsDto> userGoods = new ArrayList<>();
                SubjectChange studentLastChange = subjectChangeDao.getStudentLastChange(e.getUserId(), e.getMusicGroupId());
                if (studentLastChange != null) {
                    String goodsIds = "";
                    if (studentLastChange.getChangeMusical() != null) {
                        goodsIds += studentLastChange.getChangeMusical();
                    }
                    if (studentLastChange.getChangeAccessories() != null) {
                        goodsIds += StringUtils.isNotBlank(goodsIds) ? "," + studentLastChange.getChangeAccessories() : studentLastChange.getChangeAccessories();
                    }
                    if (StringUtils.isNotBlank(goodsIds)) {
                        userGoods = studentPaymentOrderDao.getUserGoods(goodsIds);
                    }
                } else {
                    userGoods = studentPaymentOrderDao.findGoodsIds(e.getMusicGroupId(), e.getUserId());
                }
                e.setUserGoodsDtos(userGoods);
            }
        }
        List<MusicGroupQuit> userMusicQuits = musicGroupQuitDao.getUserMusicQuit(userId);
        for (StudentManageBaseInfoOfMusicGroupDto musicGroup : musicGroups) {
            for (MusicGroupQuit userMusicQuit : userMusicQuits) {
                if (musicGroup.getMusicGroupId().equals(userMusicQuit.getMusicGroupId())) {
                    musicGroup.setQuitMusicGroupDate(userMusicQuit.getQuitDate());
                }
            }
        }

        return musicGroups;
    }

    @Override
    public List<MusicCardDto> queryUserMusicInfos(Integer userId) {
        return musicGroupDao.queryUserMusicInfos(userId);
    }

    @Override
    public PageInfo findStudentCourseList(StudentManageCourseQueryInfo queryInfo) {
        PageInfo pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<String, Object>();
        MapUtil.populateMap(params, queryInfo);

        List dataList = null;
        int count = studentManageDao.countStudentCourses(params);
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList = studentManageDao.findStudentCourseList(params);
        }
        if (count == 0) {
            dataList = new ArrayList<>();
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    public PageInfo findStudentAttendances(StudentManageAttendanceQueryInfo queryInfo) {
        PageInfo pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<String, Object>();
        MapUtil.populateMap(params, queryInfo);

        List<StudentManageCourseListDto> dataList = null;
        int count = studentManageDao.countStudentAttendances(params);
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList = studentManageDao.findStudentAttendances(params);
        }
        if (count == 0) {
            dataList = new ArrayList<>();
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    public PageInfo<StudentManageVipGroupDto> findStudentVipGroups(StudentManageCourseQueryInfo queryInfo) {
        PageInfo pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<String, Object>();
        MapUtil.populateMap(params, queryInfo);

        List dataList = null;
        int count = vipGroupDao.countStudentVipGroups(params);
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList = vipGroupDao.findStudentVipGroups(params);
        }
        if (count == 0) {
            dataList = new ArrayList<>();
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    public StudentManageAccountBaseInfoDto getStudentAccountBaseInfo(Integer userId) {
        return studentManageDao.getStudentAccountBaseInfo(userId);
    }

    @Override
    public PageInfo queryStudentPayment(TeacherPaymentRecordInfo queryInfo) {
        PageInfo pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<String, Object>();
        MapUtil.populateMap(params, queryInfo);

        List dataList = null;
        int count = studentManageDao.countStudentPayment(params);
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList = studentManageDao.queryStudentPayment(params);
        }
        if (count == 0) {
            dataList = new ArrayList<>();
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    public PageInfo<MusicGroupStudentsDto> queryMusicGroupStudent(MusicGroupStudentQueryInfo queryInfo) {
        PageInfo<MusicGroupStudentsDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<>();
        MapUtil.populateMap(params, queryInfo);
        List<MusicGroupStudentsDto> dataList = null;
        int count = studentManageDao.countMusicGroupStudent(params);
        if (queryInfo.getIsExport() && count > 50000) {
            throw new BizException("数据集太大，不能导出.最大数据集不能超过50000");
        }
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList = studentManageDao.queryMusicGroupStudent(params);
            //退团的学生
            List<Integer> quitUserIds = dataList.stream().filter(e -> e.getStudentStatus().equals("QUIT")).map(MusicGroupStudentsDto::getUserId).collect(Collectors.toList());
            if (quitUserIds.size() > 0) {
                List<MusicGroupQuit> quits = musicGroupQuitDao.getQuits(queryInfo.getMusicGroupId(), quitUserIds);
                for (MusicGroupStudentsDto musicGroupStudentsDto : dataList) {
                    for (MusicGroupQuit quit : quits) {
                        if (!quit.getUserId().equals(musicGroupStudentsDto.getUserId())) continue;
                        musicGroupStudentsDto.setQuitReason(quit.getReason());
                    }
                }
            }
        }
        if (count == 0) {
            dataList = new ArrayList<>();
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    public Object musicGroupStudentsSum(String musicGroupId) {
        Map<String, Integer> resultMap = new HashMap<>(3);
        //乐团在读人数
        resultMap.put("studying", studentManageDao.countStudyNum(musicGroupId));
        //退团人数
        resultMap.put("quit", studentManageDao.countQuitNum(musicGroupId));
        //新增人数
        resultMap.put("add", studentManageDao.countAddNum(musicGroupId));
        return resultMap;
    }

    @Override
    public PageInfo<MusicGroupStudentSignDto> queryMusicGroupStudentsSign(StudentSignQueryInfo queryInfo) {
        PageInfo<MusicGroupStudentSignDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<>();
        MapUtil.populateMap(params, queryInfo);

        List<MusicGroupStudentSignDto> dataList = null;
        int count = studentManageDao.countMusicGroupStudentsSign(params);
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList = studentManageDao.queryMusicGroupStudentsSign(params);
        }
        if (count == 0) {
            dataList = new ArrayList<>();
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    public List<ConditionDto> queryStudentClassGroup(String musicGroupId, Integer teacherId) {
        return classGroupDao.queryStudentClassGroup(musicGroupId, teacherId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(SysUser sysUser) {
        studentManageDao.updateUser(sysUser);
        StudentRegistration studentRegistration = new StudentRegistration();
        studentRegistration.setUserId(sysUser.getId());
        studentRegistration.setCurrentClass(sysUser.getCurrentClass());
        studentRegistration.setCurrentGrade(sysUser.getCurrentGrade());
        studentRegistrationDao.updateCurrentClass(studentRegistration);
    }

    @Override
    public PageInfo<StudentManageVipGroupClassDto> findStudentVipGroupClass(StudentManageVipClassQueryInfo queryInfo) {
        PageInfo<StudentManageVipGroupClassDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<>();
        MapUtil.populateMap(params, queryInfo);

        List<StudentManageVipGroupClassDto> dataList = null;
        int count = studentManageDao.countStudentVipGroupClass(params);
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList = studentManageDao.findStudentVipGroupClass(params);
            Set<Integer> teacherIds = dataList.stream().map(e -> e.getTeacherId()).collect(Collectors.toSet());
            teacherIds.addAll(dataList.stream().map(e -> e.getEduTeacherId()).collect(Collectors.toSet()));
            List<Map<Integer, String>> maps = teacherDao.queryNameByIds(StringUtils.join(teacherIds, ","));
            Map<Integer, String> teacherNameMap = MapUtil.convertMybatisMap(maps);
            dataList.forEach(e -> {
                e.setTeacherName(teacherNameMap.get(e.getTeacherId()));
                e.setEduTeacherName(teacherNameMap.get(e.getEduTeacherId()));
            });
        }
        if (count == 0) {
            dataList = new ArrayList<>();
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int studentRegister(Student student) {
        if (student == null || StringUtils.isEmpty(student.getPhone())) {
            throw new BizException("参数校验失败");
        }
        Date date = new Date();
        SysUser sysUser = sysUserFeignService.queryUserByMobile(student.getPhone());
        if (sysUser != null) {
            if (sysUser.getUserType().contains("STUDENT")) {
                throw new BizException("手机号已被占用");
            } else {
                student.setId(sysUser.getId());
                student.setUserType(sysUser.getUserType() + ",STUDENT");
                student.setUpdateTime(date);
                sysUserFeignService.updateSysUser(student);
            }
        } else {
            student.setUpdateTime(date);
            student.setCreateTime(date);
            student.setUserType("STUDENT");
            HttpResponseResult<Integer> result = sysUserFeignService.addUser(student);
            student.setId(result.getData());

            ImResult register = imFeignService.register(new ImUserModel(student.getId().toString(), student.getPhone(), null));
            student.setImToken(register.getToken());
            sysUserFeignService.updateSysUser(student);

            sysUserCashAccountDao.insert(new SysUserCashAccount(student.getId(), "CNY"));
        }
        student.setUserId(student.getId());

        studentService.upSet(student);
        return student.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int studentUpdate(Student student) {
        Integer userId = student.getId();
        if (userId == null || StringUtils.isEmpty(student.getPhone())) {
            throw new BizException("参数校验失败");
        }
        SysUser sysUser1 = sysUserFeignService.queryUserByMobile(student.getPhone());
        if (sysUser1 != null && !userId.equals(sysUser1.getId())) {
            throw new BizException("手机号已被占用");
        }
        sysUserFeignService.updateSysUser(student);

        student.setUserId(student.getId());
        student.setOperatingTag(student.getOperatingTag());
        student.setOperatingTempTag(0);
        student.setServiceTag(student.getServiceTag() == 0 ? 2 : 1);
        student.setTeacherId(student.getTeacherId());
        studentService.upSet(student);
        if (new Integer(2).equals(student.getServiceTag())) {
            LocalDate nowDate = LocalDateTime.now(DateUtil.zoneId).toLocalDate();
            LocalDate monDayDate = nowDate.with(DateUtil.weekFields.dayOfWeek(), DayOfWeek.MONDAY.getValue());
            studentExtracurricularExercisesSituationDao.deleteByStudent(student.getId(), monDayDate.toString());
        }
        return userId;
    }

    @Override
    public List<StudentRegisterPerDto> queryStudentPer() {
        Set<Integer> musicUserIds = scheduleStudentPaymentDao.queryMusicStudentPer();
        Set<Integer> vipUserIds = scheduleStudentPaymentDao.queryVipStudentPer();
        musicUserIds.addAll(vipUserIds);
        return studentRegistrationDao.queryStudentPer(musicUserIds);
    }

    @Override
    public List<StudentManageListDto> queryHasCourseStudent(StudentManageQueryInfo queryInfo) {
        Map<String, Object> params = new HashMap<>();
        MapUtil.populateMap(params, queryInfo);
        List<StudentManageListDto> studentHasCourseDtos = studentManageDao.queryHasCourseStudent(params);
        /*Set<Integer> userIds = studentHasCourseDtos.stream().map(e -> e.getUserId()).collect(Collectors.toSet());
        Map<Integer,Integer> hasPracticeCourseMap = MapUtil.convertIntegerMap(studentManageDao.getHasPracticeCourse(userIds));
        Map<Integer,Integer> isActiveMap = MapUtil.convertIntegerMap(studentManageDao.getIsActive(userIds));
        Map<Integer,Integer> isMakeMap = MapUtil.convertIntegerMap(studentManageDao.getIsMake(userIds));
        studentHasCourseDtos.forEach(e->{
            e.setHasPracticeCourse(hasPracticeCourseMap.get(e.getUserId()) == null?YesOrNoEnum.NO:YesOrNoEnum.YES);
            e.setIsActive(isActiveMap.get(e.getUserId()) == null?YesOrNoEnum.YES:YesOrNoEnum.NO);
            e.setIsMake(isMakeMap.get(e.getUserId()) == null?YesOrNoEnum.NO:YesOrNoEnum.YES);
        });*/
        return studentHasCourseDtos;
    }

    @Override
    public Map<String, Integer> sumStudentAttendance(Integer courseScheduleId) {
        CourseSchedule courseSchedule = courseScheduleDao.get(courseScheduleId.longValue());
        Map<String, Integer> sum = new HashMap<>(5);
        Integer studentNum = scheduleStudentPaymentDao.countStudentNum(courseScheduleId);
        sum.put("studentNum", studentNum);
        Integer signInNum = studentManageDao.countStudentSignInNum(courseScheduleId, "NORMAL");
        sum.put("signInNum", signInNum);
        Integer leaveNum = studentManageDao.countStudentSignInNum(courseScheduleId, "LEAVE");
        sum.put("leaveNum", leaveNum);
        studentNum = studentNum == null ? 0 : studentNum;
        signInNum = signInNum == null ? 0 : signInNum;
        leaveNum = leaveNum == null ? 0 : leaveNum;
        if(Objects.nonNull(courseSchedule)&& !CourseStatusEnum.NOT_START.equals(courseSchedule.getStatus())){
            sum.put("truantNum", studentNum - signInNum - leaveNum);
        }else{
            sum.put("truantNum", 0);
        }
        sum.put("homeworkNum", studentManageDao.countHomeworkNum(courseScheduleId));
        sum.put("repliedNum", studentManageDao.countRepliedNum(courseScheduleId));
        return sum;
    }

    @Override
    public PageInfo<Student4operating> getOperatingStudents(StudentOperatingQueryInfo queryInfo) {
        PageInfo<Student4operating> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<>();
        MapUtil.populateMap(params, queryInfo);
        params.put("offset", pageInfo.getOffset());
        Integer count = studentDao.countOperatingStudents(params);

        List<Student4operating> dataList = new ArrayList<>();

        if (count > 0) {
            pageInfo.setTotal(count);
            dataList = studentDao.getOperatingStudents(params);

            Set<Integer> studentIds = dataList.stream().map(Student4operating::getStudentId).collect(Collectors.toSet());

            List<UserGroupDto> allUserGroups = studentRegistrationDao.getUserGroups(new ArrayList<>(studentIds));
            Map<Integer, List<UserGroupDto>> userGroupsMap = new HashMap<>();
            if(!CollectionUtils.isEmpty(allUserGroups)){
                userGroupsMap = allUserGroups.stream().collect(Collectors.groupingBy(UserGroupDto::getUserId));
            }

            for (Student4operating student4operating : dataList) {
                List<UserGroupDto> userGroupDtos = userGroupsMap.get(student4operating.getStudentId());
                if(!CollectionUtils.isEmpty(userGroupDtos)){
                    student4operating.setGroupNames(userGroupDtos.stream().map(UserGroupDto::getGroupName).sorted().collect(Collectors.joining(",")));
                }
            }
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    public List<BasicUserDto> queryCanAddStudent(String musicGroupId, String batchNo,String search,Integer subjectId) {
        return studentManageDao.queryCanAddStudent(musicGroupId, batchNo,search,subjectId);
    }

    @Override
    public PageInfo<BasicUserDto> queryGroupStudents(StudentQueryInfo queryInfo) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if(sysUser == null || sysUser.getId() == null){
            throw new BizException("用户信息获取失败");
        }
        PageInfo<BasicUserDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<>();
        queryInfo.setTeacherId(sysUser.getId());
        MapUtil.populateMap(params, queryInfo);
        params.put("offset", pageInfo.getOffset());
        Integer count = 0;
        if("VIP".equals(queryInfo.getGroupType())){
            count = studentManageDao.countVipGroupStudents(params);
        }else {
            count = studentManageDao.countPracticeGroupStudents(params);
        }
        List<BasicUserDto> dataList = new ArrayList<>();
        if (count > 0) {
            pageInfo.setTotal(count);
            if("VIP".equals(queryInfo.getGroupType())){
                dataList = studentManageDao.queryVipGroupStudents(params);
            }else {
                dataList = studentManageDao.queryPracticeGroupStudents(params);
            }
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    public PageInfo<StudentNoStartCoursesDto> queryStudentNoStartCourse(StudentQueryInfo queryInfo) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if(sysUser == null || sysUser.getId() == null){
            throw new BizException("用户信息获取失败");
        }
        PageInfo<StudentNoStartCoursesDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<>();
        queryInfo.setTeacherId(sysUser.getId());
        MapUtil.populateMap(params, queryInfo);
        params.put("offset", pageInfo.getOffset());
        Integer count = courseScheduleDao.countStudentNoStartCourse(params);
        List<StudentNoStartCoursesDto> dataList = new ArrayList<>();
        if (count > 0) {
            pageInfo.setTotal(count);
            dataList = courseScheduleDao.queryStudentNoStartCourse(params);
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    public List<StudentSubTotalCourseTimesDto> queryStudentSubTotalCourseTimes(String musicGroupId) {
        return musicGroupPaymentStudentCourseDetailDao.queryStudentSubTotalCourseTimes(musicGroupId);
    }
}
