package com.tofly.xrtygis.config;

import com.alibaba.fastjson.JSON;
import feign.Request;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class FeignConfig implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //添加token
        requestTemplate.header("Authorization", request.getHeader("Authorization"));
        //将body的数据写入参数
        if("GET".equals(requestTemplate.method())){
            try{
                //获取body内容
                String json = requestTemplate.requestBody().asString();
                if (StringUtils.isEmpty(json)) {
                    return ;
                }
                Map<String, Object> map= JSON.parseObject(json);
                Set<String> set = map.keySet();
                Iterator<String> it = set.iterator();
                while (it.hasNext()) {
                    String key = (String) it.next();
                    Object values = map.get(key);
                    if (values!=null && !"".equals(values) && !"null".equals(values)) {
                        //将body的参数写入queries
                        requestTemplate.query(key,values.toString());
                    }
                }
                Class requestClass=requestTemplate.getClass();
                Field field = requestClass.getDeclaredField("body");
                field.setAccessible(true);
                //修改body为空。
                field.set(requestTemplate, Request.Body.empty());
            }catch (Exception e){

            }


        }

    }
}
