package cn.com.qmth.stmms.biz.report.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.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
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.report.dao.ReportSubjectGroupDao;
import cn.com.qmth.stmms.biz.report.model.ReportSubjectGroup;
import cn.com.qmth.stmms.biz.report.query.ReportSubjectQuery;
import cn.com.qmth.stmms.biz.report.service.ReportSubjectGroupService;

/**
 * 大题型统计分析 service 实现
 *
 * @author xuwenjin
 * @Date 2019-04-18
 */
@Service
public class ReportSubjectGroupServiceImpl extends BaseQueryService<ReportSubjectGroup>
        implements ReportSubjectGroupService {

    @Autowired
    private ReportSubjectGroupDao reportSubjectGroupDao;

    @Transactional
    @Override
    public void deleteByExamId(Integer examId) {
        reportSubjectGroupDao.deleteByExamId(examId);

    }

    @Override
    public List<ReportSubjectGroup> findByQuery(final ReportSubjectQuery query) {
        query.setSort(new Sort(Direction.ASC, "groupNumber"));
        Page<ReportSubjectGroup> result = reportSubjectGroupDao.findAll(new Specification<ReportSubjectGroup>() {

            @Override
            public Predicate toPredicate(Root<ReportSubjectGroup> root, CriteriaQuery<?> cQuery, CriteriaBuilder cb) {
                List<Predicate> predicates = new LinkedList<Predicate>();
                if (query.getExamId() != null) {
                    predicates.add(cb.equal(root.get("examId"), query.getExamId()));
                }
                if (StringUtils.isNotBlank(query.getSubjectCode())) {
                    predicates.add(cb.equal(root.get("subjectCode"), query.getSubjectCode()));
                }
                if (query.getGroupNumber() > 0) {
                    predicates.add(cb.equal(root.get("groupNumber"), query.getGroupNumber()));
                }
                return predicates.isEmpty() ? cb.conjunction()
                        : cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        }, query);
        return result.getContent();
    }

    @Override
    public ReportSubjectGroup save(ReportSubjectGroup r) {
        return reportSubjectGroupDao.save(r);
    }

}
