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.TeacherAttendanceDto;
import com.ym.mec.biz.dal.dto.TeacherPersonalAttendanceDto;
import com.ym.mec.biz.dal.dto.TeacherSignOutDto;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.dal.enums.ParamEnum;
import com.ym.mec.biz.dal.enums.SignStatusEnum;
import com.ym.mec.biz.dal.enums.YesOrNoEnum;
import com.ym.mec.biz.dal.page.TeacherAttendanceQueryInfo;
import com.ym.mec.biz.service.CourseHomeworkService;
import com.ym.mec.biz.service.CourseScheduleService;
import com.ym.mec.biz.service.TeacherAttendanceService;
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.service.impl.BaseServiceImpl;
import com.ym.mec.util.collection.MapUtil;
import com.ym.mec.util.date.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class TeacherAttendanceServiceImpl extends BaseServiceImpl<Long, TeacherAttendance>  implements TeacherAttendanceService {
	
	@Autowired
	private TeacherAttendanceDao teacherAttendanceDao;
	@Autowired
	private CourseScheduleDao courseScheduleDao;
	@Autowired
	private CourseHomeworkService courseHomeworkService;
	@Autowired
	private StudentAttendanceDao studentAttendanceDao;
	@Autowired
	private StudentCourseHomeworkDao studentCourseHomeworkDao;
	@Autowired
	private SysUserFeignService sysUserFeignService;
	@Autowired
	private ClassGroupDao classGroupDao;
	@Autowired
	private CourseScheduleService courseScheduleService;

	@Override
	public BaseDAO<Long, TeacherAttendance> getDAO() {
		return teacherAttendanceDao;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public Map<String, Object> addTeacherAttendanceRecord(TeacherSignOutDto teacherSignOutDto) {
		SysUser user = sysUserFeignService.queryUserInfo();
		if(Objects.isNull(user)){
			throw new BizException("请登录");
		}

		if(Objects.isNull(teacherSignOutDto.getTeacherAttendanceInfo().getCourseScheduleId())){
			throw new BizException("请选择课程!");
		}

		Map<String,Object> result=new HashMap<>();

		TeacherAttendance teacherAttendance=teacherAttendanceDao.findByTeacherAttendanceInfo(user.getId().longValue(),teacherSignOutDto.getTeacherAttendanceInfo().getCourseScheduleId());

		boolean isAttendance=false;

		if(Objects.isNull(teacherAttendance)){
			teacherAttendance=teacherSignOutDto.getTeacherAttendanceInfo();
			teacherAttendance.setTeacherId(Long.valueOf(user.getId()));
		}else{
			isAttendance=true;
		}

		CourseSchedule courseSchedule=new CourseSchedule();
		TeacherAttendanceDto currentCourseDetail = courseScheduleDao.getCurrentCourseDetail(teacherSignOutDto.getTeacherAttendanceInfo().getCourseScheduleId());
		if(Objects.isNull(currentCourseDetail)){
			throw new BizException("课程不存在");
		}
		courseSchedule.setId(currentCourseDetail.getCourseScheduleId());

		teacherAttendance.setMusicGroupId(currentCourseDetail.getMusicGroupId());
		teacherAttendance.setClassGroupId(currentCourseDetail.getClassId());
		Date date = new Date();
		if(teacherSignOutDto.getTeacherAttendanceInfo().equals(SignStatusEnum.SIGN_IN.getCode())){

			if (currentCourseDetail.getEndClassTime().before(date)){
				throw new BizException("该课程已结束，不能进行签到!");
			}

			YesOrNoEnum yesOrNoEnum = courseScheduleService.enableOnlyNormalAttendance(currentCourseDetail, user.getId().longValue());

			if(yesOrNoEnum==YesOrNoEnum.YES){
				teacherAttendance.setSignInStatus(YesOrNoEnum.YES);
				result.put("signInStatus",YesOrNoEnum.YES.getCode());
			}else{
				Long timeGap=(date.getTime()-currentCourseDetail.getStartClassTime().getTime())/1000/60;
				if(timeGap<= ParamEnum.TEACHER_ATTENDANCE_TIME_GAP.getCode()){
					teacherAttendance.setSignInStatus(YesOrNoEnum.YES);
					result.put("signInStatus",YesOrNoEnum.YES.getCode());
				}else{
					if(StringUtils.isEmpty(teacherAttendance.getRemark())){
						//当前为异常签到，请填写原因!
						result.put("status",2);
						return result;
					}
					teacherAttendance.setSignInStatus(YesOrNoEnum.NO);
					result.put("signInStatus",YesOrNoEnum.NO.getCode());
				}
			}
			teacherAttendance.setSignInTime(date);
			teacherAttendanceDao.insert(teacherAttendance);
		}else{
			if (currentCourseDetail.getEndClassTime().after(date)){
				throw new BizException("该课程还未结束，不能进行签退!");
			}
			if(!Objects.isNull(teacherAttendance.getSignOutStatus())){
				throw new BizException("该课程已签退!");
			}
			int i = DateUtil.hoursBetween(currentCourseDetail.getEndClassTime(), date);
			if(i<=1){
				teacherAttendance.setSignOutStatus(YesOrNoEnum.YES);
			}else{
				teacherAttendance.setSignOutStatus(YesOrNoEnum.NO);
			}
			teacherAttendance.setSignOutTime(date);
			teacherAttendance.setCreateTime(date);
			if(isAttendance){
				teacherAttendanceDao.update(teacherAttendance);
			}else{
				teacherAttendanceDao.insert(teacherAttendance);
			}
		}
		if(teacherSignOutDto.getTeacherAttendanceInfo().getStatus().equals(SignStatusEnum.SIGN_OUT.getCode())){
			//更新课次
			ClassGroup classGroup=new ClassGroup();
			classGroup.setId(currentCourseDetail.getClassId().intValue());
			classGroup.setCurrentClassTimes(teacherAttendanceDao.countClassTime(currentCourseDetail.getClassId()));
			classGroupDao.update(classGroup);
			//新增课堂作业
			CourseHomework courseHomework=teacherSignOutDto.getCourseHomeworkInfo();
			courseHomework.setCourseScheduleId(teacherAttendance.getCourseScheduleId());
			courseHomework.setMusicGroupId(currentCourseDetail.getMusicGroupId().intValue());
			courseHomework.setClassGroupId(currentCourseDetail.getClassId().intValue());
			courseHomework.setExpectNum(studentAttendanceDao.countNormalAttendanceStudentNums(teacherAttendance.getCourseScheduleId()));
			courseHomeworkService.insert(courseHomework);
			List<StudentCourseHomework> studentCourseHomeworks = studentCourseHomeworkDao.constructInitialStudentHomeworkRecords(teacherAttendance.getCourseScheduleId(),
					courseHomework.getId());
			studentCourseHomeworkDao.batchInsertStudentCourseHomeworkRecord(studentCourseHomeworks);
		}

		result.put("status",0);
		result.put("currentTime",date);

		return result;
	}

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

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


}