package com.docus.server.common.auth;

import com.docus.server.constants.BusinessConstant;
import com.docus.server.vo.recovery.UserInfoView;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.ConcurrentHashMap;

public class RequestContextInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisStringService redisStringService;
    @Autowired(required = false)
//    private RtmAppApi rtmAppApi;
    private volatile static ConcurrentHashMap<String, String> appInfoMap = new ConcurrentHashMap<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(BusinessConstant.HEADER_API_TOKEN);
        UserInfoView userInfoview = redisStringService.getValue(BusinessConstant.REDIS_KEY_USER_TOKEN_PREFIX + token, UserInfoView.class);
        String systemCode = request.getHeader(BusinessConstant.HEADER_SYSTEM_CODE);
        String appGroup = null;
        if (StringUtils.isNotBlank(systemCode)) {
            if (appInfoMap.containsKey(systemCode)) {
                appGroup = appInfoMap.get(systemCode);
            } else {
//                if (rtmAppApi != null) {
//                    RtmApp rtmApp = rtmAppApi.getAppInfoByAppEname(systemCode);
//                    appGroup = rtmApp == null ? null : rtmApp.getAppGroup();
//                    if (StringUtils.isNotBlank(appGroup)) {
//                        appInfoMap.put(systemCode, appGroup);
//                    }
//                }
            }
        }
        ApiRequestContext.init(request, response, userInfoview, getAction(handler), appGroup);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除线程变量
        ApiRequestContext.clear();
    }

    private String getAction(Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            String className = handlerMethod.getBeanType().getSimpleName();
            return className + handlerMethod.getMethod().getName();
        }
        return null;
    }
}
