package cn.ey.biz.module.weaver.common;

import cn.ey.biz.common.exception.ErrorCode;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import static cn.ey.biz.common.exception.util.ServiceExceptionUtil.exception;

@Slf4j
public class FeignTokenInterceptor implements RequestInterceptor {

    @Resource
    TokenGetter tokenGetter;
    @Resource
    HrmGetter hrmGetter;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    AppIdConfig appIdConfig;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest  servletRequest=getRequest();
        String sysCode=(String)servletRequest.getAttribute("sysCode");
        Map<String, String>  appIdMap=appIdConfig.getAppId();
        String app=appIdMap.get(sysCode);
        if(app==null){
            throw exception(new ErrorCode(-1,"获取不到泛微appId信息"));
        }

        //获取Token
        String token = tokenGetter.token(app);
        //获取人员信息
        String spk = stringRedisTemplate.opsForValue().get(Constants.SERVER_PUBLIC_KEY+app);
        RSA rsa = new RSA(null, spk);
        //对用户信息进行加密传输,暂仅支持传输OA用户ID
        String encryptUserid = rsa.encryptBase64(hrmGetter.getCurrentUserId(app), CharsetUtil.CHARSET_UTF_8, KeyType.PublicKey);
        UserContextHolder.remove(HrmGetter.USER_ID);
        //设置头信息
        requestTemplate//.header("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
                .header("appid",app)
                .header("token", token)
                .header("userid", encryptUserid);
    }

    protected HttpServletRequest getRequest(){
        return ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
    }

}
