package cn.com.qmth.stmms.ms.marking.api;

import cn.com.qmth.stmms.ms.core.domain.Paper;
import cn.com.qmth.stmms.ms.core.repository.*;
import cn.com.qmth.stmms.ms.core.vo.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.math.BigInteger;
import java.util.*;

/**
 * Created by yuanpan on 2017/11/6.
 */
@RestController
@RequestMapping("api/inspect-progress")
public class InspectProgressApi {

    @Autowired
    private InspectTaskRepo inspectTaskRepo;

    @Autowired
    private PaperRepo paperRepo;


    @GetMapping("/papers")
    List<Paper> papers(@RequestParam(value = "rangeId") final Long rangeId, @RequestParam(value = "subject", required = false) final String subject) {

        List<BigInteger> paperIds = inspectTaskRepo.findPaperIdsByInspectRangeId(rangeId);

        return paperRepo.findAll((root, query, cb) -> {

            List<Predicate> predicateList = new ArrayList<>();

//            CriteriaBuilder.In<BigInteger> in = cb.in(root.get("id"));
//            for (BigInteger pId : paperIds) {
//                in.value(pId);
//            }
//            predicateList.add(in);

            predicateList.add(root.get("id").in(paperIds));
            if (!StringUtils.isEmpty(subject)) {
                predicateList.add(cb.equal(root.get("subject"), Subject.valueOf(subject)));
            }

            Predicate[] predicates = new Predicate[predicateList.size()];
            return query.where(predicateList.toArray(predicates)).getRestriction();
        });


    }

}
