//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.chushang.common.feign.interceptor;

import com.alibaba.fastjson2.JSONObject;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.core.annotation.Order;

@Order(5)
public class FeignHeaderInterceptor implements RequestInterceptor {
    public static final String attrKey = "transfer";
    private static final ThreadLocal<JSONObject> header = ThreadLocal.withInitial(JSONObject::new);
    private static final byte[] hex = "0123456789ABCDEF".getBytes();

    public FeignHeaderInterceptor() {
    }

    public static void add(String key, Object value) {
        header.get().put(key, value);
    }

    public static void clear() {
        header.remove();
    }

    public void apply(RequestTemplate template) {
        if (header.get() != null && !header.get().isEmpty()) {
            JSONObject h = header.get();
            template.header("transfer", this.bytes2HexString(h.toJSONString().getBytes()));
        }

    }

    public String bytes2HexString(byte[] b) {
        byte[] buff = new byte[2 * b.length];

        for(int i = 0; i < b.length; ++i) {
            buff[2 * i] = hex[b[i] >> 4 & 15];
            buff[2 * i + 1] = hex[b[i] & 15];
        }

        return new String(buff);
    }
}
