package com.qmth.qrzk.web.controller;

import java.util.ArrayList;
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.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.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.impl.CourseServiceImpl;
import com.qmth.qrzk.repository.user.service.impl.UserServiceImpl;
import com.qmth.qrzk.repository.utils.Consts;

@Controller
@RequestMapping("/teacher")
public class TeacherController extends BaseAjaxController {

	private static final Logger log = Logger.getLogger(TeacherController.class);
	
	@Autowired
	private UserServiceImpl userService;
	
	@Autowired
	private CourseServiceImpl courseService;
	
	@Autowired
	@Qualifier("roleServiceImpl")
	private IRoleService roleService;
	
	private static final String BASE_JSP_PATH = "usercenter/teacher/";
	
    @RequestMapping(value = "/list")
    public ModelAndView list(HttpServletRequest request, HttpSession session,UserQueryParams params) {
        Map<String, Object> result = new HashMap<String, Object>();
        return new ModelAndView(BASE_JSP_PATH + "list", result);
    }
    
	@RequestMapping(value="/queryUsers")
	@ResponseBody
	public Map<String, Object> queryUsers(UserQueryParams params){
		Map<String,Object> result = new HashMap<String, Object>();
		params.setUserType(Consts.USER_TYPE_TEACHER);
		List<User> users = userService.queryTeachers(params);
		result.put("rows", users);
		result.put("total", params.getTotalNum());
		return result;
	}
	
	@RequestMapping(value="/queryTeacher",method={RequestMethod.POST})
	@ResponseBody
	public Map<String,Object> validateChange(){
		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 = "/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);
			}
			return this.successResult(null);
		}catch(Exception exp){
			log.error("更新用户(userId=" + userId + ")关联的角色信息失败，原因:" + exp.getMessage(), exp);
			return this.failedResult(exp);
		}
	}
	
	@RequestMapping(value="/saveLinkSubject")
	@ResponseBody
	public Map<String,Object> saveLinkSubject(HttpServletRequest request,int userId, @RequestParam(value = "links[]",required = false)String[] links){
		try{
			List<UserCourse> list=new ArrayList<UserCourse>();
			if(links!=null){
				for(String s:links){
					UserCourse uc=new UserCourse(userId,Integer.parseInt(s));
					list.add(uc);
				}
			}
			courseService.updateUserCourses(userId,list);
			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,User user){
		try{
			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{
				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("/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){
			object.put("type", "success");
		}else{
			object.put("type", "fail");
		}
		
		this.outJsonString(response, object.toString());
	}
	
	@RequestMapping("/expForClient")
	@ResponseBody
	public Map<String,Object> expForClient(HttpSession session){
		try{
			Attachment att = userService.expForClient(this.getCurUser(session));
			Map<String,Object> result = successResult("生成导出文件成功。");
			result.put("attId", att.getId());
			return result;
		}catch(Exception e){
			log.error("生成导出文件失败!，原因:" + e.getMessage(), e);
			return failedResult(e);
		}
	}
	
	
	@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){
			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("/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);
			}
			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 User user){
		int result=userService.updatepassword(user);
		JSONObject object = new JSONObject();
		if(result>0){
			object.put("type", "success");
		}else{
			object.put("type", "fail");
		}
		this.outJsonString(response, object.toString());
	}
}
