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

import java.util.LinkedList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
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.OperationLogDao;
import cn.com.qmth.stmms.biz.exam.model.OperationLog;
import cn.com.qmth.stmms.biz.exam.query.OperationLogSearchQuery;
import cn.com.qmth.stmms.biz.exam.service.OperationLogService;

@Service
public class OperationLogServiceImpl extends BaseQueryService<OperationLog> implements OperationLogService {

    @Autowired
    private OperationLogDao logDao;

    @Transactional
    @Override
    public OperationLog save(OperationLog log) {
        return logDao.save(log);
    }

    @Override
    public OperationLogSearchQuery findByQuery(OperationLogSearchQuery query) {
        checkQuery(query);
        Page<OperationLog> result = logDao.findAll(buildSpecification(query), query);
        fillResult(result, query);
        return query;
    }

    private Specification<OperationLog> buildSpecification(OperationLogSearchQuery query) {
        return new Specification<OperationLog>() {

            @Override
            public Predicate toPredicate(Root<OperationLog> root, CriteriaQuery<?> cQuery, CriteriaBuilder cb) {
                List<Predicate> predicates = new LinkedList<Predicate>();
                if (query.getSchoolId() != null) {
                    predicates.add(cb.equal(root.get("schoolId"), query.getSchoolId()));
                }
                if (query.getExamId() > 0) {
                    predicates.add(cb.equal(root.get("examId"), query.getExamId()));
                }
                if (query.getMarker() != null) {
                    predicates.add(cb.equal(root.get("marker"), query.getMarker()));
                }
                if (query.getType() != null) {
                    predicates.add(cb.equal(root.get("type"), query.getType()));
                }
                if (StringUtils.isNotBlank(query.getLoginName())) {
                    predicates.add(cb.equal(root.get("loginName"), query.getLoginName()));
                }
                return predicates.isEmpty() ? cb.conjunction() : cb.and(predicates.toArray(new Predicate[predicates
                        .size()]));
            }
        };
    }

}
