package quant.rich.emoney.entity.config;

import java.io.IOException;
import java.net.Proxy;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import jodd.io.FileUtil;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Getter;
import lombok.experimental.Accessors;
import okhttp3.ConnectionPool;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.BufferedSource;
import okio.GzipSource;
import okio.Okio;
import quant.rich.emoney.interfaces.ConfigInfo;
import quant.rich.emoney.interfaces.IConfig;

/**
 * 指标信息配置，只做运行时管理，不做保存
 */
@Data
@Accessors(chain=true)
@Lazy(false)
@ConfigInfo(field = "indexInfo", name =" 指标信息配置", initDefault = true, managed = false)
public class IndexInfoConfig implements IConfig<IndexInfoConfig> {
    
    private static final String CONFIG_IND_ONLINE_PATH = "./conf/extra/config_ind_online.json";

    @JsonView(IConfig.Views.Persistence.class)
    private String configIndOnlineUrl;
    
    @JsonView(IConfig.Views.Persistence.class)
    private JsonNode configIndOnline;
    
    @Autowired
    @JsonIgnore
    @Getter(AccessLevel.PRIVATE)
    private EmoneyRequestConfig emoneyRequestConfig;
    
    public IndexInfoConfig() {
        try {
            String configStr = FileUtil.readString(CONFIG_IND_ONLINE_PATH);
            configIndOnline = new ObjectMapper().readTree(configStr);
        }
        catch (Exception e) {}
        configIndOnlineUrl = "https://emapp-static.oss-cn-shanghai.aliyuncs.com/down13/emstock/config/ind_config/v1000003/config_ind_online.json";
    }
    
    public String getConfigIndOnlineStr() {
        return getConfigIndOnline().toPrettyString();
    }
    
    public String getOnlineConfigByUrl(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .header("User-Agent", emoneyRequestConfig.getOkHttpUserAgent())
                .header("Accept-Encoding", "gzip")
                .header("Connection", "Keep-Alive")
                .header("Cache-Control", "no-cache")
                .get()
                // Host 不能在 OkHttp 中直接设置（由 URL 控制）
                .build();

        // 发出请求
        Response backendResponse = getInstance().newCall(request).execute();
        if (backendResponse.body() != null) {
            // 将内容复制给前端
            return 
                new String(backendResponse.body().bytes(), "UTF-8");
        } else {
            return "";
        }
    }
    
    private static OkHttpClient okHttpClient;
    
    public static ConnectionPool connectionPool = new ConnectionPool(10, 5, TimeUnit.MINUTES);
 
    public static OkHttpClient getInstance() {
        if (okHttpClient == null) { //加同步安全
            synchronized (OkHttpClient.class) {
                if (okHttpClient == null) { //okhttp可以缓存数据....指定缓存路径
                    okHttpClient = new OkHttpClient.Builder()//构建器
                            .proxy(Proxy.NO_PROXY) //来屏蔽系统代理
                            .connectionPool(connectionPool)
                            .sslSocketFactory(getSSLSocketFactory(),  getX509TrustManager())
                            .hostnameVerifier(getHostnameVerifier())
                            .connectTimeout(600, TimeUnit.SECONDS)//连接超时
                            .writeTimeout(600, TimeUnit.SECONDS)//写入超时
                            .readTimeout(600, TimeUnit.SECONDS)//读取超时
                            .addNetworkInterceptor(new GzipResponseInterceptor())
                            .build();
                    okHttpClient.dispatcher().setMaxRequestsPerHost(200);
                    okHttpClient.dispatcher().setMaxRequests(200);
                }
            }
        }
        return okHttpClient;
    }
 
    /**
     * description 忽略https证书验证
     */
    private static HostnameVerifier getHostnameVerifier() {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };
        return hostnameVerifier;
    }
    /**
     * description 忽略https证书验证
     */
    private static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
 
    private static X509TrustManager getX509TrustManager() {
        X509TrustManager trustManager = null;
        try {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
            }
            trustManager = (X509TrustManager) trustManagers[0];
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return trustManager;
    }
 
    private static TrustManager[] getTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[]{
            new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) {}
 
                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) {}
 
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[]{};
                }
            }
        };
        return trustAllCerts;
    }
    
    public static class GzipResponseInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
          Request request = chain.request();
          Response response = chain.proceed(request);

          // 只有服务器返回了 gzip 编码才处理
          if ("gzip".equalsIgnoreCase(response.header("Content-Encoding"))) {
            // 原始响应体
            ResponseBody body = response.body();
            if (body == null) return response;

            // 用 GzipSource 包装原始流，并缓冲
            GzipSource gzippedResponseBody = new GzipSource(body.source());
            BufferedSource unzippedSource = Okio.buffer(gzippedResponseBody);

            // 构造一个新的 ResponseBody，不再带 Content-Encoding/Length
            ResponseBody newBody = ResponseBody.create(
              unzippedSource,
              body.contentType(),
              -1L
            );

            // 去掉 Content-Encoding/Length，让后续调用 body().string() 时拿到解压后的内容
            return response.newBuilder()
              .removeHeader("Content-Encoding")
              .removeHeader("Content-Length")
              .body(newBody)
              .build();
          }

          return response;
        }
      }
}
