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

import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
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.service.ProblemLibraryService;
import cn.com.qmth.stmms.biz.exam.model.ExamSubject;
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.subjectheader.service.ArbitrationLibraryService;
import cn.com.qmth.stmms.biz.subjectheader.service.SubjectHeaderService;
import cn.com.qmth.stmms.common.enums.ExamSubjectStatus;
import cn.com.qmth.stmms.common.enums.LibraryType;
import cn.com.qmth.stmms.common.enums.MarkStage;
import cn.com.qmth.stmms.common.redis.RedisKeyBuilder;
import cn.com.qmth.stmms.common.session.model.StmmsSession;
import cn.com.qmth.stmms.common.utils.RequestUtils;

@Controller
@RequestMapping("/subjectheader/ending")
public class EndingCheckController {

    @Autowired
    private MarkerService markerService;

    @Autowired
    private SubjectHeaderService subjectHeaderService;

    @Autowired
    private SubjectiveBlockService subjectiveBlockService;

    @Autowired
    private ArbitrationLibraryService arbitrationLibraryService;

    @Autowired
    private ProblemLibraryService problemLibraryService;

    @Autowired
    private ExamSubjectService examSubjectService;

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

        int arbitrationCount = arbitrationLibraryService.findUntreated(examId, subjectCode);
        int problemCount = problemLibraryService.findUntreated(examId, subjectCode);
        int toMarkCount = 0;
        // 查打回总数
        int backCount = 0;
        int currentCount = 0;
        List<Marker> markerList = markerService.findByExamAndSubject(examId, subjectCode);
        for (Marker marker : markerList) {
            // String backKey =
            // RedisKeyBuilder.getBackTaskKey(LibraryType.FORMALLY,
            // marker.getId());
            // long backSize = stringRedisTemplate.opsForList().size(backKey);
            // backCount += backSize;

        }
        ExamSubject subject = examSubjectService.find(examId, subjectCode);
        List<SubjectiveBlock> blockList = null;
        blockList = subjectiveBlockService.findBlockByExamIdAndSubjectCode(examId, subjectCode);

        for (SubjectiveBlock block : blockList) {
            // String key =
            // RedisKeyBuilder.getPublicTaskKey(LibraryType.FORMALLY,
            // block.getId());
            // long size = stringRedisTemplate.opsForList().size(key);
            // toMarkCount += size;
            // currentCount += stringRedisTemplate.opsForZSet().size(
            // RedisKeyBuilder.getCurrentTaskKey(LibraryType.FORMALLY,
            // block.getId()));
        }

        ModelAndView view = new ModelAndView("subjectheader/ending/index");
        view.addObject("arbitrationCount", arbitrationCount);
        view.addObject("problemCount", problemCount);
        view.addObject("backCount", backCount);
        view.addObject("toMarkCount", toMarkCount);
        view.addObject("currentCount", currentCount);
        view.addObject("markSubjectStatus", subject.getStatus().getValue());
        return view;
    }

    @RequestMapping("/getmarkerbacklist")
    @ResponseBody
    public JSONArray getMarkerBackList(HttpServletRequest request) {
        JSONArray list = new JSONArray();
        StmmsSession session = RequestUtils.getSession(request);
        int examId = Integer.parseInt(session.getParameter("examId"));
        String subjectCode = session.getParameter("subjectCode");

        List<Marker> markerList = markerService.findByExamAndSubject(examId, subjectCode);
        for (Marker marker : markerList) {
            // String backKey =
            // RedisKeyBuilder.getBackTaskKey(LibraryType.FORMALLY,
            // marker.getId());
            // long backSize = stringRedisTemplate.opsForList().size(backKey);
            // if (backSize > 0) {
            // JSONObject object = new JSONObject();
            // object.accumulate("id", marker.getId());
            // object.accumulate("name", marker.getLoginName());
            // object.accumulate("backCount", backSize);
            // list.add(object);
            // }
        }

        return list;
    }

    @RequestMapping("/getmarkers")
    @ResponseBody
    public List<Marker> getMarkers(HttpServletRequest request) {
        StmmsSession session = RequestUtils.getSession(request);
        int examId = Integer.parseInt(session.getParameter("examId"));
        String subjectCode = session.getParameter("subjectCode");

        List<Marker> markerList = markerService.findByExamAndSubject(examId, subjectCode);

        return markerList;
    }

    @RequestMapping("/assign")
    @ResponseBody
    @Transactional
    public void assign(HttpServletRequest request, @RequestParam Integer newMarkerId, @RequestParam Integer oldMarkerId) {
        String oldKey = RedisKeyBuilder.getBackTaskKey(LibraryType.FORMALLY, oldMarkerId);
        String newKey = RedisKeyBuilder.getBackTaskKey(LibraryType.FORMALLY, newMarkerId);
        // stringRedisTemplate.opsForList().rightPopAndLeftPush(oldKey, newKey);

    }

    @RequestMapping("/endedmark")
    @ResponseBody
    @Transactional
    public void endedMark(HttpServletRequest request) {
        StmmsSession session = RequestUtils.getSession(request);
        int examId = Integer.parseInt(session.getParameter("examId"));
        String subjectCode = session.getParameter("subjectCode");

        ExamSubject markSubject = examSubjectService.find(examId, subjectCode);
        markSubject.setStatus(ExamSubjectStatus.FINISH);
        examSubjectService.save(markSubject);
        // 清空本科目在redis中的key
        clearRedis(examId, subjectCode);
    }

    @RequestMapping("/getscansubjectstatus")
    @ResponseBody
    @Transactional
    public int getScanSubjectStatus(HttpServletRequest request) {
        StmmsSession session = RequestUtils.getSession(request);
        int examId = Integer.parseInt(session.getParameter("examId"));
        String subjectCode = session.getParameter("subjectCode");

        ExamSubject subject = examSubjectService.find(examId, subjectCode);
        // 清理redis
        // clearRedis(examId, subjectId, classType);

        if (subject != null) {
            return subject.getStatus().getValue();
        } else {
            return 0;
        }

    }

    @RequestMapping("/clear")
    @ResponseBody
    @Transactional
    public void clear(HttpServletRequest request) {
        StmmsSession session = RequestUtils.getSession(request);
        int examId = Integer.parseInt(session.getParameter("examId"));
        String subjectCode = session.getParameter("subjectCode");
        clearRedis(examId, subjectCode);
    }

    public void clearRedis(int examId, String subjectCode) {
        List<String> keyList = new LinkedList<String>();

        List<SubjectiveBlock> blockList = subjectiveBlockService.findBlockByExamIdAndSubjectCode(examId, subjectCode);
        for (SubjectiveBlock block : blockList) {
            keyList.add(RedisKeyBuilder.getPublicTaskKey(LibraryType.TRY, block.getId()));
            keyList.add(RedisKeyBuilder.getPublicTaskKey(LibraryType.FORMALLY, block.getId()));
            keyList.add(RedisKeyBuilder.getBlockTotalCountKey(block.getId()));
            keyList.add(RedisKeyBuilder.getBlockMarkedTaskKey(block.getId()));
        }

        List<Marker> markerList = markerService.findByExamAndSubject(examId, subjectCode);
        for (Marker marker : markerList) {
            keyList.add(RedisKeyBuilder.getStandardTaskKey(MarkStage.TEST, marker.getId()));
            keyList.add(RedisKeyBuilder.getStandardTaskKey(MarkStage.FORMAL, marker.getId()));
            keyList.add(RedisKeyBuilder.getBackTaskKey(LibraryType.TRY, marker.getId()));
            keyList.add(RedisKeyBuilder.getBackTaskKey(LibraryType.FORMALLY, marker.getId()));
            keyList.add(RedisKeyBuilder.getSelfTaskKey(LibraryType.TRY, marker.getId()));
            keyList.add(RedisKeyBuilder.getSelfTaskKey(LibraryType.FORMALLY, marker.getId()));
            keyList.add(RedisKeyBuilder.getMarkCountKey(MarkStage.EXAMPLE, marker.getId()));
            keyList.add(RedisKeyBuilder.getMarkCountKey(MarkStage.TEST, marker.getId()));
            keyList.add(RedisKeyBuilder.getMarkCountKey(MarkStage.FORMAL, marker.getId()));
        }
        if (keyList.size() > 0) {
            // stringRedisTemplate.delete(keyList);
        }
    }
}
