package com.qmth.qrzk.web.controller;

import com.qmth.qrzk.batch.model.PaperStateView;
import com.qmth.qrzk.batch.service.BatchService;
import com.qmth.qrzk.dao.repositories.BatchRepo;
import com.qmth.qrzk.dao.repositories.PaperStateViewRepo;
import com.qmth.qrzk.dao.repositories.SupplyCourseRepo;
import com.qmth.qrzk.repository.common.enumeration.BatchType;
import com.qmth.qrzk.repository.service.query.PaperBatchParams;
import com.qmth.qrzk.repository.user.model.PaperBatch;
import com.qmth.qrzk.repository.user.model.User;
import com.qmth.qrzk.repository.user.service.SessionUser;
import com.qmth.qrzk.repository.user.service.impl.PaperBatchServiceImpl;
import com.qmth.qrzk.repository.utils.ServerConfig;
import com.qmth.qrzk.service.ConfidentialService;
import com.qmth.qrzk.supplypaper.model.SupplyCourse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 批次管理
 *
 * @author zhengmin
 */
@RestController
@RequestMapping("/batch")
public class BatchController {

    @Autowired
    private BatchRepo batchRepo;
    @Autowired
    private SessionUser sessionUser;
    @Autowired
    private BatchService batchSrv;
    @Autowired
    private PaperBatchServiceImpl paperBatchService;

    @Autowired
    private PaperStateViewRepo paperStateViewRepo;
    @Autowired
    private SupplyCourseRepo supplyCourseRepo;
    @Autowired
    private ConfidentialService confidentialService;

    @RequestMapping(value = "/{batchId}", method = RequestMethod.GET)
    public PaperBatch get(@PathVariable Integer batchId) {
        return batchRepo.findOne(batchId);
    }

    @RequestMapping("/queryBatch")
    @ResponseBody
    public Map<String, Object> queryBatch(@RequestBody PaperBatchParams params) {
        Map<String, Object> result = new HashMap<String, Object>();
        List<PaperBatch> list = paperBatchService.queryBatch(params);
        result.put("rows", list);
        result.put("total", params.getTotalNum());
        return result;
    }

    /**
     * 创建批次
     *
     * @param batch
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    public AjaxResponse create(@RequestBody PaperBatch batch) {
        User current = sessionUser.getSessionUser();
        batch.setCreatedBy(current.getId());
        batch.setCreatedTime(new Date());
        batch.setCode(String.valueOf(new Date().getTime()));
        batch.setType(batch.getBatchType().getValue());
        batchRepo.save(batch);
        if (batch.getBatchType().equals(BatchType.SUPPLY))
            confidentialService.copyConfidential(batch.getId());

        return new AjaxResponse(true);
    }

    @RequestMapping(value = "{batchId}", method = RequestMethod.DELETE)
    public AjaxResponse remove(@PathVariable int batchId) {
        List<PaperStateView> papers = paperStateViewRepo.findByBatchId(batchId);
        if (papers.size() > 0) {
            AjaxResponse result = new AjaxResponse(false);
            result.setMsg("批次下有关联的试卷，删除失败！");
            return result;
        } else {
            List<SupplyCourse> courses = supplyCourseRepo.findByBatchId(batchId, new Sort(new Order(Direction.ASC, "id")));
            if (courses.size() > 0) {
                AjaxResponse result = new AjaxResponse(false);
                result.setMsg("批次下有关联的供卷课程，删除失败！");
                return result;
            } else {
                batchSrv.removeBatch(batchId);
                return new AjaxResponse(true);
            }
        }
    }

    @RequestMapping("/export")
    public void exportBatchs(HttpServletRequest request, HttpServletResponse response
            , @RequestParam(value = "batchIds[]") Integer[] batchIds) {

        String realPath = ServerConfig.getInstance().getWorkInfo().getProperty("URL");
        String downLoadPath = realPath + "/download/";


    }

    @RequestMapping(value = "getLatest", method = RequestMethod.GET)
    public PaperBatch getLatest() {
        List<PaperBatch> batches = batchRepo.findLastest();
        if (batches.size() > 0) {
            return batches.get(0);
        } else {
            return null;
        }
    }

    @RequestMapping(method = RequestMethod.GET)
    public List<PaperBatch> query(@RequestParam(required = false) String sort) {
        List<PaperBatch> list = new ArrayList<PaperBatch>();
        if (null == sort) {
            list = batchRepo.findAll();
        } else {
            list = batchRepo.findAll(new Sort(Direction.DESC, sort));
        }
        return list;
    }
}
