package com.qmth.qrzk.web.controller;

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.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.qmth.qrzk.dao.repositories.UserRepo;
import com.qmth.qrzk.repository.constants.WebConstants;
import com.qmth.qrzk.repository.service.query.UserQueryParams;
import com.qmth.qrzk.repository.user.model.Paper;
import com.qmth.qrzk.repository.user.model.Role;
import com.qmth.qrzk.repository.user.model.User;
import com.qmth.qrzk.repository.user.model.UserRole;
import com.qmth.qrzk.repository.user.service.IRoleService;
import com.qmth.qrzk.repository.user.service.IUserService;

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

	@Autowired
	@Qualifier("userServiceImpl")
	private IUserService userService;
	
	@Autowired
	@Qualifier("roleServiceImpl")
	private IRoleService roleService;
	
	@Autowired private UserRepo userRepo;
	
	private static final String BASE_JSP_PATH = "usercenter/user/";
	
    @RequestMapping(value = "/list")
    public ModelAndView list(HttpServletRequest request, HttpSession session) {
        Map<String, Object> result = new HashMap<String, Object>();
        List<Role> roles = roleService.getAllRoles();
        result.put("roles", roles);
        return new ModelAndView(BASE_JSP_PATH + "list", result);
    }
    
	@RequestMapping(value="/queryUsers")
	@ResponseBody
	public Map<String , Object> queryUsers(@RequestBody UserQueryParams u){
		//return userRepo.findAll(new Sort(new Order(Direction.DESC, "isEnabled")));
		Map<String, Object> result = new HashMap<String, Object>();
		List<User> list = userService.queryUsers(u);
		int total = userService.queryUsersCount(u);
		if (list.size() > 0) {
			result.put("rows", list);
			result.put("total", total);
		} else {
			result.put("rows", "");
			result.put("total", 0);
		}
		return result;
	}

	@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);
    	
    	ModelAndView view = new ModelAndView("usercenter/user/info");
        view.addObject("user", user);
        view.addObject("role", role);
        view.addObject("lastLoginDate", lastLoginDate);
        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 ="/getAllRole")
	@ResponseBody
	public String queryRoles(){
		List<Role> roles=roleService.getAllRoles();
		JSONArray array=new JSONArray();
		for(Role r:roles){
			JSONObject object=new JSONObject();
			object.put("id", r.getId());
			object.put("text", r.getName());
			array.add(object);
		}
		return array.toString();
	}
	
	@RequestMapping("/addUser")
	public void addUser(HttpServletRequest request,
			HttpServletResponse response,@RequestBody String data){
		JSONObject object = new JSONObject();
		
		try{
			JSONObject userObj = JSONObject.fromObject(data);
			User user=(User)userObj.toBean(userObj, User.class);

			int result=userService.checkUserName(user.getLoginName());
			if(result==0){
				//表示该用户名数据库不存在
				user.setPassword("123456");
				user.setIsEnabled(1);
				//新增用户信息并返回数据库对应的用户id
				userRepo.save(user);
				
				UserRole userRole=new UserRole(user.getId(), Integer.parseInt(userObj.getString("role")));
				//新增用户与角色关联的信息
				roleService.insertUserRole(userRole);
				
				object.put("result", true);
				this.outJsonString(response, object.toString());
			}else{
				object.put("result", false);
				object.put("msg", "登录名已存在");
				this.outJsonString(response, object.toString());
			}
		}catch(Exception e){
			e.printStackTrace();
			object.put("result", false);
			this.outJsonString(response, object.toString());
		}
	}
	
	@RequestMapping("/checkName")
	public void checkUserName(HttpServletRequest request,
			HttpServletResponse response,@RequestBody User user){
		int result=userService.checkUserName(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("result", true);
		}else{
			object.put("result", false);
		}
		
		this.outJsonString(response, object.toString());
	}
	
	
	@RequestMapping("/updateStatus/{userId}/{operate}")
	public void updateStatus(HttpServletRequest request,
			HttpServletResponse response,@PathVariable Integer userId,@PathVariable String operate){
		User user = userRepo.findOne(userId);
		
		if(operate.equals("active")){
			user.setIsEnabled(1);
		}else{
			user.setIsEnabled(0);
		}
		
		userRepo.save(user);
		
		JSONObject object = new JSONObject();
		object.put("result", true);
		this.outJsonString(response, object.toString());
	}
	
	@RequestMapping("/editUser/{id}")
	@ResponseBody
	public User editUser(@PathVariable int id){
		User user=userService.findById(id);
        return user;
	}
	
	@RequestMapping("/editUserInfo")
	public void editUserInfo(HttpServletRequest request,
			HttpServletResponse response,@RequestBody String data){
		JSONObject object = new JSONObject();
		
		try{
			JSONObject userObj = JSONObject.fromObject(data);
			User user=(User)userObj.toBean(userObj, User.class);

			//修改用户信息
			userService.updateUser(user);
			
			//先删除用户与角色关联信息
			roleService.delByUserId(user.getId());
			
			//先删除用户与课程关联信息
			//courseService.delUserCourseByUserId(user.getId());
			UserRole userRole=new UserRole(user.getId(), Integer.parseInt(userObj.getString("role")));
			roleService.insertUserRole(userRole);
			
			object.put("result", true);
			this.outJsonString(response, object.toString());
		}catch(Exception e){
			object.put("result", false);
			this.outJsonString(response, object.toString());
		}
	}
	
	@RequestMapping("/getSelectRole/{id}")
	@ResponseBody
	public String getRole(@PathVariable int id){
		//根据用户id得到一组角色id
		List<Integer> ls=roleService.getRoleIds(id);
		
		//得到所有角色信息
		List<Role> roles=roleService.getAllRoles();
		JSONArray array=new JSONArray();
		for(Role r:roles){
			JSONObject object=new JSONObject();
			if(ls.contains(r.getId())){
				object.put("selected", true);
			}
			object.put("id", r.getId());
			object.put("text", r.getName());
			array.add(object);
		}
		return array.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(value="/changePassword", method=RequestMethod.POST)
	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());
	}
	
	@RequestMapping("/queryCurUserRole")
	@ResponseBody
	public Role queryCurUserRole(HttpSession session) {
		return (Role)session.getAttribute(WebConstants.WEB_SESSION_ROLE);
	}
}
