package cn.service.system.impl;

import cn.constant.CommonConst;
import cn.pojo.vo.LoginUser;
import cn.schedule.core.AsyncManager;
import cn.common.exception.BaseException;
import cn.common.exception.UserException;
import cn.logger.AsyncLoggingFactory;
import cn.component.RedisKit;
import cn.util.core.IsKit;
import cn.util.core.TypeKit;
import cn.util.il8n.Il8nMsgKit;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Repository;

import cn.service.system.IFacadeService;
import cn.service.token.JwtTokenService;

import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Repository("IFacadeService")
public class FacadeServiceImpl implements IFacadeService
{
	@Resource
	private JwtTokenService tokenService;
	@Resource
	private RedisKit redisCache;
	@Resource
	private AuthenticationManager authenticationManager;

	/**
	 * 删除用户身份信息
	 */
	@Override
	public void delLoginUser(String token) 
	{
		if (StringUtils.isNotEmpty(token)) {
			String userKey = tokenService.getTokenKey(token);
			redisCache.deleteObject(userKey);
		}
	}



	/**更新缓存内的用户身份信息*/
	@Override
	public void setLoginUser(LoginUser loginUser) 
	{
		if (IsKit.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) {
			tokenService.refreshToken(loginUser);
		}
	}
	/**
	 * 获取用户身份信息
	 * @return 用户信息
	 */
	@Override
	public LoginUser getLoginUser(HttpServletRequest request) 
	{
		return tokenService.getLoginUser(request);
		
	}
	/**依据给定Token返回用户登录信息*/
	@Override
	public LoginUser getLoginUser(String token) 
	{
		return tokenService.getLoginUser(token);
	}

	/**
	 * 验证码校验
	 * @param loginBody 登录信息
	 * @return 结果 验证码是否正确
	 */
	@Override
	public String verifyCode(Map<String, String> loginBody)  {
		try {
			if(IsKit.isNullOrEmpty(loginBody)) {
				AsyncManager.me().execute(AsyncLoggingFactory.insertLoginInfo("空", CommonConst.LOGIN_FAIL,Il8nMsgKit.message("param.page.empty")));
			}
		}catch (UserException e) {
			throw new UserException("param.page.empty", null);
		}finally {
			if (IsKit.isNullOrEmpty(loginBody)) {
				return "ParamEmpty";
			}
		}
		String username = loginBody.get("userName");
		String code = loginBody.get("captcha");
		String uuid = loginBody.get("uuid");
		//验证验证码
		String verifyKey = CommonConst.CAPTCHA_CODE_KEY + uuid;
		//获取预存验证码
		String captcha = TypeKit.objToStr(redisCache.getCacheObject(verifyKey));
		redisCache.deleteObject(verifyKey);

		try {
			if (IsKit.isNullOrEmpty(captcha)) {
				AsyncManager.me().execute(AsyncLoggingFactory.insertLoginInfo(username, CommonConst.LOGIN_FAIL, Il8nMsgKit.message("user.jcaptcha.expire")));
			}
		}catch (UserException e) {
			throw new UserException("user.jcaptcha.expire", null);
		}finally {
			if (IsKit.isNullOrEmpty(captcha)) {
				return "CodeExpire";
			}
		}

		try {
			if (!code.equalsIgnoreCase(captcha)) {
				AsyncManager.me().execute(AsyncLoggingFactory.insertLoginInfo(username, CommonConst.LOGIN_FAIL, Il8nMsgKit.message("user.jcaptcha.error")));
			}
		}catch (UserException e) {
			throw new UserException("user.jcaptcha.error", null);
		}finally {
			if (!code.equalsIgnoreCase(captcha)) {
				return "CodeError";
			}
		}
		return null;
	}

	/**
	 * 登录验证 成功返回Token
	 * @return 结果Map<String,String>
	 */
	@Override
	public String loginToken(Map<String,String> loginBody)
	{
		String username = loginBody.get("userName");
		String password = loginBody.get("password");
		//验证码已通过验证。验证用户验证
		Authentication authentication;
		try {
			//该方法调用cn.service.security.auth.UserDetailsServiceImpl.loadUserByUsername
			authentication = authenticationManager
					.authenticate(new UsernamePasswordAuthenticationToken(username, password));
		} catch (Exception e) {
			if (e instanceof BadCredentialsException) {
				try {
					AsyncManager.me().execute(AsyncLoggingFactory.insertLoginInfo(username, CommonConst.LOGIN_FAIL, Il8nMsgKit.message("user.password.not.match")));
				}catch (UserException e1) {
					throw new UserException("user.password.not.match", null);
				}finally {
					return "PasswordError";
				}
				//AsyncManager.me().execute(AsyncLoggingFactory.insertLoginInfo(username, CommonConst.LOGIN_FAIL, Il8nMsgKit.message("user.password.not.match")));
				//throw new UserException("user.password.not.match", null);
			}
			else {
				AsyncManager.me().execute(AsyncLoggingFactory.insertLoginInfo(username, CommonConst.LOGIN_FAIL, e.getMessage()));
				throw new BaseException(e.getMessage());
			}
		}
		//保存登录信息
		AsyncManager.me().execute(AsyncLoggingFactory.insertLoginInfo(username, CommonConst.LOGIN_SUCCESS, Il8nMsgKit.message("user.login.success")));
		LoginUser loginUser = (LoginUser) authentication.getPrincipal();
		//生成token
		return tokenService.createToken(loginUser);
	}
}

