package com.mortals.xhx.base.framework.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.ap.SysConstains;
import com.mortals.framework.service.IAuthTokenService;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.service.IUser;
import com.mortals.framework.util.DateUtils;
import com.mortals.framework.util.StringUtils;
import com.mortals.xhx.base.system.user.model.UserEntity;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * token验证处理
 *
 * @author zxfei
 */

@Service
@Order(1)
@Slf4j
public class AuthTokenServiceImpl implements IAuthTokenService {
    // 令牌自定义标识
    @Value("${token.header:Authorization}")
    private String header;

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

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

    // 令牌前缀
    @Value("${token.prefix:}")
    private String tokenPrefix;
    // redis db
    @Value("${spring.redis.database:}")
    private Integer db;

    @Value("${token.database:0}")
    private Integer portalDb;

    protected static final Long SECOND = 1l;

    protected static final Long SECOND_MINUTE = 60 * SECOND;

    protected static final Long SECOND_HOUR = 60 * SECOND_MINUTE;

    protected static final Long SECOND_DAY = 24 * SECOND_HOUR;

    protected static final Long SECOND_WEEK = 7 * SECOND_DAY;

    private static final Long SECOND_MINUTE_TEN = 1 * SECOND_MINUTE;

    @Autowired
    private ICacheService cacheService;

    /**
     * 获取信息
     *
     * @return 用户信息
     */
    @Override
    public IUser getLoginUser(HttpServletRequest request) {

        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            try {
                Claims claims = parseToken(token);
                String uuid = (String) claims.get(SysConstains.LOGIN_USER_KEY);
                String userKey = getTokenKey(uuid);
//                Rest<String> rest = userFeign.getToken(userKey);
//                String userStr = rest.getData();
                cacheService.select(portalDb);
                 String userStr = cacheService.get(userKey);

                cacheService.select(db);
                if (StringUtils.isNotEmpty(userStr)) {
                    UserEntity userEntity = JSONObject.parseObject(userStr, UserEntity.class);
                    userEntity.setToken(token);
                    return userEntity;
                }
            } catch (Exception e) {
                log.error("解析jwt token异常！", e);
                return null;
            }
        }
        return null;
    }

    /**
     * 设置用户信息
     */
    @Override
    public void setUser(IUser user) {
        if (StringUtils.isNotNull(user) && StringUtils.isNotEmpty(user.getToken())) {
            refreshToken(user);
        }
    }

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

    /**
     * 创建令牌
     *
     * @param user 用户信息
     * @return 令牌
     */
    @Override
    public String createToken(IUser user) {
//        String token = IdUtil.fastSimpleUUID();
//        user.setToken(token);
        refreshToken(user);
        Map<String, Object> claims = new HashMap<>();
        claims.put(SysConstains.LOGIN_USER_KEY, user.getToken());
        return createToken(claims);
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param user
     * @return 令牌
     */
    @Override
    public void verifyToken(IUser user) {
        long expireTime = user.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= SECOND_MINUTE_TEN) {
            log.info("不足十分钟，刷新过期时间");
            refreshToken(user);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param user 信息
     */
    public void refreshToken(IUser user) {
        //user.setLoginTime(System.currentTimeMillis());
        user.setExpireTime(user.getLoginTime() == null ? System.currentTimeMillis() : user.getLoginTime() + expireTime * SECOND_MINUTE);
        // 根据uuid将user缓存
        String userKey = getTokenKey(user.getToken());
        //设置有效时间 单位秒
        cacheService.set(userKey, user, expireTime * SECOND_MINUTE);
    }


    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        String token = Jwts.builder()
                .setExpiration(DateUtils.addCurrDate(7))
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS256, Base64.getEncoder()
                        .encodeToString(secret.getBytes())).compact();
        return token;
    }

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

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

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

    private String getTokenKey(String uuid) {
        return SysConstains.LOGIN_TOKEN_KEY + uuid;
    }
}
