package com.xintong.visualinspection.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.xintong.visualinspection.bean.User;
import com.xintong.visualinspection.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.context.SecurityContextHolder;
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.RestController;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xintong.system.err.BusinessException;
import com.xintong.system.securityTools.RedisCacheUtil;
import com.xintong.visualinspection.service.AuthService;
import com.xintong.visualinspection.service.RoleService;
import com.xintong.visualinspection.util.CacheUtil;

/**
 * 文件名：TestController
 * 版本信息：日期：2017/3/30 Copyright 江苏省交通规划设计院 Corporation 2017 版权所有.
 */
/**
 * @author wenhongquan
 *
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private AuthService authService;
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private RedisCacheUtil redisCacheUtil;
    
    @Value("${jwt.header}")
    private String tokenHeader;

    @RequestMapping(value = "/auth/login",method=RequestMethod.POST,produces="application/json;charset=UTF-8")
    public String login(@RequestBody User user){
    	User u = authService.login(user.getUsername(), user.getPassword());
    	u.setOrganname(CacheUtil.getOrgannameFromMap(new Long(u.getOrganid())));
    	u.setPassword(null);
        return returnSuccessResult("登陆成功", u);
    }
    
   
    
    @RequestMapping(value = "/logout",method=RequestMethod.GET,produces="application/json;charset=UTF-8")
    public String logout(){
    	//获取用户名
    	String username = SecurityContextHolder.getContext().getAuthentication().getName();
    	if(username!=null){
    		redisCacheUtil.removeForUserName(username);
    	}
    	//返回成功
    	return returnResult(0, "退出成功", null);
    }


    
    /**
     * 添加用户
     * @return
     * String
     * @exception
     * @since  1.0.0
     */
    @RequestMapping(value = "/addUser",method=RequestMethod.POST,produces="application/json;charset=UTF-8")
    public String addUser(@RequestBody User user) throws Exception{
    	user.setPassword(new Md5PasswordEncoder().encodePassword(user.getPassword(), null));
    	userService.insert(user);
    	List<User> us=userService.getUsers(user);
    	if(us.size()==1){
    		if(user.getRoleids()!=null){
        		for(String id:user.getRoleids()){
        			roleService.roleBindUser(Integer.parseInt(id), us.get(0).getId());
        		}
        	}
    	}
    	CacheUtil.refreshUserMap(userService);
    	return returnResult(0, "添加成功", null);
    }
    
    /**
     * 修改用户
     * @return
     * String
     * @exception
     * @since  1.0.0
     */
    @RequestMapping(value = "/updateUser/{userid}",method=RequestMethod.PUT,produces="application/json;charset=UTF-8")
    public String updateUser(@RequestBody User user,@PathVariable int userid){
        try{
        	user.setId(userid);
        	if(user.getPassword()!=null && user.getPassword()!=""){
        		user.setPassword(new Md5PasswordEncoder().encodePassword(user.getPassword(), null));
        	}else{
        		user.setPassword(null);
        	}
        	if(user.getRoleids()!=null){
        		roleService.roleUnBindUser(user.getId());
        		for(String id:user.getRoleids()){
        			roleService.roleBindUser(Integer.parseInt(id), user.getId());
        		}
        	}
        	userService.update(user);
        	CacheUtil.refreshUserMap(userService);
        	return super.returnResult(0, "修改成功", null);
        }catch(Exception e){
        	throw new BusinessException(20003);
        }
    }
    
    /**
     * 删除用户（软删除）
     * @return
     * String
     * @exception
     * @since  1.0.0
     */
    @RequestMapping(value = "/deleteUser/{userid}",method=RequestMethod.DELETE,produces="application/json;charset=UTF-8")
    public String deleteUser(@PathVariable Integer userid){
        try{
        	userService.delete((userid));
        	CacheUtil.refreshUserMap(userService);
        	return returnResult(0, "删除成功", null);
        }catch(Exception e){
        	throw new BusinessException(20002);
        }
    }
    
    /**
     * 获取所用用户
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/get/all/{page}/{size}",method=RequestMethod.GET,produces="application/json;charset=UTF-8")
    public String getallUsers(@PathVariable Integer page,@PathVariable Integer size ,HttpServletRequest request){
        try{
        	
        	PageHelper.startPage(page, size); 
        	List<User> users= userService.getAll();
        	
        	
        	return returnResult(0, "获取成功", new PageInfo(users));
        }catch(Exception e){
        	throw new BusinessException(20001);
        }
    }
    
    @RequestMapping(value = "/getUserList",method=RequestMethod.POST,produces="application/json;charset=UTF-8")
    public String getUsers(@RequestBody User user){
        try{
        	List<User> users= userService.getUsers(user);
        	
        	return returnResult(0, "获取成功", users);
        }catch(Exception e){
        	throw new BusinessException(20001);
        }
    }

    @RequestMapping(value = "/getUserInfo",method=RequestMethod.GET,produces="application/json;charset=UTF-8")
    public String getUserInfo(HttpServletRequest request){
        User user = getCurrentUser(request);
        user.setOrganname(CacheUtil.getOrgannameFromMap(new Long(user.getOrganid())));
        user.setPassword(null);
        return returnResult(0, "获取成功", user);
    }


    @RequestMapping(value = "/getUserById/{userid}",method=RequestMethod.GET,produces="application/json;charset=UTF-8")
    public String getUser(@PathVariable Integer userid){
        User u = userService.getOne(userid);
    	return returnResult(0, "获取成功", u);
    }
    
    @RequestMapping(value = "/getAllCheckman",method=RequestMethod.POST,produces="application/json;charset=UTF-8")
    public String getAllCheckman(){
        try{
        	List<User> users= userService.getAllCheckmans();
        	return returnResult(0, "获取成功", users);
        }catch(Exception e){
        	throw new BusinessException(20001);
        }
    }
    
    @RequestMapping(value = "/getFsUserList",method=RequestMethod.POST,produces="application/json;charset=UTF-8")
    public String getFsUsers(@RequestBody User user){
        try{
        	List<User> users= userService.getFsUserByDeptId(user);
        	
        	return returnResult(0, "获取成功", users);
        }catch(Exception e){
        	throw new BusinessException(20001);
        }
    }
    
    @RequestMapping(value = "/getWGUserList",method=RequestMethod.POST,produces="application/json;charset=UTF-8")
    public String getWGUserList(@RequestBody User user){
        try{
        	List<User> users= userService.getWGUserByDeptId(user);
        	
        	return returnResult(0, "获取成功", users);
        }catch(Exception e){
        	throw new BusinessException(20001);
        }
    }
}
