package cn.com.qmth.stmms.biz.exam.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.qmth.stmms.biz.common.BaseQueryService;
import cn.com.qmth.stmms.biz.exam.dao.ExamStudentDao;
import cn.com.qmth.stmms.biz.exam.model.ExamStudent;
import cn.com.qmth.stmms.biz.exam.service.ExamStudentCacheService;

@Service("examStudentCacheService")
public class ExamStudentCacheServiceImpl extends BaseQueryService<ExamStudent> implements ExamStudentCacheService {

    @Autowired
    private ExamStudentDao studentDao;

    public ExamStudent findById(int id) {
        return studentDao.findOne(id);
    }

    @Transactional
    @CachePut(value = "exam_student_cache", key = "#student.examId+'-'+#student.examNumber", condition = "#student!=null && #student.examId!=null && #student.examNumber!=null")
    public ExamStudent save(ExamStudent student) {
        if (student.getId() != null && student.getId() > 0) {
            return studentDao.save(student);
        } else {
            ExamStudent previous = findByExamIdAndExamNumber(student.getExamId(), student.getExamNumber());
            if (previous != null) {
                student.setId(previous.getId());
            }
            return studentDao.save(student);
        }
    }

    @Transactional
    @CacheEvict(value = "exam_student_cache", key = "#student.examId+'-'+#student.examNumber", condition = "#student!=null", beforeInvocation = true)
    public void delete(ExamStudent student) {
        if (student != null) {
            studentDao.delete(student);
        }
    }

    @Override
    @Cacheable(value = "exam_student_cache", key = "#examId+'-'+#examNumber")
    public ExamStudent findByExamIdAndExamNumber(int examId, String examNumber) {
        List<ExamStudent> list = studentDao.findByExamIdAndExamNumber(examId, examNumber);
        return list != null && list.size() > 0 ? list.get(0) : null;
    }

}
