package com.yunfeiyun.agmp.common.framework.web.service;
import com.yunfeiyun.agmp.common.constant.Constants;
import com.yunfeiyun.agmp.common.constant.ErrorCode;
import com.yunfeiyun.agmp.common.exception.SsoException;
import com.yunfeiyun.agmp.common.core.domain.entity.SysUser;
import com.yunfeiyun.agmp.common.core.domain.model.PortalInfo;
import com.yunfeiyun.agmp.common.enums.RedisCacheKey;
import com.yunfeiyun.agmp.common.framework.manager.AsyncFactory;
import com.yunfeiyun.agmp.common.framework.manager.AsyncManager;
import com.yunfeiyun.agmp.common.framework.manager.RedisCacheManager;
import com.yunfeiyun.agmp.common.framework.security.context.AuthenticationContextHolder;
import com.yunfeiyun.agmp.common.utils.DateUtils;
import com.yunfeiyun.agmp.common.utils.MessageUtils;
import com.yunfeiyun.agmp.common.utils.ServletUtils;
import com.yunfeiyun.agmp.common.utils.StringUtils;
import com.yunfeiyun.agmp.common.core.domain.model.LoginUser;
import com.yunfeiyun.agmp.common.utils.ip.AddressUtils;
import com.yunfeiyun.agmp.common.utils.ip.IpUtils;
import com.yunfeiyun.agmp.common.utils.spring.SpringUtils;
import com.yunfeiyun.agmp.common.utils.uuid.IdUtils;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
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.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author 杨晓辉
 */
@Component("tokenService")
public class TokenService
{
    private static final Logger log = LoggerFactory.getLogger(TokenService.class);
    @Autowired
    private PortalService portalService;


    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = Integer.parseInt(SpringUtils.getRequiredProperty("token.expireTime")) * 60 * 1000L;

    @Autowired
    private RedisCacheManager redisCacheManager;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            try
            {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(portalService.getClaimsKey());
                String userKey = getTokenKey(uuid);
                LoginUser user = redisCacheManager.getCacheObject(RedisCacheKey.SYS_LOGIN_TOKEN,userKey);
                return user;
            }
            catch (Exception e)
            {
            }
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser)
    {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken()))
        {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token)
    {
        if (StringUtils.isNotEmpty(token))
        {
            String userKey = getTokenKey(token);
            redisCacheManager.deleteObject(RedisCacheKey.SYS_LOGIN_TOKEN,userKey);
        }
    }

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser ,String ssoTokenKey)
    {
        String token = IdUtils.fastUUID();
        loginUser.setToken(token);
        setUserAgent(loginUser);
        refreshToken(loginUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(portalService.getClaimsKey(), token);
        return createToken(claims);
    }


    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginUser
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser)
    {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser)
    {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        log.info("写入登录认证UserKey=" + userKey);
        redisCacheManager.setCacheObject(RedisCacheKey.SYS_LOGIN_TOKEN,userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 设置用户代理信息
     *
     * @param loginUser 登录信息
     */
    public void setUserAgent(LoginUser loginUser)
    {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr();
        loginUser.setIpaddr(ip);
        loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims)
    {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token)
    {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }


    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    public Claims parseSsoToken(String token)
    {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token)
    {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
        {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    public String getTokenKey(String uuid)
    {
        PortalInfo portalInfo = SpringUtils.getBean(PortalService.class).getSsoInfo();
        String tokenTag = ("1".equalsIgnoreCase(portalInfo.getSsoEnabled()) && !portalInfo.getAppName().toUpperCase().contains(Constants.PTS)) ? ("_" + portalInfo.getAppName()) : "";
        return  uuid + tokenTag;
    }




    public String loginPTS(String username,  String ssoToken, String ssoTokenKey)
    {
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, "-1");
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = SpringUtils.getBean(AuthenticationManager.class).authenticate(authenticationToken);
            SpringUtils.getBean(UserDetailsService.class).loadUserByUsername(username);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "用户不存在/密码错误"));
                throw new SsoException(ErrorCode.AUTH_SSO_PASSWOR_ERROR.getCode(),ErrorCode.AUTH_SSO_PASSWOR_ERROR.getMessage());  //网关集成失败
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new SsoException(ErrorCode.AUTH_SSO_LOGIN_USERNOEXIST.getCode(),ErrorCode.AUTH_SSO_LOGIN_USERNOEXIST.getMessage());  //网关集成失败
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功"));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //新增加
        loginUser.setPtsToken( ssoToken );
        SysUser sysUser = new SysUser("");
        sysUser.setUserId(loginUser.getUserId());
        sysUser.setUserLastloginip(IpUtils.getIpAddr());
        sysUser.setUserLastlogindate(DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss").toString());
        SpringUtils.getBean(ISysUserService.class).updateUserProfile(sysUser);
        // 生成token
        return createToken(loginUser,ssoTokenKey);
    }

}
