package com.ym.mec.student.interceptor;

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

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.common.filters.TenantIdThreadLocal;

import org.apache.commons.lang3.StringUtils;
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.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ym.mec.util.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;
	@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);
			}
		}
		String username = "";
		String userId = "";
		// 存储userId以及IP
		MDC.put(USERNAME, username + "@" + userId);
		MDC.put(IP, WebUtil.getRemoteIp(request));

		return true;
	}

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