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

import java.util.List;
import java.util.stream.Collectors;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

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 cn.com.qmth.stmms.biz.common.BaseQueryService;
import cn.com.qmth.stmms.biz.exam.bean.AddStudentInfo;
import cn.com.qmth.stmms.biz.exam.bean.UserStudentVo;
import cn.com.qmth.stmms.biz.exam.dao.UserStudentDao;
import cn.com.qmth.stmms.biz.exam.model.UserStudent;
import cn.com.qmth.stmms.biz.exam.service.UserStudentService;
import cn.com.qmth.stmms.biz.utils.BatchUpdateDataUtil;

@Service("userStudentService")
public class UserStudentServiceImpl extends BaseQueryService<UserStudent> implements UserStudentService {
	
	@PersistenceContext
	private EntityManager entityManager;
	
	@Autowired
	private UserStudentDao userStudentDao;
	
	@Transactional
	@Override
	public AddStudentInfo addStudent(List<UserStudentVo> list,Integer schoolId, Integer userId) {
		int suc=0;
		int total=0;
		if(list!=null&&list.size()>0) {
			total=list.size();
			suc=new BatchUpdateDataUtil<UserStudentVo>() {
				@Override
				protected int updateData(List<UserStudentVo> dataList) {
					List<String> examNumbers=dataList.stream().map(e->e.getExamNumber()).collect(Collectors.toList());
					StringBuilder sql = new StringBuilder();
					sql.append(" INSERT INTO eb_user_student (`user_id`, `exam_number`) ");
					sql.append(" SELECT distinct "+userId+",s.exam_number from eb_exam_student s ");
					sql.append(" where s.school_id="+schoolId +" and s.exam_number in ('"+StringUtils.join(examNumbers,"','")+"') ");
					sql.append(" and not exists (select 1 from eb_user_student t where t.user_id="+userId+" and t.exam_number=s.exam_number)");
					Query query = entityManager.createNativeQuery(sql.toString());
					return query.executeUpdate();
				}
			}.setDataForBatch(list, 500);
		}
		AddStudentInfo info=new AddStudentInfo(suc, total-suc);
		return info;
	}

	@Override
	public int countByUserId(Integer userId) {
		return userStudentDao.countByUserId(userId);
	}

	@Transactional
	@Override
	public void clear(Integer userId) {
		userStudentDao.deleteByUserId(userId);
	}

	

}
