package com.ruoyi.interfaces.service.impl;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.interfaces.domain.PtApp;
import com.ruoyi.interfaces.enums.TokenError;
import com.ruoyi.interfaces.service.PtAppService;
import com.ruoyi.interfaces.service.TokenService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private PtAppService ptAppService;

    @Autowired
    private RedisCache redisCache;

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

    /**
     * 令牌有效期（默认1天）
     */
    @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 = 20 * 60 * 1000L;

    private static final String CLIENT_CREDENTIAL = "client_credential";

    /**
     * 令牌前缀
     */
    public static final String APP_KEY = "app_key";

    /**
     * 令牌前缀
     */
    public static final String TOKEN_PREFIX = "Bearer ";

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

    /**
     * 设置用户身份信息
     */
    @Override
    public void setPtApp(PtApp ptApp) {
        if (!Optional.ofNullable(ptApp).map(PtApp::getAppToken).isPresent()) {
            refreshToken(ptApp);
        }
    }

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

    /**
     * 创建令牌
     *
     * @param ptApp 用户信息
     * @return 令牌
     */
    @Override
    public String createToken(PtApp ptApp) {
        String token = IdUtils.fastUUID();
        ptApp.setAppToken(token);
        setUserAgent(ptApp);
        refreshToken(ptApp);

        Map<String, Object> claims = new HashMap<>(1);
        claims.put(APP_KEY, token);
        claims.put("sub", ptApp.getAppId());
        return createToken(claims, ptApp.getAppSecret());
    }

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

    /**
     * 刷新令牌有效期
     *
     * @param ptApp 登录信息
     */
    @Override
    public void refreshToken(PtApp ptApp) {
        ptApp.setRqTime(new Date());
        ptApp.setExpireTime(ptApp.getRqTime().getTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将ptApp缓存
        String userKey = getTokenKey(ptApp.getAppToken());
        redisCache.setCacheObject(userKey, ptApp, expireTime, TimeUnit.MINUTES);
    }

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

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims, String sercet) {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, sercet).compact();
        redisCache.setCacheObject("token:" + token, sercet, expireTime, TimeUnit.MINUTES);
        return token;
    }

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

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    @Override
    public String getAppIdFromToken(String token) {
        String secret = redisCache.getCacheObject("token:" + token);
        Claims claims = parseToken(token, secret);
        return claims.getSubject();
    }

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

    private String getToken(String headerToken) {
        if (StringUtils.isNotEmpty(headerToken) && headerToken.startsWith(TOKEN_PREFIX)) {
            return headerToken.replace(TOKEN_PREFIX, "");
        }
        return null;
    }

    private String getTokenKey(String uuid) {
        return APP_KEY + ":" + uuid;
    }

    @Override
    public Map<String, Object> token(String grantType, String appId, String secret) {
        PtApp ptApp = ptAppService.get(appId);
        if (ptApp == null) {
            return failResponse(TokenError.APPID_ERR);
        } else if (!Optional.of(ptApp).map(PtApp::getAppSecret).isPresent() ||
                !ptApp.getAppSecret().equals(secret)) {
            return failResponse(TokenError.APPSECRET_ERR);
        } else if (!CLIENT_CREDENTIAL.equals(grantType)) {
            return failResponse(TokenError.GRANT_TYPE_ERR);
        }

        Map<String, Object> ret = new HashMap<>(2);
        ret.put("access_token", createToken(ptApp));
        ret.put("expires_in", expireTime);
        return ret;
    }

    private Map<String, Object> failResponse(int code, String msg) {
        Map<String, Object> ret = new HashMap<>(2);
        ret.put("errcode", code);
        ret.put("errmsg", msg);
        return ret;
    }

    private Map<String, Object> failResponse(TokenError tokenError) {
        return failResponse(tokenError.getCode(), tokenError.getInfo());
    }
}
