package cn.com.qmth.stmms.subjectheader.random;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.com.qmth.stmms.biz.distributpaper.model.FormallyHistory;
import cn.com.qmth.stmms.biz.distributpaper.model.FormallyLibrary;
import cn.com.qmth.stmms.biz.distributpaper.model.TryHistory;
import cn.com.qmth.stmms.biz.distributpaper.model.TryLibrary;
import cn.com.qmth.stmms.biz.distributpaper.service.FormallyHistoryService;
import cn.com.qmth.stmms.biz.distributpaper.service.FormallyLibraryService;
import cn.com.qmth.stmms.biz.distributpaper.service.TryHistoryService;
import cn.com.qmth.stmms.biz.distributpaper.service.TryLibraryService;
import cn.com.qmth.stmms.biz.exam.model.Marker;
import cn.com.qmth.stmms.biz.exam.model.SubjectiveBlock;
import cn.com.qmth.stmms.biz.exam.service.ExamSubjectService;
import cn.com.qmth.stmms.biz.exam.service.MarkerService;
import cn.com.qmth.stmms.biz.exam.service.SubjectiveBlockService;
import cn.com.qmth.stmms.biz.mark.model.Task;
import cn.com.qmth.stmms.biz.subjectheader.model.RandomHistory;
import cn.com.qmth.stmms.biz.subjectheader.model.RandomLibrary;
import cn.com.qmth.stmms.biz.subjectheader.model.SubjectHeader;
import cn.com.qmth.stmms.biz.subjectheader.query.RandomLibrarySearchQuery;
import cn.com.qmth.stmms.biz.subjectheader.service.RandomHistoryService;
import cn.com.qmth.stmms.biz.subjectheader.service.RandomLibraryService;
import cn.com.qmth.stmms.biz.subjectheader.service.SubjectHeaderService;
import cn.com.qmth.stmms.common.controller.BaseController;
import cn.com.qmth.stmms.common.enums.LibraryStatus;
import cn.com.qmth.stmms.common.enums.LibraryType;
import cn.com.qmth.stmms.common.redis.RedisKeyBuilder;
import cn.com.qmth.stmms.common.session.model.StmmsSession;
import cn.com.qmth.stmms.common.utils.HessianUtils;
import cn.com.qmth.stmms.common.utils.RequestUtils;

@Controller
@RequestMapping("/subjectheader/random")
public class RandomController extends BaseController {

    @Autowired
    private SubjectiveBlockService subjectiveBlockService;

    @Autowired
    private RandomLibraryService randomLibraryService;

    @Autowired
    private RandomHistoryService randomHistoryService;

    @Autowired
    private SubjectHeaderService subjectHeaderService;

    @Autowired
    private FormallyLibraryService formallyLibraryService;

    @Autowired
    private FormallyHistoryService formallyHistoryService;

    @Autowired
    private TryHistoryService tryHistoryService;

    @Autowired
    private TryLibraryService tryLibraryService;

    @Autowired
    private MarkerService markerService;

    @Autowired
    private ExamSubjectService examSubjectService;

    @RequestMapping
    public ModelAndView index(HttpServletRequest request) {
        StmmsSession session = RequestUtils.getSession(request);
        Integer examId = Integer.parseInt(session.getParameter("examId"));
        String subjectCode = session.getParameter("subjectCode");

        List<SubjectiveBlock> bList = null;
        bList = subjectiveBlockService.findBlockByExamIdAndSubjectCode(examId, subjectCode);
        List<Marker> mList = markerService.findByExamAndSubject(examId, subjectCode);

        ModelAndView view = new ModelAndView("subjectheader/random/list");
        view.addObject("bList", bList);
        view.addObject("mList", mList);
        return view;
    }

    @RequestMapping("/list")
    @ResponseBody
    public Map<String, Object> pageList(HttpServletRequest request, @RequestParam Integer page,
            @RequestParam Integer rows, RandomLibrarySearchQuery query) {
        Integer examId = Integer.parseInt(RequestUtils.getSession(request).getParameter("examId"));
        String subjectCode = RequestUtils.getSession(request).getParameter("subjectCode");
        // 抽查
        randomLibraryService.randomCheck(examId, subjectCode, query);

        List<SubjectiveBlock> bList = null;
        bList = subjectiveBlockService.findBlockByExamIdAndSubjectCode(examId, subjectCode);
        List<RandomLibrary> list = new ArrayList<RandomLibrary>();
        int total = 0;
        for (SubjectiveBlock block : bList) {
            query.setPageNumber(page);
            query.setPageSize(rows);
            query.setStatus(0);
            query.setBlockId(block.getId());
            query = randomLibraryService.findByQuery(query);
            list.addAll(query.getResult());
            total += query.getTotalCount();
        }

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

    @RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
    public ModelAndView view(HttpServletRequest request, @PathVariable Integer id) {
        RandomLibrary randomLibrary = randomLibraryService.findById(id);
        SubjectHeader subjectHeader = RequestUtils.getWebUser(request).getSubjectHeader();
        ModelAndView view = new ModelAndView("subjectheader/random/view");
        view.addObject("randomLibrary", randomLibrary);
        view.addObject("subjectHeader", subjectHeader);
        view.addObject("startTime", new Date().getTime());
        return view;
    }

    @RequestMapping(value = "/mark", method = RequestMethod.POST)
    public ModelAndView mark(HttpServletRequest request, RandomHistory randomHistory) {
        SubjectHeader subjectHeader = RequestUtils.getWebUser(request).getSubjectHeader();
        randomHistory.setSubmitter(subjectHeader.getId());

        randomHistoryService.saveRandom(randomHistory);

        RandomLibrary randomLibrary = randomLibraryService.findById(randomHistory.getLibraryId());
        if (randomLibrary.getType().getValue() == 1) {
            // 试评
            List<TryLibrary> tryLibraryList = tryLibraryService.findByBlockIdAndSecretNo(randomLibrary.getBlockId(),
                    randomLibrary.getSecretNo());
            for (TryLibrary tryLibrary : tryLibraryList) {
                tryLibrary.setHeaderScore(randomHistory.getTotalScore());
                tryLibrary.setHeaderScoreList(randomHistory.getScoreList());
                tryLibrary.setStatus(LibraryStatus.MARKED);
                tryLibraryService.save(tryLibrary);
            }
        } else {
            // 正评
            List<FormallyLibrary> formallyLibraryList = formallyLibraryService.findByBlockIdAndSecretNo(
                    randomLibrary.getBlockId(), randomLibrary.getSecretNo());
            for (FormallyLibrary formallyLibrary : formallyLibraryList) {
                formallyLibrary.setHeaderScore(randomHistory.getTotalScore());
                formallyLibrary.setHeaderScoreList(randomHistory.getScoreList());
                formallyLibrary.setStatus(LibraryStatus.MARKED);
                formallyLibraryService.save(formallyLibrary);

                // BlockTaskCountUtil.addBlockMarkedTask(stringRedisTemplate,
                // formallyLibrary.getBlockId(),
                // formallyLibrary.getId());
            }
        }
        return new ModelAndView("redirect:/subjectheader/random");
    }

    @RequestMapping(value = "/remark", method = RequestMethod.POST)
    @Transactional
    public ModelAndView reMark(HttpServletRequest request, @RequestParam Integer historyId,
            @RequestParam Integer libraryId) {
        RandomLibrary randomLibrary = randomLibraryService.findById(libraryId);
        randomLibrary.setStatus(LibraryStatus.BACKED);
        randomLibraryService.save(randomLibrary);
        if (randomLibrary.getType().getValue() == LibraryType.TRY.getValue()) {
            TryHistory tryHistory = tryHistoryService.findById(historyId);
            TryLibrary tryLibrary = tryLibraryService.findById(tryHistory.getLibraryId());

            SubjectiveBlock block = subjectiveBlockService.findBlockById(tryLibrary.getBlockId(), true);
            tryLibrary.setStatus(LibraryStatus.QUEUED);
            tryLibraryService.save(tryLibrary);

            String key = RedisKeyBuilder.getBackTaskKey(LibraryType.TRY, tryHistory.getScorer());
            Task task = new Task();
            task.setBack(true);

            String value = HessianUtils.serialize(task);
            // stringRedisTemplate.opsForList().rightPush(key, value);

        } else {
            FormallyHistory formallyHistory = formallyHistoryService.findById(historyId);
            FormallyLibrary formallyLibrary = formallyLibraryService.findById(formallyHistory.getLibraryId());
            SubjectiveBlock block = subjectiveBlockService.findBlockById(formallyLibrary.getBlockId(), true);
            formallyLibrary.setStatus(LibraryStatus.QUEUED);
            formallyLibraryService.save(formallyLibrary);

            String key = RedisKeyBuilder.getBackTaskKey(LibraryType.FORMALLY, formallyHistory.getScorer());
            Task task = new Task();
            task.setBack(true);
            String value = HessianUtils.serialize(task);
            // stringRedisTemplate.opsForList().rightPush(key, value);
        }
        return new ModelAndView("redirect:/subjectheader/random");
    }
}
