package com.qmth.qrzk.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

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

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
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.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.qmth.qrzk.repository.constants.WebConstants;
import com.qmth.qrzk.repository.service.query.CourseQueryParams;
import com.qmth.qrzk.repository.service.query.UserQueryParams;
import com.qmth.qrzk.repository.user.model.Attachment;
import com.qmth.qrzk.repository.user.model.Course;
import com.qmth.qrzk.repository.user.model.ImportBean;
import com.qmth.qrzk.repository.user.model.OLUser;
import com.qmth.qrzk.repository.user.model.Role;
import com.qmth.qrzk.repository.user.model.User;
import com.qmth.qrzk.repository.user.model.UserCourse;
import com.qmth.qrzk.repository.user.model.UserRole;
import com.qmth.qrzk.repository.user.service.IRoleService;
import com.qmth.qrzk.repository.user.service.IUserService;
import com.qmth.qrzk.repository.user.service.impl.AttachmentService;
import com.qmth.qrzk.repository.user.service.impl.CourseServiceImpl;
import com.qmth.qrzk.repository.utils.Consts;
import com.qmth.qrzk.repositry.utils.excel.ExcelOperate;

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

	private static final Logger log = Logger.getLogger(QuestionTypeController.class);
	
	@Autowired
	private AttachmentService attachmentService;
	@Autowired
	@Qualifier("userServiceImpl")
	private IUserService userService;
	
	@Autowired
	private CourseServiceImpl courseService;
	
	@Autowired
	@Qualifier("roleServiceImpl")
	private IRoleService roleService;
	
	private static final String BASE_JSP_PATH = "usercenter/user/";
	
    @RequestMapping(value = "/list")
    public ModelAndView list(HttpServletRequest request, HttpSession session,UserQueryParams params) {

        Map<String, Object> result = new HashMap<String, Object>();
        List<Role> roles = roleService.getAllRoles(params);
        result.put("roles", roles);
        return new ModelAndView(BASE_JSP_PATH + "list", result);
    }
    
	@RequestMapping(value="/queryUsers")
	@ResponseBody
	public Map<String, Object> queryUsers(@RequestBody UserQueryParams params){
		Map<String,Object> result = new HashMap<String, Object>();
		List<User> users = userService.queryUsers(params);
		result.put("rows", users);
		result.put("total", params.getTotalNum());
		return result;
	}
	
	@RequestMapping("/backups")
	public ModelAndView backups() {
		ModelAndView view = new ModelAndView(BASE_JSP_PATH + "backups");
		return view;
	}
	
	@RequestMapping(value="/queryTeacher",method={RequestMethod.POST})
	@ResponseBody
	public Map<String,Object> validateChange(HttpSession session,HttpServletRequest request,HttpServletResponse response,int id){
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			List<User> users=userService.queryUsers(null);
			result.put("users", users);
			return result;
		}catch(Exception e){
			log.error("查询用户失败!",e);
		}
		return null;
	}

	@RequestMapping(value = "/info")
    public ModelAndView showInfo(HttpSession session) {
    	User user = (User) session.getAttribute(WebConstants.WEB_SESSION_USER);
    	Role role = (Role)session.getAttribute(WebConstants.WEB_SESSION_ROLE);
    	Date lastLoginDate = (Date)session.getAttribute(WebConstants.WEB_SESSION_USER_LAST_LOGIN_DATE);
    	List<Course> courses = courseService.findCoursesByUserId(user.getId());
    	
    	ModelAndView view = new ModelAndView("usercenter/user/info");
        view.addObject("user", user);
        view.addObject("role", role);
        view.addObject("lastLoginDate", lastLoginDate);
        view.addObject("courses", courses);
        return view;
    }
    
    @RequestMapping(value = "/checkpassword")
    public ModelAndView checkPassword(HttpServletRequest request) {
        String fieldValue = request.getParameter("fieldValue");
        User user = (User) request.getSession().getAttribute(WebConstants.WEB_SESSION_USER);
        Map<String, Object> map = new HashMap<String, Object>();
        boolean status = false;
        
        Md5PasswordEncoder encoder = new Md5PasswordEncoder();
        if (!(encoder.encodePassword(fieldValue, WebConstants.PASSWORD_SALT).equals(user.getPassword()))) {
            status = false;
        } else {
            status = true;
        }
        map.put("status", status);
        return new ModelAndView("", map);
    }
    
	@RequestMapping(value = "/add")
    public ModelAndView addUser(HttpSession session) {
    	ModelAndView view = new ModelAndView("usercenter/user/userAdd");
        return view;
    }
	
	@RequestMapping(value ="/getLinkRole")
	@ResponseBody
	public Map<String, Object> queryRoles(UserQueryParams params){
		Map<String,Object> result = new HashMap<String, Object>();
		List<Role> roles=roleService.getAllRoles(params);
		int total=roleService.getAllRolesCount(params);
		result.put("rows", roles);
		result.put("total", total);
		return result;
	}
	
	
	@RequestMapping(value="/getAllRole")
	@ResponseBody
	public List<Role> getAllRole(){
		UserQueryParams params=new UserQueryParams();
		List<Role> list=roleService.getAllRoles(params);
		return list;
	}
	
	
	
	@RequestMapping(value="/saveLinkRoll")
	@ResponseBody
	public Map<String,Object> saveLinkRoll(HttpServletRequest request,int userId, @RequestParam(value = "links[]")String[] links){
		try{
			if(links!=null){
				//先删除跟userId相关联的角色信息
				roleService.delByUserId(userId);
				
				List<UserRole> list=new ArrayList<UserRole>();
				for(String s:links){
					UserRole ur=new UserRole(userId, Integer.parseInt(s));
					list.add(ur);
				}
				roleService.addLinkRole(list);
			}
			userService.initUserInfo();
			return this.successResult(null);
		}catch(Exception exp){
			log.error("更新用户(userId=" + userId + ")关联的角色信息失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	@RequestMapping(value="/addRelatedCourse/{userId}/{courseId}")
	@ResponseBody
	public Map<String,Object> addRelatedCourse(@PathVariable Integer userId, @PathVariable Integer courseId){
		try{
			List<UserCourse> list=new ArrayList<UserCourse>();
			UserCourse uc=new UserCourse(userId, courseId);
			list.add(uc);
			courseService.addUserCourses(userId, list);
			return this.successResult(null);
		}catch(Exception exp){
			log.error("更新用户(userId=" + userId + ")关联的角色信息失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	@RequestMapping(value="/removeRelatedCourse/{userId}/{courseId}")
	@ResponseBody
	public Map<String,Object> removeRelatedCourse(@PathVariable Integer userId, @PathVariable Integer courseId){
		try{
			UserCourse uc=new UserCourse(userId, courseId);
			courseService.deleteUserCourses(uc);
			return this.successResult(null);
		}catch(Exception exp){
			log.error("更新用户(userId=" + userId + ")关联的角色信息失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	
	@RequestMapping(value="/getAllSubject")
	@ResponseBody
	public Map<String, Object> querySubject(CourseQueryParams params){
		Map<String,Object> result = new HashMap<String, Object>();
		List<Course> course=courseService.queryCourses(params);
		int total=params.getTotalNum();
		result.put("rows", course);
		result.put("total", total);
		return result;
	}
	
	@RequestMapping("/addUser")
	public void addUser(HttpServletRequest request,
			HttpServletResponse response,@RequestBody String data){
		JSONObject object = new JSONObject();
		
		try{
			JSONObject obj = JSONObject.fromObject(data);
			JSONObject userObj = obj.getJSONObject("User");
			User user=(User)userObj.toBean(userObj, User.class);

			//新增用户信息并返回数据库对应的用户id
			userService.addUser(user);
			
			String arrCourse = obj.getString("arrCourse");
			JSONArray arrayCourse=JSONArray.fromObject(arrCourse);
			
			String arrRole=obj.getString("arrRole");
			JSONArray arrayRole=JSONArray.fromObject(arrRole);
			for(int i=0;i<arrayRole.size();i++){
				//构造UserRole对象
				UserRole userRole=new UserRole(user.getId(),arrayRole.getInt(i));
				
				//新增用户与角色关联的信息
				roleService.insertUserRole(userRole);
			}
			
			//前端新建角色时,会赋予很多课程给具体某个老师
			for(int i=0;i<arrayCourse.size();i++){
				UserCourse uc=new UserCourse(user.getId(),arrayCourse.getInt(i));
				courseService.insertUserCourse(uc);
			}
			object.put("type", "success");
			this.outJsonString(response, object.toString());
		}catch(Exception e){
			object.put("type", "fail");
			this.outJsonString(response, object.toString());
		}
	}
	
	@RequestMapping("/save")
	@ResponseBody
	public Map<String,Object> save(HttpServletRequest request, @RequestBody User user){
		try{
			int isLoginNameExists=userService.checkLoginName(user.getId(), user.getLoginName());
			if(isLoginNameExists > 0){
				return this.failedResult("登录名重复！");
			}
			
			if(user.getId()==null){
				user.setPassword("123456");
				user.setIsEnabled(1);
				userService.addUser(user);
				
				if(user.getRole() != null){
					//关联角色
					List<UserRole> ls=new ArrayList<UserRole>();
					for(String ss:user.getRole()){
						UserRole ur=new UserRole(user.getId(),Integer.parseInt(ss));
						ls.add(ur);
					}
					roleService.addLinkRole(ls);
				}else{
					//关联角色
					List<UserRole> ls=new ArrayList<UserRole>();
					List<Role> roles=roleService.getAllRoles(null);
					int domesticConsumerId=0;
					for(Role r:roles){
						if(r.getCode().equals("domesticConsumer")||r.getName().equals("普通用户")){
							domesticConsumerId=r.getId();
							break;
						}
					}
					UserRole ur=new UserRole(user.getId(),domesticConsumerId);
					ls.add(ur);
					roleService.addLinkRole(ls);
				}
			}else{
				userService.updateUser(user);
				
				if(user.getRole()!=null){
					//关联角色
					roleService.delByUserId(user.getId());
					List<UserRole> ls=new ArrayList<UserRole>();
					for(String ss:user.getRole()){
						UserRole ur=new UserRole(user.getId(),Integer.parseInt(ss));
						ls.add(ur);
					}
					roleService.addLinkRole(ls);
				}
				
			}
			return this.successResult(null);
		}catch(Exception e){
			log.error("更新课程信息失败，原因:" + e.getMessage(), e);
			return this.failedResult(e);
		}
	}
	
	@RequestMapping("validateLoginName")
	@ResponseBody
	public Map<String,Object> validateLoginName(User user){
		try{
			int result=userService.checkLoginName(user.getId(), user.getLoginName());
			if(result>0){
				return failedResult("该登录名在系统中已存在!");
			}else{
				return successResult("该登录名在系统中不存在");
			}
		}catch(Exception e){
			log.error("检查用户名是否存在失败,原因:"+e.getMessage(),e);
			return failedResult("检查用户名是否存在失败");
		}
	}
	
	@RequestMapping("/checkName")
	public void checkUserName(HttpServletRequest request,
			HttpServletResponse response,@RequestBody User user){
		int result=userService.checkLoginName(null,user.getLoginName());
		JSONObject object = new JSONObject();
		if(result==0){
			//表示该用户名数据库不存在
			object.put("type", "success");
		}else{
			object.put("type", "fail");
		}
		
		this.outJsonString(response, object.toString());
	}
	
	@RequestMapping("/resetPwd")
	public void resetPwd(HttpServletRequest request,
			HttpServletResponse response,@RequestBody User user){
		user.setPassword("123456");
		int result=userService.updatepassword(user);
		
		JSONObject object = new JSONObject();
		if(result>0){
			userService.initUserInfo();
			object.put("type", "success");
		}else{
			object.put("type", "fail");
		}
		
		this.outJsonString(response, object.toString());
	}
	
	
	@RequestMapping("/updateStatus/{operate}")
	public void updateStatus(HttpServletRequest request,
			HttpServletResponse response,@RequestBody User user,@PathVariable String operate){
		if(operate.equals("active")){
			user.setIsEnabled(1);
		}else{
			user.setIsEnabled(0);
		}
		int result=userService.updateisEnabled(user);
		JSONObject object = new JSONObject();
		if(result>0){
			userService.initUserInfo();
			object.put("type", "success");
		}else{
			object.put("type", "fail");
		}
		
		this.outJsonString(response, object.toString());
	}
	
	@RequestMapping("/editUser/{id}")
	public ModelAndView editUser(@PathVariable int id){
		User user=userService.findById(id);
		ModelAndView view = new ModelAndView("usercenter/user/userEdit");
		view.addObject("user", user);
        return view;
	}
	
	@RequestMapping(value = "/getById/{id}")
	@ResponseBody
	public User getById(@PathVariable Integer id){
		return userService.findById(id);
	}
	
	@RequestMapping("/editUserInfo")
	public void editUserInfo(HttpServletRequest request,
			HttpServletResponse response,@RequestBody String data){
		JSONObject object = new JSONObject();
		
		try{
			JSONObject obj = JSONObject.fromObject(data);
			JSONObject userObj = obj.getJSONObject("User");
			User user=(User)userObj.toBean(userObj, User.class);

			//修改用户信息
			userService.updateUser(user);
			
			//先删除用户与角色关联信息
			roleService.delByUserId(user.getId());
			
			String arrCourse = obj.getString("arrCourse");
			JSONArray arrayCourse=JSONArray.fromObject(arrCourse);
			
			String arrRole=obj.getString("arrRole");
			JSONArray arrayRole=JSONArray.fromObject(arrRole);
			for(int i=0;i<arrayRole.size();i++){
				//构造UserRole对象
				UserRole userRole=new UserRole(user.getId(),arrayRole.getInt(i));
				
				//新增用户与角色关联的信息
				roleService.insertUserRole(userRole);
			}
			
			//前端新建角色时,会赋予很多课程给具体某个老师
			for(int i=0;i<arrayCourse.size();i++){
				UserCourse uc=new UserCourse(user.getId(),arrayCourse.getInt(i));
				courseService.insertUserCourse(uc);
			}
			userService.initUserInfo();
			object.put("type", "success");
			this.outJsonString(response, object.toString());
		}catch(Exception e){
			object.put("type", "fail");
			this.outJsonString(response, object.toString());
		}
	}
	
	@RequestMapping("/getSelectRole/{user_id}")
	@ResponseBody
	public List<Role> getRole(@PathVariable int user_id){
		
		//得到所有角色信息
		List<Role> roles=roleService.getRolesByUserId(user_id);
		return roles;
	}
	
	@RequestMapping("/getSelectCourse/{id}")
	@ResponseBody
	public String getCourse(@PathVariable int id,HttpSession session){
		List<Course> myCourses = courseService.findCoursesByUserId(id);
		List<Integer> ls = new ArrayList<Integer>();
		for(int i=0;i<myCourses.size();i++){
			ls.add(myCourses.get(i).getId());
		}
		
		List<Course> courses=courseService.queryAllCourses();
		JSONArray array=new JSONArray();
		for(Course c:courses){
			JSONObject object=new JSONObject();
			if(ls.contains(c.getId())){
				object.put("selected", true);
			}
			object.put("id", c.getId());
			object.put("code", c.getCode());
			object.put("text", c.getName());
			array.add(object);
		}
		return array.toString();
	}
	
	@RequestMapping("/getEditRole/{id}")
	@ResponseBody
	public String getSelectRole(@PathVariable int id,HttpSession session){
		List<Role> roles = roleService.getRolesByUserId(id);
		List<Integer> ls = new ArrayList<Integer>();
		for(int i=0;i<roles.size();i++){
			ls.add(roles.get(i).getId());
		}
		
		List<Role> list=roleService.getAllRoles(null);
		JSONArray array=new JSONArray();
		for(Role c:list){
			JSONObject object=new JSONObject();
			if(ls.contains(c.getId())){
				object.put("selected", true);
			}
			object.put("id", c.getId());
			object.put("code", c.getCode());
			object.put("name", c.getName());
			array.add(object);
		}
		return array.toString();
	}
	
	@RequestMapping("/selectedId/{id}")
	public void selectedId(HttpServletRequest request,
			HttpServletResponse response,@PathVariable int id){
		List<Course> myCourses = courseService.findCoursesByUserId(id);
		List<Integer> ls = new ArrayList<Integer>();
		for(int i=0;i<myCourses.size();i++){
			ls.add(myCourses.get(i).getId());
		}
//		JSONArray array=new JSONArray();
//		array.add(ls);
		this.outJsonString(response, ls.toString());
	}
	
	@RequestMapping("/validateOldPassword")
	public void  validateOldPassword(HttpServletRequest request,
			HttpServletResponse response,@RequestBody User user){
		int result=userService.checkPassword(user);
		JSONObject object = new JSONObject();
		if(result>0){
			object.put("type", "success");
		}else{
			object.put("type", "fail");
		}
		this.outJsonString(response, object.toString());
	}
	
	@RequestMapping("/changePassword")
	public void  changePassword(HttpServletRequest request,
			HttpServletResponse response,@RequestBody String password){
		User user = (User) request.getSession().getAttribute(WebConstants.WEB_SESSION_USER);
		user.setPassword(password);
		int result=userService.updatepassword(user);
		JSONObject object = new JSONObject();
		if(result>0){
			object.put("result", true);
		}else{
			object.put("result", false);
		}
		this.outJsonString(response, object.toString());
	}
	
	
	/**
	 * 导入命题教师信息,前面因为已经将文件导入保存到磁盘,并且在数据库中有存储,现在只需要把数据库物理路径获取到,然后读取解析 再存储
	 * @param request
	 * @param response
	 * @param attId		附件表的id
	 */
	@RequestMapping(value="/upLoadUser")
	@ResponseBody
	public Map<String, Object> upLoadUser(HttpServletRequest request,HttpServletResponse response, @RequestParam int attId){
		Map<String, Object> result = new HashMap<String, Object>();
		
		InputStream is=null;
		try{
			Attachment att=attachmentService.getAttachmentById(attId);
			is=new FileInputStream(new File(att.getStorePath()));
			String fileName=att.getOriginalName();
			
			List<ImportBean> list=new ExcelOperate().readTeacherExcel(is, fileName);
			
			result = userService.saveImportUser(Consts.USER_TYPE_TEACHER, list);
			
		}catch(Exception e){
			log.error("导入命题教师");
		}finally{
			if(is!=null){
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	
	/**
	 * 导入用户
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/importUser/{userType}")
	@ResponseBody
	public Map<String, Object> importUser(HttpServletRequest request,HttpServletResponse response, @PathVariable Integer userType){
		Map<String, Object> result = new HashMap<String, Object>();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
		InputStream stream = null;
		try{
			stream = file.getInputStream();
			String fileName = file.getOriginalFilename();
			fileName = new String(fileName.getBytes(), "utf-8");
			
			List<ImportBean> list = new ArrayList<ImportBean>();
			
			switch(userType){
			case Consts.USER_TYPE_TEACHER:
				list=new ExcelOperate().readTeacherExcel(stream, fileName);
				break;
			case Consts.USER_TYPE_SECRETARY:
				list=new ExcelOperate().readSecretaryExcel(stream, fileName);
				break;
			case Consts.USER_TYPE_INPUTER:
				list=new ExcelOperate().readInputExcel(stream, fileName);
				break;
			}
			result = userService.saveImportUser(userType, list);
			
		}catch(Exception e){
			log.error("导入用户，用户类型：" + userType);
		}finally{
			if(stream != null){
				try {
					stream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	
	/**
	 * 导入学科秘书信息,前面因为已经将文件导入保存到磁盘,并且在数据库中有存储,现在只需要把数据库物理路径获取到,然后读取解析 再存储
	 * @param request
	 * @param response
	 * @param attId		附件表的id
	 */
	@RequestMapping(value="/upLoadSecretary")
	@ResponseBody
	public Map<String, Object> upLoadSecretary(HttpServletRequest request,HttpServletResponse response,@RequestParam int attId){
		Map<String, Object> result = new HashMap<String, Object>();
		
		InputStream is=null;
		try{
			Attachment att=attachmentService.getAttachmentById(attId);
			is=new FileInputStream(new File(att.getStorePath()));
			String fileName=att.getOriginalName();
			
			List<ImportBean> list=new ExcelOperate().readSecretaryExcel(is, fileName);
			
			result = userService.saveImportUser(Consts.USER_TYPE_SECRETARY, list);
					
		}catch(Exception e){
			log.error("导入课程失败");
		}finally{
			if(is!=null){
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	
	/**
	 * 导入录入员信息,前面因为已经将文件导入保存到磁盘,并且在数据库中有存储,现在只需要把数据库物理路径获取到,然后读取解析 再存储
	 * @param request
	 * @param response
	 * @param attId		附件表的id
	 */
	@RequestMapping(value="/upLoadInputer")
	@ResponseBody
	public Map<String, Object> upLoadInputer(HttpServletRequest request,HttpServletResponse response,@RequestParam int attId){
		Map<String, Object> result = new HashMap<String, Object>();
		InputStream is=null;
		try{
			Attachment att=attachmentService.getAttachmentById(attId);
			is=new FileInputStream(new File(att.getStorePath()));
			String fileName=att.getOriginalName();
			
			List<ImportBean> list=new ExcelOperate().readSecretaryExcel(is, fileName);
			
			result = userService.saveImportUser(Consts.USER_TYPE_INPUTER, list);
		}catch(Exception e){
			log.error("导入课程失败");
		}finally{
			if(is!=null){
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	
	
	/**
	 * 导入命题教师与课程关联关系信息,前面因为已经将文件导入保存到磁盘,并且在数据库中有存储,现在只需要把数据库物理路径获取到,然后读取解析 再存储
	 * @param request
	 * @param response
	 * @param attId		附件表的id
	 */
	@RequestMapping(value="/upLoadUserCourse")
	@ResponseBody
	public Map<String, Object> upLoadUserCourse(HttpServletRequest request,HttpServletResponse response,@RequestParam int attId){
		Map<String, Object> result = new HashMap<String, Object>();
		InputStream is=null;
		try{
			Attachment att=attachmentService.getAttachmentById(attId);
			is=new FileInputStream(new File(att.getStorePath()));
			String fileName=att.getOriginalName();
			
			List<ImportBean> list=new ExcelOperate().readTeacherCourseExcel(is, fileName);
			result = userService.saveImportUserCourse(list);
			
		}catch(Exception e){
			log.error("导入课程失败");
		}finally{
			if(is!=null){
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	
    @RequestMapping(value = "/secretaryList")
    public ModelAndView secretaryList(HttpServletRequest request, HttpSession session,UserQueryParams params) {
        Map<String, Object> result = new HashMap<String, Object>();
        return new ModelAndView(BASE_JSP_PATH + "secretaryList", result);
    }
    
	@RequestMapping(value="/querySecretarys")
	@ResponseBody
	public Map<String, Object> querySecretarys(UserQueryParams params){
		Map<String,Object> result = new HashMap<String, Object>();
		List<User> users = userService.querySecretarys(params);
		result.put("rows", users);
		result.put("total", params.getTotalNum());
		return result;
	}
	
    @RequestMapping(value = "/inputerList")
    public ModelAndView inputerList(HttpServletRequest request, HttpSession session,UserQueryParams params) {
        Map<String, Object> result = new HashMap<String, Object>();
        return new ModelAndView(BASE_JSP_PATH + "inputerList", result);
    }
    
	@RequestMapping(value="/queryInputers")
	@ResponseBody
	public Map<String, Object> queryInputers(UserQueryParams params){
		Map<String,Object> result = new HashMap<String, Object>();
		List<User> users = userService.queryInputers(params);
		result.put("rows", users);
		result.put("total", params.getTotalNum());
		return result;
	}
	
	@RequestMapping("/queryCurUserRole")
	@ResponseBody
	public Role queryCurUserRole(HttpSession session){
		return this.getCurRole(session);
	}
	
	/**
	 * 获取当前用户所有的角色Code，包括虚拟角色：QUES_AUDITOR、QUES_INPUTER
	 * @param session
	 * @return
	 */
	@RequestMapping("/queryCurAllRoleCodes")
	@ResponseBody
	public List<String> queryCurAllRoleCodes(HttpSession session) {
		List<String> roleCodes = new ArrayList<String>();
		roleCodes.add(this.getCurRole(session).getCode());
		if(roleService.isQuesAuditor(this.getCurUser(session).getId())){
			roleCodes.add(Consts.UserRoleCodes.QUES_AUDITOR);
		}
		if(roleService.isQuesInputer(this.getCurUser(session).getId())){
			roleCodes.add(Consts.UserRoleCodes.QUES_INPUTER);
		}
		return roleCodes;
	}
	
	@RequestMapping("/olUser")
	@ResponseBody
	public List<OLUser> olUser(){
		List<OLUser> result = new ArrayList<OLUser>(Consts.OLUserMap.values());
        return result;
	}
	
	@RequestMapping("/queryCurUser")
	@ResponseBody
	public User queryCurUser(HttpSession session) {
		return this.getCurUser(session);
	}
}
