package com.ym.mec.teacher.interceptor;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.TeacherDao;
import com.ym.mec.biz.dal.entity.Teacher;
import com.ym.mec.common.filters.TenantIdThreadLocal;

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;

@Component
public class MDCInterceptor extends HandlerInterceptorAdapter {
	@Autowired
	@Lazy
	private SysUserFeignService sysUserFeignService;
	@Autowired
	private TeacherDao teacherDao;
	@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){
			Teacher teacher = teacherDao.get(sysUser.getId());
			if(teacher != null){
				if (teacher.getTeacherOrganId() == tenantClientId) {
					TenantIdThreadLocal.set(2);
				}else {
					TenantIdThreadLocal.set(1);
				}
			}
		}
		return true;
	}

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