package com.qiaoba.api.auth.utils;

import cn.hutool.core.util.StrUtil;
import com.qiaoba.api.auth.constants.SecurityConstant;
import com.qiaoba.api.auth.entity.dto.OnlineUserDto;
import com.qiaoba.common.base.constant.BaseConstant;
import com.qiaoba.common.base.exception.ServiceException;

import javax.servlet.http.HttpServletRequest;

/**
 * TokenUtil
 *
 * @author ailanyin
 * @version 1.0
 * @since 2022/6/8 0008 上午 11:44
 */
public class TokenUtil {

    /**
     * token 过期时间 单位: 小时
     */
    public static final Integer TOKEN_EXPIRE_HOUR_TIME = 3;
    private static final String TOKEN_TEMPLATE = "{}:{}";

    public static String generateToken(String username, String deviceSn) {
        return StrUtil.format(TOKEN_TEMPLATE, username, deviceSn);
    }

    public static String getToken(HttpServletRequest request, boolean allowNull) {
        // 取Header中的Token
        String authHeader = request.getHeader(SecurityConstant.TOKEN_HEADER);
        if (StrUtil.isNotBlank(authHeader) && authHeader.startsWith(SecurityConstant.TOKEN_HEAD)) {
            return authHeader.substring(SecurityConstant.TOKEN_HEAD.length());
        }

        if (allowNull) {
            return null;
        }

        throw new ServiceException("Token不存在");
    }

    public static OnlineUserDto getUsernameAndDeviceSn(String token) {
        try {
            String[] split = token.split(BaseConstant.COLON_JOIN_STR);
            return new OnlineUserDto(split[0], split[1]);
        } catch (Exception e) {
            throw new ServiceException("Token解析失败");
        }
    }

    /**
     * 解析 username
     *
     * @param request request
     * @return username
     */
    public static String analyzeUsername(HttpServletRequest request) {
        // 取Header中的Token
        try {
            String authHeader = request.getHeader(SecurityConstant.TOKEN_HEADER);
            if (StrUtil.isNotBlank(authHeader) && authHeader.startsWith(SecurityConstant.TOKEN_HEAD)) {
                String token = authHeader.substring(SecurityConstant.TOKEN_HEAD.length());
                return token.split(BaseConstant.COLON_JOIN_STR)[0];
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }
}
