package com.mortals.xhx.busiz.security;

import cn.hutool.core.util.IdUtil;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.util.StringUtils;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.module.device.model.DeviceEntity;
import io.jsonwebtoken.Claims;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * token验证处理
 *
 * @author zxfei
 */
@Component
@CommonsLog
public class DeviceTokenService {
    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

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

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

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private ICacheService cacheService;

    /**
     * 获取设备信息
     *
     * @return 设备信息
     */
    public DeviceEntity getLoginDevice(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            try {
                Claims claims = parseToken(token);
                String uuid = (String) claims.get(Constant.LOGIN_DEVICE_KEY);
                String deviceKey = getTokenKey(uuid);
                DeviceEntity device = cacheService.get(deviceKey, DeviceEntity.class);
                return device;
            } catch (Exception e) {
                log.error("解析jwt token异常！",e);
                return null;
            }
        }
        return null;
    }

    /**
     * 设置设备信息
     */
    public void setDevice(DeviceEntity device) {
        if (StringUtils.isNotNull(device) && StringUtils.isNotEmpty(device.getToken())) {
            refreshToken(device);
        }
    }

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

    /**
     * 创建令牌
     *
     * @param device 设备信息
     * @return 令牌
     */
    public String createToken(DeviceEntity device) {
        String token = IdUtil.fastSimpleUUID();
        device.setToken(token);
        refreshToken(device);
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constant.LOGIN_DEVICE_KEY, token);
        return createToken(claims);
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param device
     * @return 令牌
     */
    public void verifyToken(DeviceEntity device) {
        long expireTime = device.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(device);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param device 信息
     */
    public void refreshToken(DeviceEntity device) {
        device.setLoginTime(System.currentTimeMillis());
        device.setExpireTime(device.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将device缓存
        String deviceKey = getTokenKey(device.getToken());
        //设置有效时间 单位秒
        cacheService.setnx(deviceKey, device, expireTime * MILLIS_MINUTE * MILLIS_SECOND);
    }


    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

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

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

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

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