package com.hzs.common.security.service;

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

import com.hzs.common.core.enums.ELoginType;
import com.hzs.common.core.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.hzs.common.core.constant.CacheConstants;
import com.hzs.common.core.constant.SecurityConstants;
import com.hzs.common.core.utils.JwtUtils;
import com.hzs.common.core.utils.ServletUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.ip.IpUtils;
import com.hzs.common.core.utils.uuid.IdUtils;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.system.sys.dto.LoginUser;

/**
 * token验证处理
 */
@Component
public class UserTokenService {

    @Autowired
    private RedisService redisService;

    /**
     * 毫秒->秒
     */
    protected static final long MILLIS_SECOND = 1000;
    /**
     * 毫秒->分钟
     */
    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;
    /**
     * 到期时间
     */
    private final static long expireTime = CacheConstants.LOGIN_TOKEN_EXPIRATION;
    /**
     * 缓存前缀
     */
    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;
    /**
     * 刷新缓存时间
     */
    private final static Long MILLIS_MINUTE_TEN = CacheConstants.LOGIN_TOKEN_REFRESH_TIME * MILLIS_MINUTE;

    /**
     * 创建令牌
     */
    public Map<String, Object> createToken(LoginUser loginUser) {
        String token = IdUtils.fastUUID();
        Long userId = loginUser.getLoginSysUser().getUserId();
        String userName = loginUser.getLoginSysUser().getUserName();
        loginUser.setToken(token);
        loginUser.setUserId(userId);
        loginUser.setUsername(userName);
        loginUser.setIpAddr(IpUtils.getIpAddr(ServletUtils.getRequest()));
        refreshToken(loginUser);

        // Jwt存储信息
        Map<String, Object> claimsMap = new HashMap<>();
        claimsMap.put(SecurityConstants.USER_KEY, token);
        claimsMap.put(SecurityConstants.DETAILS_USER_ID, userId);
        claimsMap.put(SecurityConstants.DETAILS_USERNAME, userName);
        claimsMap.put(SecurityConstants.DETAILS_USER_TYPE, loginUser.getLoginSysUser().getUserType());
        claimsMap.put(SecurityConstants.DETAILS_USER_COUNTRY, loginUser.getDataCountry());
        claimsMap.put(SecurityConstants.SYSTEM_TYPE, loginUser.getSystemType());

        // 接口返回信息
        Map<String, Object> rspMap = new HashMap<>();
        rspMap.put("access_token", JwtUtils.createToken(claimsMap));
        rspMap.put("expires_in", expireTime);
        rspMap.put("data_country", loginUser.getDataCountry());
        rspMap.put("system_type", loginUser.getSystemType());
        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) {
        try {
            if (StringUtils.isNotEmpty(token)) {
                String userKey = JwtUtils.getUserKey(token);
                return redisService.getCacheObject(getTokenKey(userKey));
            }
        } 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 = JwtUtils.getUserKey(token);
            redisService.deleteObject(getTokenKey(userKey));
        }
    }

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

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