package com.qmth.qrzk.web.controller;

import com.qmth.qrzk.dao.repositories.PaperAnalysisRepo;
import com.qmth.qrzk.repository.service.query.PaperAnalysisParams;
import com.qmth.qrzk.repository.user.model.PaperAnalysis;
import com.qmth.qrzk.service.PaperAnalysisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("papers/analysis")
public class PaperAnalysisController {

    @Autowired
    private PaperAnalysisRepo paperAnalysisRepo;
    @Autowired
    private PaperAnalysisService paperAnalysisService;

    @RequestMapping("/page")
    @ResponseBody
    public Map<String, Object> page(@RequestBody final PaperAnalysisParams cp) {

        Specification<PaperAnalysis> specification = new Specification<PaperAnalysis>() {

            @Override
            public Predicate toPredicate(Root<PaperAnalysis> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder builder) {
                List<Predicate> predicates = new ArrayList();
                if (cp.getBatchId() != null) {
                    predicates.add(builder.equal(root.get("paperBatch").get("id"), cp.getBatchId()));
                }
                if (cp.getKeyword() != null && !cp.getKeyword().equals("")) {
                    predicates.add(builder.or(builder.like(root.<String>get("courseName"), "%" + cp.getKeyword() + "%"), builder.like(root.<String>get("courseCode"), "%" + cp.getKeyword() + "%")));
                }
                return builder.and(predicates.toArray(new Predicate[0]));
            }
        };
        PageRequest page = new PageRequest(cp.getPage() - 1, cp.getRows());
        Page<PaperAnalysis> pageInfo = paperAnalysisRepo.findAll(specification, page);

        Map<String, Object> result = new HashMap<String, Object>();
        result.put("rows", pageInfo.getContent());
        result.put("total", pageInfo.getTotalElements());
        return result;
    }

    @ResponseStatus(HttpStatus.OK)
    @RequestMapping(value = "/upload/{batchId}")
    public Map<String, Object> upload(@PathVariable Integer batchId, @RequestParam("file") MultipartFile file) {
//        System.out.println(String.format(file.getOriginalFilename()));
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            if (!file.isEmpty()) {
                paperAnalysisService.upload(file.getInputStream(), batchId);
                resultMap.put("flag", "success");
            } else {
                resultMap.put("flag", "failed");
                resultMap.put("msg", "上传的是空文件！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("flag", "failed");
            resultMap.put("msg", e.getMessage());
        }
        return resultMap;
    }

    @RequestMapping(value = "/list/{id}", method = RequestMethod.GET)
    @ResponseBody
    public List<PaperAnalysis> list(@PathVariable Integer id) {
        PaperAnalysis pa = paperAnalysisRepo.findOne(id);
        List<PaperAnalysis> list = paperAnalysisRepo.findByBatchIdAndCourseCode(pa.getPaperBatch().getId(), pa.getCourseCode());
        return list;
    }
}
