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

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

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

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.Value;
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 org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;

import cn.com.qmth.stmms.admin.dto.SubjectViewerDTO;
import cn.com.qmth.stmms.admin.vo.MarkerVO;
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.Marker;
import cn.com.qmth.stmms.biz.exam.model.MarkerDTO;
import cn.com.qmth.stmms.biz.exam.query.MarkerSearchQuery;
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.mark.query.MarkLibrarySearchQuery;
import cn.com.qmth.stmms.biz.mark.service.MarkLibraryService;
import cn.com.qmth.stmms.biz.mark.service.TaskService;
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.enums.ExamSubjectStatus;
import cn.com.qmth.stmms.common.enums.LibraryStatus;
import cn.com.qmth.stmms.common.enums.MarkerExcelError;
import cn.com.qmth.stmms.common.enums.Role;
import cn.com.qmth.stmms.common.enums.UserType;
import cn.com.qmth.stmms.common.utils.DateUtils;
import cn.com.qmth.stmms.common.utils.ExportExcel;
import cn.com.qmth.stmms.common.utils.ImportExcel;
import cn.com.qmth.stmms.common.utils.Md5EncryptUtils;
import cn.com.qmth.stmms.common.utils.RequestUtils;
import net.sf.json.JSONObject;

@Controller("examMarkerController")
@RequestMapping("/admin/exam-param/marker")
public class ExamMarkerController extends BaseParameterController {

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

    public static final String USER_PASSWORD = "123456";

    @Autowired
    private MarkerService markerService;

    @Autowired
    private ExamSubjectService subjectService;

    @Autowired
    private MarkLibraryService libraryService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private UserService userService;

    @Autowired
    private ExamService examService;

    @Value("${marker.showBtnImportAndBtnUpdateImport}")
    private String showBtnImport;

    @RequestMapping
    public String list(Model model, HttpServletRequest request, MarkerSearchQuery query) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            query.setExamId(examId);
            query.orderById();
            query = markerService.findByQuery(query);
            if (query.getCurrentCount() > 0) {
                for (Marker marker : query.getResult()) {
                    if (!marker.isCommon()) {
                        marker.setSubject(subjectService.find(marker.getExamId(), marker.getSubjectCode()));
                    }
                }
            }
            model.addAttribute("query", query);
            model.addAttribute("showBtnImport", showBtnImport);
            model.addAttribute("subjectList", getMarkExamSubject(examId));
            return "modules/exam/param/markerList";
        } else {
            return "redirect:/admin/exam/list";
        }
    }

    @RequestMapping("/progress")
    public String progress(Model model, HttpServletRequest request, MarkerSearchQuery query) {
        int examId = getSessionExamId(request);
        String subjectCode = RequestUtils.getSession(request).getParameter("subjectCode");
        if (examId > 0) {
            List<ExamSubject> subjectList = subjectService.list(examId, ExamSubjectStatus.MARKING);
            ExamSubject subject = null;
            if (subjectCode != null) {// 科组长
                subject = subjectService.find(examId, subjectCode);
            } else if (query.getSubjectCode() != null) {
                subject = subjectService.find(examId, query.getSubjectCode());
            } else if (subjectList.size() > 0) {
                subject = subjectList.get(0);
                query.setSubjectCode(subject.getCode());
            }
            List<Marker> markers = markerService.findByExamAndSubject(examId, subject.getCode());
            List<Marker> commonMarkers = markerService.findExamAndCommon(examId, true);
            List<MarkerVO> markerVOs = new ArrayList<MarkerVO>();
            Set<Integer> set = new HashSet<>();
            for (Marker marker : commonMarkers) {
                set.add(marker.getId());
            }
            for (Marker marker : markers) {
                set.add(marker.getId());
            }
            for (Integer id : set) {
                Marker marker = markerService.findById(id);
                marker.setSubject(subject);
                MarkLibrarySearchQuery query2 = new MarkLibrarySearchQuery();
                query2.setExamId(examId);
                query2.setSubjectCode(
                        query.getSubjectCode() != null ? query.getSubjectCode() : marker.getSubjectCode());
                query2.setMarkerId(marker.getId());
                query2.setStatus(LibraryStatus.MARKED);
                marker.setMarkedCount(libraryService.countByQuery(query2));
                marker.setCurrentCount(taskService.countCurrent(marker));
                MarkerVO markerVO = new MarkerVO(marker);
                markerVO = getMarkerInfo(markerVO, query2.getSubjectCode());
                markerVOs.add(markerVO);
            }
            model.addAttribute("markerVOs", markerVOs);
            model.addAttribute("query", query);
            model.addAttribute("subjectList", subjectList);
            return "modules/exam/param/markerProgress";
        } else {
            return "redirect:/admin/exam/list";
        }
    }

    private MarkerVO getMarkerInfo(MarkerVO marker, String subjectCode) {
        List<Object[]> list = libraryService.getMarkerInfo(marker.getId(), subjectCode);
        double maxScore = (Double) list.get(0)[0] == null ? 0 : (Double) list.get(0)[0];
        marker.setMaxScore(maxScore);
        double minScore = (Double) list.get(0)[1] == null ? 0 : (Double) list.get(0)[1];
        marker.setMinScore(minScore);
        double avgScore = (Double) list.get(0)[2] == null ? 0 : (Double) list.get(0)[2];
        if (avgScore >= 0) {
            marker.setAvgScore(new BigDecimal(avgScore).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        }
        long maxSpeed = (Long) list.get(0)[3] == null ? 0 : (Long) list.get(0)[3];
        marker.setMaxSpeed(maxSpeed);
        long minSpeed = (Long) list.get(0)[4] == null ? 0 : (Long) list.get(0)[4];
        marker.setMinSpeed(minSpeed);
        double avgSpeed = (Double) list.get(0)[5] == null ? 0 : (Double) list.get(0)[5];
        if (avgSpeed >= 0) {
            marker.setAvgSpeed(new BigDecimal(avgSpeed).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        } else {
            marker.setAvgSpeed(0d);
        }
        List<Double> scores = libraryService.getAllScore(marker.getId(), subjectCode);
        Double sum = 0D;
        for (Double score : scores) {
            if (score != null) {
                sum = sum + Math.pow(score - marker.getAvgScore(), 2);
            }
        }
        // Double sum = scores.stream().mapToDouble(s ->
        // Math.pow((s-marker.getAvgScore()),2)).sum();
        Double stdDev = Math.sqrt(sum / scores.size());
        if (stdDev >= 0) {
            marker.setStdDev(new BigDecimal(stdDev).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        } else {
            marker.setStdDev(0D);
        }
        return marker;
    }

    @RequestMapping("/release")
    public ModelAndView release(@RequestParam Integer markerId) {
        ModelAndView view = new ModelAndView("redirect:/admin/exam-param/marker/progress");
        Marker marker = markerService.findById(markerId);
        if (marker != null) {
            taskService.clearCurrent(marker);
            view.addObject("subjectCode", marker.getSubjectCode());
        }
        return view;
    }

    @RequestMapping("/batch-create")
    public String createInit(Model model, HttpServletRequest request) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            model.addAttribute("subjectList", getMarkExamSubject(examId));
            return "modules/exam/param/markerCreate";
        } else {
            return "redirect:/admin/exam/list";
        }
    }

    @RequestMapping(value = "/batch-create", method = RequestMethod.POST)
    public ModelAndView create(HttpServletRequest request, @RequestParam String subjectCode,
            @RequestParam Integer count, @RequestParam(required = false) String password,
            @RequestParam Boolean common) {
        int examId = getSessionExamId(request);
        ModelAndView view = new ModelAndView("redirect:/admin/exam-param/marker");
        if (examId > 0 && count > 0) {
            if (common.booleanValue()) {
                markerService.batchCreateCommon(examId, count, password);
            } else if (!"all".equals(subjectCode)) {
                markerService.batchCreate(subjectService.find(examId, subjectCode), count, password);
            } else {
                List<ExamSubject> subjectList = getMarkExamSubject(examId);
                for (ExamSubject subject : subjectList) {
                    markerService.batchCreate(subject, count, password);
                }
            }
        }
        return view;
    }

    @RequestMapping(value = "/delete")
    public String delete(@RequestParam Integer id) {
        Marker marker = markerService.findById(id);
        if (marker != null) {
            if (!marker.isCommon() && isMarking(marker.getExamId(), marker.getSubjectCode())) {
            } else {
                libraryService.resetByMarker(marker);
                markerService.deleteById(id);
            }
        }
        return "redirect:/admin/exam-param/marker?repage";
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject deleteMarker(@RequestParam Integer id) {
        Marker marker = markerService.findById(id);
        JSONObject obj = new JSONObject();
        if (marker != null) {
            if (!marker.isCommon() && isMarking(marker.getExamId(), marker.getSubjectCode())) {
                obj.accumulate("success", false);
                obj.accumulate("message", "评卷已开始，不能进行修改");
            } else {
                libraryService.resetByMarker(marker);
                markerService.deleteById(id);
                obj.accumulate("success", true);
            }
        } else {
            obj.accumulate("success", false);
            obj.accumulate("message", "该评卷员不存在");
        }
        return obj;
    }

    @RequestMapping(value = "/toggle", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject toggle(@RequestParam Integer id, @RequestParam Boolean enable) {
        Marker marker = markerService.findById(id);
        JSONObject obj = new JSONObject();
        if (marker != null) {
            marker.setEnable(enable);
            markerService.save(marker);
            obj.accumulate("success", true);
        } else {
            obj.accumulate("success", false);
            obj.accumulate("message", "该评卷员不存在");
        }
        return obj;
    }

    @RequestMapping(value = "/clear", method = RequestMethod.POST)
    public String clear(HttpServletRequest request, HttpServletResponse response,
            RedirectAttributes redirectAttributes) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            markerService.deleteByExam(examId);
        }
        return "redirect:/admin/exam-param/marker?repage";
    }

    @RequestMapping(value = "/export", method = RequestMethod.POST)
    public String exportFile(MarkerSearchQuery query, HttpServletRequest request, HttpServletResponse response,
            RedirectAttributes redirectAttributes) {
        int examId = getSessionExamId(request);
        query.setExamId(examId);
        try {
            query.setPageNumber(1);
            query.setPageSize(Integer.MAX_VALUE);
            query.setExamId(examId);
            query.orderById();
            String fileName = "评卷员数据" + DateUtils.getDate("yyyyMMdd") + ".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(marker.getSubjectCode());
                }
            }
            new ExportExcel("评卷员数据", Marker.class).setDataList(query.getResult()).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导出评卷员失败！" + e.getMessage());
        }
        return "redirect:/admin/exam-param/marker?repage";
    }

    @RequestMapping(value = "/subjectViewer", method = RequestMethod.GET)
    public String subjectViewer(Model model, HttpServletRequest request, UserSearchQuery query) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            Exam exam = examService.findById(examId);
            String subjectCode = query.getLoginName();
            query.setSchoolId(exam.getSchoolId());
            query.setType(UserType.VIEWER);
            query.addIncludeRole(Role.SUBJECT_VIEWER);
            if (subjectCode != null) {
                query.setLoginName(examId + "-" + subjectCode);
            } else {
                query.setLoginName(examId + "-");
            }
            query = userService.searchByQuery(query);
            List<Marker> markers = new ArrayList<Marker>();
            if (query.getCurrentCount() > 0) {
                for (User u : query.getResult()) {
                    Marker marker = new Marker();
                    marker.setId(u.getId());
                    marker.setExamId(examId);
                    marker.setLoginName(u.getLoginName());
                    marker.setName(u.getName());
                    String code = u.getLoginName().split("-")[1];
                    ExamSubject subject = subjectService.find(examId, code);
                    if (subject != null) {
                        marker.setSubject(subject);
                        marker.setSubjectCode(subject.getCode());
                        marker.setSubjectName(subject.getName());
                        markers.add(marker);
                    }
                }
            }
            model.addAttribute("markers", markers);
            query.setLoginName(subjectCode);
            ;
            model.addAttribute("query", query);
            model.addAttribute("subjectList", getMarkExamSubject(examId));
            return "modules/exam/param/subjectViewerList";
        } else {
            return "redirect:/admin/exam/list";
        }
    }

    @RequestMapping(value = "/exportSubjectViewer", method = RequestMethod.GET)
    public String exportSubjectViewer(UserSearchQuery query, HttpServletRequest request, HttpServletResponse response,
            RedirectAttributes redirectAttributes) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            try {
                Exam exam = examService.findById(examId);
                String subjectCode = query.getLoginName();
                query.setSchoolId(exam.getSchoolId());
                query.setType(UserType.VIEWER);
                query.addIncludeRole(Role.SUBJECT_VIEWER);
                if (subjectCode != null) {
                    query.setLoginName(examId + "-" + subjectCode);
                } else {
                    query.setLoginName(examId + "-");
                }
                query = userService.searchByQuery(query);
                List<SubjectViewerDTO> list = new ArrayList<SubjectViewerDTO>();
                if (query.getCurrentCount() > 0) {
                    for (User u : query.getResult()) {
                        String code = u.getLoginName().split("-")[1];
                        ExamSubject subject = subjectService.find(examId, code);
                        if (subject != null) {
                            SubjectViewerDTO dto = new SubjectViewerDTO(u, subject);
                            list.add(dto);
                        }
                    }
                }
                String fileName = "科组长数据" + DateUtils.getDate("yyyyMMdd") + ".xlsx";
                new ExportExcel("科组长数据", SubjectViewerDTO.class).setDataList(list).write(response, fileName).dispose();
                return null;
            } catch (Exception e) {
                addMessage(redirectAttributes, "导出科组长失败！" + e.getMessage());
            }
        }
        return "redirect:/admin/exam-param/marker/subjectViewer?repage";
    }

    @RequestMapping(value = "/rest", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject rest(@RequestParam Integer id) {
        User user = userService.findById(id);
        JSONObject obj = new JSONObject();
        if (user != null) {
            user.setPassword(Md5EncryptUtils.md5(USER_PASSWORD));
            userService.save(user);
            obj.accumulate("success", true);
        } else {
            obj.accumulate("success", false);
            obj.accumulate("message", "该用户不存在");
        }
        return obj;
    }

    @RequestMapping(value = "/setTaskCount", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject setTaskCount(@RequestParam Integer id, @RequestParam Integer taskCount) {
        Marker marker = markerService.findById(id);
        JSONObject obj = new JSONObject();
        if (marker != null) {
            marker.setTopCount(taskCount);
            marker = markerService.save(marker);
            obj.accumulate("success", true);
        } else {
            obj.accumulate("success", false);
            obj.accumulate("message", "该评卷员不存在");
        }
        return obj;
    }

    @RequestMapping(value = "/reSetPassword", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject reSetPassword(@RequestParam Integer id, @RequestParam String password) {
        Marker marker = markerService.findById(id);
        JSONObject obj = new JSONObject();
        if (marker != null) {
            marker.setPassword(password);
            marker = markerService.save(marker);
            obj.accumulate("success", true);
        } else {
            obj.accumulate("success", false);
            obj.accumulate("message", "该评卷员不存在");
        }
        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-param/marker";
    }

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

    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public String importFile(HttpServletRequest request, MultipartFile file, RedirectAttributes redirectAttributes) {
        int examId = getSessionExamId(request);
        // Exam exam = examService.findById(examId);
        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);
            List<Marker> saveList = new LinkedList<Marker>();
            Map<String, Marker> saveMap = new HashMap<String, Marker>();
            Map<String, ExamSubject> current = null;
            current = new HashMap<String, ExamSubject>();
            List<ExamSubject> list2 = subjectService.list(examId);
            for (ExamSubject s : list2) {
                current.put(s.getCode(), s);
            }
            for (Marker marker : list) {
                String password = "";
                if (StringUtils.isBlank(marker.getSubjectCode()) || StringUtils.isBlank(marker.getLoginName())) {
                    continue;
                }
                marker.setExamId(examId);
                marker.setName(marker.getLoginName());
                marker.setEnable(true);
                marker.setCommon(false);
                if (StringUtils.isBlank(marker.getPassword())) {
                    Random random = new Random();
                    for (int i = 0; i < 6; i++) {
                        password += random.nextInt(10);
                    }
                    marker.setPassword(password);
                }
                MarkerExcelError markerExcelError = checkLongNameAndPassword(marker, current, saveMap);
                if (markerExcelError.equals(MarkerExcelError.MARKER)) {
                    saveList.add(marker);
                    saveMap.put(marker.getLoginName(), marker);
                } else {
                    failureMsg.append("<br/>评卷员 " + marker.getLoginName() + "," + markerExcelError.getName());
                    failureNum++;
                }
            }
            successNum = markerService.batchSave(saveList);
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条记录！");
            }
            addMessage(redirectAttributes, "已成功导入 " + successNum + " 条评卷员" + failureMsg);
        } catch (Exception e) {
            log.error("Batch import marker error!", e);
            addMessage(redirectAttributes, "导入评卷员失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + "/admin/exam-param/marker";
    }

    @RequestMapping(value = "/importUpdate", method = RequestMethod.POST)
    public String importUpdateFile(HttpServletRequest request, MultipartFile file,
            RedirectAttributes redirectAttributes) {
        // int examId = getSessionExamId(request);
        // Exam exam = examService.findById(examId);
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<MarkerDTO> list = ei.getDataList(MarkerDTO.class);
            List<Marker> saveList = new LinkedList<Marker>();
            Map<String, Marker> current = null;
            List<Marker> list2 = markerService.findCommon(false);
            if (list2.size() < 10000) {
                current = new HashMap<String, Marker>();
                for (Marker s : list2) {
                    current.put(s.getLoginName(), s);
                }
            }
            for (MarkerDTO markerDTO : list) {
                if (StringUtils.isBlank(markerDTO.getSubjectCode()) || StringUtils.isBlank(markerDTO.getLoginName())
                        || StringUtils.isBlank(markerDTO.getNewLoginName())
                        || StringUtils.isBlank(markerDTO.getPassword())) {
                    continue;
                }
                MarkerExcelError markerExcelError = checkExcelData(markerDTO, current);
                if (markerExcelError.equals(MarkerExcelError.MARKER)) {
                    Marker marker = null;
                    if (current != null) {
                        marker = current.get(markerDTO.getLoginName());
                    } else {
                        marker = markerService.findByLoginName(markerDTO.getLoginName());
                    }
                    marker.setLoginName(markerDTO.getNewLoginName());
                    marker.setPassword(markerDTO.getPassword());
                    saveList.add(marker);
                } else {
                    failureMsg.append("<br/>科目代码(" + markerDTO.getSubjectCode() + ")原评卷员(" + markerDTO.getLoginName()
                            + ")更换新评卷员为(" + markerDTO.getNewLoginName() + ")失败!");
                    failureMsg.append("---->失败原因：(" + markerExcelError.getName() + ")");
                    failureNum++;
                }
            }
            successNum = markerService.batchSave(saveList);
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条记录！");
            }
            addMessage(redirectAttributes, "已成功导入 " + successNum + " 条" + failureMsg);
        } catch (Exception e) {
            log.error("Batch import marker error!", e);
            addMessage(redirectAttributes, "导入修改评卷员账号失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + "/admin/exam-param/marker";
    }

    private MarkerExcelError checkLongNameAndPassword(Marker marker, Map<String, ExamSubject> current,
            Map<String, Marker> saveMap) {
        Marker previous = null;

        if (current != null && current.get(marker.getSubjectCode()) == null) {
            return MarkerExcelError.MARKERNOTCODE;
        }
        if (saveMap != null) {
            previous = saveMap.get(marker.getLoginName());
        }

        if (previous != null) {
            return MarkerExcelError.MARKERED;
        }

        previous = markerService.findByLoginName(marker.getLoginName());

        if (marker.getPassword().length() > 0 && marker.getPassword().length() < 4) {
            return MarkerExcelError.MARKERPWERROR;
        }

        if (previous == null) {
            return MarkerExcelError.MARKER;
        }
        return MarkerExcelError.MARKERED;
    }

    // 校验excel中数据
    public MarkerExcelError checkExcelData(MarkerDTO markerDTO, Map<String, Marker> current) {
        if (markerDTO != null) {
            Marker marker = null;
            if (current == null) {
                marker = markerService.findByLoginName(markerDTO.getLoginName());
            } else {
                marker = current.get(markerDTO.getLoginName());
            }
            if (markerDTO.getPassword().length() < 4) {
                return MarkerExcelError.MARKERPWERROR;
            }
            if (marker != null) {
                if (marker.getSubjectCode().equals(markerDTO.getSubjectCode())) {
                    if (markerService.countByLoginName(markerDTO.getNewLoginName()) > 0) {
                        return MarkerExcelError.MARKERNEWMISS;
                    } else {
                        return MarkerExcelError.MARKER;
                    }
                } else {
                    return MarkerExcelError.MARKERCODEMISS;
                }
            } else {
                return MarkerExcelError.MARKERMISS;
            }
        } else {
            return MarkerExcelError.MARKERNOTINFO;
        }
    }
}
