package cn.cslg.report.common.utils.SecurityUtils;

import cn.cslg.report.common.utils.RedisUtil;
import cn.cslg.report.common.utils.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

@Component
public class LoginUtils {
    @Resource
    private RedisUtil redisUtil;

    public static String getToken() {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest httpRequest = Objects.requireNonNull(sra).getRequest();
        String tem = httpRequest.getHeader("Cookie");
        List<String> lst = StringUtils.changeStringToString(tem, ";");
        final String[] token = {null};
        lst.forEach(item -> {
            if (item.contains("token")) {
                token[0] = item;
            }
        });
        return token[0].replaceAll(" ", "");
    }

    public Integer getId() {
        String oriToken = LoginUtils.getToken();
        String q = "token:login:" + oriToken.replace("=", ":");
        String IdS = redisUtil.get(q);
        return Integer.parseInt(IdS);
    }
}
