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

import cn.com.qmth.stmms.biz.common.BaseQueryService;
import cn.com.qmth.stmms.biz.report.dao.ReportSubjectRangeDao;
import cn.com.qmth.stmms.biz.report.model.ReportSubjectRange;
import cn.com.qmth.stmms.biz.report.query.ReportSubjectRangeQuery;
import cn.com.qmth.stmms.biz.report.service.ReportSubjectRangeService;
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 javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.LinkedList;
import java.util.List;

/**
 * 课程分段统计 service 实现
 *
 * @author xuwenjin
 * @Date 2019-04-19
 */
@Service
public class ReportSubjectRangeServiceImpl extends BaseQueryService<ReportSubjectRange>
        implements ReportSubjectRangeService {

    @Autowired
    private ReportSubjectRangeDao reportSubjectRangetDao;

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

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

    @Override
    public ReportSubjectRangeQuery findByQuery(final ReportSubjectRangeQuery query) {
        checkQuery(query);
        Page<ReportSubjectRange> result = reportSubjectRangetDao.findAll(new Specification<ReportSubjectRange>() {

            @Override
            public Predicate toPredicate(Root<ReportSubjectRange> 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()));
                }
                return predicates.isEmpty() ?
                        cb.conjunction() :
                        cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        }, query);
        fillResult(result, query);

        return query;
    }

    @Override
    public ReportSubjectRange save(ReportSubjectRange r) {
        return reportSubjectRangetDao.save(r);
    }

}
