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

import com.alibaba.fastjson.JSON;
import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
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.StudentMusicGroupStatusEnum;
import com.ym.mec.biz.dal.enums.SysUserRoleEnum;
import com.ym.mec.biz.dal.enums.YesOrNoEnum;
import com.ym.mec.biz.dal.page.*;
import com.ym.mec.biz.service.*;
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.common.tenant.TenantContextHolder;
import com.ym.mec.im.ImFeignService;
import com.ym.mec.util.collection.MapUtil;
import com.ym.mec.util.date.DateUtil;
import com.ym.mec.web.WebFeignService;
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 java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @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 StudentExtracurricularExercisesSituationService studentExtracurricularExercisesSituationService;
    @Autowired
    private MusicGroupQuitDao musicGroupQuitDao;
    @Autowired
    private SubjectChangeDao subjectChangeDao;
    @Autowired
    private MusicGroupPaymentCalenderDetailDao musicGroupPaymentCalenderDetailDao;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private CourseScheduleStudentPaymentDao courseScheduleStudentPaymentDao;
    @Autowired
    private CourseScheduleDao courseScheduleDao;
    @Autowired
    private SysUserContractsDao sysUserContractsDao;
    @Autowired
    private WebFeignService webFeignService;
    @Autowired
    private StudentCourseHomeworkDao studentCourseHomeworkDao;
    @Autowired
    private IndexBaseMonthDataDao indexBaseMonthDataDao;
    @Autowired
    private StudentInstrumentDao studentInstrumentDao;
    @Autowired
    private CloudTeacherOrderService cloudTeacherOrderService;
    @Autowired
    private OrganizationDegreeCourseFeeDao organizationDegreeCourseFeeDao;
    @Autowired
    private ActivityUserMapperDao activityUserMapperDao;
    @Autowired
    private SysTenantConfigService sysTenantConfigService;
    @Autowired
    private SysEmployeePositionService employeePositionService;
    @Autowired
    private TenantInfoService tenantInfoService;

    @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);

        if(StringUtils.isNotEmpty(queryInfo.getOrganId())){
            String[] organIds = queryInfo.getOrganId().split(",");
            params.put("organIds", organIds);
        }

        List<StudentManageListDto> dataList = null;
        int count = studentManageDao.countStudentByOrganId(params);
        if (queryInfo.getIsExport()) {
            if (count > 50000) {
                throw new BizException("数据集太大，不能导出.最大数据集不能超过50000");
            }
        }
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList = studentManageDao.findStudentsByOrganId(params);
        }
        if (dataList == null) {
            dataList = new ArrayList<>();
        }
        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));

        //用户协议
        List<SysUserContracts> userAllContract = sysUserContractsDao.getUserAllContract(new ArrayList<>(userIds));
        Map<Integer, Set<Integer>> userContractVersionMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(userAllContract)) {
            userContractVersionMap = userAllContract.stream().collect(Collectors.groupingBy(SysUserContracts::getUserId, Collectors.mapping(SysUserContracts::getVersion, Collectors.toSet())));
        }
        Map<Long, String> cloudMap = MapUtil.convertMybatisMap(cloudTeacherOrderService.queryNoStartByUserIds(userIds, null));
        //List<Subject> studentSubject = studentManageDao.getStudentSubject(userIds);
        StudentListCourseDto studentListCourseDto = null;
        //获取所在乐团
        Map<Integer, String> musicGroupNames = null;
        //获取所在vip
        Map<Integer, String> vipGroupNames = null;
        //获取所在乐团状态
        Map<Integer, String> musicGroupStatus = null;
        //获取所在vip状态
        Map<Integer, String> vipGroupStatus = null;
        if (queryInfo.getIsExport()) {
            //获取所在乐团
            musicGroupNames = MapUtil.convertMybatisMap(musicGroupDao.queryUserMusicNames(userIds));
            //获取所在vip
            vipGroupNames = MapUtil.convertMybatisMap(vipGroupDao.queryUserVipNames(userIds));
            //获取所在乐团状态
            musicGroupStatus = MapUtil.convertMybatisMap(musicGroupDao.queryUserMusicStatus(userIds));
            //获取所在vip状态
            vipGroupStatus = MapUtil.convertMybatisMap(vipGroupDao.queryUserVipStatus(userIds));
        }
        for (StudentManageListDto dto : dataList) {
            if (queryInfo.getIsExport()) {
                dto.setMusicGroupName(musicGroupNames.get(dto.getUserId()));
                dto.setVipGroupName(vipGroupNames.get(dto.getUserId()));
                dto.setMusicGroupStatus(musicGroupStatus.get(dto.getUserId()));
                dto.setVipGroupStatus(vipGroupStatus.get(dto.getUserId()));
            }
            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);
                    dto.setNoStartPracticeCourseNum(studentListCourseDto.getRemainPracticeNum());
                } else {
                    dto.setHasPracticeCourse(YesOrNoEnum.NO);
                }
                if (studentListCourseDto.getRemainVipNum() > 0) {
                    dto.setNoStartVipCourseNum(studentListCourseDto.getRemainVipNum());
                }
            } else {
                dto.setHasCourse(YesOrNoEnum.NO);
                dto.setHasPracticeCourse(YesOrNoEnum.NO);
            }
            //如果会员已过期、是否有未生效的会员
            if (dto.getMemberRankSettingId() == null) {
                String s = cloudMap.get(dto.getUserId().longValue());
                if (StringUtils.isNotEmpty(s)) {
                    dto.setHasNoStartCloudTeacher(true);
                }
            }

            if (userContractVersionMap.containsKey(dto.getUserId())) {
                dto.setIsSignedContract(true);
            } else {
                dto.setIsSignedContract(false);
            }
            //年级
            dto.setCurrentGrade(studentService.getStudentGrade(dto.getGradeType(), dto.getCurrentGradeNum()));
        }
        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<SimpleUserDto> queryStudentsWithTeacherByOrganId(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 (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 = new ArrayList<>();
        List<StudentRegistration> studentRegistrations = studentRegistrationDao.getMusicGroupStu(queryInfo.getMusicGroupId());
        if (studentRegistrations.size() == 0) {
            return pageInfo;
        }
        List<Integer> userIds = studentRegistrations.stream().map(e -> e.getUserId()).collect(Collectors.toList());
        if (queryInfo.getHasCourse() != null) {
            //有剩余课程的学员
            List<Integer> hasCourseStudent = courseScheduleDao.findHasCourseStudent(userIds, "VIP,PRACTICE");
            if (queryInfo.getHasCourse()) {
                userIds = hasCourseStudent;
            } else {
                userIds.removeAll(hasCourseStudent);
            }
        }
        if (userIds.size() > 0 && queryInfo.getOweFlag() != null) {
            List<Integer> studentIds = musicGroupPaymentCalenderDetailDao.queryNoPaymentUserIds(queryInfo.getMusicGroupId(), userIds, null);
            if (queryInfo.getOweFlag()) {
                userIds = studentIds;
            } else {
                userIds.removeAll(studentIds);
            }
        }
        if (userIds.size() == 0) {
            return pageInfo;
        }
        params.put("userIds", userIds);
        int count = studentManageDao.countMusicGroupStudent(params);
        if (queryInfo.getIsExport() && count > 50000) {
            throw new BizException("数据集太大，不能导出.最大数据集不能超过50000");
        }
        pageInfo.setTotal(count);
        if (queryInfo.getPage() <= pageInfo.getTotalPage()) {
            params.put("offset", pageInfo.getOffset());
            dataList = studentManageDao.queryMusicGroupStudent(params);
            //获取乐团学员欠费金额
            Map<Integer, BigDecimal> totalAmountMap = MapUtil.convertIntegerMap(musicGroupPaymentCalenderDetailDao.queryNoPaymentTotalAmount(queryInfo.getMusicGroupId()));
            //退团的学生
            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());
                    }
                }
            }
            List<Integer> collect = dataList.stream().map(e -> e.getUserId()).collect(Collectors.toList());
            List<Integer> hasCourseStudent = courseScheduleDao.findHasCourseStudent(collect, "VIP,PRACTICE");
            List<SubjectChange> waitPayChange = subjectChangeDao.getMusicGroupWaitPay(queryInfo.getMusicGroupId());
            Map<Integer, List<SubjectChange>> studentWaitPayChange = waitPayChange.stream().collect(Collectors.groupingBy(SubjectChange::getStudentId));
            //查询是否有有效期内乐保
            List<StudentInstrument> studentsMaintenanceNum = studentInstrumentDao.getStudentsMaintenanceNum(collect, queryInfo.getMusicGroupId());
            Map<Integer, Integer> studentMaintenanceMap = studentsMaintenanceNum.stream().collect(Collectors.toMap(StudentInstrument::getStudentId, StudentInstrument::getGoodsId));

            //查询云教练订单
            List<CloudTeacherOrder> studentCloudTeacherOrders = cloudTeacherOrderService.getStudentCloudTeacherOrders(collect, queryInfo.getMusicGroupId());
            Map<Integer, List<CloudTeacherOrder>> studentCloudTeacherMap = studentCloudTeacherOrders.stream().collect(Collectors.groupingBy(CloudTeacherOrder::getStudentId));
            Date nowDate = new Date();
            Map<Long, String> cloudMap = MapUtil.convertMybatisMap(cloudTeacherOrderService.queryNoStartByUserIds(new HashSet<>(collect), null));
            dataList.forEach(e -> {
                //如果会员已过期、是否有未生效的会员
                if (e.getMemberRankSettingId() == null) {
                    String s = cloudMap.get(e.getUserId().longValue());
                    if (StringUtils.isNotEmpty(s)) {
                        e.setHasNoStartCloudTeacher(true);
                    }
                }
                e.setHasCourse(hasCourseStudent.contains(e.getUserId()));
                e.setNoPaymentAmount(totalAmountMap.get(e.getUserId()));
                if (studentWaitPayChange.containsKey(e.getUserId())) {
                    e.setSubjectChange(studentWaitPayChange.get(e.getUserId()).get(0));
                }
                if (studentMaintenanceMap.containsKey(e.getUserId())) {
                    e.setHasMaintenance(true);
                }
                if (studentCloudTeacherMap.containsKey(e.getUserId())) {
                    List<CloudTeacherOrder> cloudTeacherOrders = studentCloudTeacherMap.get(e.getUserId());
                    if (cloudTeacherOrders != null && cloudTeacherOrders.size() > 0) {
                        BigDecimal cloudAmount = BigDecimal.ZERO;
                        for (CloudTeacherOrder cloudTeacherOrder : cloudTeacherOrders) {
                            if (cloudTeacherOrder.getEndTime() == null || DateUtil.stringToDate(DateUtil.format(cloudTeacherOrder.getEndTime(), DateUtil.ISO_EXPANDED_DATE_FORMAT), DateUtil.ISO_EXPANDED_DATE_FORMAT).compareTo(
                                    DateUtil.stringToDate(DateUtil.format(nowDate, DateUtil.ISO_EXPANDED_DATE_FORMAT), DateUtil.ISO_EXPANDED_DATE_FORMAT)) >= 0) {
                                cloudAmount = cloudAmount.add(cloudTeacherOrder.getAmount());
                            }
                        }
                        e.setCloudTeacherAmount(cloudAmount);
                    }
                }
            });
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    public Object musicGroupStudentsSum(String musicGroupId) {
        Map<String, Object> resultMap = new HashMap<>(4);
        //乐团在读人数
        resultMap.put("studying", studentManageDao.countStudyNum(musicGroupId));
        //退团人数
        resultMap.put("quit", studentManageDao.countQuitNum(musicGroupId));
        //新增人数
        resultMap.put("add", studentManageDao.countAddNum(musicGroupId));
        //未完成vip、网管课学员数量/该乐团在读学员人数*100%
        List<StudentRegistration> studentRegistrations = studentRegistrationDao.getMusicGroupStu(musicGroupId);
        List<Integer> userIds = studentRegistrations.stream().filter(e -> e.getMusicGroupStatus() == StudentMusicGroupStatusEnum.NORMAL).map(StudentRegistration::getUserId).collect(Collectors.toList());
        if (userIds.size() == 0) {
            resultMap.put("courseRate", "0.00%");
            return resultMap;
        }
        List<Integer> hasCourseStudent = courseScheduleDao.findHasCourseStudent(userIds, "VIP,PRACTICE");
        double size = userIds.size() + 0d;
        if (hasCourseStudent.size() == 0) {
            resultMap.put("courseRate", "0.00%");
        } else {
            double d = (hasCourseStudent.size() / size) * 100;
            resultMap.put("courseRate", String.format("%.2f", d) + "%");
        }
        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);
        Student student = studentDao.get(sysUser.getId());
        if (student != null) {
            student.setCurrentGradeNum(sysUser.getCurrentGradeNum());
            student.setCurrentClass(sysUser.getCurrentClass());
            Optional.ofNullable(sysUser.getSubjectId()).ifPresent(student::setSubjectIdList);
            studentDao.update(student);
        }
    }

    @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 = teacherDao.getUserWithPhone(student.getPhone());
        if (sysUser != null) {
            EmployeeServiceImpl.checkTenantId(student.getTenantId(), sysUser.getTenantId());
            if (sysUser.getUserType().contains("STUDENT")) {
                throw new BizException("手机号已被占用");
            } else {
                student.setId(sysUser.getId());
                student.setUserType(sysUser.getUserType() + ",STUDENT");
                student.setUpdateTime(date);
                teacherDao.updateUser(student);
            }
        } else {
            student.setUpdateTime(date);
            student.setCreateTime(date);
            student.setUserType("STUDENT");
            teacherDao.addSysUser(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());
            teacherDao.updateUser(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 = teacherDao.getUserWithPhone(student.getPhone());
        if (sysUser1 != null && !userId.equals(sysUser1.getId())) {
            throw new BizException("手机号已被占用");
        }
        //不更新真实姓名
        student.setRealName(null);
        teacherDao.updateUser(student);

        student.setUserId(student.getId());
        student.setOperatingTag(student.getOperatingTag());
        student.setOperatingTempTag(0);
        student.setServiceTag(student.getServiceTag() == 0 ? 2 : 1);
        student.setTeacherId(student.getTeacherId());
        // 同步更新机构手机号 如果它存在
        SysUser user = teacherDao.getUser(student.getId());
        tenantInfoService.updatePhone(student.getPhone(), user.getPhone());
        activityUserMapperDao.updateTeacherId(student.getUserId(), student.getTeacherId());
        if (Objects.nonNull(student.getCarePackage()) || Objects.nonNull(student.getComeOnPackage())) {
            Student oldStudent = studentDao.get(userId);
            if (Objects.nonNull(oldStudent.getCarePackage()) && oldStudent.getCarePackage().equals(2)) {
                student.setCarePackage(oldStudent.getCarePackage());
            }
            if (Objects.nonNull(oldStudent.getComeOnPackage()) && oldStudent.getComeOnPackage().equals(2)) {
                student.setComeOnPackage(oldStudent.getComeOnPackage());
            }
        }
        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());
            studentExtracurricularExercisesSituationService.deleteByStudent(student.getId(), monDayDate.toString());
        }
        webFeignService.updateNickName(userId, student.getUsername());
        imFeignService.update(new ImUserModel(userId.toString(), student.getUsername(), sysUser1 == null ? null : sysUser1.getAvatar()));
        return userId;
    }

    @Override
    public List<StudentRegisterPerDto> queryStudentPer(Integer tenantId) {
        String format = DateUtil.format(DateUtil.addDays(new Date(), -1), DateUtil.ISO_EXPANDED_DATE_FORMAT);
        return studentRegistrationDao.queryStudentPer1(tenantId, format);
    }

    @Override
    public List<StudentManageListDto> queryHasCourseStudent(StudentManageQueryInfo queryInfo) {
        Map<String, Object> params = new HashMap<>();
        MapUtil.populateMap(params, queryInfo);
        List<StudentManageListDto> studentHasCourseDtos = studentManageDao.queryHasCourseStudent(params);
        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("homeworkStudentNum", studentCourseHomeworkDao.countHomeworkStudentNumWithCourse(courseScheduleId.longValue()));
        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().filter(ug -> StringUtils.isNotBlank(ug.getGroupName())).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 Integer countStudentSubTotalCourseTimes(StudentSubTotalCourseTimesQueryInfo queryInfo) {
        Map<String, Object> params = new HashMap<>();
        MapUtil.populateMap(params, queryInfo);
        return musicGroupPaymentStudentCourseDetailDao.countStudentSubTotalCourseTimes(params);
    }

    @Override
    public PageInfo<StudentSubTotalCourseTimesDto> queryStudentSubTotalCourseTimes(StudentSubTotalCourseTimesQueryInfo queryInfo) {
        PageInfo<StudentSubTotalCourseTimesDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<>();
        MapUtil.populateMap(params, queryInfo);
        params.put("offset", pageInfo.getOffset());

        int count = musicGroupPaymentStudentCourseDetailDao.countStudentSubTotalCourseTimes(params);
        List<StudentSubTotalCourseTimesDto> dataList = new ArrayList<>();
        if (count > 0) {
            pageInfo.setTotal(count);
            dataList = musicGroupPaymentStudentCourseDetailDao.pageStudentSubTotalCourseTimes(params);
            //内部分页
            int endIdx = pageInfo.getPageNo() * pageInfo.getLimit();
            dataList = dataList.subList(pageInfo.getOffset(), dataList.size() > endIdx ? endIdx : dataList.size());

            Map<Integer, String> classMap = MapUtil.convertMybatisMap(classGroupDao.queryStudentClassGroupMap(queryInfo.getMusicGroupId()));
            for (StudentSubTotalCourseTimesDto timesDto : dataList) {
                timesDto.setClassGroupId(classMap.get(timesDto.getUserId()));
            }
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    public PageInfo<StudentErrorLeaveDto> queryStudentErrorLeaveList(StudentErrorLeaveQueryInfo queryInfo) {
        //学员请假异常提醒(获取前两个月的)
        Date date = new Date();
        PageInfo<StudentErrorLeaveDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());

        Integer tenantId = TenantContextHolder.getTenantId();
        String studentErrorLeaveNum = sysTenantConfigService.getTenantConfigValue(SysConfigService.STUDENT_ERROR_LEAVE_NUM, tenantId);
        if (StringUtils.isEmpty(studentErrorLeaveNum)) {
            return pageInfo;
        }
        Map<String, Object> params = new HashMap<>();
        MapUtil.populateMap(params, queryInfo);
        params.put("offset", pageInfo.getOffset());
        String totalMonth = DateUtil.format(DateUtil.addMonths(date, -1), DateUtil.ISO_YEAR_MONTH_FORMAT);
        String currentMonth = DateUtil.format(date, DateUtil.ISO_YEAR_MONTH_FORMAT);
        params.put("totalMonth", totalMonth);
        params.put("currentMonth", currentMonth);
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        //当前用户是否是分部经理
        Boolean onlyForRole = employeePositionService.onlyForRole(SysUserRoleEnum.EDUCATION, sysUser.getId(), sysUser.getIsSuperAdmin());
        if (onlyForRole) {
            //获取教务老师关联的班级列表
            List<Long> classGroupIds = classGroupDao.queryGroupClassGroupIds(sysUser.getId());
            if (classGroupIds == null || classGroupIds.size() == 0) {
                return pageInfo;
            }
            params.put("classGroupIds", classGroupIds);
        }
        params.put("studentErrorLeaveNum", studentErrorLeaveNum);
        int count = indexBaseMonthDataDao.countStudentErrorLeave1(params);
        List<StudentErrorLeaveDto> dataList = new ArrayList<>();
        if (count > 0) {
            //获取近两个月异常请假次数
            Map<Integer, BigDecimal> leaveNumMap = MapUtil.convertIntegerMap(indexBaseMonthDataDao.getStudentErrorLeaveNumMap(params));
            pageInfo.setTotal(count);
            dataList = indexBaseMonthDataDao.queryStudentErrorLeave(params);
            for (StudentErrorLeaveDto studentErrorLeaveDto : dataList) {
                studentErrorLeaveDto.setTotalNum(leaveNumMap.get(studentErrorLeaveDto.getUserId()).intValue());
            }
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    public PageInfo<StudentLeaveCourseDto> queryStudentLeaveCourseList(StudentErrorLeaveQueryInfo queryInfo) {
        PageInfo<StudentLeaveCourseDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
        Map<String, Object> params = new HashMap<>();
        MapUtil.populateMap(params, queryInfo);
        params.put("offset", pageInfo.getOffset());
        int count = indexBaseMonthDataDao.countStudentLeaveCourseList(params);
        List<StudentLeaveCourseDto> dataList = new ArrayList<>();
        if (count > 0) {
            pageInfo.setTotal(count);
            dataList = indexBaseMonthDataDao.queryStudentLeaveCourseList(params);
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateChildrenDayStudent(ActivityCourseDetailDto activityCourseDetailDto) {
        Student student = studentDao.getLocked(activityCourseDetailDto.getUserId());
        if (student == null) {
            throw new BizException("学员信息不存在");
        }
        if (!activityCourseDetailDto.getVip1().equals(0) && !activityCourseDetailDto.getVip1().equals(1)) {
            throw new BizException("修改失败：排课次数异常");
        }
        if (!activityCourseDetailDto.getVip2().equals(0) && !activityCourseDetailDto.getVip2().equals(1)) {
            throw new BizException("修改失败：排课次数异常");
        }
        if (!activityCourseDetailDto.getFree_vip().equals(0) && !activityCourseDetailDto.getFree_vip().equals(1)) {
            throw new BizException("修改失败：排课次数异常");
        }
        if (!activityCourseDetailDto.getMusic_theory().equals(0) && !activityCourseDetailDto.getMusic_theory().equals(1)) {
            throw new BizException("修改失败：排课次数异常");
        }
        if (activityCourseDetailDto.getMusic_theory().equals(1)) {
            String activityCourseDetail = student.getActivityCourseDetail();
            if (StringUtils.isNotEmpty(activityCourseDetail)) {
                ActivityCourseDetailDto detailDto = JSON.parseObject(activityCourseDetail, ActivityCourseDetailDto.class);
                if (detailDto.getMusic_theory() == null || detailDto.getMusic_theory().equals(0)) {
                    SysUser sysUser = sysUserFeignService.queryUserById(student.getUserId());
                    if (sysUser == null) {
                        throw new BizException("请登录");
                    }
                    OrganizationDegreeCourseFee degreeCourseFee = organizationDegreeCourseFeeDao.getByOrganId(sysUser.getOrganId());
                    if (degreeCourseFee == null) {
                        throw new BizException("学员所在分部未配置考级价格");
                    }
                    activityCourseDetailDto.setMusic_theory_price(degreeCourseFee.getTheory());
                } else {
                    activityCourseDetailDto.setMusic_theory_price(detailDto.getMusic_theory_price());
                }
            } else {
                SysUser sysUser = teacherDao.getUser(student.getUserId());
                OrganizationDegreeCourseFee degreeCourseFee = organizationDegreeCourseFeeDao.getByOrganId(sysUser.getOrganId());
                if (degreeCourseFee == null) {
                    throw new BizException("学员所在分部未配置考级价格");
                }
                activityCourseDetailDto.setMusic_theory_price(degreeCourseFee.getTheory());
            }
        } else {
            activityCourseDetailDto.setMusic_theory_price(BigDecimal.ZERO);
        }
        activityCourseDetailDto.setUserId(null);
        student.setActivityCourseDetail(JSON.toJSONString(activityCourseDetailDto));
        studentDao.update(student);
    }

    @Override
    public PageInfo<Student> queryStudent(StudentActivityQueryInfo queryInfo) {
        Map<String, Object> params = new HashMap<>();
        MapUtil.populateMap(params, queryInfo);
        List<Integer> studentIds = new ArrayList<>();
        params.put("studentIds", studentIds);
        PageInfo<Student> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
        if (queryInfo.getHasMusicCourse() != null) {
            params.put("groupType", "MUSIC");
            params.put("hasCourse", queryInfo.getHasMusicCourse());
            studentIds = courseScheduleDao.queryHasCourseStudentIds(params);
            if (studentIds == null || studentIds.size() == 0) {
                return pageInfo;
            }
        }
        if (queryInfo.getHasPracticeCourse() != null) {
            params.put("groupType", "PRACTICE");
            params.put("hasCourse", queryInfo.getHasPracticeCourse());
            params.put("studentIds", studentIds);
            studentIds = courseScheduleDao.queryHasCourseStudentIds(params);
            if (studentIds == null || studentIds.size() == 0) {
                return pageInfo;
            }
        }
        if (queryInfo.getHasVipCourse() != null) {
            params.put("groupType", "VIP");
            params.put("hasCourse", queryInfo.getHasVipCourse());
            params.put("studentIds", studentIds);
            studentIds = courseScheduleDao.queryHasCourseStudentIds(params);
            if (studentIds == null || studentIds.size() == 0) {
                return pageInfo;
            }
        }
        params.put("studentIds", studentIds);
        List<Student> dataList = null;
        int count = studentDao.countStudent(params);
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList = studentDao.queryStudent(params);
        }
        if (count == 0) {
            dataList = new ArrayList<>();
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    public List<BaseMapDto> queryStuSubjectId(Integer userId) {
        return studentDao.queryStuSubjectIdByTeacherId(userId);
    }
}
