package com.persagy.adm.server.custom.interceptor;

import com.persagy.adm.server.auth.service.AdmAuthService;
import com.persagy.dmp.auth.domain.BossAuthUser;
import com.persagy.dmp.common.constant.ResponseCode;
import com.persagy.dmp.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

@Component
@Slf4j
public class TokenInterceptor extends HandlerInterceptorAdapter {
    public static ThreadLocal<BossAuthUser> bossAuthUserThreadLocal = new ThreadLocal<>();

    @Autowired
    private AdmAuthService admAuthService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)){
            throw new BusinessException(ResponseCode.A0220.getCode(),ResponseCode.A0220.getDesc());
        }

        try {
            BossAuthUser bossAuthUser = admAuthService.loginInfo();
            bossAuthUserThreadLocal.set(bossAuthUser);
        }catch (Exception e){
            log.error("获取用户信息失败",e);
            throw new BusinessException(ResponseCode.A0311.getCode(),ResponseCode.A0311.getDesc());
        }
        return super.preHandle(request, response, handler);
    }
}
