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

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

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

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
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 cn.com.qmth.stmms.admin.dto.MarkerDTO;
import cn.com.qmth.stmms.admin.dto.SubjectUserDTO;
import cn.com.qmth.stmms.admin.exam.BaseExamController;
import cn.com.qmth.stmms.biz.exam.bean.AddStudentInfo;
import cn.com.qmth.stmms.biz.exam.bean.UserStudentVo;
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.model.SubjectUser;
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.MarkerService;
import cn.com.qmth.stmms.biz.exam.service.SubjectUserService;
import cn.com.qmth.stmms.biz.exam.service.UserExamService;
import cn.com.qmth.stmms.biz.exam.service.UserStudentService;
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.enums.LogType;
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 net.sf.json.JSONObject;

@Controller
@RequestMapping("/admin/user")
public class UserController extends BaseExamController {

    public static final String SPLIT = ",";

    public static Role[] ROLE_LIST = { Role.SCANNER, Role.SUBJECT_HEADER, Role.INSPECTOR, Role.MARKER,
            Role.SCHOOL_VIEWER, Role.SCHOOL_ADMIN, Role.COLLEGE_ADMIN };

    @Autowired
    private UserService userService;

    @Autowired
    private SubjectUserService subjectUserService;

    @Autowired
    private UserExamService userExamService;

    @Autowired
    private MarkerService markerService;

    @Autowired
    private ExamSubjectService subjectService;

    @Autowired
    private MarkGroupService groupService;

    @Autowired
    private ExamQuestionService questionService;

    @Autowired
    private ExamService examService;

    @Autowired
    private ExamStudentService studentService;

    @Autowired
    private UserStudentService userStudentService;

    @Logging(menu = "查询用户", type = LogType.QUERY)
    @RequestMapping("/list")
    @RoleRequire(Role.SCHOOL_ADMIN)
    public ModelAndView list(HttpServletRequest request, UserSearchQuery query) {
        User user = RequestUtils.getWebUser(request).getUser();
        query.setSchoolId(user.getSchoolId());
        query = userService.findByQuery(query);

        ModelAndView view = new ModelAndView("modules/user/userList");
        view.addObject("roleList", ROLE_LIST);
        view.addObject("sourceList", UserSource.values());
        view.addObject("query", query);
        return view;
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    @RoleRequire(Role.SCHOOL_ADMIN)
    public ModelAndView addInit(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("modules/user/userEdit");
        User user = new User();
        user.setEnable(true);
        view.addObject("user", user);
        view.addObject("roleList", ROLE_LIST);
        return view;
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    @RoleRequire(Role.SCHOOL_ADMIN)
    public ModelAndView editInit(HttpServletRequest request, @RequestParam Integer id, UserSearchQuery query) {
        User current = RequestUtils.getWebUser(request).getUser();
        User user = userService.findById(id);
        if (user != null && user.getSchoolId().equals(current.getSchoolId())) {
            ModelAndView view = new ModelAndView("modules/user/userEdit");
            view.addObject("user", user);
            if (user.getRole() == Role.SUBJECT_HEADER || user.getRole() == Role.INSPECTOR
                    || user.getRole() == Role.COLLEGE_ADMIN || user.getRole() == Role.SCHOOL_VIEWER) {
                view.addObject("subjectCodeString",
                        StringUtils.join(subjectUserService.findSubjectCode(user.getId()), SPLIT));
                view.addObject("examIdString", StringUtils.join(userExamService.findExamIds(user.getId()), SPLIT));
            }
            view.addObject("query", query);
            if (user.getRole() == Role.SCHOOL_VIEWER) {
                int studentCount = userStudentService.countByUserId(id);
                view.addObject("studentCount", studentCount);
            }
            return view;
        } else {
            return new ModelAndView("redirect:/admin/user/list");
        }
    }

    @Logging(menu = "新增（修改）用户", type = LogType.UPDATE)
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @RoleRequire(Role.SCHOOL_ADMIN)
    @Transactional
    public String save(HttpServletRequest request, RedirectAttributes redirectAttributes, Model model, User user,
            @RequestParam(required = false) String subjectCodeString,
            @RequestParam(required = false) String examIdString,
            @RequestParam(required = false, defaultValue = "1") int pageNumber,
            @RequestParam(required = false) UserSource querySource, @RequestParam(required = false) Role queryRole,
            @RequestParam(required = false) String queryLoginName, @RequestParam(required = false) String queryName,
            @RequestParam(required = false) Boolean queryEnable,
            @RequestParam(required = false) MultipartFile studentFile) {
        User current = RequestUtils.getWebUser(request).getUser();
        int examId = getSessionExamId(request);
        User previous = null;
        if (user.getId() != null) {
            previous = userService.findById(user.getId());
        }
        AddStudentInfo suc = null;
        if (previous == null) {
            String message = validate(user, subjectCodeString, examIdString);
            if (message == null) {
                String password = StringEscapeUtils.unescapeHtml(user.getPassword());
                user.setPassword(EncryptUtils.md5(password));
                user.setSchoolId(current.getSchoolId());
                user.setSource(UserSource.INTERNAL);
                user.setCreatedTime(new Date());
                user.setUpdatedTime(new Date());
                userService.save(user);
                if (user.getRole() == Role.SUBJECT_HEADER || user.getRole() == Role.INSPECTOR) {
                    subjectUserService.updateByUserId(user.getId(), getSubjectCodeSet(subjectCodeString));
                }
                if (user.getRole() == Role.SCHOOL_VIEWER) {
                    userExamService.updateByUserId(user.getId(), getExamIdSet(examIdString));
                    subjectUserService.updateByUserId(user.getId(), getSubjectCodeSet(subjectCodeString));
                }
                if (user.getRole() == Role.COLLEGE_ADMIN) {
                    subjectUserService.updateByUserId(user.getId(),
                            getSubjectCodeSetByCollege(examId, user.getDescription()));
                    userService.save(user);
                }
                if (user.getRole() == Role.SCHOOL_VIEWER && !studentFile.isEmpty()) {
                    suc = addStudent(studentFile, user.getSchoolId(), user.getId());
                }
            } else {
                model.addAttribute("user", user);
                model.addAttribute("roleList", ROLE_LIST);
                if (user.getRole() == Role.SUBJECT_HEADER || user.getRole() == Role.INSPECTOR
                        || user.getRole() == Role.COLLEGE_ADMIN || user.getRole() == Role.SCHOOL_VIEWER) {
                    model.addAttribute("subjectCodeString",
                            StringUtils.join(subjectUserService.findSubjectCode(user.getId()), SPLIT));
                    model.addAttribute("examIdString",
                            StringUtils.join(userExamService.findExamIds(user.getId()), SPLIT));
                }
                if (user.getRole() == Role.SCHOOL_VIEWER) {
                    int studentCount = userStudentService.countByUserId(user.getId());
                    model.addAttribute("studentCount", studentCount);
                }
                UserSearchQuery query = new UserSearchQuery();
                query.setPageNumber(pageNumber);
                query.setSource(querySource);
                query.setRole(queryRole);
                query.setLoginName(queryLoginName);
                query.setName(queryName);
                query.setEnable(queryEnable);
                model.addAttribute("query", query);
                model.addAttribute("message", message);
                return "modules/user/userEdit";
            }
        } else if (previous.getSchoolId().equals(current.getSchoolId())) {
            previous.setLoginName(user.getLoginName());
            previous.setName(user.getName());
            if (StringUtils.isNotBlank(user.getPassword())) {
                String password = StringEscapeUtils.unescapeHtml(user.getPassword());
                previous.setPassword(EncryptUtils.md5(password));
                previous.setRandomPassword(null);
            }
            previous.setEmpno(user.getEmpno());
            previous.setEnable(user.isEnable());
            previous.setDescription(user.getDescription());
            String message = validate(previous, subjectCodeString, examIdString);
            if (message == null) {
                if (previous.getRole() == Role.SUBJECT_HEADER || user.getRole() == Role.INSPECTOR) {
                    previous.refreshAccessToken();
                    subjectUserService.updateByUserId(previous.getId(), getSubjectCodeSet(subjectCodeString));
                }
                if (user.getRole() == Role.SCHOOL_VIEWER) {
                    previous.refreshAccessToken();
                    userExamService.updateByUserId(user.getId(), getExamIdSet(examIdString));
                    subjectUserService.updateByUserId(previous.getId(), getSubjectCodeSet(subjectCodeString));
                }
                if (user.getRole() == Role.COLLEGE_ADMIN) {
                    previous.refreshAccessToken();
                    subjectUserService.updateByUserId(user.getId(),
                            getSubjectCodeSetByCollege(examId, user.getDescription()));
                }
                if (user.getRole() == Role.MARKER) {
                    markerService.updateEnableByUserId(previous.getId(), previous.isEnable());
                }
                previous.setUpdatedTime(new Date());
                userService.save(previous);
                if (previous.getRole() == Role.SCHOOL_VIEWER && !studentFile.isEmpty()) {
                    suc = addStudent(studentFile, previous.getSchoolId(), previous.getId());
                }
            } else {
                model.addAttribute("user", previous);
                model.addAttribute("roleList", ROLE_LIST);
                model.addAttribute("message", message);
                UserSearchQuery query = new UserSearchQuery();
                query.setPageNumber(pageNumber);
                query.setSource(querySource);
                query.setRole(queryRole);
                query.setLoginName(queryLoginName);
                query.setName(queryName);
                query.setEnable(queryEnable);
                model.addAttribute("query", query);
                if (user.getRole() == Role.SUBJECT_HEADER || user.getRole() == Role.INSPECTOR
                        || user.getRole() == Role.COLLEGE_ADMIN || user.getRole() == Role.SCHOOL_VIEWER) {
                    model.addAttribute("subjectCodeString",
                            StringUtils.join(subjectUserService.findSubjectCode(user.getId()), SPLIT));
                    model.addAttribute("examIdString",
                            StringUtils.join(userExamService.findExamIds(user.getId()), SPLIT));
                }
                if (user.getRole() == Role.SCHOOL_VIEWER) {
                    int studentCount = userStudentService.countByUserId(user.getId());
                    model.addAttribute("studentCount", studentCount);
                }
                return "modules/user/userEdit";
            }
        }
        String enable = queryEnable == null ? "" : queryEnable.toString();
        String role = queryRole == null ? "" : String.valueOf(queryRole.getValue());
        String source = querySource == null ? "" : String.valueOf(querySource.getValue());
        if (suc != null) {
            addMessage(redirectAttributes, "成功绑定考生" + suc.getSuccess() + "条，失败" + suc.getFailed() + "条（已绑定或无效的准考证号）");
        }
        return "redirect:/admin/user/list?pageNumber=" + pageNumber + "&source=" + source + "&role=" + role
                + "&loginName=" + queryLoginName + "&name=" + queryName + "&enable=" + enable;
    }

    private AddStudentInfo addStudent(MultipartFile file, Integer schoolId, Integer userId) {
        try {
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<UserStudentVo> list = ei.getDataList(UserStudentVo.class);
            return userStudentService.addStudent(list, schoolId, userId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private String validate(User user, String subjectCodeString, String examIdString) {
        String message = null;
        if (StringUtils.isBlank(user.getLoginName())) {
            message = "登录名不能为空";
        } else if (!checkLoginName(user)) {
            message = "登录名不能重复";
        } else if (StringUtils.isBlank(user.getName())) {
            message = "名称不能为空";
        } else if (StringUtils.isBlank(user.getPassword())) {
            message = "密码不能为空";
        } else if (user.getRole() == Role.SUBJECT_HEADER && StringUtils.isBlank(subjectCodeString)) {
            message = "评卷组长必须绑定科目代码";
        } else if (user.getRole() == Role.INSPECTOR && StringUtils.isBlank(subjectCodeString)) {
            message = "复核员必须绑定科目代码";
        } else if (user.getRole() == Role.COLLEGE_ADMIN && StringUtils.isBlank(user.getDescription())) {
            message = "评卷管理员必须绑定电厂";
        } else if (user.getRole() == Role.SCHOOL_VIEWER
                && (StringUtils.isBlank(subjectCodeString) || StringUtils.isBlank(examIdString))) {
            message = "成绩查询员必须绑定考试ID和科目代码";
        }
        return message;
    }

    private Set<String> getSubjectCodeSet(String subjectCodeString) {
        Set<String> set = new HashSet<>();
        try {
            String[] values = StringUtils.split(subjectCodeString, SPLIT);
            for (String value : values) {
                value = StringUtils.trimToNull(value);
                if (value != null) {
                    set.add(value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return set;
    }

    private Set<Integer> getExamIdSet(String examIdString) {
        Set<Integer> set = new HashSet<>();
        try {
            String[] values = StringUtils.split(examIdString, SPLIT);
            for (String value : values) {
                value = StringUtils.trimToNull(value);
                if (value != null) {
                    set.add(Integer.parseInt(value));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return set;
    }

    private Set<String> getSubjectCodeSetByCollege(int examId, String college) {
        Set<String> set = new HashSet<>();
        try {
            List<String> subject = studentService.findDistinctSubjectCodeByCollege(examId, college);
            for (String value : subject) {
                value = StringUtils.trimToNull(value);
                if (value != null) {
                    set.add(value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return set;
    }

    @Logging(menu = "导出用户", type = LogType.EXPORT)
    @RequestMapping(value = "/export", method = RequestMethod.POST)
    public String exportFile(UserSearchQuery query, HttpServletRequest request, HttpServletResponse response,
            RedirectAttributes redirectAttributes) {
        try {
            String fileName = "用户数据.xlsx";
            User user = RequestUtils.getWebUser(request).getUser();
            query.setSchoolId(user.getSchoolId());
            query.setPageNumber(1);
            query.setPageSize(Integer.MAX_VALUE);
            query = userService.findByQuery(query);
            for (User s : query.getResult()) {
                s.setRoleName(s.getRole().getName());
            }
            new ExportExcel("用户数据", User.class).setDataList(query.getResult()).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导出用户数据失败！" + e.getMessage());
        }
        return "redirect:/admin/user/list";
    }

    @Logging(menu = "导出用户", type = LogType.EXPORT)
    @RequestMapping(value = "/exportExam", method = RequestMethod.POST)
    public String exportExam(UserSearchQuery query, HttpServletRequest request, HttpServletResponse response,
            RedirectAttributes redirectAttributes) {
        try {
            String fileName = "用户数据.xlsx";
            User user = RequestUtils.getWebUser(request).getUser();
            query.setSchoolId(user.getSchoolId());
            query.setPageNumber(1);
            query.setPageSize(Integer.MAX_VALUE);
            int examId = getSessionExamId(request);
            if (query.getRole() != null && query.getRole().equals(Role.MARKER)) {
                Map<String, ExamSubject> subjectMap = new HashMap<String, ExamSubject>();
                Map<String, MarkGroup> groupMap = new HashMap<String, MarkGroup>();
                MarkerSearchQuery mQuery = new MarkerSearchQuery();
                mQuery.setExamId(examId);
                mQuery.setLoginName(query.getLoginName());
                mQuery.setName(query.getName());
                mQuery.setPageSize(Integer.MAX_VALUE);
                mQuery = markerService.findByQuery(mQuery);
                List<MarkerDTO> list = new ArrayList<MarkerDTO>();
                for (Marker m : mQuery.getResult()) {
                    MarkerDTO s = new MarkerDTO();
                    ExamSubject subject = subjectMap.get(m.getSubjectCode());
                    if (subject == null) {
                        subject = subjectService.find(examId, m.getSubjectCode());
                        subjectMap.put(m.getSubjectCode(), subject);
                    }
                    s.setSubjectCode(m.getSubjectCode());
                    s.setSubjectName(subject.getName());
                    String groupKey = m.getSubjectCode() + "/t" + m.getGroupNumber();
                    MarkGroup group = groupMap.get(groupKey);
                    if (group == null) {
                        group = groupService.findOne(examId, m.getSubjectCode(), m.getGroupNumber());
                        group.setQuestionList(questionService.findByExamAndSubjectAndObjectiveAndGroupNumber(examId,
                                subject.getCode(), false, group.getNumber()));
                        groupMap.put(groupKey, group);
                    }
                    s.setGroupName(group.getQuestionTitle());
                    s.setGroupNumber(m.getGroupNumber());
                    s.setRole(Role.MARKER.getName());
                    User u = userService.findById(m.getUserId());
                    s.setLoginName(u.getLoginName());
                    s.setRandomPassword(u.getRandomPassword());
                    list.add(s);
                }
                new ExportExcel("评卷员数据", MarkerDTO.class).setDataList(list).write(response, fileName).dispose();
                return null;
            }
            if (query.getRole() != null
                    && (query.getRole().equals(Role.SUBJECT_HEADER) || query.getRole().equals(Role.INSPECTOR))) {
                List<SubjectUserDTO> list = new ArrayList<SubjectUserDTO>();
                Map<String, ExamSubject> subjectMap = new HashMap<String, ExamSubject>();
                query = userService.findByQuery(query);
                for (User u : query.getResult()) {
                    List<SubjectUser> subjectUsers = subjectUserService.findByUserId(u.getId());
                    if (!subjectUsers.isEmpty()) {
                        for (SubjectUser subjectUser : subjectUsers) {
                            SubjectUserDTO s = new SubjectUserDTO();
                            s.setRole(query.getRole().getName());
                            s.setLoginName(u.getLoginName());
                            s.setRandomPassword(u.getRandomPassword());
                            ExamSubject subject = subjectMap.get(subjectUser.getSubjectCode());
                            if (subject == null) {
                                subject = subjectService.find(examId, subjectUser.getSubjectCode());
                                subjectMap.put(subjectUser.getSubjectCode(), subject);
                            }
                            if (subject != null) {
                                s.setSubjectCode(subjectUser.getSubjectCode());
                                s.setSubjectName(subject.getName());
                                list.add(s);
                            }
                        }
                    }
                }
                new ExportExcel("用户数据", SubjectUserDTO.class).setDataList(list).write(response, fileName).dispose();
                return null;
            }
        } catch (Exception e) {
            addMessage(redirectAttributes, "导出用户数据失败！" + e.getMessage());
        }
        return "redirect:/admin/user/list";
    }

    @Logging(menu = "用户启用/禁用", type = LogType.UPDATE)
    @RequestMapping("/toggle")
    @RoleRequire({ Role.SCHOOL_ADMIN, Role.SUBJECT_HEADER, Role.COLLEGE_ADMIN })
    public String toggle(HttpServletRequest request, Model model, RedirectAttributes redirectAttributes,
            @RequestParam Integer[] ids, @RequestParam Boolean enable) {
        for (Integer id : ids) {
            User user = userService.findById(id);
            if (user == null) {
                continue;
            }
            user.setEnable(enable);
            markerService.updateEnableByUserId(id, enable);
            userService.save(user);
        }
        return "redirect:/admin/user/list";
    }

    @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) {
            User user = userService.findById(id);
            if (user == null || UserSource.EXTERNAL.equals(user.getSource())) {
                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;
    }

    @RequestMapping(value = "/batchAdd", method = RequestMethod.GET)
    @RoleRequire(Role.SCHOOL_ADMIN)
    public ModelAndView batchAdd(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("modules/user/userAdd");
        Role[] roleList = { Role.SUBJECT_HEADER, Role.INSPECTOR, Role.MARKER };
        view.addObject("roleList", roleList);
        int examId = getSessionExamId(request);
        view.addObject("exam", examService.findById(examId));
        return view;
    }

    @Logging(menu = "批量新增用户", type = LogType.ADD)
    @RequestMapping(value = "/batchSave", method = RequestMethod.POST)
    @RoleRequire(Role.SCHOOL_ADMIN)
    public String batchSave(HttpServletRequest request, Model model, RedirectAttributes redirectAttributes,
            @RequestParam Role role, @RequestParam(required = false) String password, @RequestParam Integer number,
            @RequestParam String subjectCodeString, @RequestParam(required = false) Boolean random) {
        int examId = getSessionExamId(request);
        if (Role.MARKER.equals(role)) {
            int successNum = userService.batchSaveMarker(examId, getSubjectCodeSet(subjectCodeString), number,
                    password, random == null ? false : random);
            String message = "已成功新增 " + successNum + " 条用户";
            addMessage(redirectAttributes, message);
        } else {
            int successNum = userService.batchSaveSubjectUser(examId, role, getSubjectCodeSet(subjectCodeString),
                    number, password, random == null ? false : random);
            String message = "已成功新增 " + successNum + " 条用户";
            addMessage(redirectAttributes, message);
        }
        return "redirect:/admin/user/list";
    }

    @RequestMapping("/getSubjectCode")
    @RoleRequire(Role.SCHOOL_ADMIN)
    public String get(HttpServletRequest request, Model model, RedirectAttributes redirectAttributes,
            @RequestParam(required = false) String code) {
        int examId = getSessionExamId(request);
        List<ExamSubject> list = new ArrayList<ExamSubject>();
        if (StringUtils.isNotBlank(code)) {
            list.add(subjectService.find(examId, code));
        } else {
            list = subjectService.list(examId);
        }
        if (list.size() > 0) {
            model.addAttribute("list", list);
            return "modules/exam/subjectSelect";
        } else {
            model.addAttribute("message", "没有科目");
            return "modules/exam/subjectSelect";
        }
    }

    @RequestMapping(value = "student/template")
    public String importStudentTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "绑定考生导入模板.xlsx";
            String title = "绑定考生数据";
            List<SubjectUser> list = new ArrayList<SubjectUser>();
            list.add(new SubjectUser());
            new ExportExcel(title, UserStudentVo.class, 2).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
        }
        return "redirect:/admin/user/edit";
    }

    @RequestMapping(value = "student/clear")
    public String studentClear(@RequestParam Integer id,
            @RequestParam(required = false, defaultValue = "1") int pageNumber,
            @RequestParam(required = false) UserSource querySource, @RequestParam(required = false) Role queryRole,
            @RequestParam(required = false) String queryLoginName, @RequestParam(required = false) String queryName,
            @RequestParam(required = false) Boolean queryEnable) {
        userStudentService.clear(id);
        String enable = queryEnable == null ? "" : queryEnable.toString();
        String role = queryRole == null ? "" : String.valueOf(queryRole.getValue());
        String source = querySource == null ? "" : String.valueOf(querySource.getValue());
        return "redirect:/admin/user/list?pageNumber=" + pageNumber + "&source=" + source + "&role=" + role
                + "&loginName=" + queryLoginName + "&name=" + queryName + "&enable=" + enable;
    }
}
