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

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.com.qmth.stmms.admin.thread.MarkerResetThread;
import cn.com.qmth.stmms.biz.config.service.impl.SystemCache;
import cn.com.qmth.stmms.biz.exam.model.Exam;
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.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.ExamService;
import cn.com.qmth.stmms.biz.exam.service.ExamStudentService;
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.MarkerClassService;
import cn.com.qmth.stmms.biz.exam.service.MarkerService;
import cn.com.qmth.stmms.biz.lock.LockService;
import cn.com.qmth.stmms.biz.mark.service.MarkLibraryService;
import cn.com.qmth.stmms.biz.mark.service.MarkService;
import cn.com.qmth.stmms.biz.mark.service.TrialService;
import cn.com.qmth.stmms.biz.school.model.School;
import cn.com.qmth.stmms.biz.school.service.SchoolService;
import cn.com.qmth.stmms.biz.user.model.User;
import cn.com.qmth.stmms.biz.user.service.UserService;
import cn.com.qmth.stmms.biz.user.service.query.UserSearchQuery;
import cn.com.qmth.stmms.common.annotation.Logging;
import cn.com.qmth.stmms.common.annotation.RoleRequire;
import cn.com.qmth.stmms.common.domain.WebUser;
import cn.com.qmth.stmms.common.enums.LockType;
import cn.com.qmth.stmms.common.enums.LogType;
import cn.com.qmth.stmms.common.enums.MarkerExcelError;
import cn.com.qmth.stmms.common.enums.Role;
import cn.com.qmth.stmms.common.enums.UserSource;
import cn.com.qmth.stmms.common.utils.EncryptUtils;
import cn.com.qmth.stmms.common.utils.ExportExcel;
import cn.com.qmth.stmms.common.utils.ImportExcel;
import cn.com.qmth.stmms.common.utils.RequestUtils;

import com.google.common.collect.Lists;

@Controller("examMarkerController")
@RequestMapping("/admin/exam/marker")
public class MarkerController extends BaseExamController {

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

    public static final String USER_PASSWORD = "123456";

    @Autowired
    private UserService userService;

    @Autowired
    private ExamService examService;

    @Autowired
    private MarkerService markerService;

    @Autowired
    private ExamSubjectService subjectService;

    @Autowired
    private MarkGroupService groupService;

    @Autowired
    private MarkService markService;

    @Autowired
    private LockService lockService;

    @Autowired
    private MarkerClassService classService;

    @Autowired
    private ExamQuestionService questionService;

    @Autowired
    private MarkLibraryService libraryService;

    @Autowired
    private TrialService trialService;

    @Qualifier("task-executor")
    @Autowired
    private AsyncTaskExecutor taskExecutor;

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private SystemCache systemCache;

    @Value("${mark.group.delete}")
    private String markDeleteCode;

    @Logging(menu = "评卷员查询", type = LogType.QUERY)
    @RequestMapping
    public String list(Model model, HttpServletRequest request, MarkerSearchQuery query) {
        WebUser wu = RequestUtils.getWebUser(request);
        int examId = getSessionExamId(request);
        query.setExamId(examId);
        List<ExamSubject> subjectList = getExamSubject(examId, wu);
        if (StringUtils.isBlank(query.getSubjectCode()) && wu.getRole() != Role.SCHOOL_ADMIN) {
            List<String> subjectCodeIn = new ArrayList<String>();
            subjectList.forEach(e -> subjectCodeIn.add(e.getCode()));
            query.setSubjectCodeIn(StringUtils.join(subjectCodeIn, ","));
        }
        query.orderById();
        query = markerService.findByQuery(query);
        for (Marker marker : query.getResult()) {
            marker.setSubject(subjectService.find(marker.getExamId(), marker.getSubjectCode()));
            MarkGroup group = groupService.findOne(examId, marker.getSubjectCode(), marker.getGroupNumber());
            int percent = group.getLibraryCount() > 0
                    ? (int) (group.getMarkedCount() * 100.00 / group.getLibraryCount())
                    : 0;
            if (group.getMarkedCount() > 0 && percent == 0) {
                percent = 1;
            } else if (group.getLeftCount() > 0 && percent == 100) {
                percent = 99;
            }
            group.setQuestionList(questionService.findByExamAndSubjectAndObjectiveAndGroupNumber(examId,
                    marker.getSubjectCode(), false, group.getNumber()));
            group.setPercent(percent);
            marker.setGroup(group);
            marker.setMarkedCount(markService.markedCount(marker));
            marker.setCurrentCount(markService.applyCount(marker));
            marker.setUser(userService.findById(marker.getUserId()));
            marker.setReseting(lockService.isLocked(LockType.MARKER_RESET, marker.getId()));
            marker.setClassCount(classService.countByUserIdAndExamId(marker.getUserId(), examId));
        }
        model.addAttribute("query", query);
        model.addAttribute("subjectList", subjectList);
        Exam exam = examService.findById(examId);
        School school = schoolService.findById(exam.getSchoolId());
        model.addAttribute("deleteCheck", systemCache.isGroupDeleteWarn() ? true : school.isGroupDeleteCheck());
        return "modules/exam/markerList";
    }

    @RequestMapping("/query")
    @ResponseBody
    public JSONArray query(HttpServletRequest request, @RequestParam String subjectCode,
            @RequestParam(required = false) Integer groupNumber) {
        int examId = getSessionExamId(request);
        JSONArray array = new JSONArray();
        MarkerSearchQuery query = new MarkerSearchQuery();
        query.setExamId(examId);
        query.setSubjectCode(subjectCode);
        query.setGroupNumber(groupNumber);
        query.setPageSize(Integer.MAX_VALUE);
        List<Marker> list = markerService.findByQuery(query).getResult();
        for (Marker marker : list) {
            JSONObject obj = new JSONObject();
            obj.accumulate("id", marker.getId());
            User user = userService.findById(marker.getUserId());
            obj.accumulate("loginName", user.getLoginName());
            obj.accumulate("name", user.getName());
            array.add(obj);
        }
        return array;
    }

    @Logging(menu = "评卷员回收任务", type = LogType.UPDATE)
    @RequestMapping("/release")
    @ResponseBody
    @RoleRequire({ Role.SCHOOL_ADMIN, Role.SUBJECT_HEADER, Role.COLLEGE_ADMIN })
    public JSONObject release(@RequestParam Integer[] ids) {
        for (Integer id : ids) {
            Marker marker = markerService.findById(id);
            if (marker != null) {
                try {
                    lockService.waitlock(LockType.MARKER, marker.getId());
                    markService.releaseByMarker(marker);
                } catch (Exception e) {
                    log.error("release marker error", e);
                } finally {
                    lockService.unlock(LockType.MARKER, marker.getId());
                }
            }
        }
        JSONObject result = new JSONObject();
        result.accumulate("success", true);
        return result;
    }

    // @RequestMapping("/batch-create")
    // @RoleRequire(Role.SCHOOL_ADMIN)
    // public String createInit(Model model, HttpServletRequest request,
    // @RequestParam(required = false) String subjectCode,
    // @RequestParam(required = false) Integer groupNumber) {
    // int examId = getSessionExamId(request);
    // model.addAttribute("subjectList", getExamSubject(examId,
    // RequestUtils.getWebUser(request)));
    // if (subjectCode != null) {
    // model.addAttribute("subjectCode", subjectCode);
    // model.addAttribute("groupList", groupService.findByExamAndSubject(examId,
    // subjectCode));
    // if (groupNumber != null) {
    // model.addAttribute("groupNumber", groupNumber);
    // }
    // } else {
    // model.addAttribute("groupList", new ArrayList<MarkGroup>());
    // }
    // return "modules/exam/markerCreate";
    // }

    // @Logging(menu = "创建评卷员", type = LogType.ADD)
    // @RequestMapping(value = "/batch-create", method = RequestMethod.POST)
    // @RoleRequire(Role.SCHOOL_ADMIN)
    // public ModelAndView create(HttpServletRequest request, @RequestParam
    // String subjectCode,
    // @RequestParam Integer groupNumber, @RequestParam Integer count,
    // @RequestParam(required = false) String password) {
    // int examId = getSessionExamId(request);
    // ExamSubject subject = subjectService.find(examId, subjectCode);
    // ModelAndView view = new ModelAndView("redirect:/admin/exam/marker");
    // if (subject != null && count > 0) {
    // // markerService.batchCreate(subject, groupNumber, count, password);
    // }
    // view.addObject("subjectCode", subjectCode);
    // if (groupNumber > 0) {
    // view.addObject("groupNumber", groupNumber);
    // }
    // return view;
    // }

    @Logging(menu = "评卷员重置", type = LogType.UPDATE)
    @RequestMapping(value = "/reset", method = RequestMethod.POST)
    @ResponseBody
    @RoleRequire(Role.SCHOOL_ADMIN)
    public JSONObject resetMarker(HttpServletRequest request, @RequestParam Integer id,
            @RequestParam(required = false) String deleteCode) {
        Marker marker = markerService.findById(id);
        JSONObject obj = new JSONObject();
        int examId = getSessionExamId(request);
        if (marker != null) {
            Exam exam = examService.findById(examId);
            School school = schoolService.findById(exam.getSchoolId());
            boolean warn = systemCache.isGroupDeleteWarn() ? true : school.isGroupDeleteCheck();
            MarkGroup group = groupService.findOne(examId, marker.getSubjectCode(), marker.getGroupNumber());
            if (warn && group.getLibraryCount() != 0 && group.getLeftCount() == 0
                    && !markDeleteCode.equals(deleteCode)) {
                obj.accumulate("success", false);
                obj.accumulate("message", "授权码不正确");
                return obj;
            }
            if (lockService.trylock(LockType.MARKER_RESET, marker.getId())) {
                taskExecutor.submit(new MarkerResetThread(marker, markService, lockService));
                obj.accumulate("success", true);
            } else {
                obj.accumulate("success", false);
                obj.accumulate("message", "评卷员正在重置");
            }

            // try {
            // lockService.waitlock(LockType.EXAM_SUBJECT, marker.getExamId(),
            // marker.getSubjectCode());
            // lockService
            // .waitlock(LockType.GROUP, marker.getExamId(),
            // marker.getSubjectCode(), marker.getGroupNumber());
            // lockService.waitlock(LockType.MARKER, marker.getId());
            //
            // markService.resetMarker(marker);
            // obj.accumulate("success", true);
            // } catch (Exception e) {
            // log.error("reset marker error", e);
            // obj.accumulate("success", false);
            // obj.accumulate("message", "重置评卷员失败");
            // } finally {
            // lockService.unlock(LockType.MARKER, marker.getId());
            // lockService
            // .unlock(LockType.GROUP, marker.getExamId(),
            // marker.getSubjectCode(), marker.getGroupNumber());
            // lockService.unlock(LockType.EXAM_SUBJECT, marker.getExamId(),
            // marker.getSubjectCode());
            // }
        } else {
            obj.accumulate("success", false);
            obj.accumulate("message", "该评卷员不存在");
        }
        return obj;
    }

    @Logging(menu = "评卷员禁用/启用", type = LogType.UPDATE)
    @RequestMapping(value = "/toggle", method = RequestMethod.POST)
    @ResponseBody
    @RoleRequire({ Role.SCHOOL_ADMIN, Role.SUBJECT_HEADER, Role.COLLEGE_ADMIN })
    public JSONObject toggle(@RequestParam Integer[] ids, @RequestParam Boolean enable) {
        for (Integer id : ids) {
            Marker marker = markerService.findById(id);
            if (marker != null) {
                marker.setEnable(enable);
                markerService.save(marker);
            }
        }
        JSONObject obj = new JSONObject();
        obj.accumulate("success", true);
        return obj;
    }

    // @Logging(menu = "评卷员导出", type = LogType.EXPORT)
    // @RequestMapping(value = "/export", method = RequestMethod.POST)
    // public String exportFile(MarkerSearchQuery query, HttpServletRequest
    // request, HttpServletResponse response,
    // RedirectAttributes redirectAttributes) {
    // WebUser wu = RequestUtils.getWebUser(request);
    // int examId = getSessionExamId(request);
    // query.setExamId(examId);
    // try {
    // query.setPageNumber(1);
    // query.setPageSize(Integer.MAX_VALUE);
    // query.setExamId(examId);
    // query.orderById();
    // subjectFilter(query, wu);
    // String fileName = "评卷员账号.xlsx";
    // query = markerService.findByQuery(query);
    // for (Marker marker : query.getResult()) {
    // ExamSubject subject = subjectService.find(examId,
    // marker.getSubjectCode());
    // if (subject != null) {
    // marker.setSubjectName(subject.getCode() + "-" + subject.getName());
    // } else {
    // marker.setSubjectName("");
    // }
    // MarkGroup group = groupService.findOne(examId, marker.getSubjectCode(),
    // marker.getGroupNumber());
    // if (group != null) {
    // group.setQuestionList(questionService.findByExamAndSubjectAndObjectiveAndGroupNumber(examId,
    // group.getSubjectCode(), false, group.getNumber()));
    // marker.setGroupName(group.getNumber() + "-" + group.getTitle());
    // } else {
    // marker.setGroupName("");
    // }
    // }
    // new ExportExcel("评卷员数据",
    // Marker.class).setDataList(query.getResult()).write(response,
    // fileName).dispose();
    // return null;
    // } catch (Exception e) {
    // addMessage(redirectAttributes, "导出评卷员失败！" + e.getMessage());
    // }
    // return "redirect:/admin/exam/marker?repage";
    // }

    @Logging(menu = "评卷员重置密码", type = LogType.UPDATE)
    @RequestMapping(value = "/reSetPassword", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject reSetPassword(@RequestParam Integer[] ids, @RequestParam String password) {
        for (Integer id : ids) {
            Marker marker = markerService.findById(id);
            User user = userService.findById(marker.getUserId());
            if (user == null) {
                continue;
            }
            password = StringEscapeUtils.unescapeHtml(password);
            user.setPassword(EncryptUtils.md5(password));
            user.setRandomPassword(null);
            user = userService.save(user);
        }
        JSONObject obj = new JSONObject();
        obj.accumulate("success", true);
        return obj;
    }

    @Logging(menu = "评卷员设置任务数量", type = LogType.UPDATE)
    @RequestMapping(value = "/setTaskCount", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject setTaskCount(@RequestParam Integer[] ids, @RequestParam Integer taskCount) {
        for (Integer id : ids) {
            Marker marker = markerService.findById(id);
            if (marker != null) {
                marker.setTopCount(taskCount);
                marker = markerService.save(marker);
            }
        }
        JSONObject obj = new JSONObject();
        obj.accumulate("success", true);
        return obj;
    }

    @RequestMapping(value = "/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "评卷员数据导入模板.xlsx";
            List<Marker> list = Lists.newArrayList();
            list.add(new Marker());
            new ExportExcel("评卷员数据", Marker.class, 2).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + "/admin/exam/marker";
    }

    @Logging(menu = "评卷员导入", type = LogType.IMPORT_FILE)
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public String importFile(HttpServletRequest request, MultipartFile file, RedirectAttributes redirectAttributes,
            @RequestParam String subjectCode) {
        int examId = getSessionExamId(request);
        WebUser wu = RequestUtils.getWebUser(request);
        Integer schoolId = wu.getUser().getSchoolId();
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<Marker> list = ei.getDataList(Marker.class);

            Map<String, User> userMap = new HashMap<String, User>();
            Map<String, ExamSubject> subjectMap = new HashMap<String, ExamSubject>();
            Map<String, MarkGroup> groupMap = new HashMap<String, MarkGroup>();
            Map<String, Marker> markerMap = new HashMap<String, Marker>();
            for (Marker marker : list) {
                if (StringUtils.isBlank(marker.getLoginName())) {
                    failureMsg.append("<br/>评卷员 " + marker.getLoginName() + "," + marker.getSubjectCode()
                            + MarkerExcelError.NAMENULL.getName());
                    failureNum++;
                    continue;
                }
                ExamSubject examSubject = subjectMap.get(marker.getSubjectCode());
                if (examSubject == null) {
                    examSubject = subjectService.find(examId, marker.getSubjectCode());
                    if (examSubject == null) {
                        failureMsg.append("<br/>评卷员 " + marker.getLoginName() + "," + marker.getSubjectCode()
                                + MarkerExcelError.CODENULL.getName());
                        failureNum++;
                        continue;
                    }
                }
                MarkGroup markGroup = groupMap.get(marker.getSubjectCode() + "-" + marker.getGroupNumber());
                if (markGroup == null) {
                    markGroup = groupService.findOne(examId, marker.getSubjectCode(), marker.getGroupNumber());
                    if (markGroup == null) {
                        failureMsg.append("<br/>评卷员 " + marker.getLoginName() + "," + marker.getSubjectCode()
                                + MarkerExcelError.GROUPNULL.getName());
                        failureNum++;
                        continue;
                    }
                }
                User user = userMap.get(marker.getLoginName().trim());
                if (user == null) {
                    user = userService.findByLoginName(marker.getLoginName().trim());
                    if (user != null && !schoolId.equals(user.getSchoolId())) {
                        failureMsg.append("<br/>评卷员 " + marker.getLoginName() + "," + marker.getSubjectCode()
                                + MarkerExcelError.NAMEUSED.getName());
                        failureNum++;
                        continue;
                    }
                    if (user != null && !user.getRole().equals(Role.MARKER)) {
                        failureMsg.append("<br/>评卷员 " + marker.getLoginName() + "," + marker.getSubjectCode()
                                + MarkerExcelError.NAMENOTMARKER.getName());
                        failureNum++;
                        continue;
                    }
                    if (user == null) {
                        user = getUser(userMap, marker.getLoginName().trim(), schoolId);
                    }
                }
                subjectMap.put(examSubject.getCode(), examSubject);
                groupMap.put(markGroup.getSubjectCode() + "-" + markGroup.getNumber(), markGroup);
                marker = getMarker(markerMap, examId, examSubject.getCode(), markGroup.getNumber(), user.getId());
            }
            List<Marker> saveList = new ArrayList<Marker>();
            for (Marker m : markerMap.values()) {
                saveList.add(m);
            }
            successNum = markerService.batchSave(saveList);
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条记录！");
            }
            String message = "已成功导入 " + successNum + " 条评卷员 ";
            addMessage(redirectAttributes, message + failureMsg);
            RequestUtils.setLog(request, message);
        } catch (Exception e) {
            log.error("Batch import marker error!", e);
            if (StringUtils.isBlank(e.getMessage())) {
                addMessage(redirectAttributes, "导入评卷员失败！");
            } else {
                addMessage(redirectAttributes, "导入评卷员失败！失败信息:" + e.getMessage());
            }
        }
        return "redirect:" + "/admin/exam/marker?subjectCode=" + subjectCode;
    }

    private Marker getMarker(Map<String, Marker> markerMap, int examId, String subjectCode, Integer groupNumber,
            Integer userId) {
        String key = examId + "-" + subjectCode + "-" + groupNumber + "-" + userId;
        Marker marker = markerMap.get(key);
        if (marker == null) {
            marker = markerService.findByExamAndSubjectAndNumberAndUserId(examId, subjectCode, groupNumber, userId);
        }
        if (marker == null) {
            marker = new Marker();
            marker.setExamId(examId);
            marker.setSubjectCode(subjectCode);
            marker.setGroupNumber(groupNumber);
            marker.setUserId(userId);
            marker.setEnable(true);
        }
        markerMap.put(key, marker);
        return marker;
    }

    private User getUser(Map<String, User> saveMap, String loginName, Integer schoolId) {
        User user = saveMap.get(loginName);
        if (user == null) {
            user = new User();
            user.setLoginName(loginName);
            user.setName(loginName);
            user.setPassword(EncryptUtils.md5(USER_PASSWORD));
            user.setRole(Role.MARKER);
            user.setSource(UserSource.INTERNAL);
            user.setSchoolId(schoolId);
            user.setEnable(true);
            user.setCreatedTime(new Date());
            userService.save(user);
            saveMap.put(loginName, user);
        }
        return user;
    }

    @RequestMapping("/save")
    public String add(Model model, HttpServletRequest request, UserSearchQuery query,
            @RequestParam String subjectCode) {
        int examId = getSessionExamId(request);
        Exam exam = examService.findById(examId);
        query.setSchoolId(exam.getSchoolId());
        query.setRole(Role.MARKER);
        query = userService.findByQuery(query);
        model.addAttribute("query", query);
        model.addAttribute("subject", subjectService.find(examId, subjectCode));
        // model.addAttribute("group", groupService.findOne(examId, subjectCode,
        // groupNumber));
        return "modules/exam/markerSubject";
    }

    @Logging(menu = "评卷员绑定", type = LogType.ADD)
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String save(@RequestParam String subjectCode, @RequestParam Integer[] groupNumbers,
            @RequestParam Integer[] userIds, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        int examId = getSessionExamId(request);
        for (Integer groupNumber : groupNumbers) {
            MarkGroup group = groupService.findOne(examId, subjectCode, groupNumber);
            if (group != null) {
                markerService.save(group, userIds);
            } else {
                addMessage(redirectAttributes, "科目分组不存在");
                return "redirect:/admin/exam/marker?subjectCode=" + subjectCode;
            }
        }
        addMessage(redirectAttributes, "设置成功");
        return "redirect:/admin/exam/marker?subjectCode=" + subjectCode;
    }

    @RequestMapping("/delete")
    public String delete(@RequestParam Integer markerId, RedirectAttributes redirectAttributes) {
        Marker marker = markerService.findById(markerId);
        if (marker == null) {
            return "redirect:/admin/exam/marker";
        }
        long count = libraryService.countByMarker(markerId);
        long trialCount = trialService.countByMarkerId(markerId);
        String subjectCode = marker.getSubjectCode();
        Integer groupNumber = marker.getGroupNumber();
        if (count > 0 || trialCount > 0) {
            addMessage(redirectAttributes, "删除评卷员失败，该评卷员已开始评卷");
        } else {
            markerService.deleteById(markerId);
        }
        return "redirect:/admin/exam/marker?subjectCode=" + subjectCode + "&groupNumber=" + groupNumber;
    }

    @RequestMapping(value = "/class/{markerId}", method = RequestMethod.GET)
    public String classList(@PathVariable Integer markerId, Model model, RedirectAttributes redirectAttributes) {
        Marker marker = markerService.findById(markerId);
        if (marker != null) {
            marker.setUser(userService.findById(marker.getUserId()));
            model.addAttribute("marker", marker);
            Set<String> classes = classService.findClassNameByUserIdAndExamId(marker.getUserId(), marker.getExamId());
            model.addAttribute("classes", classes);
            return "modules/exam/markerClass";
        }
        addMessage(redirectAttributes, "评卷员不存在");
        return "redirect:/admin/exam/marker";
    }

    @Logging(menu = "评卷员机组绑定", type = LogType.UPDATE)
    @RequestMapping(value = "/class/{markerId}", method = RequestMethod.POST)
    public String classSave(@PathVariable Integer markerId, @RequestParam(required = false) String[] classes,
            Model model, RedirectAttributes redirectAttributes) {
        Marker marker = markerService.findById(markerId);
        if (marker != null) {
            classService.save(marker.getUserId(), marker.getExamId(), classes);
            addMessage(redirectAttributes, "保存成功");
            return "redirect:" + "/admin/exam/marker?subjectCode=" + marker.getSubjectCode() + "&groupNumber="
                    + marker.getGroupNumber();
        }
        addMessage(redirectAttributes, "评卷员不存在");
        return "redirect:/admin/exam/marker";
    }

    @Logging(menu = "评卷员机组清空", type = LogType.DELETE)
    @RequestMapping(value = "/class/delete", method = RequestMethod.GET)
    public String classDelete(@RequestParam Integer markerId, Model model, RedirectAttributes redirectAttributes) {
        Marker marker = markerService.findById(markerId);
        if (marker != null) {
            classService.deleteByUserIdAndExamId(marker.getUserId(), marker.getExamId());
            addMessage(redirectAttributes, "清空成功");
            return "redirect:" + "/admin/exam/marker?subjectCode=" + marker.getSubjectCode() + "&groupNumber="
                    + marker.getGroupNumber();
        }
        addMessage(redirectAttributes, "评卷员不存在");
        return "redirect:/admin/exam/marker";
    }

    // @RequestMapping(value = "/account/{markerId}")
    // public String editAccount(HttpServletRequest request, Model model,
    // RedirectAttributes redirectAttributes,
    // @PathVariable Integer markerId) {
    // Exam exam = examService.findById(getSessionExamId(request));
    // Marker marker = markerService.findById(markerId);
    // if (exam != null && marker != null &&
    // exam.getId().equals(marker.getExamId())) {
    // model.addAttribute("marker", marker);
    // model.addAttribute("openAccountList",
    // userService.listUnbindOpenAccount(exam.getSchoolId(),
    // marker.getExamId(), marker.getSubjectCode(), marker.getGroupNumber()));
    // return "modules/exam/markerAccount";
    // }
    // addMessage(redirectAttributes, "评卷员不存在");
    // return "redirect:/admin/exam/marker";
    // }

    // @RequestMapping(value = "/account/bind", method = RequestMethod.POST)
    // @ResponseBody
    // @RoleRequire({ Role.SCHOOL_ADMIN, Role.SUBJECT_HEADER })
    // public boolean bindAccount(@RequestParam Integer markerId, @RequestParam
    // Integer accountId) {
    // Marker marker = markerService.findById(markerId);
    // if (marker == null) {
    // return false;
    // }
    // OpenAccount oa = userService.findOpenAccount(accountId);
    // if (oa == null || !oa.isEnable()) {
    // return false;
    // }
    // if
    // (markerService.countByExamAndSubjectAndGroupAndOpenAccount(marker.getExamId(),
    // marker.getSubjectCode(),
    // marker.getGroupNumber(), accountId) == 0) {
    // markerService.updateOpenAccountById(markerId, accountId);
    // return true;
    // }
    // return false;
    // }

    // @RequestMapping(value = "/account/unbind", method = RequestMethod.POST)
    // @ResponseBody
    // @RoleRequire({ Role.SCHOOL_ADMIN, Role.SUBJECT_HEADER })
    // public boolean unbindOpenAccount(@RequestParam Integer markerId) {
    // markerService.updateOpenAccountById(markerId, null);
    // return true;
    // }
}
