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.resource.service.ResourceService;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.common.code.PlatformTypeEnum;
import com.mortals.xhx.common.key.RedisKey;
import com.mortals.xhx.common.utils.MenuEncodeUtil;
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;
import java.util.Set;

/**
 * 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;

    @Value("${platform.type:cloud}")
    private String platFormType;//版本，默认云服务版本

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private UserService userService;

    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 = 20 * SECOND_MINUTE;

    @Autowired
    private ICacheService cacheService;

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

        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            try {
                boolean signed = Jwts.parser().isSigned(token);
                if (!signed) {
                    log.error("token非法！=>{}", token);
                    return null;
                }
                Claims claims = parseToken(token);
                String uuid = (String) claims.get(SysConstains.LOGIN_USER_KEY);
                String userKey = getTokenKey(uuid);
                String userStr = "";
                if (platFormType.equalsIgnoreCase(PlatformTypeEnum.CLOUD.getValue())) {
/*                    cacheService.select(portalDb);
                    userStr = cacheService.get(userKey);*/
                    RedisTemplate<String, String> redisTemplate = cacheService.selectDbRedisTemplate(portalDb);
                     userStr =redisTemplate.opsForValue().get(userKey);
                    //刷新token时间
                    UserEntity userEntity = JSONObject.parseObject(userStr, UserEntity.class);
                    if (!ObjectUtils.isEmpty(userEntity)) {
                        verifyToken(userEntity);
                    }
                  //  cacheService.select(db);
                } else {
                    userStr = cacheService.get(userKey);
                    //刷新token时间
                    UserEntity userEntity = JSONObject.parseObject(userStr, UserEntity.class);
                    if (!ObjectUtils.isEmpty(userEntity)) {
                        verifyToken(userEntity);
                    }
                }
                if (StringUtils.isNotEmpty(userStr)) {
                    UserEntity userEntity = JSONObject.parseObject(userStr, UserEntity.class);
                    userEntity.setToken(token);
                    //更新portal 中的id 为 device中的id
                    //  UserEntity temp = userService.selectOne(new UserQuery().loginName(userEntity.getLoginName()));
                    UserEntity temp = userService.getExtCache(userEntity.getLoginName());
                    if (!ObjectUtils.isEmpty(temp)) {
                        userEntity.setId(temp.getId());
                    }
                    //更新resource 路径
                    String menuUrlCode = cacheService.hget(RedisKey.KEY_USER_MENU_CACHE, userEntity.getId().toString(), String.class);
                    if (ObjectUtils.isEmpty(menuUrlCode)) {
                        Set<String> urls = resourceService.findUrlSetByUserId(userEntity.getId());
                        menuUrlCode = MenuEncodeUtil.generateMenuUrlCode(urls);
                        cacheService.hset(RedisKey.KEY_USER_MENU_CACHE, userEntity.getId().toString(), menuUrlCode);
                    }
                    userEntity.setMenuUrl(menuUrlCode);
                    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*1000) {
            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;
    }
}
