package cn.com.qmth.stmms.admin.exam;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 cn.com.qmth.stmms.biz.exam.model.ExamSubject;
import cn.com.qmth.stmms.biz.exam.model.MarkGroup;
import cn.com.qmth.stmms.biz.exam.service.ExamQuestionService;
import cn.com.qmth.stmms.biz.exam.service.MarkGroupService;
import cn.com.qmth.stmms.biz.exam.service.MarkerService;
import cn.com.qmth.stmms.biz.lock.LockService;
import cn.com.qmth.stmms.biz.mark.model.MarkLibrary;
import cn.com.qmth.stmms.biz.mark.query.MarkLibrarySearchQuery;
import cn.com.qmth.stmms.biz.mark.service.MarkLibraryService;
import cn.com.qmth.stmms.biz.mark.service.MarkService;
import cn.com.qmth.stmms.common.auth.annotation.RoleRequire;
import cn.com.qmth.stmms.common.domain.WebUser;
import cn.com.qmth.stmms.common.enums.LibraryStatus;
import cn.com.qmth.stmms.common.enums.LockType;
import cn.com.qmth.stmms.common.enums.MarkStatus;
import cn.com.qmth.stmms.common.enums.Role;
import cn.com.qmth.stmms.common.utils.RequestUtils;

@Controller("libraryController")
@RequestMapping("/admin/exam/library")
public class LibraryController extends BaseExamController {

    protected static Logger log = LoggerFactory.getLogger(LibraryController.class);

    @Autowired
    private MarkGroupService groupService;

    @Autowired
    private MarkLibraryService libraryService;

    @Autowired
    private MarkerService markerService;

    @Autowired
    private MarkService markService;

    @Autowired
    private LockService lockService;

    @Autowired
    private ExamQuestionService questionService;

    @RequestMapping
    public String list(Model model, HttpServletRequest request, MarkLibrarySearchQuery query,
            @RequestParam(required = false) LibraryStatus status) {
        int examId = getSessionExamId(request);
        WebUser wu = RequestUtils.getWebUser(request);
        List<ExamSubject> subjectList = getExamSubject(examId, wu);
        if (subjectList.isEmpty()) {
            return "redirect:/admin/exam/mark";
        }
        query.setExamId(examId);
        if (status != null) {
            query.addStatus(status);
        }
        if (query.getSubjectCode() == null && !subjectList.isEmpty()) {
            query.setSubjectCode(subjectList.get(0).getCode());
        }
        subjectFilter(query, wu);
        List<MarkGroup> groupList = groupService.findByExamAndSubjectAndStatus(examId, query.getSubjectCode(),
                MarkStatus.FORMAL);
        // if (groupList.isEmpty()) {
        // return "redirect:/admin/exam/mark";
        // }
        if (!groupList.isEmpty()) {
            if (query.getGroupNumber() == 0 && !groupList.isEmpty()) {
                query.setGroupNumber(groupList.get(0).getNumber());
            }
            query.orderById();
            query = libraryService.findByQuery(query);
            for (MarkLibrary library : query.getResult()) {
                if (library.getMarkerId() != null) {
                    library.setMarker(markerService.findById(library.getMarkerId()));
                }
            }
            for (MarkGroup group : groupList) {
                group.setQuestionList(questionService.findByExamAndSubjectAndObjectiveAndGroupNumber(examId,
                        group.getSubjectCode(), false, group.getNumber()));
            }
        }
        model.addAttribute("query", query);
        model.addAttribute("subjectList", getExamSubject(examId, wu));
        model.addAttribute("groupList", groupList);
        model.addAttribute("statusList", LibraryStatus.getOptionList());
        model.addAttribute("status", status);
        model.addAttribute("markerList",
                markerService.findByExamAndSubjectAndGroup(examId, query.getSubjectCode(), query.getGroupNumber()));
        return "modules/exam/libraryList";
    }

    @RequestMapping(value = "/back", method = RequestMethod.POST)
    @ResponseBody
    @RoleRequire({ Role.SCHOOL_ADMIN, Role.SUBJECT_HEADER })
    public JSONObject back(HttpServletRequest request, @RequestParam Integer id) {
        JSONObject obj = new JSONObject();
        MarkLibrary library = libraryService.findById(id);
        if (library != null) {
            if (subjectCheck(library.getSubjectCode(), RequestUtils.getWebUser(request))) {
                try {
                    lockService.watch(LockType.GROUP, library.getExamId(), library.getSubjectCode(),
                            library.getGroupNumber());
                    if (markService.backLibrary(library)) {
                        obj.accumulate("success", true);
                    } else {
                        obj.accumulate("success", false);
                        obj.accumulate("message", "无法打回该评卷任务");
                    }
                } catch (Exception e) {
                    obj.accumulate("success", false);
                    obj.accumulate("message", "打回评卷任务失败");
                    log.error("back library error", e);
                } finally {
                    lockService.unwatch(LockType.GROUP, library.getExamId(), library.getSubjectCode(),
                            library.getGroupNumber());
                }
            } else {
                obj.accumulate("success", false);
                obj.accumulate("message", "没有操作该评卷任务的权限");
            }
        } else {
            obj.accumulate("success", false);
            obj.accumulate("message", "该评卷任务不存在");
        }
        return obj;
    }

}
