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

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.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
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.FormallyLibrary;
import cn.com.qmth.stmms.biz.distributpaper.model.ProblemHistory;
import cn.com.qmth.stmms.biz.distributpaper.model.ProblemLibrary;
import cn.com.qmth.stmms.biz.distributpaper.model.TryLibrary;
import cn.com.qmth.stmms.biz.distributpaper.service.FormallyLibraryService;
import cn.com.qmth.stmms.biz.distributpaper.service.ProblemLibraryService;
import cn.com.qmth.stmms.biz.distributpaper.service.TryLibraryService;
import cn.com.qmth.stmms.biz.exam.model.Exam;
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.ExamService;
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.SubjectHeader;
import cn.com.qmth.stmms.biz.subjectheader.query.ProblemLibrarySearchQuery;
import cn.com.qmth.stmms.biz.subjectheader.service.SubjectHeaderService;
import cn.com.qmth.stmms.biz.utils.BlockTaskCountUtil;
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.enums.ProblemType;
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/problem")
public class ProblemController extends BaseController {

    @Autowired
    private SubjectiveBlockService subjectiveBlockService;

    @Autowired
    private ProblemLibraryService problemLibraryService;

    @Autowired
    private MarkerService markerService;

    @Autowired
    private SubjectHeaderService subjectHeaderService;

    @Autowired
    private FormallyLibraryService formallyLibraryService;

    @Autowired
    private TryLibraryService tryLibraryService;

    @Autowired
    private ExamSubjectService examSubjectService;

    @Autowired
    private ExamService examService;

    @Value("${slice.image.server}")
    private String imageServer;

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

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

        ModelAndView view = new ModelAndView("subjectheader/problem/list");
        view.addObject("reason", ProblemType.values());
        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, ProblemLibrarySearchQuery query) {
        SubjectHeader subjectHeader = RequestUtils.getWebUser(request).getSubjectHeader();
        query.setExamId(subjectHeader.getExamId());
        query.setSubjectCode(subjectHeader.getSubjectCode());
        query.setPageNumber(page);
        query.setPageSize(rows);
        query = problemLibraryService.findByQuery(query);

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

    @RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
    public ModelAndView view(HttpServletRequest request, @PathVariable Integer id) {
        ProblemLibrary problemLibrary = problemLibraryService.findById(id);
        SubjectiveBlock subjectiveBlock = subjectiveBlockService.findBlockById(problemLibrary.getBlockId(), true);
        Exam exam = examService.findById(problemLibrary.getExamId());
        SubjectHeader subjectHeader = RequestUtils.getWebUser(request).getSubjectHeader();
        ModelAndView view = new ModelAndView("subjectheader/problem/view");
        StmmsSession session = RequestUtils.getSession(request);
        session.setParameter("imageServer", imageServer);
        view.addObject("imageServer", imageServer);

        view.addObject("problemLibrary", problemLibrary);
        view.addObject("subjectiveBlock", subjectiveBlock);
        view.addObject("subjectHeader", subjectHeader);
        view.addObject("startTime", new Date().getTime());
        return view;
    }

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

        problemLibraryService.saveMark(problemHistory);

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

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

    @RequestMapping(value = "/remark", method = RequestMethod.POST)
    @Transactional
    public ModelAndView reMark(HttpServletRequest request, @RequestParam Integer libraryId) {
        ProblemLibrary problemLibrary = problemLibraryService.findById(libraryId);
        problemLibrary.setStatus(LibraryStatus.BACKED);
        problemLibraryService.save(problemLibrary);
        if (problemLibrary.getType().getValue() == LibraryType.TRY.getValue()) {
            TryLibrary tryLibrary = tryLibraryService.findById(problemLibrary.getLibraryId());

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

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

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

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

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

}
