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

import cn.com.qmth.stmms.ms.core.domain.InspectRange;
import cn.com.qmth.stmms.ms.core.domain.InspectTask;
import cn.com.qmth.stmms.ms.core.domain.user.MarkUser;
import cn.com.qmth.stmms.ms.core.repository.*;
import cn.com.qmth.stmms.ms.core.vo.Subject;
import cn.com.qmth.stmms.ms.marking.service.InspectService;
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.util.*;
import java.util.stream.Collectors;

/**
 * Created by yuanpan on 2017/11/22.
 */
@RestController
@RequestMapping("/api/inspect-task")
public class InspectTaskController {

    @Autowired
    private InspectRangeRepo inspectRangeRepo;

    @Autowired
    private MarkUserRepo markUserRepo;

    @Autowired
    private InspectTaskRepo inspectTaskRepo;

    @Autowired
    private InspectService inspectService;

    @GetMapping
    public List<InspectTask> list(@RequestParam(value = "rangeId") Long rangeId, @RequestParam(value = "markerId", required = false) Long markerId, @RequestParam(value = "subject", required = false) String subject) {

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

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

            if (!StringUtils.isEmpty(rangeId)) {
                predicates.add(cb.equal(root.get("inspectRangeId"), rangeId));
            }

            if (!StringUtils.isEmpty(markerId)) {
                predicates.add(cb.equal(root.get("markerId"), markerId));
            }

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

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

    }


    @GetMapping(value = "/sort")
    public List<Map<String, Object>> sort(@RequestParam(value = "workId") Long workId, @RequestParam(value = "markerId") Long markerId) {

        InspectRange inspectRange = inspectRangeRepo.findByWorkIdAndActive(workId, true);

        if (inspectRange == null) {
            return new ArrayList<>();
        }
        MarkUser inspector = markUserRepo.findOne(markerId);

        List<InspectTask> inspectTasks = inspectTaskRepo.findByMarkerIdAndInspectRangeId(inspector.getId(), inspectRange.getId());

        Map<String, List<InspectTask>> group = inspectTasks.stream().collect(Collectors.groupingBy(task -> task.getPaper().getAreaCode()));

        List<Map<String, Object>> resultList = new LinkedList<>();
        group.forEach((k, v) -> {
            Map<String, Object> map = new HashMap<>();
            //将试卷按照分数大小从高到低排序
            v.sort((t1, t2) -> t2.getPaper().getScore().intValue() - t1.getPaper().getScore().intValue());
            map.put("area", k);
            map.put("tasks", v);
            resultList.add(map);
        });

        //按数量倒序排序
        resultList.sort((o1, o2) -> {
            List l1 = (List) o1.get("tasks");
            List l2 = (List) o2.get("tasks");

            return l2.size() - l1.size();
        });
        return resultList;
    }

    @PatchMapping(value = "{domain}")
    public void inspect(@PathVariable(value = "domain") InspectTask inspectTask, @RequestBody Integer score) {

        MarkUser inspector = markUserRepo.findOne(inspectTask.getMarkerId());
        String level = inspectService.getLevel(inspectTask.getWorkId(), score);
        inspectTask.setLevel(level);
        inspectTask.setScore(score);
        inspectTask.setMarkerName(inspector.getName());
        inspectTask.setUpdatedOn(new Date());

        inspectService.inspect(inspectTask);
    }
}
