package com.bcxin.ars.rest;

import com.alibaba.fastjson.JSONObject;
import com.bcxin.ars.dao.sys.MessageLogDao;
import com.bcxin.ars.dto.*;
import com.bcxin.ars.dto.report.ReportDataSearchDto;
import com.bcxin.ars.exception.ArsException;
import com.bcxin.ars.model.*;
import com.bcxin.ars.model.sb.UserBusinessType;
import com.bcxin.ars.rest.dto.AppAjaxResult;
import com.bcxin.ars.rest.util.ArsRestUtil;
import com.bcxin.ars.service.*;
import com.bcxin.ars.service.sys.ApprovalService;
import com.bcxin.ars.util.*;
import com.bcxin.ars.util.redis.RedisUtil;
import com.bcxin.zw.dao.ZWDao;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.text.DecimalFormat;
import java.util.*;

@Controller
@RequestMapping("user")
public class UserController {

	Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserService userService;

	@Autowired
	private SearchHistoryService searchHistoryService;
	@Autowired
	private MessageLogDao messageLogDao;
	@Autowired
	private ArsRestUtil arsUtil;

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private PermissionService permissionService;

	@Autowired
	private PoliceService policeService;

	@Autowired
	private ConfigService configService;
	@Autowired
	private SecurityPersonService securityPersonService;

	@Autowired
	private SecurityCompanyService securityCompanyService;

	@Autowired
	private LoginLogService loginLogService;

	@Autowired
	private PoliceRoleService policeRoleService;

	@Autowired
	private ApprovalService approvalService;
	@Autowired
	private ZWDao zwDao;

	@Value("${message-code-timeout}")
	private int messageCodeTimeout = 2;

    /**
     * 单位 ：天
     */
	@Value("${login-timeout}")
	private int loginTimeout = 10;

	@Value("${JWT_SECRET}")
	public String JWT_SECRET = ""; //私钥

	@Value("${BLB_PARTY}")
	public String BLB_PARTY ="ARS-NC";
	/**
	 * The Redis key prefix for the sessions
	 */
	private String keyPrefix = "ARS:shiro_redis_session:";
    @Value("${redis.shiro.expire}")
    public String  shiroExpire="0";
	/**
	 * 登录
	 * @param username
	 * @param password
	 * @return
	 */
	@RequestMapping(value="web/login", method=RequestMethod.POST)
	public @ResponseBody AjaxResult webLogin(@RequestParam(value="username", required=true)String username,
											 @RequestParam(value="password", required=true)String password, HttpServletRequest request, HttpServletResponse response) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			Subject currentUser = SecurityUtils.getSubject();
			token.setRememberMe(false);
			try {
				currentUser.login(token);
			} catch (AuthenticationException e) {
				logger.error(e.getMessage(), e);
				result.setSuccessful(false);
				result.setMsg("用户名/密码错误");
			}
			//判断是否登录成功！
			if(currentUser.isAuthenticated()){
				Session session=currentUser.getSession();
				User user = userService.findByUsername(username,null);
				logger.info("当前登录用户是："+user.getUsername());
				//功能权限
				if(user.getPlatform() == 1  ) {
					List list = permissionService.findByGAUserId(user.getId());
					//List arealist = policeService.findByAreaUserId(user);
					//用户与类型权限关系
					List userbusinesslist  =  approvalService.findAllUserBusinessType(user.getId());
					user.setUserBusinessTypeList(userbusinesslist);
					//user.setAreaslist(arealist);
					user.setPermissionList(list);
					Police police = policeService.findById(user.getOrgid());
					if(police!=null){
						user.setPolice(police);
					}



					/***
					 * 城市区域
					 */
					user.setCityAreaCode(police.getAreacode().substring(0,4)+"00");
				}else{
					List list = permissionService.findByUserId(user.getId());
					user.setPermissionList(list);
				}
				//更新一下登陆状态
				user.setLoginstate(1);
				//登录次数+1
				if( user.getLoginNum()!=null) {
					user.setLoginNum(user.getLoginNum()+1);
				}else{
					user.setLoginNum(1);
				}
				//登录时间为当前时间
				user.setLoginDate(new Date());

				//如果没有上传registrationID，就存USERID
				if( StringUtil.isEmpty(user.getRegistrationID())) {
					user.setRegistrationID(user.getId().toString());
				}
				userService.updateLoginState(user);
				Map<String,String> p = new HashMap<String,String>();
				//百保联加密
				p.put("userid", user.getId().toString());//用户iD
				String usertoken = JwtUtil.createJWT(p);//加密生成token
				user.setToken(usertoken+"&party="+BLB_PARTY);
				if(user.getPlatform() == 2){
					user.setCompanyUserId(user.getId());
					user.setCompanyUsername(user.getUsername());
				}
				user.setSessionId(session.getId().toString());
				arsUtil.setCurrentUser(user,1000*120*loginTimeout);
				result.setData(user);
				result.setSuccessful(true);
				loginLogService.logIn(request);
			}else{
				result.setSuccessful(false);
				result.setMsg("用户名/密码错误");
			}
		} catch (UnknownAccountException e) {
			logger.error(e.getMessage(), e);
			result.setSuccessful(false);
			result.setMsg("用户名/密码错误");
		} catch (IncorrectCredentialsException e) {
			logger.error(e.getMessage(), e);
			result.setSuccessful(false);
			result.setMsg("用户名/密码错误");
		} catch (ExcessiveAttemptsException e) {
			logger.error(e.getMessage(), e);
			result.setSuccessful(false);
			result.setMsg("登录失败多次，账户锁定10分钟");
		} catch (AuthenticationException e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 通过sid验证对应登录信息是否有效
	 * @param sid
	 * @return
	 */
	@RequestMapping(value="validateLogin", method=RequestMethod.POST)
	public @ResponseBody AjaxResult validateLogin(@RequestParam(value="sid", required=true)String sid) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			User user = arsUtil.getCurrentUser();
			if(user != null) {
				result.setSuccessful(true);
				result.setData(user);
			} else {
				result.setSuccessful(false);
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	@RequestMapping(value="getCurrentUser", method=RequestMethod.POST)
	public @ResponseBody AjaxResult getCurrentUser() throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			User currentUser = arsUtil.getCurrentUser();
			if(currentUser != null) {
				result.setSuccessful(true);
				User user = userService.findById(currentUser.getId());
				result.setData(user);
			} else {
				result.setSuccessful(false);
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/**
	 * <b>Function </b>登出
	 *
	 * @param sid
	 * @return
	 * @author LinQingLin
	 * @date 2017年2月6日 下午5:11:33
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping(value="logout", method=RequestMethod.POST)
	public @ResponseBody AjaxResult logOut(String sid, HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			//更新一下下线状态
			User user =   arsUtil.getCurrentUser();
			if(user!=null) {
				loginLogService.logOut(request);
				user.setLoginstate(0);
				user.setRegistrationID("");
				userService.updateLoginState(user);
			}

			Subject currentUser = SecurityUtils.getSubject();
			currentUser.logout();
			arsUtil.removeCurrentUser(request);
			result.setSuccessful(true);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 忘记密码
	 * @param username
	 * @param realname
	 * @param phone
	 * @param request
	 * @return
	 */
	@RequestMapping("forgetPwd")
	public @ResponseBody AjaxResult forgetPwd(@RequestParam(value="username", required=true)String username,
											  @RequestParam(value="realname", required=true)String realname,
											  @RequestParam(value="phone", required=true)String phone, HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			User user = userService.findByUsername(username,null);
			if(user != null) {
				//查询经办人号码
				SecurityCompany securityCompany = securityCompanyService.findByUserid(user.getId());

				if(user.getRealname().equals(realname.trim()) && (user.getPhone().equals(phone.trim())||securityCompany.getOperatorphone().equals(phone.trim()))) {
					int code = MessageUtil.sendMessageCode(phone,messageLogDao);
					//判断是向法人还是经办人发送验证码，保证法人经办人都能收到一致的验证码
					if(user.getPhone().equals(phone)){
						MessageUtil.sendMessageHaveCode(securityCompany.getOperatorphone(),messageLogDao,code);
					}else if(securityCompany.getOperatorphone().equals(phone)){
						MessageUtil.sendMessageHaveCode(user.getPhone(),messageLogDao,code);
					}
					redisUtil.set(code+"", username, (messageCodeTimeout*60));
					result.setSuccessful(true);
					result.setMsg("验证码已发送。");
					logger.debug(code+"");
				} else {
					result.setSuccessful(false);
					result.setMsg("信息不正确，请重新输入！");
				}
			} else {
				result.setSuccessful(false);
				result.setMsg("信息不正确，请重新输入！");
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 获取短信验证码
	 * @param request
	 */
	@RequestMapping("getop")
	public @ResponseBody AjaxResult getop(HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			User user = arsUtil.getCurrentUser();
			if(user != null) {
				//查询经办人号码
				SecurityCompany securityCompany = securityCompanyService.findByUserid(user.getId());
				result.setData(securityCompany);
				result.setSuccessful(true);
			} else {
				result.setSuccessful(false);
				result.setMsg("该用户不存在。");
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 获取短信验证码
	 * @param request
	 */
	@RequestMapping("getMessageCode")
	public @ResponseBody AjaxResult getMessageCode(String phone,HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			User user = arsUtil.getCurrentUser();
			if(user != null) {
				if (phone == null) {
					int code = MessageUtil.sendMessageCode(user.getPhone(),messageLogDao);
					redisUtil.set(code+"", user.getUsername(), (messageCodeTimeout*60));
				} else{
					//查询经办人号码
					String[] phoneArr = phone.split("/");
					int code = MessageUtil.sendMessageCode(phoneArr[0], messageLogDao);
					if(phone.split("/").length>1&&phoneArr[1]!=null&& !phoneArr[1].equals("") && !phoneArr[1].equals(phoneArr[0])){
						MessageUtil.sendMessageHaveCode(phoneArr[1], messageLogDao, code);
						redisUtil.set(code + "", user.getUsername(), (messageCodeTimeout * 60));
						//	redisUtil.set(code + "", phoneArr[1], (messageCodeTimeout * 60));
					}
					redisUtil.set(code + "", user.getUsername(), (messageCodeTimeout * 60));

				}

				result.setSuccessful(true);
				result.setMsg("验证码已发送。");
			} else {
				result.setSuccessful(false);
				result.setMsg("该用户不存在。");
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	@RequestMapping(value="verifyMessageCode", method=RequestMethod.POST)
	public @ResponseBody AjaxResult verifyMessageCode(@RequestParam(value="username", required=true)String username,
													  @RequestParam(value="messageCode", required=true)String messageCode, HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			String un = redisUtil.get(messageCode);
			if(un != null && un.equals(username)) {
				result.setSuccessful(true);
				result.setMsg("短信验证码正确.");
			} else {
				result.setSuccessful(false);
				result.setMsg("短信验证码错误.");
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 修改密码
	 * @param password
	 * @param messageCode
	 * @param request
	 * @return
	 */
	@RequestMapping(value="updatePwd", method=RequestMethod.POST)
	public @ResponseBody AjaxResult updatePwd(@RequestParam(value="username", required=true)String username,
											  @RequestParam(value="password", required=true)String password,
											  @RequestParam(value="messageCode", required=true)String messageCode,
											  @RequestParam(value="operatorphone", required=false)String operatorphone,
											  @RequestParam(value="operatorname", required=false)String operatorname,HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			logger.info(messageCode + "," + username);
			String un = redisUtil.get(messageCode);
			if(un != null && un.equals(username)) {
				User user = userService.findByUsername(username,null);
				if(user != null) {
					//法人填写经办人手机号码
					SecurityCompany securityCompany = securityCompanyService.findByUserid(user.getId());
					if(securityCompany!=null){
						if(operatorphone!=null&& !operatorphone.equals("")){
							securityCompany.setOperatorphone(operatorphone);
						}
						if(operatorname!=null&& !operatorname.equals("") ){
							securityCompany.setOperatorname(operatorname);
						}
						securityCompanyService.updateOperatorphone(securityCompany);
					}
					user.setPassword(Sha1Util.entryptPassword(password));
					user.setUpdateTime(new Date());
					user.setUpdateBy(user.getUsername());
					userService.updatePassword(user);
					result.setSuccessful(true);
				} else {
					result.setSuccessful(false);
					result.setMsg("用户信息错误.");
				}
			} else {
				result.setSuccessful(false);
				result.setMsg("短信验证码错误.");
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}


	/**
	 * 修改密码（公安内网专用）
	 * @param username
	 * @param password
	 * @param request
	 * @return
	 */
	@RequestMapping(value="editPwd", method=RequestMethod.POST)
	public @ResponseBody AjaxResult editPwd(@RequestParam(value="username", required=true)String username,
											@RequestParam(value="password", required=true)String password, HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			Config config = configService.findByKey("police");
			if (config.getValue().equals("1")) {//公安内网
				logger.info(username);
				User user = userService.findByUsername(username,null);
				if(user != null) {
					user.setPassword(Sha1Util.entryptPassword(password));
					user.setUpdateTime(new Date());
					user.setUpdateBy(user.getUsername());
					userService.updatePassword(user);
					result.setSuccessful(true);
				} else {
					result.setSuccessful(false);
					result.setMsg("用户信息错误.");
				}
			}else{
				throw new ArsException("非公安内网，无法使用此功能！");
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/**
	 * 完成初始化
	 * @param request
	 * @return
	 */
	@RequestMapping(value="finishInit", method=RequestMethod.POST)
	public @ResponseBody AjaxResult finishInit(HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			User user = arsUtil.getCurrentUser();
			if(user != null){
				User dbUser = userService.findByUsername(user.getUsername(),null);
				dbUser.setInit(true);
				dbUser.setInitstep(Constants.INTISTEP_ROL);
				userService.updateInitstep(dbUser);
				result.setSuccessful(true);
				dbUser.setSessionId(user.getSessionId());
				Subject currentUser = SecurityUtils.getSubject();
				Session session=currentUser.getSession();
				arsUtil.setCurrentUser(dbUser,(int)session.getTimeout());
				result.setData(dbUser);
			} else {
				result.setSuccessful(false);
				result.setMsg("当前用户信息错误");
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}

	/**
	 * 查询搜索历史
	 * <b>Function </b>
	 *
	 * @param dto
	 * @return
	 * @throws Exception
	 * @author LinQingLin
	 * @date 2017年8月1日 下午1:48:28
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping(value="searchHistory")
	public @ResponseBody AjaxResult searchHistory(HistorySearchDto dto) throws Exception{
		try {
			return searchHistoryService.searchHistory(dto);
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * 删除指定搜索历史
	 * <b>Function </b>
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 * @author LinQingLin
	 * @date 2017年8月1日 下午1:48:49
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping(value="deleteHistory")
	public @ResponseBody AjaxResult deleteHistory(long id) throws Exception{
		try {
			return searchHistoryService.deleteHistory(id);
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * 删除当前登录账号下的全部搜索历史
	 * <b>Function </b>
	 *
	 * @return
	 * @throws Exception
	 * @author LinQingLin
	 * @date 2017年8月1日 下午1:48:54
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping(value="deleteAllHistory")
	public @ResponseBody AjaxResult deleteAllHistory() throws Exception{
		try {
			return searchHistoryService.deleteAllHistory();
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * 根据手机号获取验证码
	 * <b>Function </b>
	 *
	 * @param phone
	 * @return
	 * @throws Exception
	 * @author LinQingLin
	 * @date 2017年8月1日 下午1:54:25
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping("getCodeByPhone")
	public @ResponseBody AjaxResult getCodeByPhone(String phone) throws Exception{
		AjaxResult result = new AjaxResult();
		try {
			String[] phoneArr = phone.split("/");
			int code = MessageUtil.sendMessageCode(phoneArr[0],messageLogDao);
			if(phone.split("/").length>1&&phoneArr[1]!=null&& !phoneArr[1].equals("") && !phoneArr[1].equals(phoneArr[0])){
				MessageUtil.sendMessageHaveCode(phoneArr[1],messageLogDao,code);
				redisUtil.set(code+"", phoneArr[1], (messageCodeTimeout*60));
			}
			redisUtil.set(code+"", phoneArr[0], (messageCodeTimeout*60));
			result.setSuccessful(true);
			result.setMsg("验证码已发送。");
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}


	@RequestMapping(value="verifyCode", method=RequestMethod.POST)
	public @ResponseBody AjaxResult verifyCode(@RequestParam(value="messageCode", required=true)String messageCode, HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			User user = arsUtil.getCurrentUser();
			String un = redisUtil.get(messageCode);
			if(user!=null){
				//查询经办人号码
				SecurityCompany securityCompany = securityCompanyService.findByUserid(user.getId());
//				if(un != null && un.equals(user.getPhone())||un.equals(securityCompany.getOperatorphone())) {
				if(un != null &&(un.equals(user.getPhone())|| (StringUtil.isNotEmpty(securityCompany.getOperatorphone()) && un.equals(securityCompany.getOperatorphone())))) {
					result.setSuccessful(true);
					result.setMsg("短信验证码正确.");
				} else {
					result.setSuccessful(false);
					result.setMsg("短信验证码错误.");
				}
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}
	/**
	 * 搜索用户列表
	 * <b>Function </b>
	 *
	 * @param dto
	 * @param request
	 * @return
	 * @throws Exception
	 * @author LinQingLin
	 * @date 2017年8月1日 下午1:54:39
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping("search")
	public @ResponseBody AjaxResult search(UserSearchDto dto, HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			UserSearchDto data = userService.search(dto);
			result.setSuccessful(true);
			result.setData(data);
		} catch(Exception e) {
			throw e;
		}
		return result;
	}

	/**
	 * 修改用户信息
	 * <b>Function </b>
	 *
	 * @param user
	 * @param roleIds
	 * @param request
	 * @return
	 * @throws Exception
	 * @author LinQingLin
	 * @date 2017年8月1日 下午1:54:54
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping("update")
	public @ResponseBody AjaxResult update(User user,Long[] roleIds, HttpServletRequest request) throws Exception{
		AjaxResult result = new AjaxResult();
		try {
			User currentUser = arsUtil.getCurrentUser();
			if(currentUser != null){
				user.setUsername(user.getIdNumber());
				List<PoliceRole> roleList = new ArrayList<PoliceRole>();
				if(roleIds != null && roleIds.length >0){

					PoliceRole role = null;
					for (Long roleId : roleIds) {
						role = new PoliceRole();
						role.setId(roleId);
						roleList.add(role);
					}


				}
				if(currentUser.getPlatform().intValue() == 1){
					//公安以警号为登陆名
					user.setUsername(user.getCodeNo());
				}
				//业务类型的值
				if(user.getBusinessTypes()!=null && !user.getBusinessTypes().equals("")){
					List userBusinessTypeList =  new ArrayList();
					String[] businessTypes =  user.getBusinessTypes().split("#");
					for (String type :
							businessTypes) {
						String[] arr = type.split("@");
						UserBusinessType temp = new UserBusinessType();
						temp.setBusinessType(arr[0]);
						temp.setTypeValue(arr[1]);
						String[] roleids =  arr[1].split(",");
						for(String roleId: roleids){
							PoliceRole role = new PoliceRole();
							role.setId(Long.parseLong(roleId));
							roleList.add(role);
						}
						userBusinessTypeList.add(temp);
					}
					user.setUserBusinessTypeList(userBusinessTypeList);
				}
				//角色
				user.setRoles(roleList);
				userService.saveOrUpdate(user,String.valueOf(currentUser.getPlatform()));
				result.setSuccessful(true);
			} else {
				result.setSuccessful(false);
				result.setMsg("当前用户信息错误");
			}
		} catch(Exception e) {
			throw e;
		}
		return result;
	}

	/**
	 * 重置密码
	 * <b>Function </b>
	 *
	 * @param user
	 * @param request
	 * @return
	 * @throws Exception
	 * @author LinQingLin
	 * @date 2017年8月1日 下午1:52:27
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping("resetPassword")
	public @ResponseBody AjaxResult resetPassword(User user, HttpServletRequest request) throws Exception{
		AjaxResult result = new AjaxResult();
		try {
			user.setPassword(Sha1Util.entryptPassword(user.getPassword()));
			userService.updatePasswordBypolice(user);
			result.setSuccessful(true);
		} catch(Exception e) {
			throw e;
		}
		return result;
	}

	/**
	 * 根据id获取用户信息
	 * <b>Function </b>
	 *
	 * @param id
	 * @param request
	 * @return
	 * @throws Exception
	 * @author LinQingLin
	 * @date 2017年8月1日 下午1:55:10
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping("findById/{id}")
	public @ResponseBody AjaxResult findById(@PathVariable("id")Long id, HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			User currentUser = arsUtil.getCurrentUser();
			if(currentUser != null){
				User user = userService.findById(id);
				if(user != null) {
					user.getRoles();
					result.setSuccessful(true);
					result.setData(user);
				} else {
					result.setSuccessful(false);
					result.setMsg("未找到指定用户信息。");
				}
			} else {
				result.setSuccessful(false);
				result.setMsg("当前用户信息错误");
			}
		} catch(Exception e) {
			throw e;
		}
		return result;
	}

	/**
	 * 根据id获取用户信息(用户管理专用)
	 * <b>Function </b>
	 *
	 * @param id
	 * @param request
	 * @return
	 * @throws Exception
	 * @author LinQingLin
	 * @date 2017年8月1日 下午1:55:33
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping("findByIdForManager/{id}")
	public @ResponseBody AjaxResult findByIdForManager(@PathVariable("id")Long id, HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			User currentUser = arsUtil.getCurrentUser();
			if(currentUser != null){
				User user = userService.findByIdForManager(id);
				if(user != null) {
					user.getRoles();
					result.setSuccessful(true);
					result.setData(user);
				} else {
					result.setSuccessful(false);
					result.setMsg("未找到指定用户信息。");
				}
			} else {
				result.setSuccessful(false);
				result.setMsg("当前用户信息错误");
			}
		} catch(Exception e) {
			throw e;
		}
		return result;
	}

	/**
	 * 删除用户
	 * <b>Function </b>
	 *
	 * @param userid
	 * @param request
	 * @return
	 * @throws Exception
	 * @author LinQingLin
	 * @date 2017年8月1日 下午1:55:53
	 * @注意事项 </b>
	 * <b>
	 */
	@RequestMapping("delete/{userid}")
	public @ResponseBody AjaxResult delete(@PathVariable Long userid, HttpServletRequest request) throws Exception {
		AjaxResult result = new AjaxResult();
		try{
			User currentUser = arsUtil.getCurrentUser();
			if(currentUser != null){
				if(currentUser.getId().equals(userid)){
					result.setSuccessful(false);
					result.setMsg("无法删除自己的账号！");
				}else{
					User user = userService.findById(userid);
					user.getRoles();
					userService.delete(user);
					result.setSuccessful(true);
				}
			} else {
				result.setSuccessful(false);
				result.setMsg("当前用户信息错误");
			}
		} catch(Exception e) {
			throw e;
		}
		return result;
	}


	@RequestMapping("findByAreaReport")
	public @ResponseBody AjaxResult findByAreaReport(ReportDataSearchDto searchDto) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			JSONObject resultObj = new JSONObject();
			DecimalFormat df = new DecimalFormat("#.0");
			List<ReportData> data = userService.findByAreaReport(searchDto);
			List<String> nameList = new ArrayList<String>();
			Long total = 0l;
			for (ReportData reportData : data) {
				total = total + reportData.getValue();
			}
			for (ReportData reportData : data) {
				System.out.println(reportData.getName()+ "  "+ reportData.getValue() +"人  " + df.format(reportData.getValue()*100.0/total)+"%");
//				nameList.add(reportData.getName());
				nameList.add(reportData.getName()+ "  "+ reportData.getValue() +"人  " + df.format(reportData.getValue()*100.0/total)+"%");
				reportData.setName(reportData.getName()+ "  "+ reportData.getValue() +"人  " + df.format(reportData.getValue()*100.0/total)+"%");
			}
			resultObj.put("names", nameList);
			resultObj.put("values", data);
			resultObj.put("total", total);
			result.setSuccessful(true);
			result.setData(resultObj);
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}


	/*********************************与SaaS对接start*******************************************/
	/**
	 * 修改密码（用于与SaaS对接）
	 * @param userDto 用户信息
	 * @return 是否执行成这功
	 */
	@RequestMapping(value="modify-pwd", method=RequestMethod.POST)
	public @ResponseBody AjaxResult modifyPwd(@Valid UserDto userDto) throws Exception {
		AjaxResult result = new AjaxResult();
		try {
			logger.info(userDto.getUsername());
			User user = userService.findByUsername(userDto.getUsername(),null);
			if(user != null) {
				user.setPassword(Sha1Util.entryptPassword(userDto.getPassword()));
				user.setUpdateTime(new Date());
				user.setUpdateBy(user.getUsername());
				userService.updatePassword(user);
				result.setSuccessful(true);
			} else {
				result.setSuccessful(false);
				result.setMsg("用户信息错误.");
			}
		} catch(Exception e) {
			logger.error(e.getMessage(),e);
			result.setSuccessful(false);
			result.setMsg(e.getMessage());
		}
		return result;
	}
	/**
	 * SaaS登录之后回调百保盾
	 * @param userDto 用户信息
	 * @return
	 */
	@RequestMapping(value="saas/login",method=RequestMethod.POST)
	public @ResponseBody
	AppAjaxResult saasLogin(@Valid UserDto userDto, HttpServletRequest request, HttpServletResponse response) {
		AppAjaxResult result = new AppAjaxResult();
		try {
			//判断saas传过来的sid是否为空
			if(StringUtil.isEmpty(userDto.getSid())){
				throw new ArsException("登录信息错误！");
			}
            /*sessonID加密规则：
            公司ID+用户名+密码+机构类别+失效日期：comId+username+password+orgType+expiresDate  (|分割,AES对称加密)
            */
			String sessionID = AESUtil.decode(userDto.getSid());
			String[] userInfos = sessionID.split("\\|");
			//公司ID
			String comId = userInfos[0];
			//密码
			String password = userInfos[2];
			User loginUser = new User();
			loginUser.setSid(userDto.getSid());
			loginUser.setComId(comId);
			loginUser.setPassword(password);
			result = userLogin(loginUser,request);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result.setMsg("用户名/密码错误");
		}
		return result;
	}


    /***
     * 登陆
     * @param loginUser 用户信息
     * @return
     * @throws Exception
     */
	private AppAjaxResult userLogin(User loginUser,HttpServletRequest request) throws Exception{
		AppAjaxResult result = new AppAjaxResult();
		UsernamePasswordToken token = new UsernamePasswordToken(loginUser.getComId(), loginUser.getPassword());
		Subject currentUser = SecurityUtils.getSubject();
		try {
			token.setRememberMe(true);
			token.setHost(Constants.SaaSCode);
			try {
				currentUser.login(token);
			} catch (AuthenticationException e) {
				logger.error(e.getMessage(), e);
				result.setSuccessful(false);
				result.setMsg("用户名/密码错误");
				return result;
			}
			// 判断是否登录成功！
			if (currentUser.isAuthenticated()) {
				Session session = currentUser.getSession();
				SecurityCompany securityCompany = securityCompanyService.findByComId(Long.parseLong(loginUser.getComId()));
				if (securityCompany == null) {
					logger.error("公共安全服务平台公司id(" + loginUser.getComId() + ")不存在");
				}
				User user = securityCompany.getUser();
				user.setComId(loginUser.getComId());
				logger.info("当前登录用户是：" + user.getUsername());
				user.setSessionId(session.getId().toString());
				/***
				 * saas的SID
				 */
				//如果有key先做删除操作，再设置redis
				if (StringUtil.isNotEmpty(redisUtil.get(keyPrefix + loginUser.getSid()))) {
					redisUtil.delete(keyPrefix + loginUser.getSid());
				}
				if (Integer.valueOf(shiroExpire) != 0) {
                    redisUtil.set(keyPrefix + loginUser.getSid(), session.getId().toString(), Integer.valueOf(shiroExpire));
                }else{
                    redisUtil.set(keyPrefix + loginUser.getSid(), session.getId().toString());
                }
				arsUtil.setCurrentUser(user, -1000);
				result.setEncodeData(user);
				result.setSuccessful(true);
				// 更新一下登陆状态
				user.setLoginstate(1);
				// 登录次数+1
				if (user.getLoginNum() != null) {
					user.setLoginNum(user.getLoginNum() + 1);
				} else {
					user.setLoginNum(1);
				}
				// 登录时间为当前时间
				user.setLoginDate(new Date());
				if (StringUtil.isNotEmpty(loginUser.getUuid())) {
					user.setUuid(loginUser.getUuid());
				}
				// 如果没有上传registrationID，就存USERID
				if (loginUser.getRegistrationID() != null) {
					user.setRegistrationID(loginUser.getRegistrationID() + user.getId());
				} else {
					user.setRegistrationID(user.getId().toString());
				}
				userService.updateLoginState(user);
				loginLogService.logIn(request);

			} else {
				result.setSuccessful(false);
				result.setMsg("用户名/密码错误");
			}
		} catch (UnknownAccountException e) {
			logger.error(e.getMessage(), e);
			result.setSuccessful(false);
			result.setMsg("用户名/密码错误");
		} catch (IncorrectCredentialsException e) {
			logger.error(e.getMessage(), e);
			result.setSuccessful(false);
			result.setMsg("用户名/密码错误");
		} catch (ExcessiveAttemptsException e) {
			logger.error(e.getMessage(), e);
			result.setSuccessful(false);
			result.setMsg("登录失败多次，账户锁定10分钟");
		} catch (AuthenticationException e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
		return result;
	}


	/**
	 * SaaS公司登录
	 * @param comId saas公司id信息
	 * @return
	 */
	@RequestMapping(value="saas/com/login",method=RequestMethod.POST)
	public @ResponseBody
	AppAjaxResult saasComLogin(String comId,HttpServletRequest request) {
		AppAjaxResult result = new AppAjaxResult();
		try {
			String companyId = AESUtil.decode(comId);
			UsernamePasswordToken token = new UsernamePasswordToken(companyId,StringUtil.EMPTY);
			Subject currentUser = SecurityUtils.getSubject();
			try {
				token.setRememberMe(true);
				token.setHost(Constants.SaaSCode);
				try {
					currentUser.login(token);
				} catch (AuthenticationException e) {
					logger.error(e.getMessage(), e);
					result.setSuccessful(false);
					result.setMsg("用户名/密码错误");
					return result;
				}
				// 判断是否登录成功！
				if (currentUser.isAuthenticated()) {
					Session session = currentUser.getSession();
					SecurityCompany securityCompany = securityCompanyService.findByComId(Long.parseLong(companyId));
					if(securityCompany == null){
						logger.error("公共安全服务平台公司id("+comId+")不存在");
					}
					User user = securityCompany.getUser();
					logger.info("当前登录用户是：" + user.getUsername());
					user.setSessionId(session.getId().toString());

					JSONObject sessionInfo = new JSONObject();
					sessionInfo.put("sid",session.getId());
					sessionInfo.put("timeout",DateUtil.convertDateToString(DateUtil.dateAdd(DateUtil.DATATYPE_DAY,new Date(),loginTimeout),DateUtil.FORMAT1));
					//redisUtil.set( keyPrefix + session.getId(),session.getId().toString(),loginTimeout, TimeUnit.DAYS);
                    //与shiro的会话超时时间保持一致
                    if(Integer.valueOf(shiroExpire)!=0) {
                        redisUtil.set(keyPrefix + session.getId(), session.getId().toString(), Integer.valueOf(shiroExpire));
                    }else{
                        redisUtil.set(keyPrefix + session.getId(), session.getId().toString());
                    }
					//天转毫秒
					arsUtil.setCurrentUser(user, loginTimeout*24*60*60*1000);
					result.setSuccessful(true);
					result.setData(sessionInfo);
					// 更新一下登陆状态
					user.setLoginstate(1);
					// 登录次数+1
					if (user.getLoginNum() != null) {
						user.setLoginNum(user.getLoginNum() + 1);
					} else {
						user.setLoginNum(1);
					}
					// 登录时间为当前时间
					user.setLoginDate(new Date());
					userService.updateLoginState(user);
					loginLogService.logIn(request);

				} else {
					result.setSuccessful(false);
					result.setMsg("用户名/密码错误");
				}
			} catch (UnknownAccountException e) {
				logger.error(e.getMessage(), e);
				result.setSuccessful(false);
				result.setMsg("用户名/密码错误");
			} catch (IncorrectCredentialsException e) {
				logger.error(e.getMessage(), e);
				result.setSuccessful(false);
				result.setMsg("用户名/密码错误");
			} catch (ExcessiveAttemptsException e) {
				logger.error(e.getMessage(), e);
				result.setSuccessful(false);
				result.setMsg("登录失败多次，账户锁定10分钟");
			} catch (AuthenticationException e) {
				logger.error(e.getMessage(), e);
				throw e;
			}
			return result;


		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result.setMsg("用户名/密码错误");
		}
		return result;
	}
	/*********************************与SaaS对接end*******************************************/
}
