package com.ym.mec.auth.interceptor;

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

import com.ym.mec.common.exception.BizException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.auth.api.entity.TenantInfo;
import com.ym.mec.auth.service.SysUserService;
import com.ym.mec.auth.service.TenantInfoService;
import com.ym.mec.common.security.AuthUser;
import com.ym.mec.common.security.SecurityUtils;
import com.ym.mec.common.tenant.TenantContextHolder;

@Component
public class TenantInterceptor extends HandlerInterceptorAdapter {

	private static final String DATA_SOURCE_ID = "datasourceId";

	@Autowired
	private SysUserService userService;
	
	@Autowired
	private TenantInfoService tenantInfoService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
		String tenantId = request.getHeader("tenantId");
		if(StringUtils.isEmpty(tenantId)){
			AuthUser authUser = SecurityUtils.getUser();
			SysUser sysUser = null;
			if(authUser != null){
				sysUser = userService.get(authUser.getUserId());
			}
			if(sysUser != null && sysUser.getTenantId() != null){
				tenantId = sysUser.getTenantId().toString();
			}
		}
		if(StringUtils.isNotEmpty(tenantId)){
			TenantContextHolder.setTenantId(Integer.parseInt(tenantId));
			if(Integer.parseInt(tenantId) != -1){
				TenantInfo tenantInfo = tenantInfoService.getOpenTenant(Integer.parseInt(tenantId));
				if(tenantInfo != null){
					request.setAttribute(DATA_SOURCE_ID, tenantInfo.getDataSource());
				}else {
					throw new BizException("机构服务已停用，请联系机构管理员");
				}
			}
		}
		return true;
	}

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

}
