package com.keao.edu.user.service.impl;


import com.keao.edu.common.dal.BaseDAO;
import com.keao.edu.common.service.impl.BaseServiceImpl;
import com.keao.edu.user.api.entity.ExamRoom;
import com.keao.edu.user.api.entity.TeacherAttendance;
import com.keao.edu.user.dao.TeacherAttendanceDao;
import com.keao.edu.user.service.ExamRoomService;
import com.keao.edu.user.service.TeacherAttendanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class TeacherAttendanceServiceImpl extends BaseServiceImpl<Long, TeacherAttendance> implements TeacherAttendanceService {
	
	@Autowired
	private TeacherAttendanceDao teacherAttendanceDao;
	@Autowired
	private ExamRoomService examRoomService;

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

	@Override
	@Transactional(rollbackFor = Exception.class,isolation = Isolation.SERIALIZABLE)
	public void upsetAttendance(Long roomId, Integer userId, Integer signFlag) {
		TeacherAttendance teacherAttendance = teacherAttendanceDao.findByRoomIdAndTeacher(roomId,userId);
		ExamRoom examRoom = examRoomService.get(roomId);
		Date date = new Date();
		if(teacherAttendance == null){
			teacherAttendance = new TeacherAttendance();
			teacherAttendance.setExamRoomId(roomId);
			teacherAttendance.setExaminationBasicId(examRoom.getExaminationBasicId());
			teacherAttendance.setSignInTime(date);
			teacherAttendance.setTeacherId(userId);
			teacherAttendanceDao.insert(teacherAttendance);
		}
		//0代表签到1签退
		if(signFlag == 1){
			teacherAttendance.setSignOutTime(date);
			teacherAttendanceDao.update(teacherAttendance);
		}
	}
}