package com.docus.server.common.auth;

import com.docus.infrastructure.core.db.KeyGenerator;
import com.docus.server.constants.BusinessConstant;
import com.docus.server.vo.recovery.UserInfoView;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.TimeUnit;

//feign微服务之间调用header传入用户登录信息
public class FeignRequestInterceptor implements RequestInterceptor {
    private static final String internalUserName = " internal";
    private String token;
    @Autowired
    private RedisStringService redisStringService;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ApiRequestContext requestContext = ApiRequestContext.get();
        if (requestContext != null) {
            if (requestContext.getIsGrantInternalRequest()) {
                if (token == null || redisStringService.getValue(BusinessConstant.REDIS_KEY_USER_TOKEN_PREFIX + token, UserInfoView.class) != null) {
                    initToken();
                }
                requestTemplate.header(BusinessConstant.HEADER_SYSTEM_CODE, internalUserName);
                requestTemplate.header(BusinessConstant.HEADER_USER_ID, internalUserName);
                requestTemplate.header(BusinessConstant.HEADER_API_TOKEN, token);
            } else {
                requestTemplate.header(BusinessConstant.HEADER_SYSTEM_CODE, requestContext.getSystemCode());
                requestTemplate.header(BusinessConstant.HEADER_USER_ID, requestContext.getUserId());
                requestTemplate.header(BusinessConstant.HEADER_API_TOKEN, requestContext.getToken());
                if (requestContext.getAdminCode() != null) {
                    requestTemplate.header(BusinessConstant.HEADER_ADMIN_CODE, requestContext.getAdminCode().toString());
                }
                if (requestContext.getOwnerId() != null) {
                    requestTemplate.header(BusinessConstant.HEADER_OWNER_ID, requestContext.getOwnerId());
                }
                if (requestContext.getAppId() != null) {
                    requestTemplate.header(BusinessConstant.HEADER_APP_ID, requestContext.getAppId());
                }
            }
        }
    }

    //创建虚拟用户和token,用于微服务直接调用
    private void initToken() {
        token = KeyGenerator.genId();
        UserInfoView userInfoview = new UserInfoView();
        userInfoview.setToken(token);
        userInfoview.setUserId(internalUserName);
        userInfoview.setUserName(internalUserName);
        userInfoview.setRealName(internalUserName);
        redisStringService.setValue(BusinessConstant.REDIS_KEY_USER_TOKEN_PREFIX + token, userInfoview, 3, TimeUnit.MINUTES);
    }
}
