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

import java.math.BigInteger;
import java.util.List;
import java.util.Set;

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

import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
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.InspectWorkVo;
import cn.com.qmth.stmms.biz.exam.dao.InspectHistoryDao;
import cn.com.qmth.stmms.biz.exam.model.InspectHistory;
import cn.com.qmth.stmms.biz.exam.service.ExamStudentService;
import cn.com.qmth.stmms.biz.exam.service.ExamSubjectService;
import cn.com.qmth.stmms.biz.exam.service.InspectHistoryService;

@Service("inspectHistoryService")
public class InspectHistoryServiceImpl extends BaseQueryService<InspectHistory> implements InspectHistoryService {

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private InspectHistoryDao inspectHistoryDao;

    @Autowired
    private ExamStudentService examStudentService;

    @Autowired
    private ExamSubjectService examSubjectService;

    @Override
    public InspectHistory save(InspectHistory i) {
        return inspectHistoryDao.saveAndFlush(i);
    }

    // @Override
    // public List<InspectHistory> findByStudentIdLimit3(Integer studentId) {
    // List<InspectHistory> list =
    // inspectHistoryDao.findByStudentIdLimit3(studentId, 3);
    // for (InspectHistory inspectHistory : list) {
    // User user = userDao.findOne(inspectHistory.getInspectorId());
    // inspectHistory.setInspectorName(user.getLoginName() + "/" +
    // user.getName());
    // }
    // return list;
    // }

    @Override
    public Integer countByStudentId(Integer studentId) {
        return inspectHistoryDao.countByStudentId(studentId);
    }

    @Transactional
    @Override
    public void deleteByExamIdAndSubjectCode(int examId, String subjectCode) {
        inspectHistoryDao.deleteByExamIdAndSubjectCode(examId, subjectCode);
        examStudentService.cancelInspect(examId, subjectCode);
        examSubjectService.resetInspect(examId, subjectCode);
    }

    @Transactional
    @Override
    public void deleteByStudentId(Integer studentId) {
        inspectHistoryDao.deleteByStudentId(studentId);
    }

//    @Override
//    public InspectHistory findByStudentIdAndInspectRound(Integer studentId, Integer inspectRound) {
//        return inspectHistoryDao.findByStudentIdAndInspectRound(studentId, inspectRound);
//    }

    @SuppressWarnings("unchecked")
    @Override
    public List<InspectHistory> findByStudentIdIn(List<Integer> sids) {
        StringBuilder sql = new StringBuilder();
        sql.append("select t.id,t.exam_id examId,t.inspect_time inspectTime,t.inspector_id inspectorId,t.student_id studentId,t.subject_code subjectCode,CONCAT(u.login_name, '/', u.name) inspectorName "
                + "from eb_inspect_history t  left join b_user u on t.inspector_id=u.id ");
        sql.append("where t.student_id in(" + StringUtils.join(sids, ",") + ") order by t.inspect_time ");
        Query query = entityManager.createNativeQuery(sql.toString());
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.aliasToBean(InspectHistory.class));
        return query.getResultList();
    }

    @Transactional
    @Override
    public void deleteByStudentIdAndInspectRound(Integer studentId) {
//        inspectHistoryDao.deleteByStudentIdAndInspectRound(studentId);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<InspectWorkVo> findInspectWork(Integer examId) {
        StringBuilder sql = new StringBuilder();
        sql.append(" select u.login_name loginName,u.empno,u.name,count(*) work"
                + " from eb_inspect_history t  left join b_user u on t.inspector_id=u.id ");
        sql.append(" where t.exam_id=" + examId + " group by u.id order by u.login_name ");
        Query query = entityManager.createNativeQuery(sql.toString());
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.aliasToBean(InspectWorkVo.class));
        return query.getResultList();
    }

    @SuppressWarnings("unchecked")
    @Override
    public Boolean existByStudentIdAndUserId(Integer studentId, Integer userId) {
        StringBuilder sql = new StringBuilder();
        sql.append(" select r.id from eb_inspect_history r where r.student_id=" + studentId + " and r.inspector_id="
                + userId);
        sql.append(" limit 1");
        Query query = entityManager.createNativeQuery(sql.toString());
        List<InspectHistory> ret = query.getResultList();
        if (ret != null && ret.size() > 0) {
            return true;
        }
        return false;
    }

    @Transactional
    @Override
    public void deleteByExamIdAndSubjectCode(Integer examId, String subjectCode) {
        inspectHistoryDao.deleteByExamIdAndSubjectCode(examId, subjectCode);
    }

	@SuppressWarnings("unchecked")
	@Override
	public int findMaxInspectCount(Set<Integer> stuIds) {
		StringBuilder sql = new StringBuilder();
        sql.append(" select max(tm.cc) cc from (select count(1) cc from eb_inspect_history r where r.student_id in(" 
		+ StringUtils.join(stuIds,",") + ") group by r.student_id)tm");
        sql.append(" limit 1");
        Query query = entityManager.createNativeQuery(sql.toString());
        List<BigInteger> ret = query.getResultList();
        if (ret != null && ret.size() > 0&&ret.get(0)!=null) {
            return ret.get(0).intValue();
        }
		return 0;
	}

}
