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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.ap.SysConstains;
import com.mortals.framework.common.Rest;
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 com.mortals.xhx.base.system.user.model.UserQuery;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.feign.user.IUserFeign;
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.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

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;
//    @Autowired
//    private IUserFeign userFeign;


    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;
    @Autowired
    private UserService userService;

    /**
     * 获取信息
     *
     * @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);
                //cacheService.select(portalDb);
               // cacheService.select(0);
                RedisTemplate<String, String> redisTemplate = cacheService.selectDbRedisTemplate(0);
                String userStr =redisTemplate.opsForValue().get(userKey);
               // String userStr = cacheService.get(userKey);
             //   cacheService.select(db);
                if (StringUtils.isNotEmpty(userStr)) {
                    UserEntity userEntity = JSONObject.parseObject(userStr, UserEntity.class);
                    //与本地转换
                    UserQuery userQuery = new UserQuery();
                    userQuery.setLoginName(userEntity.getLoginName());
                    UserEntity localuserEntity = userService.selectOne(userQuery);
                    if(ObjectUtils.isEmpty(localuserEntity)){
                        localuserEntity.setToken(token);
                        return localuserEntity;
                    }
                    userEntity.setToken(token);
                    return userEntity;
                }else{
                     userStr = cacheService.get(userKey);
                    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;
    }
}
