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

import cn.com.qmth.stmms.ms.admin.assembler.WorkOverviewAssembler;
import cn.com.qmth.stmms.ms.admin.dto.WorkOverview;
import cn.com.qmth.stmms.ms.admin.service.WorkService;
import cn.com.qmth.stmms.ms.commons.utils.RandomUtil;
import cn.com.qmth.stmms.ms.core.domain.Level;
import cn.com.qmth.stmms.ms.core.domain.MarkStage;
import cn.com.qmth.stmms.ms.core.domain.MarkSubject;
import cn.com.qmth.stmms.ms.core.domain.Work;
import cn.com.qmth.stmms.ms.core.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 评卷工作api
 * Created by zhengmin on 2016/10/14.
 */
@RestController
@RequestMapping("api/admin/works")
public class WorkApi {

    @Autowired
    private WorkRepo workRepo;

    @Autowired
    private LevelRepo levelRepo;

    @Autowired
    private MarkUserRepo markUserRepo;

    @Autowired
    private ExamQuestionRepo questionRepo;

    @Autowired
    private WorkService workService;

    @Autowired
    private StudentRepo studentRepo;

    @Autowired
    private WorkOverviewAssembler workOverviewAssembler;

    @Autowired
    private MarkSubjectRepo markSubjectRepo;

    @Autowired
    private MarkTaskRepo markTaskRepo;

    @Autowired
    RandomUtil randomUtil;

    /**
     * 列表
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public List<Work> list(HttpServletRequest request) {
        String organizationId = request.getHeader("organizationId");
//        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return workRepo.findByOrganizationIdOrderByIdDesc(Long.valueOf(organizationId));
    }

    /**
     * 单个信息
     *
     * @param work
     * @return
     */
    @RequestMapping(value = "{work}", method = RequestMethod.GET)
    public Work getOne(@PathVariable Work work) {
        if (work.isActive()) {
            randomUtil.getRandom(work.getId(), false);
        }
        int count = markTaskRepo.countByWorkIdAndStageAndResultNotNull(work.getId(), MarkStage.LEVEL);
        work.setModifyOtherVal(count == 0);
        return work;
    }

    /**
     * 新增
     *
     * @param work
     */
    @RequestMapping(method = RequestMethod.POST)
    public void create(HttpServletRequest request, @RequestBody Work work) {
        String organizationId = request.getHeader("organizationId");
        work.setOrganizationId(Long.valueOf(organizationId));
        workService.save(work);
    }

    /**
     * 修改
     *
     * @param workId
     * @param work
     * @return
     */
    @RequestMapping(value = "{workId}", method = RequestMethod.PUT)
    public Work update(@PathVariable Long workId, @RequestBody Work work) {
        List<MarkSubject> subjects = markSubjectRepo.findAllByWorkId(workId);
//        long count = subjects.stream().filter(m->m.getStage().ordinal() != 0).count();
//        if(count > 0){
//            throw new RuntimeException("已有分档数据，不可更改");
//        }

        work.setCreatedOn(new Date());
        return workRepo.save(work);
    }

    /**
     * 激活为当前，采集和评卷用户登录影响
     *
     * @param workId
     */
    @RequestMapping(value = "{workId}", method = RequestMethod.PATCH)
    public void active(@PathVariable Long workId) {
        Work work = workRepo.findOne(workId);
//        List<Work> works = workRepo.findAll();
        List<Work> works = workRepo.findByOrganizationId(work.getOrganizationId());
        for (Work w : works) {
            w.setActive(false);
            if (w.getId().equals(workId)) {
                w.setActive(true);
            }
        }
        workRepo.save(works);
    }

    /**
     * 删除
     *
     * @param workId
     */
    @RequestMapping(value = "{workId}", method = RequestMethod.DELETE)
    public void remove(@PathVariable Long workId) {
        workService.delete(workId);
    }

    //////////////////////    levels

    /**
     * 档位设定列表
     *
     * @param workId
     * @return
     */
    @RequestMapping(value = "{workId}/levels", method = RequestMethod.GET)
    public List<Level> list(@PathVariable Long workId) {
        return levelRepo.findByWorkId(workId);
    }

    /**
     * 删除档位
     *
     * @param workId
     * @param levelId
     */
    @RequestMapping(value = "{workId}/levels/{levelId}", method = RequestMethod.DELETE)
    public void deleteLevel(@PathVariable Long workId, @PathVariable Long levelId) {
        levelRepo.delete(levelId);
    }
    //////////////////////   overview

    /**
     * 总览，各统计数据
     *
     * @param work
     * @return
     */
    @RequestMapping(value = "{work}/overview", method = RequestMethod.GET)
    public WorkOverview overview(@PathVariable Work work) {
        //生成随机数，已生成的工作，直接跳过
        if(randomUtil.getRandomMap().get(work.getId()) == null) {
            randomUtil.getRandom(work.getId(), false);
        }
        return workOverviewAssembler.toDTO(work);
    }

}
