package com.tenlionsoft.baselib.core.retrofit_net.conver;


import com.tenlionsoft.baselib.core.retrofit_net.BaseUrlApi;

import java.io.IOException;
import java.util.List;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 作者: Adam
 * 日期: 2021-9-26
 * 邮箱: itgaojian@163.com
 * 描述: URL拦截器
 */
public class BaseUrlInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder builder = request.newBuilder();
        HttpUrl oldHttpUrl = request.url();
        List<String> baseUrlName = request.headers("base_url_name");
//        List<String> need_token = request.headers("need_token");
//        if (need_token.size() > 0) {
//            //需要添加token
//            builder.addHeader("token", UserLgUtils.getToken());
//        }
        if (baseUrlName.size() > 0) {
            builder.removeHeader("base_url_name");
            String headerValue = baseUrlName.get(0);
            HttpUrl newBaseUrl = null;
            if ("person".equals(headerValue)) {
                //人口系统
                newBaseUrl = HttpUrl.parse(BaseUrlApi.BASE_PERSON_IP);
            } else if ("house".equals(headerValue)) {
                //房屋系统
                newBaseUrl = HttpUrl.parse(BaseUrlApi.BASE_HOUSE_IP);
            } else if ("case".equals(headerValue)) {
                newBaseUrl = HttpUrl.parse(BaseUrlApi.BASE_CASE_IP);
            } else if ("security".equals(headerValue)) {
                newBaseUrl = HttpUrl.parse(BaseUrlApi.BASE_SECURITY_IP);
            } else if ("task".equals(headerValue)) {
                newBaseUrl = HttpUrl.parse(BaseUrlApi.BASE_TASK_IP);
            } else if ("library".equals(headerValue)) {
                newBaseUrl = HttpUrl.parse(BaseUrlApi.BASE_LIBRARY_IP);
            } else if ("visits".equals(headerValue)) {
                newBaseUrl = HttpUrl.parse(BaseUrlApi.BASE_VISITS_IP);
            } else {
                newBaseUrl = oldHttpUrl;
            }

            HttpUrl newFullUrl = oldHttpUrl.newBuilder()
                .scheme(newBaseUrl.scheme())
                .host(newBaseUrl.host())
                .port(newBaseUrl.port())
                .setPathSegment(0, newBaseUrl.pathSegments().get(0))
                .build();
            return chain.proceed(builder.url(newFullUrl).build());
        } else {
            return chain.proceed(request);
        }
    }
}
