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

import cn.hutool.core.util.IdUtil;
import com.mortals.framework.service.IAuthTokenService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 
 * 请求过滤链
 * @author: zxfei
 * @date: 2022/4/20 14:52
 */
//@Component
@Slf4j
public class RequestFilter extends OncePerRequestFilter implements Filter {

    @Autowired
    private IAuthTokenService authTokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            //每个请求记录一个traceId,可以根据traceId搜索出本次请求的全部相关日志
            MDC.put("traceId", IdUtil.fastSimpleUUID().substring(0,12));
            setUsername(request);
            request = new ContentCachingRequestWrapper(request);
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            throw e;
        } finally {
            //清理ThreadLocal
            MDC.clear();
        }
    }


    private void setUsername(HttpServletRequest request) {
        //通过token解析出username
        String token = authTokenService.getToken(request);
        //String token = request.getHeader("token");
        if (!ObjectUtils.isEmpty(token)) {
            MDC.put("token",token);
//            MDC.put("token", token);
//            try {
//                SessionUserInfo info = tokenService.getUserInfo();
//                if (info != null) {
//                    String username = info.getUsername();
//                    MDC.put("username", username);
//                }
//            } catch (CommonJsonException e) {
//                log.info("无效的token:{}", token);
//            }
        }
    }
}
