package com.ym.mec.cms.interceptor;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
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.cms.dal.entity.TenantInfo;
import com.ym.mec.cms.service.TenantInfoService;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.tenant.TenantContextHolder;

public class TenantInterceptor extends HandlerInterceptorAdapter {

	private static final String DATA_SOURCE_ID = "datasourceId";
	
	private static final String TENANT_ID = "tenantId";

	@Autowired
	@Lazy
	private SysUserFeignService sysUserFeignService;
	
	@Autowired
	private TenantInfoService tenantInfoService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		String tenantId = request.getParameter(TENANT_ID);

        if (StringUtils.isBlank(tenantId)) {
            tenantId = request.getHeader(TENANT_ID);
        }

        if (StringUtils.isBlank(tenantId)) {
            SysUser sysUser = sysUserFeignService.queryUserInfo();
            if (sysUser != null && sysUser.getTenantId() != null) {
                tenantId = sysUser.getTenantId().toString();
            }
        }
        if (StringUtils.isNotBlank(tenantId)) {
            TenantContextHolder.setTenantId(Integer.parseInt(tenantId));
            TenantInfo tenantInfo = tenantInfoService.get(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();
	}

}
