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

import static com.ym.mec.biz.dal.enums.IndexDataType.CLOUD_NEW_STUDENT_NUM;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;

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.page.*;
import com.ym.mec.common.page.QueryInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONArray;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.enums.FivePlusGradeEnum;
import com.ym.mec.biz.dal.enums.GradeTypeEnum;
import com.ym.mec.biz.dal.enums.MessageTypeEnum;
import com.ym.mec.biz.dal.enums.PeriodEnum;
import com.ym.mec.biz.dal.enums.SixPlusGradeEnum;
import com.ym.mec.biz.service.OrganizationService;
import com.ym.mec.biz.service.StudentService;
import com.ym.mec.biz.service.SysConfigService;
import com.ym.mec.biz.service.SysMessageService;
import com.ym.mec.biz.service.SysTenantConfigService;
import com.ym.mec.common.constant.CommonConstants;
import com.ym.mec.common.dal.BaseDAO;
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.service.impl.BaseServiceImpl;
import com.ym.mec.common.tenant.TenantContextHolder;
import com.ym.mec.im.ImFeignService;
import com.ym.mec.thirdparty.message.MessageSenderPluginContext;
import com.ym.mec.util.collection.MapUtil;
import com.ym.mec.util.date.DateUtil;

@Service
public class StudentServiceImpl extends BaseServiceImpl<Integer, Student> implements StudentService {

    @Autowired
    private StudentDao studentDao;
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private CourseScheduleStudentPaymentDao courseScheduleStudentPaymentDao;
    @Autowired
    private StudentRegistrationDao studentRegistrationDao;
    @Autowired
    private StudentStatisticsDao studentStatisticsDao;
    @Autowired
    private MusicGroupDao musicGroupDao;
    @Autowired
    private PracticeGroupDao practiceGroupDao;
    @Autowired
    private MemberRankSettingDao memberRankSettingDao;
    @Autowired
    private SysConfigDao sysConfigDao;
    @Autowired
    private SysTenantConfigService sysTenantConfigService;
    @Autowired
    private SysMessageService sysMessageService;
    @Autowired
    private SysMusicCompareRecordDao sysMusicCompareRecordDao;
    @Autowired
    private CloudTeacherDao cloudTeacherDao;
    @Autowired
    private CloudTeacherOrderDao cloudTeacherOrderDao;
    @Autowired
    private OrganizationDao organizationDao;
    @Autowired
    private IndexBaseMonthDataDao indexBaseMonthDataDao;
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private SysUserCashAccountDao sysUserCashAccountDao;
    @Autowired
    private ImFeignService imFeignService;
    @Autowired
    private StudentOperatingVisitDao studentOperatingVisitDao;

    @Override
    public BaseDAO<Integer, Student> getDAO() {
        return studentDao;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
	public boolean register(StudentPreRegistration studentPreRegistration) {
        TenantContextHolder.setTenantId(studentPreRegistration.getTenantId());
        Date date = new Date();
    	// 判断用户是否存在
        SysUser user = teacherDao.getUserWithPhone(studentPreRegistration.getPhone());
        Integer userId = null;

        if(user != null && user.getId() != null){
        	if (user.getUserType().contains("STUDENT")) {
        		throw new BizException("您已注册，请直接下载APP！");
        	} else { // 当前用户是 SYSTEM, TEACHER 添加学生
                user.setUserType(user.getUserType() + ",STUDENT");
            }
        	userId = user.getId();
            if (studentPreRegistration.getOrganId() != null) {
                user.setOrganId(studentPreRegistration.getOrganId());
            }
            if (studentPreRegistration.getParentName() != null) {
                user.setRealName(studentPreRegistration.getParentName());
            }
            if (studentPreRegistration.getUserName() != null) {
                user.setUsername(studentPreRegistration.getUserName());
            }

            user.setUpdateTime(date);
            teacherDao.updateUser(user);
        }else{
        	user = new SysUser();
            user.setPhone(studentPreRegistration.getPhone());
            user.setOrganId(studentPreRegistration.getOrganId());
            user.setRealName(studentPreRegistration.getParentName());
            user.setUsername(studentPreRegistration.getUserName());
            user.setUserType("STUDENT");
            user.setCreateTime(date);
            user.setUpdateTime(date);
            // 注册账户信息
            teacherDao.addSysUser(user);
            userId = user.getId();
            sysUserCashAccountDao.insert(new SysUserCashAccount(userId, "CNY"));
        }

        //添加student
        Student student = new Student();
        student.setUserId(userId);
        student.setCreateTime(date);
        student.setUpdateTime(date);
        student.setIsNewUser(true);
        student.setSchoolName(studentPreRegistration.getSchool());
        student.setCurrentGradeNum(studentPreRegistration.getCurrentGradeNum());
        student.setSubjectIdList(studentPreRegistration.getSelectionSubjectId().toString());
        student.setCurrentClass(studentPreRegistration.getCurrentClass());
        studentDao.insert(student);
        TenantContextHolder.clearTenantId();
        
        if(studentPreRegistration.getOrganId() == 59){
        	
        	if(student.getMembershipEndTime() == null){
        		student.setMembershipEndTime(date);
        	}
        	if(student.getMembershipStartTime() == null){
        		student.setMembershipStartTime(date);
        	}
        	if(student.getMemberRankSettingId() == null){
        		student.setMemberRankSettingId(1);
        	}
        	//赠送一个月的会员
        	if(student.getMembershipEndTime().before(date)){
        		student.setMembershipEndTime(DateUtil.addMonths(date, 1));
        		student.setMembershipStartTime(date);
        	}else{
        		student.setMembershipEndTime(DateUtil.addMonths(student.getMembershipEndTime(), 1));
        	}
        	student.setUpdateTime(date);
        	studentDao.update(student);
        }
        
        return true;
	}

	@Override
    public PageInfo findStudentVipGroupList(StudentQueryInfo 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 = studentDao.countStudents(params);
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList = studentDao.findStudents(params);
        }
        if (count == 0) {
            dataList = new ArrayList<>();
        }
        pageInfo.setRows(dataList);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long upSet(Student student) {
        if (studentDao.get(student.getUserId()) == null) {
            return studentDao.insert(student);
        } else {
            student.setUpdateTime(new Date());
            studentDao.update(student);
            return student.getUserId().longValue();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOperatingTempTag() {
        String month = DateUtil.format(new Date(), DateUtil.ISO_YEAR_MONTH_FORMAT);
        studentOperatingVisitDao.deleteByUserId(month);
        List<Integer> operatingUserIds = studentDao.queryByOperatingTag(1);
        if (!CollectionUtils.isEmpty(operatingUserIds)) {
            List<Integer> userIds = studentOperatingVisitDao.queryUserIds(month);
            operatingUserIds.removeAll(userIds);
            if(!CollectionUtils.isEmpty(operatingUserIds)){
                //需要新增的用户
                studentOperatingVisitDao.batchAdd(operatingUserIds,month);
            }
        }
        //更新学员基本信息
        return true;
    }

    @Override
    public void initTeacherId() {
        List<StudentTeacherCourseDto> allStudentCourseInfo = courseScheduleStudentPaymentDao.findAllStudentCourseInfo(TenantContextHolder.getTenantId());
        Map<Integer, List<StudentTeacherCourseDto>> studentCoursesMap = allStudentCourseInfo.stream().collect(Collectors.groupingBy(StudentTeacherCourseDto::getStudentId));
        List<Student> students = new ArrayList<>();
        for (Map.Entry<Integer, List<StudentTeacherCourseDto>> studentCoursesEntry : studentCoursesMap.entrySet()) {
            Map<CourseSchedule.CourseScheduleType, List<StudentTeacherCourseDto>> courseTypeCourseMap = studentCoursesEntry.getValue().stream().collect(Collectors.groupingBy(StudentTeacherCourseDto::getCourseScheduleType));
            List<StudentTeacherCourseDto> practiceCourses = courseTypeCourseMap.get(CourseSchedule.CourseScheduleType.PRACTICE);
            if (!CollectionUtils.isEmpty(practiceCourses)) {
                practiceCourses.sort(Comparator.comparing(StudentTeacherCourseDto::getClassesStartTime).reversed());
                Student student = new Student(studentCoursesEntry.getKey());
                student.setTeacherId(practiceCourses.get(0).getTeacherId());
                students.add(student);
                continue;
            }

            List<StudentTeacherCourseDto> vipCourses = courseTypeCourseMap.get(CourseSchedule.CourseScheduleType.VIP);
            if (!CollectionUtils.isEmpty(vipCourses)) {
                Student student = new Student(studentCoursesEntry.getKey());
                vipCourses.sort(Comparator.comparing(StudentTeacherCourseDto::getClassesStartTime).reversed());
                student.setTeacherId(vipCourses.get(0).getTeacherId());
                students.add(student);
                continue;
            }

            List<StudentTeacherCourseDto> singleCourses = courseTypeCourseMap.get(CourseSchedule.CourseScheduleType.SINGLE);
            if (!CollectionUtils.isEmpty(singleCourses)) {
                Student student = new Student(studentCoursesEntry.getKey());
                singleCourses.sort(Comparator.comparing(StudentTeacherCourseDto::getClassesStartTime).reversed());
                student.setTeacherId(singleCourses.get(0).getTeacherId());
                students.add(student);
                continue;
            }

            List<StudentTeacherCourseDto> mixCourses = courseTypeCourseMap.get(CourseSchedule.CourseScheduleType.MIX);
            if (!CollectionUtils.isEmpty(mixCourses)) {
                Student student = new Student(studentCoursesEntry.getKey());
                mixCourses.sort(Comparator.comparing(StudentTeacherCourseDto::getClassesStartTime).reversed());
                student.setTeacherId(mixCourses.get(0).getTeacherId());
                students.add(student);
                continue;
            }
        }
        if (!CollectionUtils.isEmpty(students)) {
            studentDao.batchUpdate(students);
        }
        students = null;
        studentCoursesMap = null;
        allStudentCourseInfo = null;
    }

    @Override
    public void batchUpdateAdviser(Integer teacherId, String studentIds) {
        studentDao.batchUpdateAdviser(teacherId, studentIds);
    }

    @Override
    public Integer updateGrade() {
        return studentDao.updateGrade();
    }

    @Override
    public String getStudentGrade(GradeTypeEnum gradeType, Integer gradeNum) {
        String grade = "";
        if (GradeTypeEnum.FIVE_PLUS.equals(gradeType)) {
            FivePlusGradeEnum[] fivePlusGradeEnums = FivePlusGradeEnum.values();
            for (FivePlusGradeEnum fivePlusGradeEnum : fivePlusGradeEnums) {
                if (!fivePlusGradeEnum.getCode().equals(gradeNum)) continue;
                grade = fivePlusGradeEnum.getDesc();
            }
        }
        if (GradeTypeEnum.SIX_PLUS.equals(gradeType)) {
            SixPlusGradeEnum[] sixPlusGradeEnums = SixPlusGradeEnum.values();
            for (SixPlusGradeEnum sixPlusGradeEnum : sixPlusGradeEnums) {
                if (!sixPlusGradeEnum.getCode().equals(gradeNum)) continue;
                grade = sixPlusGradeEnum.getDesc();
            }
        }
        return grade;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStudentTeacherAndSubject() {
        //更新新学员状态
        List<Integer> newStudentIds = studentDao.getHasVipCourseStudentIdsFromNewStudents();
        if(!CollectionUtils.isEmpty(newStudentIds)){
            studentDao.updateNewStudentsToOld(newStudentIds);
        }

        List<Student> noTeacherOrNoSubjectStudent = studentDao.getNoTeacherOrNoSubjectStudent();
        if (CollectionUtils.isEmpty(noTeacherOrNoSubjectStudent)) {
            return;
        }
        List<Integer> studentIds = noTeacherOrNoSubjectStudent.stream().map(Student::getUserId).collect(Collectors.toList());
        List<StudentClassInfoDto> studentClassInfo = studentRegistrationDao.getStudentClassInfo(studentIds);
        if (CollectionUtils.isEmpty(studentClassInfo)) {
            return;
        }
        //更新学员指导老师和声部信息
        List<Student> needUpdateStudents = new ArrayList<>();
        Map<Integer, List<StudentClassInfoDto>> scm = studentClassInfo.stream().collect(Collectors.groupingBy(StudentClassInfoDto::getStudentId));
        for (Student student : noTeacherOrNoSubjectStudent) {
            if (!scm.containsKey(student.getUserId())) {
                continue;
            }
            List<StudentClassInfoDto> studentClassInfoDtos = scm.get(student.getUserId());
            StudentClassInfoDto studentClassInfoDto = studentClassInfoDtos.stream().max(Comparator.comparing(StudentClassInfoDto::getClassGroupId)).get();
            if (Objects.isNull(student.getTeacherId())) {
                student.setTeacherId(studentClassInfoDto.getMainTeacherId());
            }
            if (StringUtils.isBlank(student.getSubjectIdList())) {
                student.setSubjectIdList(studentClassInfoDto.getSubjectId().toString());
            }
            if (Objects.isNull(student.getCooperationOrganId())) {
                student.setCooperationOrganId(studentClassInfoDto.getCooperationOrganId());
            }
            needUpdateStudents.add(student);
        }
        if (!CollectionUtils.isEmpty(needUpdateStudents)) {
            studentDao.batchUpdate(needUpdateStudents);
        }
    }

    @Override
    public CooperationOrgan getStudentEduTeacher(Integer userId) {
        CooperationOrgan cooperationOrgan = musicGroupDao.findUserMusicGroupCooperationOrgan(userId);
        if (cooperationOrgan != null) {
            return cooperationOrgan;
        }
        cooperationOrgan = new CooperationOrgan();
        String studentEduTeacher = courseScheduleStudentPaymentDao.getStudentEduTeacher(userId);
        if (studentEduTeacher == null) {
            studentEduTeacher = practiceGroupDao.getStudentEduTeacher(userId);
        }
        cooperationOrgan.setLinkman(studentEduTeacher);
        return cooperationOrgan;
    }

    public Date getMembershipEndTime(PeriodEnum periodEnum,Date endTime,Integer memberNum){
        BiFunction<Date, Integer, Date> dateBiFunction = periodStrategyMap.get(periodEnum);
        if(dateBiFunction == null){
            throw new BizException("错误的会员时长单位");
        }
        return dateBiFunction.apply(endTime,memberNum);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMemberRank(CloudTeacherOrder cloudTeacherOrder) {
        // 添加会员有效时长
        Student student = this.get(cloudTeacherOrder.getStudentId());
        if (student == null) {
            throw new BizException("学员信息不存在");
        }
        Date nowDate = new Date();
        if (student.getMembershipEndTime()  == null || student.getMemberRankSettingId() == null || nowDate.after(student.getMembershipEndTime())) {
            student.setMembershipStartTime(getMembershipEndTime(cloudTeacherOrder.getType(),nowDate, cloudTeacherOrder.getTime()));
        } else {
            student.setMembershipStartTime(getMembershipEndTime(cloudTeacherOrder.getType(),student.getMembershipEndTime(), cloudTeacherOrder.getTime()));
        }
        student.setMemberRankSettingId(cloudTeacherOrder.getLevel());
        student.setUpdateTime(nowDate);
        this.update(student);
    }

    private Map<PeriodEnum, BiFunction<Date,Integer,Date>> periodStrategyMap = new HashMap<>();

    @PostConstruct
    public void periodStrategyMapInit(){
        periodStrategyMap.put(PeriodEnum.DAY, (date, times) -> DateUtil.addDays(date, times));
        periodStrategyMap.put(PeriodEnum.MONTH, (date, times) -> DateUtil.addMonths(date, times));
        periodStrategyMap.put(PeriodEnum.QUARTERLY, (date, times) -> DateUtil.addMonths(date, times*3));
        periodStrategyMap.put(PeriodEnum.YEAR_HALF, (date, times) -> DateUtil.addMonths(date, times*6));
        periodStrategyMap.put(PeriodEnum.YEAR, (date, times) -> DateUtil.addYears(date, times));
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
	public void updateMemberRank(Integer userId, PeriodEnum periodEnum, int times, Integer memberRankSettingId) {
    	Student student = this.get(userId);
        if (student == null) {
            throw new BizException("学员信息不存在");
        }

        Date nowDate = new Date();

        if(student.getMembershipStartTime() == null){
            student.setMembershipStartTime(nowDate);
        }
        if(student.getMembershipEndTime() != null && student.getMembershipEndTime().after(nowDate)){
        	nowDate = student.getMembershipEndTime();
        }
        Date membershipEndTime = getMembershipEndTime(periodEnum, nowDate, times);
        //所有购买会员的额外加一天时间
        student.setMembershipEndTime(DateUtil.addDays(membershipEndTime, 1));
        student.setMemberRankSettingId(memberRankSettingId);
        this.update(student);
	}

	@Override
    public void updateStudentServiceTag(Integer studentId,List<Integer> studentIds,Integer serviceTag) {
        studentDao.updateStudentServiceTag(studentId, studentIds, serviceTag);
    }

    @Override
    public List<String> getStudentNames(List<Integer> studentIdList) {
        return studentDao.getStudentNames(studentIdList);
    }

	@Override
	public Student getLocked(Integer userId) {
		return studentDao.getLocked(userId);
	}

    @Override
    public void cleanMember(Integer userId) {
        studentDao.cleanMember(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMemberExperience(String studentIds, Integer rankId, Date endTime) {
        //会员是否存在
        MemberRankSetting memberRankSetting = memberRankSettingDao.get(rankId);
        if(memberRankSetting == null){
            throw new BizException("会员信息不存在");
        }
        if(StringUtils.isEmpty(studentIds)){
            throw new BizException("请选择学员");
        }
        //学员是否有会员
        List<Integer> studentIdList = Arrays.stream(studentIds.split(",")).map(Integer::parseInt).collect(Collectors.toList());
        List<Student> studentList = studentDao.findByStudentIds(studentIdList);
        List<Student> collect = studentList.stream().filter(e -> e.getMemberRankSettingId() != null).collect(Collectors.toList());
        if(collect.size() > 0){
            StringBuffer sb = new StringBuffer("操作失败：学员 ");
            List<Integer> studentId = collect.stream().map(e -> e.getUserId()).collect(Collectors.toList());
            Map<Integer, String> maps = MapUtil.convertMybatisMap(teacherDao.queryUserNameByIdList(studentId));
            for (Integer integer : studentId) {
                sb.append(maps.get(integer)).append(" ");
            }
            sb.append("已有会员权限");
            throw new BizException(sb.toString());
        }
        //最多到10月1号
        String configValue = sysConfigDao.findConfigValue(SysConfigService.EXPERIENCE_MEMBERSHIP_END_TIME);
        if(StringUtils.isNotEmpty(configValue)){
            Date date = DateUtil.stringToDate(configValue, DateUtil.ISO_EXPANDED_DATE_FORMAT);
            if(endTime.after(date)){
                throw new BizException("操作失败：会员试用期不可超过{}",configValue);
            }
        }

        int i = studentDao.updateMemberExperience(studentIds, rankId, endTime);

        if(studentIdList.size() == i){
            Map<Integer, String> studentPhoneMap = MapUtil.convertMybatisMap(teacherDao.queryPhoneByIds(studentIds));
            Map<Integer,String> userMap = new HashMap<>(studentIdList.size());
            Map<Integer,String> userMap1 = new HashMap<>(studentIdList.size());
            for (Integer studentId : studentIdList) {
                userMap.put(studentId,studentPhoneMap.get(studentId));
                userMap1.put(studentId,studentId.toString());
            }
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.AWSMS,
                    MessageTypeEnum.PUSH_EXPERIENCE_MEMBERSHIP_MESSAGE,
                    userMap,
                    null,
                    0,
                    null,
                    null);

            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG,
                    MessageTypeEnum.PUSH_EXPERIENCE_MEMBERSHIP_MESSAGE,
                    userMap1,
                    null,
                    0,
                    null,
                    "STUDENT");
        }
    }

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

        List<EduOrganStudentListDto> dataList = new ArrayList<>();
        int count = studentDao.countCloudStudyStudentData(params);
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList = studentDao.queryCloudStudyStudentData(params);
            List<Integer> studentIds = dataList.stream().map(EduOrganStudentListDto::getStudentId).collect(Collectors.toList());
            List<Map<Integer, String>> studentGroupNamesMapList = studentRegistrationDao.queryStudentMusicGroupNamesMap(studentIds);
            Map<Integer, String> studentGroupNamesMap = MapUtil.convertIntegerMap(studentGroupNamesMapList);
            Set<Integer> hasVipCourseStudentIds = courseScheduleStudentPaymentDao.getHasVipCourseStudentIds(studentIds);

            for (EduOrganStudentListDto eduOrganStudentListDto : dataList) {
                if(studentGroupNamesMap.containsKey(eduOrganStudentListDto.getStudentId())){
                    eduOrganStudentListDto.setMusicGroupNames(studentGroupNamesMap.get(eduOrganStudentListDto.getStudentId()));
                }
                if(hasVipCourseStudentIds.contains(eduOrganStudentListDto.getStudentId())){
                    eduOrganStudentListDto.setHasVipGroup(1);
                }
                if(eduOrganStudentListDto.getCloudStudyUseNum()>0 && eduOrganStudentListDto.getCloudStudyUseTime()>0){
                    eduOrganStudentListDto.setCloudStudyUseAvgTime(eduOrganStudentListDto.getCloudStudyUseTime()/eduOrganStudentListDto.getCloudStudyUseNum());
                }
                eduOrganStudentListDto.setCloudStudyUseTime(eduOrganStudentListDto.getCloudStudyUseTime()/60);
                eduOrganStudentListDto.setCloudStudyUseAvgTime(eduOrganStudentListDto.getCloudStudyUseAvgTime()/60);
            }
        }
        pageInfo.setRows(dataList);

        StatDto result = new StatDto();
        if(queryInfo.getPage()==1){
            EduOrganStudentDataDto organStudentVipData = new EduOrganStudentDataDto();
            organStudentVipData.setTotalStudentNum(studentDao.getOrganStudentNum(queryInfo.getOrganId()));
            organStudentVipData.setVipStudentNum(cloudTeacherDao.getOrganVipStudentNum(queryInfo.getOrganId()));
//            organStudentVipData.seteVipStudentNum(studentDao.getOrganEVipStudentNum(queryInfo.getOrganId()));
            organStudentVipData.setCloudStudyUseStudentNum(studentDao.getCloudStudyStudentNum(queryInfo.getOrganId()));
            organStudentVipData.setCloudStudyLivelyStudentNum(studentDao.getCloudStudyLivelyStudentNum(queryInfo.getOrganId()));
            organStudentVipData.setNewCloudStudyStudentNum(sysMusicCompareRecordDao.getOrganNewCloudStudyNum(queryInfo.getOrganId()));
            if(organStudentVipData.getVipStudentNum()>0&&organStudentVipData.getTotalStudentNum()>0){
                organStudentVipData.setVipStudentDuty(new BigDecimal(organStudentVipData.getVipStudentNum()).divide(new BigDecimal(organStudentVipData.getTotalStudentNum()), 4, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100)).floatValue());
            }
            result.setHead(organStudentVipData);
        }
        result.setDetail(pageInfo);

        return result;
    }

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

        List<EduOrganStudentListDto> dataList1 = new ArrayList<>();
        List<EduOrganStudentListExportDto> dataList = new ArrayList<>();
        int count = studentDao.countCloudStudyStudentData(params);
        if (count > 0) {
            pageInfo.setTotal(count);
            params.put("offset", pageInfo.getOffset());
            dataList1 = studentDao.queryCloudStudyStudentData(params);
            List<Integer> studentIds = dataList1.stream().map(EduOrganStudentListDto::getStudentId).collect(Collectors.toList());

            List<Map<Integer, String>> studentGroupNamesMapList = studentRegistrationDao.queryStudentMusicGroupNamesMap(studentIds);
            Map<Integer, String> studentGroupNamesMap = MapUtil.convertIntegerMap(studentGroupNamesMapList);

            List<Map<Integer, String>> studentGroupEduMapList = studentRegistrationDao.queryStudentMusicGroupEduMap(studentIds);
            Map<Integer, String> studentGroupEduMap = MapUtil.convertIntegerMap(studentGroupEduMapList);

            List<Map<Long, BigDecimal>> activeAmountMapList = cloudTeacherOrderDao.queryActiveAmountMap(studentIds);
            Map<Long, BigDecimal> activeAmountMap = MapUtil.convertIntegerMap(activeAmountMapList);

            Set<Integer> hasVipCourseStudentIds = courseScheduleStudentPaymentDao.getHasVipCourseStudentIds(studentIds);

            List<Map<Integer, String>> studentSchoolNamesMapList = studentDao.getStudentCooperationNameMap(studentIds);
            Map<Integer, String> studentSchoolNamesMap = MapUtil.convertIntegerMap(studentSchoolNamesMapList);

            List<SysUser> users = employeeDao.getUsers(studentIds);
            Map<Integer, SysUser> idUserMap = new HashMap<>();
            if(!CollectionUtils.isEmpty(users)){
                idUserMap = users.stream().collect(Collectors.toMap(SysUser::getId, u -> u, (u1, u2) -> u1));
            }

            List<Student> students = studentDao.findByStudentIds(studentIds);
            Map<Integer, Student> idStudentMap = new HashMap<>();
            if(!CollectionUtils.isEmpty(students)){
                idStudentMap = students.stream().collect(Collectors.toMap(Student::getUserId, s->s, (s1, s2)->s1));
            }

            List<Map<Integer, Integer>> studentNotStartCourseNumMapList = courseScheduleStudentPaymentDao.countStudentsNotStartCourseNumWithCourseType(studentIds, null);
            Map<Integer, Long> studentNotStartCourseNumMap = new HashMap<>();
            if(!CollectionUtils.isEmpty(studentNotStartCourseNumMapList)){
                studentNotStartCourseNumMap = MapUtil.convertIntegerMap(studentNotStartCourseNumMapList);
            }
            List<Map<Integer, Integer>> studentNotStartVipCourseNumMapList = courseScheduleStudentPaymentDao.countStudentsNotStartCourseNumWithCourseType(studentIds, CourseSchedule.CourseScheduleType.VIP);
            Map<Integer, Long> studentNotStartVipCourseNumMap = new HashMap<>();
            if(!CollectionUtils.isEmpty(studentNotStartVipCourseNumMapList)){
                studentNotStartVipCourseNumMap = MapUtil.convertIntegerMap(studentNotStartVipCourseNumMapList);
            }
            List<Map<Integer, Integer>> studentNotStartPracticeCourseNumMapList = courseScheduleStudentPaymentDao.countStudentsNotStartCourseNumWithCourseType(studentIds, CourseSchedule.CourseScheduleType.PRACTICE);
            Map<Integer, Long> studentNotStartPracticeCourseNumMap = new HashMap<>();
            if(!CollectionUtils.isEmpty(studentNotStartPracticeCourseNumMapList)){
                studentNotStartPracticeCourseNumMap = MapUtil.convertIntegerMap(studentNotStartPracticeCourseNumMapList);
            }
            //获取分部年级列表
            Map<Integer, String> gradeList = organizationService.getGradeList(1);
            for (EduOrganStudentListDto eduOrganStudentListDto : dataList1) {
                EduOrganStudentListExportDto data = new EduOrganStudentListExportDto();
                BeanUtils.copyProperties(eduOrganStudentListDto, data);
                if (StringUtils.isNotEmpty(eduOrganStudentListDto.getCurrentGradeNum())) {
                    data.setCurrentGradeNum(eduOrganStudentListDto.getCurrentGradeNum());
                    String grade = gradeList.get(Integer.parseInt(eduOrganStudentListDto.getCurrentGradeNum()));
                    if (StringUtils.isNotEmpty(grade)) {
                        data.setCurrentGradeNum(grade);
                    }
                }
                if (StringUtils.isNotEmpty(eduOrganStudentListDto.getCurrentClass())) {
                    data.setCurrentClass(eduOrganStudentListDto.getCurrentClass());
                }
                if(activeAmountMap.containsKey(data.getStudentId().longValue())){
                    data.setActiveAmount(activeAmountMap.get(data.getStudentId().longValue()));
                }
                if(studentGroupEduMap.containsKey(data.getStudentId())){
                    data.setEducationName(studentGroupEduMap.get(data.getStudentId()));
                }
                if(studentGroupNamesMap.containsKey(data.getStudentId())){
                    data.setMusicGroupNames(studentGroupNamesMap.get(data.getStudentId()));
                }
                if(studentSchoolNamesMap.containsKey(data.getStudentId())){
                    data.setSchoolNames(studentSchoolNamesMap.get(data.getStudentId()));
                }
                if(hasVipCourseStudentIds.contains(data.getStudentId())){
                    data.setHasVipGroup(1);
                }
                if(data.getCloudStudyUseNum()>0 && data.getCloudStudyUseTime()>0){
                    data.setCloudStudyUseAvgTime(data.getCloudStudyUseTime()/data.getCloudStudyUseNum());
                }
                data.setCloudStudyUseTime(data.getCloudStudyUseTime()/60);
                data.setCloudStudyUseAvgTime(data.getCloudStudyUseAvgTime()/60);

                if(idUserMap.containsKey(eduOrganStudentListDto.getStudentId())){
                    SysUser sysUser = idUserMap.get(data.getStudentId());
                    data.setPhone(sysUser.getPhone());
                    data.setEnable(StringUtils.isNotBlank(sysUser.getPassword()));
                }

                if(idStudentMap.containsKey(data.getStudentId())){
                    Student student = idStudentMap.get(data.getStudentId());
                    data.setNewUser(student.getIsNewUser());
                    data.setServiceTag(Objects.isNull(student.getServiceTag())?0:student.getServiceTag());
                    data.setOperatingTag(Objects.isNull(student.getOperatingTag())?0:student.getOperatingTag());
                    data.setCarePackage(Objects.nonNull(student.getCarePackage())?student.getCarePackage():0);
                    data.setComeOnPackage(Objects.isNull(student.getComeOnPackage())?0:student.getComeOnPackage());
                }

                if(studentNotStartCourseNumMap.containsKey(data.getStudentId())){
                    data.setNotStartCourseNum(studentNotStartCourseNumMap.get(data.getStudentId()).intValue());
                }
                if(studentNotStartVipCourseNumMap.containsKey(data.getStudentId())){
                    data.setNotStartVipCourseNum(studentNotStartVipCourseNumMap.get(data.getStudentId()).intValue());
                }
                if(studentNotStartPracticeCourseNumMap.containsKey(data.getStudentId())){
                    data.setNotStartPracticeCourseNum(studentNotStartPracticeCourseNumMap.get(data.getStudentId()).intValue());
                }

                dataList.add(data);
            }
        }
        pageInfo.setRows(dataList);

        StatDto result = new StatDto();
        result.setDetail(pageInfo);

        return result;
    }

    @Override
    public List<EduOrganStudentDataDto> organStudentOverView(List<Integer> organIds) {
        List<Organization> organs = organizationDao.getOrgans(organIds,TenantContextHolder.getTenantId());

        if(CollectionUtils.isEmpty(organs)){
            return Collections.emptyList();
        }

        List<Map<Integer, Integer>> organsStudentNumMapList = studentDao.getOrgansStudentNum(organIds);
        Map<String, Long> organsStudentNumMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(organsStudentNumMapList)){
            organsStudentNumMap = MapUtil.convertIntegerMap(organsStudentNumMapList);
        }
        List<Map<Integer, Integer>> organsVipStudentNumMapList = cloudTeacherDao.getOrgansVipStudentNum(organIds);
        Map<String, Long> organsVipStudentNumMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(organsVipStudentNumMapList)){
            organsVipStudentNumMap = MapUtil.convertIntegerMap(organsVipStudentNumMapList);
        }
//        List<Map<Integer, Integer>> organsEVipStudentNumMapList = studentDao.getOrgansEVipStudentNum(organIds);
//        Map<String, Long> organsEVipStudentNumMap = new HashMap<>();
//        if(!CollectionUtils.isEmpty(organsEVipStudentNumMapList)){
//            organsEVipStudentNumMap = MapUtil.convertIntegerMap(organsEVipStudentNumMapList);
//        }
        List<Map<Integer, Integer>> organCloudStudyStudentNumMapList = studentDao.getOrganCloudStudyStudentNum(organIds);
        Map<String, Long> organCloudStudyStudentNumMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(organCloudStudyStudentNumMapList)){
            organCloudStudyStudentNumMap = MapUtil.convertIntegerMap(organCloudStudyStudentNumMapList);
        }
        List<Map<Integer, Integer>> organCloudStudyLivelyStudentNumMapList = studentDao.getOrganCloudStudyLivelyStudentNum(organIds);
        Map<String, Long> organCloudStudyLivelyStudentNumMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(organCloudStudyLivelyStudentNumMapList)){
            organCloudStudyLivelyStudentNumMap = MapUtil.convertIntegerMap(organCloudStudyLivelyStudentNumMapList);
        }
        List<Map<Integer, Integer>> organsNewCloudStudyNumMapList = sysMusicCompareRecordDao.getOrgansNewCloudStudyNum(organIds);
        Map<String, Long> organsNewCloudStudyNumMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(organsNewCloudStudyNumMapList)){
            organsNewCloudStudyNumMap = MapUtil.convertIntegerMap(organsNewCloudStudyNumMapList);
        }
        List<IndexBaseMonthData> withDayAndDataType = indexBaseMonthDataDao.getWithDayAndDataType(LocalDate.now().toString(), CLOUD_NEW_STUDENT_NUM, TenantContextHolder.getTenantId());
        Map<Integer, Integer> organsNewCloudNewStudentNumMap = withDayAndDataType.stream().collect(Collectors.toMap(IndexBaseMonthData::getOrganId, e -> e.getActivateNum().intValue(), (e1, e2) -> e1));

        Integer tenantId = TenantContextHolder.getTenantId();
        //获取分部目标
        String cloudTeacherActiveTarget = sysTenantConfigService.getTenantConfigValue(SysConfigService.CLOUD_TEACHER_ACTIVE_TARGET,tenantId);
        if(StringUtils.isEmpty(cloudTeacherActiveTarget)){
            return null;
        }
        List<CloudTeacherActiveTargetDto> targetDtoList = JSONArray.parseArray(cloudTeacherActiveTarget, CloudTeacherActiveTargetDto.class);
        Map<Integer, List<CloudTeacherActiveTargetDto>> targetMap = targetDtoList.stream().collect(Collectors.groupingBy(e -> e.getOrganId()));

        List<EduOrganStudentDataDto> result = new ArrayList<>();

        for (Organization organ : organs) {
            EduOrganStudentDataDto organStudentVipData = new EduOrganStudentDataDto();
            organStudentVipData.setOrganId(organ.getId());
            organStudentVipData.setOrganName(organ.getName());
            List<CloudTeacherActiveTargetDto> targetDtos = targetMap.get(organ.getId());
            if(targetDtos != null && targetDtos.size() > 0){
                CloudTeacherActiveTargetDto target = targetDtos.get(0);
                organStudentVipData.setTargetNum(target.getTargetNum());
            }
            if(organsStudentNumMap.containsKey(organ.getId().toString())){
                organStudentVipData.setTotalStudentNum(organsStudentNumMap.get(organ.getId().toString()).intValue());
            }
            if(organsVipStudentNumMap.containsKey(organ.getId().toString())){
                organStudentVipData.setVipStudentNum(organsVipStudentNumMap.get(organ.getId().toString()).intValue());
            }
//            if(organsEVipStudentNumMap.containsKey(organ.getId().toString())){
//                organStudentVipData.seteVipStudentNum(organsEVipStudentNumMap.get(organ.getId().toString()).intValue());
//            }
            if(organCloudStudyStudentNumMap.containsKey(organ.getId().toString())){
                organStudentVipData.setCloudStudyUseStudentNum(organCloudStudyStudentNumMap.get(organ.getId().toString()).intValue());
            }
            if(organCloudStudyLivelyStudentNumMap.containsKey(organ.getId().toString())){
                organStudentVipData.setCloudStudyLivelyStudentNum(organCloudStudyLivelyStudentNumMap.get(organ.getId().toString()).intValue());
            }
            if(organStudentVipData.getVipStudentNum()>0&&organStudentVipData.getTotalStudentNum()>0){
                organStudentVipData.setVipStudentDuty(new BigDecimal(organStudentVipData.getVipStudentNum()).divide(new BigDecimal(organStudentVipData.getTotalStudentNum()), 4, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100)).floatValue());
            }
            if(organStudentVipData.getCloudStudyUseStudentNum()>0&&organStudentVipData.getTotalStudentNum()>0){
                organStudentVipData.setCloudStudyUseStudentDuty(new BigDecimal(organStudentVipData.getCloudStudyUseStudentNum()).divide(new BigDecimal(organStudentVipData.getTotalStudentNum()), 4, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100)).floatValue());
            }
            if(organsNewCloudStudyNumMap.containsKey(organ.getId().toString())){
                organStudentVipData.setNewCloudStudyStudentNum(organsNewCloudStudyNumMap.get(organ.getId().toString()).intValue());
            }
            if(organsNewCloudNewStudentNumMap.containsKey(organ.getId())){
                organStudentVipData.setNewStudentNum(organsNewCloudNewStudentNumMap.get(organ.getId()));
                if(organStudentVipData.getNewStudentNum() > 0 && organStudentVipData.getTotalStudentNum()>0){
                    organStudentVipData.setNewStudentDuty(new BigDecimal(organStudentVipData.getNewStudentNum()).divide(new BigDecimal(organStudentVipData.getTotalStudentNum()), 4, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100)).floatValue());
                }
            }
            result.add(organStudentVipData);
        }
        return result;
    }

    @Override
    public PageInfo<EduOrganStudentDataDto> queryOrganStudentOverView(List<Integer> organIds, OrganCloudStudyStudentDataQueryInfo queryInfo) {
        PageInfo<EduOrganStudentDataDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());

        if(StringUtils.isNotBlank(queryInfo.getOrganIds())&&(organIds == null || organIds.size() == 0)){
            return pageInfo;
        }
        Integer tenantId = TenantContextHolder.getTenantId();
        //获取分部目标
        String cloudTeacherActiveTarget = sysTenantConfigService.getTenantConfigValue(SysConfigService.CLOUD_TEACHER_ACTIVE_TARGET,tenantId);
        if(StringUtils.isEmpty(cloudTeacherActiveTarget)){
            return null;
        }
        List<CloudTeacherActiveTargetDto> targetDtoList = JSONArray.parseArray(cloudTeacherActiveTarget, CloudTeacherActiveTargetDto.class);
        Map<Integer, List<CloudTeacherActiveTargetDto>> targetMap = targetDtoList.stream().collect(Collectors.groupingBy(e -> e.getOrganId()));

        List<Organization> organs = organizationDao.getOrgans(organIds, queryInfo.getTenantId());
        pageInfo.setTotal(organs.size());

        if(CollectionUtils.isEmpty(organs)){
            return pageInfo;
        }

        List<Map<Integer, Integer>> organsStudentNumMapList = studentDao.getOrgansStudentNum(organIds);
        Map<String, Long> organsStudentNumMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(organsStudentNumMapList)){
            organsStudentNumMap = MapUtil.convertIntegerMap(organsStudentNumMapList);
        }
        List<Map<Integer, Integer>> organsVipStudentNumMapList = cloudTeacherDao.getOrgansVipStudentNum(organIds);
        Map<String, Long> organsVipStudentNumMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(organsVipStudentNumMapList)){
            organsVipStudentNumMap = MapUtil.convertIntegerMap(organsVipStudentNumMapList);
        }
        List<Map<Integer, Integer>> organCloudStudyStudentNumMapList = studentDao.getOrganCloudStudyStudentNum(organIds);
        Map<String, Long> organCloudStudyStudentNumMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(organCloudStudyStudentNumMapList)){
            organCloudStudyStudentNumMap = MapUtil.convertIntegerMap(organCloudStudyStudentNumMapList);
        }
        List<Map<Integer, Integer>> organCloudStudyLivelyStudentNumMapList = studentDao.getOrganCloudStudyLivelyStudentNum(organIds);
        Map<String, Long> organCloudStudyLivelyStudentNumMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(organCloudStudyLivelyStudentNumMapList)){
            organCloudStudyLivelyStudentNumMap = MapUtil.convertIntegerMap(organCloudStudyLivelyStudentNumMapList);
        }
        List<Map<Integer, Integer>> organsNewCloudStudyNumMapList = sysMusicCompareRecordDao.getOrgansNewCloudStudyNum(organIds);
        Map<String, Long> organsNewCloudStudyNumMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(organsNewCloudStudyNumMapList)){
            organsNewCloudStudyNumMap = MapUtil.convertIntegerMap(organsNewCloudStudyNumMapList);
        }

        List<IndexBaseMonthData> withDayAndDataType = indexBaseMonthDataDao.getWithDayAndDataType(LocalDate.now().toString(), CLOUD_NEW_STUDENT_NUM, queryInfo.getTenantId());
        Map<Integer, Integer> organsNewCloudNewStudentNumMap = withDayAndDataType.stream().collect(Collectors.toMap(IndexBaseMonthData::getOrganId, e -> e.getActivateNum().intValue(), (e1, e2) -> e1));

        List<EduOrganStudentDataDto> result = new ArrayList<>();

        for (Organization organ : organs) {
            List<CloudTeacherActiveTargetDto> targetDtos = targetMap.get(organ.getId());
            EduOrganStudentDataDto organStudentVipData = new EduOrganStudentDataDto();
            if(targetDtos != null && targetDtos.size() > 0){
                CloudTeacherActiveTargetDto target = targetDtos.get(0);
                organStudentVipData.setTargetNum(target.getTargetNum());
            }
            organStudentVipData.setOrganId(organ.getId());
            organStudentVipData.setOrganName(organ.getName());
            if(organsStudentNumMap.containsKey(organ.getId().toString())){
                organStudentVipData.setTotalStudentNum(organsStudentNumMap.get(organ.getId().toString()).intValue());
            }
            if(organsVipStudentNumMap.containsKey(organ.getId().toString())){
                organStudentVipData.setVipStudentNum(organsVipStudentNumMap.get(organ.getId().toString()).intValue());
            }
            if(organCloudStudyStudentNumMap.containsKey(organ.getId().toString())){
                organStudentVipData.setCloudStudyUseStudentNum(organCloudStudyStudentNumMap.get(organ.getId().toString()).intValue());
            }
            if(organCloudStudyLivelyStudentNumMap.containsKey(organ.getId().toString())){
                organStudentVipData.setCloudStudyLivelyStudentNum(organCloudStudyLivelyStudentNumMap.get(organ.getId().toString()).intValue());
            }
            if(organStudentVipData.getVipStudentNum()>0&&organStudentVipData.getTotalStudentNum()>0){
                organStudentVipData.setVipStudentDuty(new BigDecimal(organStudentVipData.getVipStudentNum()).divide(new BigDecimal(organStudentVipData.getTotalStudentNum()), 4, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100)).floatValue());
            }
            if(organStudentVipData.getCloudStudyUseStudentNum()>0&&organStudentVipData.getTotalStudentNum()>0){
                organStudentVipData.setCloudStudyUseStudentDuty(new BigDecimal(organStudentVipData.getCloudStudyUseStudentNum()).divide(new BigDecimal(organStudentVipData.getTotalStudentNum()), 4, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100)).floatValue());
            }
            if(organsNewCloudStudyNumMap.containsKey(organ.getId().toString())){
                organStudentVipData.setNewCloudStudyStudentNum(organsNewCloudStudyNumMap.get(organ.getId().toString()).intValue());
            }
            if(organsNewCloudNewStudentNumMap.containsKey(organ.getId())){
                organStudentVipData.setNewStudentNum(organsNewCloudNewStudentNumMap.get(organ.getId()));
                if(organStudentVipData.getNewStudentNum() > 0 && organStudentVipData.getTotalStudentNum()>0){
                    organStudentVipData.setNewStudentDuty(new BigDecimal(organStudentVipData.getNewStudentNum()).divide(new BigDecimal(organStudentVipData.getTotalStudentNum()), 4, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100)).floatValue());
                }
            }
            result.add(organStudentVipData);
        }
        Comparator<EduOrganStudentDataDto> comparing = null;
        if(StringUtils.isNotBlank(queryInfo.getTargetNum())){
            if(Objects.isNull(comparing)){
                comparing = Comparator.comparing(EduOrganStudentDataDto::getTargetNum, "ASC".equals(queryInfo.getTargetNum())?Comparator.naturalOrder():Comparator.reverseOrder());
            }else{
                comparing.thenComparing(EduOrganStudentDataDto::getTargetNum, "ASC".equals(queryInfo.getTargetNum())?Comparator.naturalOrder():Comparator.reverseOrder());
            }
        }
        if(StringUtils.isNotBlank(queryInfo.getTotalStudentNum())){
            if(Objects.isNull(comparing)){
                comparing = Comparator.comparing(EduOrganStudentDataDto::getTotalStudentNum, "ASC".equals(queryInfo.getTotalStudentNum())?Comparator.naturalOrder():Comparator.reverseOrder());
            }else{
                comparing.thenComparing(EduOrganStudentDataDto::getTotalStudentNum, "ASC".equals(queryInfo.getTotalStudentNum())?Comparator.naturalOrder():Comparator.reverseOrder());
            }
        }
        if(StringUtils.isNotBlank(queryInfo.getCloudStudyLivelyStudentNum())){
            if(Objects.isNull(comparing)){
                comparing = Comparator.comparing(EduOrganStudentDataDto::getCloudStudyLivelyStudentNum, "ASC".equals(queryInfo.getCloudStudyLivelyStudentNum())?Comparator.naturalOrder():Comparator.reverseOrder());
            }else{
                comparing.thenComparing(EduOrganStudentDataDto::getCloudStudyLivelyStudentNum, "ASC".equals(queryInfo.getCloudStudyLivelyStudentNum())?Comparator.naturalOrder():Comparator.reverseOrder());
            }
        }
        if(StringUtils.isNotBlank(queryInfo.getCloudStudyUseStudentDuty())){
            if(Objects.isNull(comparing)){
                comparing = Comparator.comparing(EduOrganStudentDataDto::getCloudStudyUseStudentDuty, "ASC".equals(queryInfo.getCloudStudyUseStudentDuty())?Comparator.naturalOrder():Comparator.reverseOrder());
            }else{
                comparing.thenComparing(EduOrganStudentDataDto::getCloudStudyUseStudentDuty, "ASC".equals(queryInfo.getCloudStudyUseStudentDuty())?Comparator.naturalOrder():Comparator.reverseOrder());
            }
        }
        if(StringUtils.isNotBlank(queryInfo.getVipStudentNum())){
            if(Objects.isNull(comparing)){
                comparing = Comparator.comparing(EduOrganStudentDataDto::getVipStudentNum, "ASC".equals(queryInfo.getVipStudentNum())?Comparator.naturalOrder():Comparator.reverseOrder());
            }else{
                comparing.thenComparing(EduOrganStudentDataDto::getVipStudentNum, "ASC".equals(queryInfo.getVipStudentNum())?Comparator.naturalOrder():Comparator.reverseOrder());
            }
        }
        if(StringUtils.isNotBlank(queryInfo.getVipStudentDuty())){
            if(Objects.isNull(comparing)){
                comparing = Comparator.comparing(EduOrganStudentDataDto::getVipStudentDuty, "ASC".equals(queryInfo.getVipStudentDuty())?Comparator.naturalOrder():Comparator.reverseOrder());
            }else{
                comparing.thenComparing(EduOrganStudentDataDto::getVipStudentDuty, "ASC".equals(queryInfo.getVipStudentDuty())?Comparator.naturalOrder():Comparator.reverseOrder());
            }
        }
        if(StringUtils.isNotBlank(queryInfo.geteVipStudentNum())){
            if(Objects.isNull(comparing)){
                comparing = Comparator.comparing(EduOrganStudentDataDto::geteVipStudentNum, "ASC".equals(queryInfo.geteVipStudentNum())?Comparator.naturalOrder():Comparator.reverseOrder());
            }else{
                comparing.thenComparing(EduOrganStudentDataDto::geteVipStudentNum, "ASC".equals(queryInfo.geteVipStudentNum())?Comparator.naturalOrder():Comparator.reverseOrder());
            }
        }
        if(StringUtils.isNotBlank(queryInfo.getNewMemberStudentNum())){
            if(Objects.isNull(comparing)){
                comparing = Comparator.comparing(EduOrganStudentDataDto::getNewMemberStudentNum, "ASC".equals(queryInfo.getNewMemberStudentNum())?Comparator.naturalOrder():Comparator.reverseOrder());
            }else{
                comparing.thenComparing(EduOrganStudentDataDto::getNewMemberStudentNum, "ASC".equals(queryInfo.getNewMemberStudentNum())?Comparator.naturalOrder():Comparator.reverseOrder());
            }
        }
        if(StringUtils.isNotBlank(queryInfo.getCloudStudyLivelyStudentDuty())){
            if(Objects.isNull(comparing)){
                comparing = Comparator.comparing(EduOrganStudentDataDto::getCloudStudyLivelyStudentDuty, "ASC".equals(queryInfo.getCloudStudyLivelyStudentDuty())?Comparator.naturalOrder():Comparator.reverseOrder());
            }else{
                comparing.thenComparing(EduOrganStudentDataDto::getCloudStudyLivelyStudentDuty, "ASC".equals(queryInfo.getCloudStudyLivelyStudentDuty())?Comparator.naturalOrder():Comparator.reverseOrder());
            }
        }
        if(StringUtils.isNotBlank(queryInfo.getNewStudentNum())){
            if(Objects.isNull(comparing)){
                comparing = Comparator.comparing(EduOrganStudentDataDto::getNewStudentNum, "ASC".equals(queryInfo.getNewStudentNum())?Comparator.naturalOrder():Comparator.reverseOrder());
            }else{
                comparing.thenComparing(EduOrganStudentDataDto::getNewStudentNum, "ASC".equals(queryInfo.getNewStudentNum())?Comparator.naturalOrder():Comparator.reverseOrder());
            }
        }
        if(StringUtils.isNotBlank(queryInfo.getNewStudentDuty())){
            if(Objects.isNull(comparing)){
                comparing = Comparator.comparing(EduOrganStudentDataDto::getNewStudentDuty, "ASC".equals(queryInfo.getNewStudentDuty())?Comparator.naturalOrder():Comparator.reverseOrder());
            }else{
                comparing.thenComparing(EduOrganStudentDataDto::getNewStudentDuty, "ASC".equals(queryInfo.getNewStudentDuty())?Comparator.naturalOrder():Comparator.reverseOrder());
            }
        }

        if(Objects.isNull(comparing)){
            comparing = Comparator.comparing(EduOrganStudentDataDto::getOrganId);
        }

        result = result.stream().sorted(comparing).skip(pageInfo.getOffset()).limit(pageInfo.getLimit()).collect(Collectors.toList());
        AtomicInteger i= new AtomicInteger();
        result.forEach(e->e.setIndex(i.incrementAndGet()));
        pageInfo.setRows(result);
        return pageInfo;
    }

    @Override
    public CloudStudyStudentDataDto getCloudStudyStudentOverView(List<Integer> organIds) {
        CloudStudyStudentDataDto result = new CloudStudyStudentDataDto();
        
        /*IndexCloudStudyListDto dto = studentDao.getOrgansCloudTeacherStudent(organIds);
        result.setTotalStudentNum(dto.getTotalStudentNum());
        result.setEffectiveVipStudentNum(dto.getEffectiveVipStudentNum());
        result.setWaitActivateVipStudentNum(dto.getWaitActivateVipStudentNum());
        
        result.setVipStudentNum(cloudTeacherDao.getOrgansTotalVipStudentNum(organIds));*/
//        result.seteVipStudentNum(studentDao.getOrgansTotalEVipStudentNum(organIds));
        result.setCloudStudyUseStudentNum(studentDao.getOrgansTotalCloudStudyStudentNum(organIds));
        result.setCloudStudyTodayUseStudentNum(studentDao.getOrgansTodayTotalCloudStudyStudentNum(organIds));
        
        Calendar cal = Calendar.getInstance();    
        cal.setTime(new Date());    
        //cal.add(Calendar.WEEK_OF_YEAR, -1);// 一周    
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        Date endTime = cal.getTime();
        
        cal.setTime(new Date());    
        cal.add(Calendar.WEEK_OF_YEAR, -4);// 一周    
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        Date startTime = cal.getTime();
        
        //result.setCloudStudyLivelyStudentNum(studentDao.getOrganTotalCloudStudyLivelyStudentNum(organIds, startTime, endTime));
        //result.setNewCloudStudyStudentNum(sysMusicCompareRecordDao.getOrgansTotalNewCloudStudyNum(organIds));
//        if(result.getVipStudentNum()>0&&result.getTotalStudentNum()>0){
//            result.setVipStudentDuty(new BigDecimal(result.getVipStudentNum()).divide(new BigDecimal(result.getTotalStudentNum()), 4, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100)).floatValue());
//        }
        return result;
    }

    @Override
	public List<IndexCloudStudyListDto> getCloudStudyStudentOverViewList(List<Integer> organIds) {
    	
    	List<IndexCloudStudyListDto> list = studentDao.getCloudStudyStudentOverViewList(organIds);
    	
    	Calendar cal = Calendar.getInstance();    
        cal.setTime(new Date());    
        //cal.add(Calendar.WEEK_OF_YEAR, -1);// 一周    
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        Date endTime = cal.getTime();
        
        cal.setTime(new Date());    
        cal.add(Calendar.WEEK_OF_YEAR, -4);// 一周    
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        Date startTime = cal.getTime();
        
        List<Mapper> mapperList = studentDao.getOrganActiveCloudStudyStudentNum(organIds, startTime, endTime);
        
        Map<Integer, Integer> organActiveNum = new HashMap<Integer, Integer>();
        for(Mapper mapper : mapperList){
        	organActiveNum.put(Integer.parseInt(mapper.getKey().toString()), Integer.parseInt(mapper.getValue().toString()));
        }
        
        List<Mapper> organCloudTeacherStudentNum = studentDao.getOrganCloudTeacherStudentNum(organIds);
        Map<Integer, Integer> organCloudTeacherStudentNumMap = new HashMap<Integer, Integer>();
        for(Mapper mapper : organCloudTeacherStudentNum){
        	organCloudTeacherStudentNumMap.put(Integer.parseInt(mapper.getKey().toString()), Integer.parseInt(mapper.getValue().toString()));
        }

        List<StudentOrganDto> set1 = studentRegistrationDao.queryEffectiveStudent(organIds);
        List<StudentOrganDto> set2 = courseScheduleStudentPaymentDao.queryRemainCourseStudent(organIds);
        List<StudentOrganDto> set3 = studentStatisticsDao.queryNoScheduleNumStudent(organIds);
        
        Map<Integer,Set<Integer>> map1= set1.stream().collect(Collectors.groupingBy(StudentOrganDto :: getOrganId, Collectors.mapping(StudentOrganDto :: getUserId, Collectors.toSet())));
        Map<Integer,Set<Integer>> map2= set2.stream().collect(Collectors.groupingBy(StudentOrganDto :: getOrganId, Collectors.mapping(StudentOrganDto :: getUserId, Collectors.toSet())));
        Map<Integer,Set<Integer>> map3= set3.stream().collect(Collectors.groupingBy(StudentOrganDto :: getOrganId, Collectors.mapping(StudentOrganDto :: getUserId, Collectors.toSet())));
        
        Map<Integer,Set<Integer>> organStudentMap = new HashMap<Integer, Set<Integer>>(map1);
        Set<Integer> temp = null;
        for(Entry<Integer, Set<Integer>> entry : map2.entrySet()){
        	temp = organStudentMap.get(entry.getKey());
        	if(temp == null){
        		organStudentMap.put(entry.getKey(), entry.getValue());
        	}else{
        		temp.addAll(entry.getValue());
        		organStudentMap.put(entry.getKey(), temp);
        	}
        }
        for(Entry<Integer, Set<Integer>> entry : map3.entrySet()){
        	temp = organStudentMap.get(entry.getKey());
        	if(temp == null){
        		organStudentMap.put(entry.getKey(), entry.getValue());
        	}else{
        		temp.addAll(entry.getValue());
        		organStudentMap.put(entry.getKey(), temp);
        	}
        }
        
        for(IndexCloudStudyListDto ics : list){
        	ics.setActiveStudentNum(organActiveNum.get(ics.getOrganId()) == null ? 0 : organActiveNum.get(ics.getOrganId()));
        	ics.setVipStudentNum(organCloudTeacherStudentNumMap.get(ics.getOrganId()) == null ? 0 : organCloudTeacherStudentNumMap.get(ics.getOrganId()));
        	ics.setEffectiveStudentNum(organStudentMap.get(ics.getOrganId()) == null ? 0 : organStudentMap.get(ics.getOrganId()).size());
        	if(ics.getEffectiveStudentNum() > 0){
        		ics.setVipStudentRate(ics.getVipStudentNum() * 100d / ics.getEffectiveStudentNum());
        	}
        }
        
		return list;
	}

	@Override
    public void cleanStudentCloudStudySequenceDays() {
        studentDao.cleanStudentCloudStudySequenceDays();
    }

    @Override
    public Map<String,Object> countCloudTeacherActive(List<Integer> organIdList, CloudTeacherActiveQueryInfo queryInfo) {
        Map<String, Object> params = new HashMap<String, Object>();
        MapUtil.populateMap(params, queryInfo);
        Integer tenantId = TenantContextHolder.getTenantId();
        //获取分部目标
        String cloudTeacherActiveTarget = sysTenantConfigService.getTenantConfigValue(SysConfigService.CLOUD_TEACHER_ACTIVE_TARGET,tenantId);
        if(StringUtils.isEmpty(cloudTeacherActiveTarget)){
            return null;
        }
        List<CloudTeacherActiveTargetDto> targetDtoList = JSONArray.parseArray(cloudTeacherActiveTarget, CloudTeacherActiveTargetDto.class);
        Map<Integer, List<CloudTeacherActiveTargetDto>> targetMap = targetDtoList.stream().collect(Collectors.groupingBy(e -> e.getOrganId()));
        //获取各分部总人数
//        List<Map<String, Long>> maps = indexBaseMonthDataDao.countTotalStudentNum();
//        Map<String, Long> organStudentNumMap = new HashMap<>(20);
//        if(maps != null && maps.size() > 0){
//            organStudentNumMap = MapUtil.convertIntegerMap(maps);
//        }
        params.put("organIdList",organIdList);
        List<CloudTeacherActiveTargetDto> resultList = indexBaseMonthDataDao.countCloudTeacherActive(params);
        for (CloudTeacherActiveTargetDto dto : resultList) {
//            Long aLong = organStudentNumMap.get(dto.getOrganId().toString());
//            dto.setTotalNum(aLong==null?0:aLong.intValue());
            List<CloudTeacherActiveTargetDto> targetDtos = targetMap.get(dto.getOrganId());
            if(targetDtos != null && targetDtos.size() > 0){
                CloudTeacherActiveTargetDto target = targetDtos.get(0);
                dto.setTargetNum(target.getTargetNum());
                dto.setTargetAmount(target.getTargetAmount());
            }
            if(dto.getBuyAmount().doubleValue() > 0d && dto.getBuyNum() > 0){
                BigDecimal avgBuyAmount = dto.getBuyAmount().divide(new BigDecimal(dto.getBuyNum()), 4, BigDecimal.ROUND_HALF_UP);
                dto.setAvgBuyAmount(avgBuyAmount);
            }
            if(dto.getTotalNum() > 0 && dto.getBuyNum() > 0){
                BigDecimal buyScale = new BigDecimal(dto.getBuyNum()).divide(new BigDecimal(dto.getTotalNum()), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
                dto.setBuyScale(buyScale);
            }
            if(dto.getTargetNum() > 0 && dto.getBuyNum() > 0){
                BigDecimal targetFinishScale = new BigDecimal(dto.getBuyNum()).divide(new BigDecimal(dto.getTargetNum()), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
                dto.setTargetFinishScale(targetFinishScale);
            }
            if(dto.getBuyAmount().doubleValue() > 0d && dto.getTargetAmount().doubleValue() > 0d){
                BigDecimal targetAmountFinishScale = dto.getBuyAmount().divide(dto.getTargetAmount(), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
                dto.setTargetAmountFinishScale(targetAmountFinishScale);
            }
        }
        Map<String,Object> resultMap = new HashMap<>(7);
        BigDecimal targetAmount = resultList.stream().map(CloudTeacherActiveTargetDto::getTargetAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        resultMap.put("targetAmount",targetAmount);
        BigDecimal buyAmount = resultList.stream().map(CloudTeacherActiveTargetDto::getBuyAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        resultMap.put("buyAmount",buyAmount);
        Integer buyNum = resultList.stream().mapToInt(CloudTeacherActiveTargetDto::getBuyNum).sum();
        resultMap.put("buyNum",buyNum);
//        Integer totalNum = resultList.stream().mapToInt(CloudTeacherActiveTargetDto::getTotalNum).sum();
//        resultMap.put("totalNum",totalNum);
        Integer targetNum = resultList.stream().mapToInt(CloudTeacherActiveTargetDto::getTargetNum).sum();
        resultMap.put("targetNum",targetNum);
        resultMap.put("avgBuyAmount",0);
//        resultMap.put("buyScale",0);
        resultMap.put("targetFinishScale",0);
        resultMap.put("targetAmountFinishScale",0);
        if(buyAmount.doubleValue() > 0d && buyNum > 0){
            BigDecimal avgBuyAmount = buyAmount.divide(new BigDecimal(buyNum), CommonConstants.DECIMAL_FINAL_PLACE, BigDecimal.ROUND_HALF_UP);
            resultMap.put("avgBuyAmount",avgBuyAmount);
        }
//        if(totalNum > 0 && buyNum > 0){
//            BigDecimal buyScale = new BigDecimal(buyNum).divide(new BigDecimal(totalNum), CommonConstants.DECIMAL_FINAL_PLACE, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
//            resultMap.put("buyScale",buyScale);
//        }
        if(targetNum > 0 && buyNum > 0){
            BigDecimal targetFinishScale = new BigDecimal(buyNum).divide(new BigDecimal(targetNum), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
            resultMap.put("targetFinishScale",targetFinishScale);
        }
        if(buyAmount.doubleValue() > 0d && targetAmount.doubleValue() > 0d){
            BigDecimal targetAmountFinishScale = buyAmount.divide(targetAmount, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
            resultMap.put("targetAmountFinishScale",targetAmountFinishScale);
        }
        Map<String,Object> result = new HashMap<>(2);
        result.put("head",resultMap);
        String sort = queryInfo.getSort();
        if(StringUtils.isEmpty(sort)){
            sort = "targetAmountFinishScale";
        }
        String order = queryInfo.getOrder();
        switch (sort){
            case "buyAmount":
                if("DESC".equalsIgnoreCase(order)){
                    resultList = resultList.stream().sorted(Comparator.comparing(CloudTeacherActiveTargetDto::getBuyAmount,Comparator.reverseOrder())).collect(Collectors.toList());
                }else {
                    resultList = resultList.stream().sorted(Comparator.comparing(CloudTeacherActiveTargetDto::getBuyAmount)).collect(Collectors.toList());
                }
                break;
            case "buyNum":
                if("DESC".equalsIgnoreCase(order)){
                    resultList = resultList.stream().sorted(Comparator.comparing(CloudTeacherActiveTargetDto::getBuyNum,Comparator.reverseOrder())).collect(Collectors.toList());
                }else {
                    resultList = resultList.stream().sorted(Comparator.comparing(CloudTeacherActiveTargetDto::getBuyNum)).collect(Collectors.toList());
                }
                break;
            case "avgBuyAmount":
                if("DESC".equalsIgnoreCase(order)){
                    resultList = resultList.stream().sorted(Comparator.comparing(CloudTeacherActiveTargetDto::getAvgBuyAmount,Comparator.reverseOrder())).collect(Collectors.toList());
                }else {
                    resultList = resultList.stream().sorted(Comparator.comparing(CloudTeacherActiveTargetDto::getAvgBuyAmount)).collect(Collectors.toList());
                }
                break;
//            case "totalNum":
//                if("DESC".equalsIgnoreCase(order)){
//                    resultList = resultList.stream().sorted(Comparator.comparing(CloudTeacherActiveTargetDto::getTotalNum,Comparator.reverseOrder())).collect(Collectors.toList());
//                }else {
//                    resultList = resultList.stream().sorted(Comparator.comparing(CloudTeacherActiveTargetDto::getTotalNum)).collect(Collectors.toList());
//                }
//                break;
//            case "buyScale":
//                if("DESC".equalsIgnoreCase(order)){
//                    resultList = resultList.stream().sorted(Comparator.comparing(CloudTeacherActiveTargetDto::getBuyScale,Comparator.reverseOrder())).collect(Collectors.toList());
//                }else {
//                    resultList = resultList.stream().sorted(Comparator.comparing(CloudTeacherActiveTargetDto::getBuyScale)).collect(Collectors.toList());
//                }
//                break;
            case "targetNum":
                if("DESC".equalsIgnoreCase(order)){
                    resultList = resultList.stream().sorted(Comparator.comparing(CloudTeacherActiveTargetDto::getTargetNum,Comparator.reverseOrder())).collect(Collectors.toList());
                }else {
                    resultList = resultList.stream().sorted(Comparator.comparing(CloudTeacherActiveTargetDto::getTargetNum)).collect(Collectors.toList());
                }
                break;
            case "targetFinishScale":
                if("DESC".equalsIgnoreCase(order)){
                    resultList = resultList.stream().sorted(Comparator.comparing(CloudTeacherActiveTargetDto::getTargetFinishScale,Comparator.reverseOrder())).collect(Collectors.toList());
                }else {
                    resultList = resultList.stream().sorted(Comparator.comparing(CloudTeacherActiveTargetDto::getTargetFinishScale)).collect(Collectors.toList());
                }
                break;
            case "targetAmountFinishScale":
                if("DESC".equalsIgnoreCase(order)){
                    resultList = resultList.stream().sorted(Comparator.comparing(CloudTeacherActiveTargetDto::getTargetAmountFinishScale,Comparator.reverseOrder())).collect(Collectors.toList());
                }else {
                    resultList = resultList.stream().sorted(Comparator.comparing(CloudTeacherActiveTargetDto::getTargetAmountFinishScale)).collect(Collectors.toList());
                }
                break;
        }
        result.put("resultList",resultList);
        return result;
    }

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

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public <T extends BaseStudentDto> SysUser upSetStudent(T baseStudent) {
        // 判断用户是否存在
        SysUser user = studentDao.getUserByPhone(baseStudent.getPhone());
        if (user == null || user.getId() == null) {
            user = new SysUser();
            BeanUtils.copyProperties(baseStudent,user);
            user.setUsername(baseStudent.getUserName());
            user.setUserType("STUDENT");
            // 注册账户信息
            teacherDao.addSysUser(user);
            Integer userId = user.getId();
            ImResult imResult = imFeignService.register(new ImUserModel(userId.toString(), user.getUsername(), user.getAvatar()));
            if(imResult != null && StringUtils.isNotEmpty(imResult.getToken())) {
                user.setImToken(imResult.getToken());
                teacherDao.updateUser(user);
            }
            baseStudent.setUserId(user.getId());
            //添加student
            this.insertStudent(baseStudent);
            sysUserCashAccountDao.insert(new SysUserCashAccount(userId, "CNY"));
        } else {
            if(!baseStudent.getTenantId().equals(user.getTenantId())){
                throw new BizException("手机号已注册");
            }
            baseStudent.setUserId(user.getId());
            if (!user.getUserType().contains("STUDENT")) {
                user.setOrganId(baseStudent.getOrganId());
                user.setUserType(user.getUserType() + ",STUDENT");
                //添加student
                this.insertStudent(baseStudent);
            }
            user.setUsername(baseStudent.getUserName());
            teacherDao.updateUser(user);
        }
        return user;
    }

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

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

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

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

    @Override
    public List<BaseMapDto> queryStuSubjectId(String organIds) {
        return studentDao.queryStuSubjectId(organIds);
    }

    @Transactional(rollbackFor = Exception.class)
    public  <T extends BaseStudentDto> void insertStudent(T baseStudent){
        Student student = new Student();
        BeanUtils.copyProperties(baseStudent,student);
        student.setIsNewUser(true);
        studentDao.insert(student);
    }
}
