package com.usky.common.security.service;

import com.usky.common.core.constants.CacheConstants;
import com.usky.common.core.constants.SecurityConstants;
import com.usky.common.core.util.*;
import com.usky.common.redis.core.RedisHelper;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.system.model.LoginUser;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.cloud.commons.util.IdUtils;
import org.springframework.stereotype.Component;

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

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Component
public class TokenService {

    private RedisHelper redisService = SpringContextUtils.getBean(RedisHelper.class);


    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private final static long expireTime = CacheConstants.EXPIRATION;

    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;

    private final static String LOGIN_OPENID = "login_openid:";

    private final static Long MILLIS_MINUTE_TEN = CacheConstants.REFRESH_TIME * MILLIS_MINUTE;

    /**
     * 创建令牌
     */
    public Map<String, Object> createToken(LoginUser loginUser,String openId) {
        String token = UUIDUtils.uuid();
        Long userId = loginUser.getSysUser().getUserId();
        String userName = loginUser.getSysUser().getUserName();
        Integer tenantId = loginUser.getSysUser().getTenantId();
        loginUser.setToken(token);
        loginUser.setUserid(userId);
        loginUser.setUsername(userName);
        loginUser.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));
        // 获取操作系统信息
        String userAgentString = ServletUtils.getRequest().getHeader("User-Agent");
        UserAgent userAgent = UserAgent.parseUserAgentString(userAgentString);
        String osInfo = userAgent.getOperatingSystem().getName();
        String browserInfo = userAgent.getBrowser().getName();
        loginUser.setOs(osInfo);
        loginUser.setBrowser(browserInfo);

        refreshToken(loginUser);

        // Jwt存储信息
        Map<String, Object> claimsMap = new HashMap<String, Object>();
        claimsMap.put(SecurityConstants.USER_KEY, token);
        claimsMap.put(SecurityConstants.DETAILS_USER_ID, userId);
        claimsMap.put(SecurityConstants.DETAILS_USERNAME, userName);
        claimsMap.put(SecurityConstants.DETAILS_TENANT_ID, tenantId);
        claimsMap.put(SecurityConstants.DETAILS_OS, osInfo);
        claimsMap.put(SecurityConstants.DETAILS_BROWSER, browserInfo);

        // 接口返回信息
        Map<String, Object> rspMap = new HashMap<String, Object>();
        String accessToken = JwtUtils.createToken(claimsMap);
        rspMap.put("access_token", accessToken);
        rspMap.put("expires_in", expireTime);
        rspMap.put("tenantId", tenantId);

        if((openId != null) && (StringUtils.isNotBlank(openId))){
            String userKey = LOGIN_OPENID+openId;
            redisService.set(userKey, accessToken, expireTime, TimeUnit.MINUTES);
        }

        return rspMap;
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser() {
        return getLoginUser(ServletUtils.getRequest());
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = SecurityUtils.getToken(request);
        return getLoginUser(token);
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(String token) {
        LoginUser user = null;
        try {
            if (StringUtils.isNotEmpty(token)) {
                String userkey = JwtUtils.getUserKey(token);
                user = (LoginUser) redisService.get(getTokenKey(userkey));
                return user;
            }
        } catch (Exception e) {
        }
        return user;
    }

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

    /**
     * 删除用户缓存信息
     */
    public void delLoginUser(String token,String openId) {
        if (StringUtils.isNotEmpty(token)) {
            String userkey = JwtUtils.getUserKey(token);
            redisService.delete(getTokenKey(userkey));
        }
        if((openId != null) && (StringUtils.isNotBlank(openId))){
            String userKey = LOGIN_OPENID+openId;
            if(redisService.hasKey(userKey)){
                redisService.delete(userKey);
            }
        }
    }

    /**
     * 验证令牌有效期，相差不足120分钟，自动刷新缓存
     *
     * @param loginUser
     */
    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());
        redisService.set(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

    private String getTokenKey(String token) {
        return ACCESS_TOKEN + token;
    }
}