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

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.*;
import com.ym.mec.biz.dal.page.CourseHomeworkQueryInfo;
import com.ym.mec.biz.dal.page.StudentAttendanceQueryInfo;
import com.ym.mec.biz.service.*;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.common.page.QueryInfo;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.thirdparty.message.MessageSenderPluginContext;
import com.ym.mec.util.collection.MapUtil;
import com.ym.mec.util.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

@Service
public class StudentAttendanceServiceImpl extends BaseServiceImpl<Long, StudentAttendance>  implements StudentAttendanceService {
	
	@Autowired
	private StudentAttendanceDao studentAttendanceDao;
	@Autowired
	private MusicGroupStudentFeeDao studentFeeDao;
	@Autowired
	private CourseScheduleDao courseScheduleDao;
	@Autowired
	private CourseScheduleStudentPaymentDao courseScheduleStudentPaymentDao;
	@Autowired
	private ClassGroupDao classGroupDao;
	@Autowired
	private ClassGroupStudentMapperDao classGroupStudentMapperDao;
	@Autowired
	private SysUserFeignService sysUserFeignService;
	@Autowired
	private SubjectDao subjectDao;
	@Autowired
	private MusicGroupStudentFeeDao musicGroupStudentFeeDao;
	@Autowired
	private MusicGroupQuitDao musicGroupQuitDao;
	@Autowired
	private SysMessageService sysMessageService;
	@Autowired
	private SysConfigDao sysConfigDao;
	@Autowired
	private SchoolDao schoolDao;
	@Autowired
	private SysConfigService sysConfigService;
	@Autowired
	private CourseScheduleService courseScheduleService;
	@Autowired
	private TeacherAttendanceDao teacherAttendanceDao;

	@Override
	public BaseDAO<Long, StudentAttendance> getDAO() {
		return studentAttendanceDao;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void addStudentAttendances(StudentAttendanceDto studentAttendanceInfos) {
		List<StudentAttendance> studentAttendances=studentAttendanceInfos.getStudentAttendances();
		SysUser sysUser = sysUserFeignService.queryUserInfo();
		if(Objects.isNull(sysUser)){
			throw new BizException("请登录");
		}
		if(CollectionUtils.isEmpty(studentAttendances)){
			throw new BizException("无点名信息");
		}
		Long courseScheduleId=studentAttendances.get(0).getCourseScheduleId();
		CourseSchedule courseSchedule = courseScheduleDao.get(courseScheduleId);
		if(Objects.isNull(courseSchedule)){
			throw new BizException("请指定课程");
		}
		Date date = new Date();
		SysConfig attendanceTimeRange;
		if(courseSchedule.getGroupType().equals(GroupType.MUSIC)){
			attendanceTimeRange = sysConfigService.findByParamName(SysConfigService.ENABLE_STUDENT_ATTENDANCE_TIME_RANGE);
		}else{
			SysConfig beforeAttendanceTimeRange=sysConfigService.findByParamName(SysConfigService.ENABLE_STUDENT_ATTENDANCE_BEFOR_COURSE_START_TIME_RANGE_VIP);
			int courseStartTime = DateUtil.minutesBetween(date, courseSchedule.getStartClassTime());
			if(date.before(courseSchedule.getStartClassTime())&&courseStartTime>beforeAttendanceTimeRange.getParanValue(Integer.class)){
				throw new BizException("VIP课开课前{}分钟禁止点名",beforeAttendanceTimeRange.getParanValue(Integer.class));
			}
			attendanceTimeRange = sysConfigService.findByParamName(SysConfigService.ENABLE_STUDENT_ATTENDANCE_TIME_RANGE_VIP);
		}
		int courseEndTime = DateUtil.minutesBetween(courseSchedule.getEndClassTime(), date);
		if(date.after(courseSchedule.getEndClassTime())&&courseEndTime>attendanceTimeRange.getParanValue(Integer.class)){
			throw new BizException("{}课结束{}分钟后禁止点名",
					courseSchedule.getGroupType().equals(GroupType.MUSIC)?"乐团":"VIP",
					attendanceTimeRange.getParanValue(Integer.class));
		}
		studentAttendanceDao.deleteStudentAttendancesByCourse(courseScheduleId);
		int classTimes=courseScheduleDao.countClassTimes(courseSchedule.getClassGroupId().longValue(),courseSchedule.getStartClassTime());
		studentAttendances.forEach(studentAttendance -> {
			studentAttendance.setTeacherId(sysUser.getId());
			studentAttendance.setCurrentClassTimes(classTimes+1);
			StudentAttendance studentAttendanceInfo = studentAttendanceDao.getStudentAttendanceInfo(studentAttendance);
			studentAttendanceInfo.setGroupType(courseSchedule.getGroupType());
			studentAttendanceInfo.setMusicGroupId(courseSchedule.getMusicGroupId());
			if (studentAttendance.getStatus() != StudentAttendanceStatusEnum.DROP_OUT) {
				//判断是否为连续旷课
				if(StudentAttendanceStatusEnum.TRUANT.equals(studentAttendance.getStatus())
						||StudentAttendanceStatusEnum.LEAVE.equals(studentAttendance.getStatus())){
					StudentAttendance studentLatestAttendanceInfo = studentAttendanceDao.getStudentLatestAttendanceInfo(studentAttendanceInfo);
					if(Objects.nonNull(studentLatestAttendanceInfo)){
						if(StudentAttendanceStatusEnum.TRUANT.equals(studentLatestAttendanceInfo.getStatus())
								||StudentAttendanceStatusEnum.LEAVE.equals(studentLatestAttendanceInfo.getStatus())){
							studentFeeDao.updateStudentAbsenteeismTimes(studentAttendanceInfo.getUserId(),
									studentAttendanceInfo.getMusicGroupId(),
									YesOrNoEnum.YES.getCode());
						}
					}else{
						studentFeeDao.updateStudentAbsenteeismTimes(studentAttendanceInfo.getUserId(),
								studentAttendanceInfo.getMusicGroupId(),
								YesOrNoEnum.YES.getCode());
					}
				}else{
					studentFeeDao.updateStudentAbsenteeismTimes(studentAttendanceInfo.getUserId(),
							studentAttendanceInfo.getMusicGroupId(),
							YesOrNoEnum.NO.getCode());
				}
				studentAttendanceDao.insert(studentAttendanceInfo);
			}else{
				studentFeeDao.updateStudentAbsenteeismTimes(studentAttendanceInfo.getUserId(),
						studentAttendanceInfo.getMusicGroupId(),
						YesOrNoEnum.NO.getCode());
			}
		});
		//获取正常签到的学生信息
		List<StudentAttendance> normal = studentAttendances.stream().filter(studentAttendance -> studentAttendance.getStatus() == StudentAttendanceStatusEnum.NORMAL).collect(Collectors.toList());
		if(normal != null && normal.size() > 0){
			Map<Integer,String> receivers = new HashMap<>();
			normal.forEach(e->{
				receivers.put(e.getUserId(),e.getUserId().toString());
			});
			sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG,MessageTypeEnum.STUDENT_PUSH_NAMES_ACHIEVE,
					receivers,null,0,"2","STUDENT",DateUtil.format(new Date(),DateUtil.DATE_FORMAT_MIN));
		}
		Map<StudentAttendanceStatusEnum, List<StudentAttendance>> studentAttendanceGroupByStatus = studentAttendances.stream().collect(Collectors.groupingBy(StudentAttendance::getStatus));
		Integer studentNum=studentAttendanceGroupByStatus.get(StudentAttendanceStatusEnum.NORMAL)==null?0:studentAttendanceGroupByStatus.get(StudentAttendanceStatusEnum.NORMAL).size();
		Integer leaveStudentNum=studentAttendanceGroupByStatus.get(StudentAttendanceStatusEnum.LEAVE)==null?0:studentAttendanceGroupByStatus.get(StudentAttendanceStatusEnum.LEAVE).size();
		courseSchedule.setStudentNum(studentNum);
		courseSchedule.setLeaveStudentNum(leaveStudentNum);
		courseScheduleDao.update(courseSchedule);

		if(!courseSchedule.getType().equals(CourseSchedule.CourseScheduleType.VIP)){
			return;
		}

		if(StringUtils.isBlank(studentAttendanceInfos.getSignInLongitudeLatitude())){
			throw new BizException("未获取到您的位置");
		}

		School school = schoolDao.get(courseSchedule.getSchoolId());

		//是否在范围内
		boolean isInScore = true;
		if(Objects.nonNull(school)){
			if(StringUtils.isBlank(school.getLongitudeLatitude())){
				if(studentAttendanceInfos.getUpdate().equals(YesOrNoEnum.YES.getCode())){
					school.setLongitudeLatitude(studentAttendanceInfos.getSignInLongitudeLatitude());
					schoolDao.update(school);
				}
			}else{
				SysConfig sysConfig = sysConfigService.findByParamName(SysConfigService.ATTENDANCE_RANGE);
				double attendanceRange = Double.valueOf(sysConfig.getParanValue());
				double distance = MapUtil.distance(studentAttendanceInfos.getSignInLongitudeLatitude(),
						school.getLongitudeLatitude());
				if(distance>attendanceRange){
					isInScore=false;
				}
			}
		}

		TeacherAttendance teacherAttendance=teacherAttendanceDao.findByTeacherAttendanceInfo(sysUser.getId().longValue(),courseSchedule.getId());

		teacherAttendance.setSignInLongitudeLatitude(studentAttendanceInfos.getSignInLongitudeLatitude());

		if(Objects.isNull(teacherAttendance)){
			teacherAttendance= new TeacherAttendance();
			teacherAttendance.setTeacherId(sysUser.getId());
			teacherAttendance.setCreateTime(date);
		}else if(teacherAttendance.getSignInTime() != null && teacherAttendance.getSignOutTime() != null){
			return;
		}

		teacherAttendance.setSignInTime(date);
		teacherAttendance.setSignInStatus(YesOrNoEnum.YES);
		teacherAttendance.setSignOutTime(date);
		teacherAttendance.setSignOutStatus(YesOrNoEnum.YES);
		teacherAttendance.setCurrentClassTimes(classTimes + 1);
		if(Objects.nonNull(teacherAttendance.getId())){
			teacherAttendanceDao.update(teacherAttendance);
		}else{
			teacherAttendanceDao.insert(teacherAttendance);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateStudentAttendances(StudentAttendanceDto studentAttendanceInfo) {
		if(Objects.isNull(studentAttendanceInfo.getCourseScheduleId())){
			throw new BizException("请指定课程编号");
		}
		List<StudentAttendance> studentAttendances=studentAttendanceInfo.getStudentAttendances();
		if(CollectionUtils.isEmpty(studentAttendances)){
			throw new BizException("无点名信息");
		}
		CourseSchedule courseSchedule = courseScheduleDao.get(studentAttendanceInfo.getCourseScheduleId().longValue());
		if(Objects.isNull(courseSchedule)){
			throw new BizException("课程不存在");
		}
		List<Integer> userIds = studentAttendances.stream().map(StudentAttendance::getUserId).collect(Collectors.toList());
		studentAttendanceDao.deleteStudentAttendancesByCourseAndUsers(studentAttendanceInfo.getCourseScheduleId().longValue(),userIds);
		for (StudentAttendance studentAttendance : studentAttendances) {
			studentAttendance.setGroupType(courseSchedule.getGroupType());
			studentAttendance.setMusicGroupId(courseSchedule.getMusicGroupId());
			studentAttendance.setClassGroupId(courseSchedule.getClassGroupId());
			studentAttendance.setTeacherId(courseSchedule.getActualTeacherId());
			studentAttendance.setCourseScheduleId(courseSchedule.getId());
		}
		studentAttendanceDao.addStudentAttendances(studentAttendances);
		List<StudentAttendance> allStudentAttendances = studentAttendanceDao.findByCourseId(studentAttendanceInfo.getCourseScheduleId());
		Map<StudentAttendanceStatusEnum, List<StudentAttendance>> studentAttendanceGroupByStatus = allStudentAttendances.stream().collect(Collectors.groupingBy(StudentAttendance::getStatus));
		Integer studentNum=studentAttendanceGroupByStatus.get(StudentAttendanceStatusEnum.NORMAL)==null?0:studentAttendanceGroupByStatus.get(StudentAttendanceStatusEnum.NORMAL).size();
		Integer leaveStudentNum=studentAttendanceGroupByStatus.get(StudentAttendanceStatusEnum.LEAVE)==null?0:studentAttendanceGroupByStatus.get(StudentAttendanceStatusEnum.LEAVE).size();
		courseSchedule.setStudentNum(studentNum);
		courseSchedule.setLeaveStudentNum(leaveStudentNum);
		courseScheduleDao.update(courseSchedule);
	}

	@Override
	public Map<String, Object> getCurrentCourseStudents(QueryInfo queryInfo) {
		Map<String,Object> result=new HashMap<>();

		PageInfo<StudentAttendance> pageInfo = super.queryPage(queryInfo);

		result.put("pageInfo",pageInfo);

		List<StudentStatusCountUtilEntity> stringIntegerMap = studentAttendanceDao.countStudentStatus(((StudentAttendanceQueryInfo) queryInfo).getClassGroupId());

		stringIntegerMap.forEach(studentStatusCount->{
			switch (studentStatusCount.getStudentStatus()){
				case LEAVE:
					result.put("numberOfLeavePeoples",studentStatusCount.getNumberOfStudent());
					break;
			default:
				break;

			}
		});

		return result;
	}

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

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

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean leave(Integer userId, Long courseScheduleId, String remark) {
		
		CourseSchedule courseSchedule = courseScheduleDao.get(courseScheduleId);
		if(courseSchedule == null){
			throw new BizException("课程编号异常");
		}
		
		if(courseSchedule.getStatus() == CourseStatusEnum.OVER){
			throw new BizException("课程已结束");
		}

		Date date = new Date();
		
		int hours = 4;
		String str = sysConfigDao.findConfigValue(SysConfigService.ADVANCE_LEAVE_HOURS);
		if (StringUtils.isNotBlank(str)) {
			hours = Integer.parseInt(str);
		}

		if(DateUtil.addHours(date, hours).after(courseSchedule.getStartClassTime())){
			throw new BizException("开课{}小时之前才可以请假",hours);
		}
		
		StudentAttendance studentAttendance  = studentAttendanceDao.findByStatusAndCourseScheduleId(userId,courseScheduleId.intValue());
		if(Objects.isNull(studentAttendance)){
			studentAttendance=new StudentAttendance();
		}
		studentAttendance.setClassGroupId(courseSchedule.getClassGroupId());
		studentAttendance.setCourseScheduleId(courseScheduleId);
		studentAttendance.setCreateTime(date);
		studentAttendance.setCurrentClassTimes(0);
		studentAttendance.setRemark(remark);
		studentAttendance.setStatus(StudentAttendanceStatusEnum.LEAVE);
		studentAttendance.setUserId(userId);
		studentAttendance.setGroupType(courseSchedule.getGroupType());
		studentAttendance.setMusicGroupId(courseSchedule.getMusicGroupId());

		if(Objects.nonNull(studentAttendance.getId())){
			studentAttendanceDao.update(studentAttendance);
		}else{
			studentAttendanceDao.insert(studentAttendance);
		}
		
		ClassGroupStudentMapper classGroupStudentMapper = classGroupStudentMapperDao.query(courseSchedule.getClassGroupId(), userId);
		if(Objects.isNull(classGroupStudentMapper)){
			throw new BizException("您不在此课程对应班级上");
		}

		Map<Integer,String> sendArgs=new HashMap<>();
		sendArgs.put(courseSchedule.getActualTeacherId(),courseSchedule.getActualTeacherId() + "");
		SysUser sysUser = sysUserFeignService.queryUserInfo();
		//发送消息至老师
		sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG,
				MessageTypeEnum.TEACHER_PUSH_STUDENT_LEAVE,
				sendArgs,
				null,0,"1","TEACHER",DateUtil.getDate(courseSchedule.getClassDate()),DateUtil.getTime(courseSchedule.getStartClassTime()),courseSchedule.getName(),sysUser.getUsername());
		return true;
	}

	@Override
	public PageInfo statisticsList(CourseHomeworkQueryInfo queryInfo) {

		if(Objects.isNull(queryInfo.getClassGroupId())){
			throw new BizException("请指定班级");
		}

		PageInfo pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
		Map<String, Object> params = new HashMap<String, Object>();
		MapUtil.populateMap(params, queryInfo);

		List<StudentAttendanceStatisticsResponse> dataList = null;
		int count = courseScheduleStudentPaymentDao.countStudentByClassGroup(params);
		if (count > 0) {
			pageInfo.setTotal(count);
			params.put("offset", pageInfo.getOffset());
			ClassGroup classGroup = classGroupDao.get(queryInfo.getClassGroupId().intValue());
			if(Objects.isNull(classGroup)){
				throw new BizException("班级不存在");
			}
			dataList = courseScheduleStudentPaymentDao.findStudentByClassGroup(params);
			//学生编号列表
			List<Integer> userIds = dataList.stream().map(StudentAttendanceStatisticsResponse::getUserId).collect(Collectors.toList());
			//学生-旷课次数关联集合
			List<Map<Integer, Integer>> continuousAbsenteeismTimesByUsersAndMusicGroup = musicGroupStudentFeeDao.findContinuousAbsenteeismTimesByUsersAndMusicGroup(classGroup.getMusicGroupId(), userIds);
			Map<Integer,Integer> continuousAbsenteeismTimesWithUser=MapUtil.convertIntegerMap(continuousAbsenteeismTimesByUsersAndMusicGroup);
			//学生签到记录列表
			List<StudentAttendanceResponse> studentAttendances = studentAttendanceDao.findByClassGroupAndUsers(queryInfo.getClassGroupId(), userIds);
			//学生签到状态统计列表
			List<StudentAttendanceStatusCountDto> studentAttendanceStatusCountDtos = studentAttendanceDao.countStudentAttendanceStatus(queryInfo.getClassGroupId(), userIds);
			Map<Integer, List<StudentAttendanceStatusCountDto>> studentAttendanceStatusCountDtosByUser = studentAttendanceStatusCountDtos.stream().collect(Collectors.groupingBy(StudentAttendanceStatusCountDto::getUserId));

			if(!CollectionUtils.isEmpty(studentAttendances)){
				//学生-签到记录关联集合
				Map<Integer, List<StudentAttendanceResponse>> studentAttendanceByUser = studentAttendances.stream().collect(Collectors.groupingBy(StudentAttendanceResponse::getUserId));

				dataList.forEach(student->{
					//判断是否是连续签到
					Integer continuousAbsenteeismTimes = continuousAbsenteeismTimesWithUser.get(student.getUserId());
					if(Objects.nonNull(continuousAbsenteeismTimes)){
						if(continuousAbsenteeismTimes>=3){
							student.setTruant(true);
						}
					}
					//当前学生的签到状态统计
					List<StudentAttendanceStatusCountDto> currentStudentAttendanceStatusCountDtos = studentAttendanceStatusCountDtosByUser.get(student.getUserId());
					if(!CollectionUtils.isEmpty(currentStudentAttendanceStatusCountDtos)){
						Map<StudentAttendanceStatusEnum, Integer> statusAndNumMap = currentStudentAttendanceStatusCountDtos.stream().collect(Collectors.toMap(StudentAttendanceStatusCountDto::getStatus, StudentAttendanceStatusCountDto::getNum));
						student.setNormalDay(statusAndNumMap.get(StudentAttendanceStatusEnum.NORMAL));
						student.setTruantDay(statusAndNumMap.get(StudentAttendanceStatusEnum.TRUANT));
						student.setLeaveDay(statusAndNumMap.get(StudentAttendanceStatusEnum.LEAVE));
					}

					//当前学生签到记录
					List<StudentAttendanceResponse> studentAttendanceResps = studentAttendanceByUser.get(student.getUserId());
					if(Objects.nonNull(studentAttendanceResps)){
						student.setList(studentAttendanceResps);
					}
				});
			}
		}
		if (count == 0) {
			dataList = new ArrayList<>();
		}
		pageInfo.setRows(dataList);
		return pageInfo;
	}

	@Override
	public CourseScheduleResponse getStatisticsInfo(Integer classGroupId) {
		if(Objects.isNull(classGroupId)){
			throw new BizException("请指定班级");
		}
		ClassGroup classGroup = classGroupDao.get(classGroupId);
		CourseScheduleResponse courseScheduleResp = new CourseScheduleResponse();
		if (Objects.nonNull(classGroup)) {
			if (Objects.nonNull(classGroup.getCurrentClassTimes()) && Objects.nonNull(classGroup.getTotalClassTimes())) {
				courseScheduleResp.setAlreadyInClass(classGroup.getCurrentClassTimes() + "/" + classGroup.getTotalClassTimes());
			}
			if (Objects.nonNull(classGroup.getStudentNum())) {
				courseScheduleResp.setStudentNum(classGroup.getStudentNum());
			}
			Date latestSignInDate = studentAttendanceDao.findLatestSignInDate(classGroupId);
			if(Objects.nonNull(latestSignInDate)){
				courseScheduleResp.setClassDate(DateUtil.format(latestSignInDate,DateUtil.DATE_FORMAT_MIN));
				courseScheduleResp.setClassTime(DateUtil.date2Week(latestSignInDate));
			}
			courseScheduleResp.setLeagueNum(musicGroupQuitDao.countMusicGroupQuitNum(classGroup.getMusicGroupId()));
		}
		return courseScheduleResp;
	}

	@Override
	public void addStudentAttendanceRecord(Integer courseScheduleId, Integer userId, StudentAttendanceStatusEnum statusEnum) {
		StudentAttendance studentAttendance = studentAttendanceDao.findByStatusAndCourseScheduleId(userId,courseScheduleId);
		if(studentAttendance == null){
			//判断是否在签到时间段内（课程开始前20~结束前）
			CourseSchedule courseSchedule = courseScheduleDao.get(courseScheduleId.longValue());
			ClassGroup classGroup = classGroupDao.findByCourseSchedule(courseScheduleId);
			if(classGroup != null && courseSchedule != null){
//				int advanceSignMinutes = Integer.parseInt(sysConfigDao.findConfigValue(SysConfigService.ADVANCE_SIGN_IN_MINUTES));
				Date date = new Date();
				String classDate = DateUtil.format(courseSchedule.getClassDate(), DateUtil.DEFAULT_PATTERN);
				String startClassTime = DateUtil.format(courseSchedule.getStartClassTime(), DateUtil.EXPANDED_TIME_FORMAT);
				String endClassTime = DateUtil.format(courseSchedule.getEndClassTime(), DateUtil.EXPANDED_TIME_FORMAT);
				//上课时间
				Date classStartDateTime = DateUtil.stringToDate(classDate + " " + startClassTime, DateUtil.EXPANDED_DATE_TIME_FORMAT);
				Date classEndDateTime = DateUtil.stringToDate(classDate + " " + endClassTime, DateUtil.EXPANDED_DATE_TIME_FORMAT);
				Date addMinutes = DateUtil.addMinutes(classStartDateTime, -60);
				//课程结束前进入，算正常
				if(DateUtil.minutesBetween(addMinutes,date) >= 0 && DateUtil.minutesBetween(date,classEndDateTime) > 0){
					studentAttendance = new StudentAttendance();
					studentAttendance.setClassGroupId(classGroup.getId());
					studentAttendance.setCourseScheduleId(courseScheduleId.longValue());
					studentAttendance.setCurrentClassTimes(classGroup.getCurrentClassTimes() + 1);
					studentAttendance.setGroupType(classGroup.getGroupType());
					studentAttendance.setMusicGroupId(classGroup.getMusicGroupId());
					studentAttendance.setStatus(statusEnum);
					studentAttendance.setUserId(userId);
					studentAttendance.setTeacherId(courseSchedule.getActualTeacherId());

					courseSchedule.setUpdateTime(date);
					courseSchedule.setStudentNum((courseSchedule.getStudentNum() == null?0:courseSchedule.getStudentNum()) + 1);
					courseScheduleDao.update(courseSchedule);
					studentAttendanceDao.insert(studentAttendance);
				}
			}else {
				throw new BizException("学员班级或课程信息异常");
			}
		}
	}

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

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