package com.yonge.cooleshow.teacher.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.toolset.utils.web.WebUtil;

@Component
public class MDCInterceptor extends HandlerInterceptorAdapter {

	private static final String IP = "ip";

	private static final String USERNAME = "username";
	
	@Autowired
	@Lazy
	private SysUserFeignService sysUserFeignService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		SysUser sysUser = sysUserFeignService.queryUserInfo();
		if (sysUser != null && sysUser.getId() != null) {
			// 存储userId以及IP
			MDC.put(USERNAME, sysUser.getUsername() + "@" + sysUser.getId());
		}
		MDC.put(IP, WebUtil.getRemoteIp(request));

		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
	}
}
