package com.ym.mec.student.interceptor;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.common.filters.TenantIdThreadLocal;
import com.ym.mec.util.web.WebUtil;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Component
public class MDCInterceptor extends HandlerInterceptorAdapter {

	private static final String IP = "ip";

	private static final String USERNAME = "username";

	private static final String REQ_ID = "reqId";
	@Autowired
	@Lazy
	private SysUserFeignService sysUserFeignService;
	@Value("${auth.sysconfig.tenantId}")
	private Integer tenantClientId;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		SysUser sysUser = sysUserFeignService.queryUserInfo();
		if(sysUser != null){
			if (sysUser.getOrganId() == tenantClientId) {
				TenantIdThreadLocal.set(2);
			}else {
				TenantIdThreadLocal.set(1);
			}
			// 存储userId以及IP
			MDC.put(USERNAME, sysUser.getUsername() + "@" + sysUser.getId());
		}
		MDC.put(IP, WebUtil.getRemoteIp(request));
		MDC.put(REQ_ID, UUID.randomUUID().toString());
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		MDC.remove(USERNAME);
		MDC.remove(IP);
		TenantIdThreadLocal.remove();
	}
}
