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

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.qmth.stmms.biz.exam.model.MarkGroup;
import cn.com.qmth.stmms.biz.exam.model.Marker;
import cn.com.qmth.stmms.biz.exam.query.MarkerSearchQuery;
import cn.com.qmth.stmms.biz.exam.service.ExamQuestionService;
import cn.com.qmth.stmms.biz.exam.service.ExamSubjectService;
import cn.com.qmth.stmms.biz.exam.service.MarkGroupService;
import cn.com.qmth.stmms.biz.exam.service.MarkerService;
import cn.com.qmth.stmms.biz.mark.model.MarkLibrary;
import cn.com.qmth.stmms.biz.mark.model.RejectHistory;
import cn.com.qmth.stmms.biz.mark.query.MarkLibrarySearchQuery;
import cn.com.qmth.stmms.biz.mark.query.RejectHistorySearchQuery;
import cn.com.qmth.stmms.biz.mark.service.MarkLibraryService;
import cn.com.qmth.stmms.biz.mark.service.RejectHistoryService;
import cn.com.qmth.stmms.biz.user.model.User;
import cn.com.qmth.stmms.biz.user.service.UserService;
import cn.com.qmth.stmms.common.annotation.Logging;
import cn.com.qmth.stmms.common.domain.WebUser;
import cn.com.qmth.stmms.common.enums.LibraryStatus;
import cn.com.qmth.stmms.common.enums.LogType;
import cn.com.qmth.stmms.common.utils.RequestUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/admin/exam/reject")
public class RejectController extends BaseExamController {

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

    @Autowired
    private RejectHistoryService historyService;

    @Autowired
    private ExamQuestionService questionService;

    @Autowired
    private ExamSubjectService subjectService;

    @Autowired
    private MarkGroupService groupService;

    @Autowired
    private MarkerService markerService;

    @Autowired
    private UserService userService;

    @Autowired
    private MarkLibraryService libraryService;

    @Logging(menu = "打回任务查询", type = LogType.QUERY)
    @RequestMapping(value = "/list")
    public String list(Model model, HttpServletRequest request, MarkLibrarySearchQuery query) {
        int examId = getSessionExamId(request);
        WebUser wu = RequestUtils.getWebUser(request);
        query.setExamId(examId);
        query.addStatus(LibraryStatus.REJECTED);
        if (wu.isSubjectHeader() && StringUtils.isBlank(query.getSubjectCode())) {
            String subjectCodeIn = StringUtils.join(wu.getSubjectCodeSet(), ",");
            query.setSubjectCodeIn(subjectCodeIn);
        }
        query = libraryService.findByQuery(query);
        for (MarkLibrary library : query.getResult()) {
            if (library.getMarkerId() != null) {
                Marker marker = markerService.findById(library.getMarkerId());
                User user = userService.findById(marker.getUserId());
                library.setMarkerLoginName(user.getLoginName() + "/" + user.getName());
            }
            RejectHistory h = historyService.findLastByLibraryId(library.getId());
            if (h != null) {
                User header = userService.findById(h.getUserId());
                library.setHeaderLoginName(header.getLoginName() + "/" + header.getName());
            }
            library.setSubject(subjectService.find(examId, library.getSubjectCode()));
            MarkGroup group = groupService.findOne(examId, library.getSubjectCode(), library.getGroupNumber());
            group.setQuestionList(questionService.findByExamAndSubjectAndObjectiveAndGroupNumber(examId,
                    group.getSubjectCode(), false, group.getNumber()));
            library.setTitle(group.getTitle());
        }

        model.addAttribute("query", query);
        model.addAttribute("subjectList", getExamSubject(examId, wu));
        List<Marker> markerList = new ArrayList<Marker>();
        List<User> headerList = new ArrayList<User>();
        if (query.getSubjectCode() != null) {
            MarkerSearchQuery mQuery = new MarkerSearchQuery();
            mQuery.setExamId(examId);
            mQuery.setSubjectCode(query.getSubjectCode());
            mQuery.setPageSize(Integer.MAX_VALUE);
            markerList = markerService.findByQuery(mQuery).getResult();
            for (Marker marker : markerList) {
                marker.setLoginName(userService.findById(marker.getUserId()).getLoginName());
            }
            headerList = historyService.getUserIdByExamIdAndSubjectCode(examId, query.getSubjectCode());

            List<MarkGroup> groupList = groupService.findByExamAndSubject(examId, query.getSubjectCode());
            for (MarkGroup group : groupList) {
                group.setQuestionList(questionService.findByExamAndSubjectAndObjectiveAndGroupNumber(examId,
                        group.getSubjectCode(), false, group.getNumber()));
            }
            model.addAttribute("groupList", groupList);
        }

        model.addAttribute("markerList", markerList);
        model.addAttribute("headerList", headerList);
        return "modules/exam/rejectList";
    }

    @Logging(menu = "打回记录查询", type = LogType.QUERY)
    @RequestMapping(value = "/history")
    public String history(Model model, HttpServletRequest request, RejectHistorySearchQuery query) {
        int examId = getSessionExamId(request);
        WebUser wu = RequestUtils.getWebUser(request);
        query.setExamId(examId);
        if (wu.isSubjectHeader() && StringUtils.isBlank(query.getSubjectCode())) {
            String subjectCodeIn = StringUtils.join(wu.getSubjectCodeSet(), ",");
            query.setSubjectCodeIn(subjectCodeIn);
        }
        query = historyService.findByQuery(query);
        for (RejectHistory h : query.getResult()) {
            Marker marker = markerService.findById(h.getMarkerId());
            User user = userService.findById(marker.getUserId());
            h.setMarkerLoginName(user.getLoginName() + "/" + user.getName());
            User header = userService.findById(h.getUserId());
            h.setHeaderLoginName(header.getLoginName() + "/" + header.getName());
            h.setSubject(subjectService.find(examId, h.getSubjectCode()));
            MarkGroup group = groupService.findOne(examId, h.getSubjectCode(), h.getGroupNumber());
            group.setQuestionList(questionService.findByExamAndSubjectAndObjectiveAndGroupNumber(examId,
                    group.getSubjectCode(), false, group.getNumber()));
            h.setTitle(group.getTitle());
        }
        model.addAttribute("query", query);
        model.addAttribute("subjectList", getExamSubject(examId, wu));
        List<Marker> markerList = new ArrayList<Marker>();
        List<User> headerList = new ArrayList<User>();
        if (query.getSubjectCode() != null) {
            MarkerSearchQuery mQuery = new MarkerSearchQuery();
            mQuery.setExamId(examId);
            mQuery.setSubjectCode(query.getSubjectCode());
            mQuery.setPageSize(Integer.MAX_VALUE);
            markerList = markerService.findByQuery(mQuery).getResult();
            for (Marker marker : markerList) {
                marker.setLoginName(userService.findById(marker.getUserId()).getLoginName());
            }
            headerList = historyService.getUserIdByExamIdAndSubjectCode(examId, query.getSubjectCode());
            List<MarkGroup> groupList = groupService.findByExamAndSubject(examId, query.getSubjectCode());
            for (MarkGroup group : groupList) {
                group.setQuestionList(questionService.findByExamAndSubjectAndObjectiveAndGroupNumber(examId,
                        group.getSubjectCode(), false, group.getNumber()));
            }
            model.addAttribute("groupList", groupList);
        }
        model.addAttribute("markerList", markerList);
        model.addAttribute("headerList", headerList);
        return "modules/exam/rejectHistory";
    }

    @RequestMapping("/user/query")
    @ResponseBody
    public JSONArray query(HttpServletRequest request, @RequestParam String subjectCode) {
        int examId = getSessionExamId(request);
        JSONArray array = new JSONArray();
        List<User> headerList = historyService.getUserIdByExamIdAndSubjectCode(examId, subjectCode);
        for (User user : headerList) {
            JSONObject obj = new JSONObject();
            obj.accumulate("id", user.getId());
            obj.accumulate("loginName", user.getLoginName());
            obj.accumulate("name", user.getName());
            array.add(obj);
        }
        return array;
    }
    
}
