package com.shanghaichengdi.ghjgitem.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName ApiUtils
 * @Author gfq
 * @Date 2020/12/03
 * @Version 1.0
 **/
@Slf4j
public class ApiUtils {

  /**
   * 由数据交换平台提供给应用系统，用于鉴别应用系统身份 ，需要替换成应用系统自己的client_id
   */
  private final static String CLIRNT_ID = "243";

  /**
   * 由数据交换平台提供给应用系统，需要替换成应用系统自己的secret_key
   */
  private final static String SECRET_KEY = "MIIBIjANBgkqhkiG9w0BAQEABCDEFG8AMIIBCgKCAQEA5mZjecr3Y63o85F55OmzRLmwY0AansLbjaBzqh3HNgAtJs7z7/oLTfNAyUxY3izM5aHPg52kzAwRslnKD1sxlSjL9EL3YQRt7wvCCBIzT+INy6rkqTkAEtK4EvbXVGF8clisY//af5F/P3CH+YecUJlFBvw29oCchb33x49+226aOmud2GU7UxUAYdzsB7GScLtI1V30+l8XKyzYlg11Yf+Na34q2TkJxheCbpwsMM4Y99PUpZR7xe14M6vD9NFk5Qb678bC7fYi04RxG+cOfxI9WYobVZW1wW6UjNW1uo0P79d3CUQFfPMqr9ZkY56QkWrh1FYn8ctXDBxUQFLnTwIDAQAB";

  //private final static  String TOKEN_URl="https://10.83.248.123:2001/externalAuth/auth/checkToken";

  /**
   * @methodName:
   * @description: TODO  调用该类直接跳过ssl证书
   * @author: sbj
   * @createTime: 2022/7/17 13:44
   * @parames:
   * @return:
   */
  static {
    try {
      trustAllHttpsCertificates();
      HttpsURLConnection.setDefaultHostnameVerifier
          (
              (urlHostName, session) -> true
          );
    } catch (Exception e) {
    }
  }

  private static void trustAllHttpsCertificates()
      throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustAllCerts = new TrustManager[1];
    trustAllCerts[0] = (TrustManager) new TrustAllManager();
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  }

  private static class TrustAllManager implements X509TrustManager {

    @Override
    public X509Certificate[] getAcceptedIssuers() {
      return null;
    }

    @Override
    public void checkServerTrusted(X509Certificate[] certs, String authType) {
    }

    @Override
    public void checkClientTrusted(X509Certificate[] certs, String authType) {
    }
  }


  public static String api(Map<String, String> map, String serverUrl, String cmd) {
    try {
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
      //1.计算签名
      //1.1请求头
      Map<String, String> headers = new HashMap();
      //用户key
      headers.put("clientid", CLIRNT_ID);
      //用户ips
      headers.put("ip", "127.0.0.1");
      //请求唯一标识，36位
      headers.put("guid", UUID.randomUUID().toString());
      headers.put("sendtime", df.format(new Date()));
      //1.2获得签名参数
      String sign = AuthUtils.getSign(headers, SECRET_KEY);
      headers.put("sign", sign);

      String url;
      if (cmd.equals("serviceValidate")) {
        url = serverUrl + cmd + "?service=" + map.get("service") + "&ticket=" + map.get("ticket")
            + "&appId=" + map.get("appId") + "&appSecret=" + map.get("appSecret");

      } else {
        url = serverUrl + cmd + "?token=" + map.get("token");
      }

      String json = null;

      return get(url, headers);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  public static String appApiTowa(Map<String, Object> map, String serverUrl, String cmd) {
    try {
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
      Map<String, String> headers = new HashMap();
      String url = serverUrl + cmd;
      String json = null;
      //2构造请求地址和参数
      if (cmd.equals("login")) {
        //登录
        json = "{\"userId\":\"" + map.get("userId") +
            "\",\"password\":\"" + map.get("password") + "\"}";
      } else if (cmd.equals("GetAppSupervision")) {
        json = "{\"CurrentPage\":\"" + map.get("CurrentPage") +
            "\",\"pageSize\":\"" + map.get("pageSize") +
            "\",\"documentType\":\"" + map.get("documentType") +
            "\",\"keywords\":\"" + map.get("keywords") + "\"}";
      }
      return post(url, headers, json, "application/json");
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  public static String apiTow(Map<String, String> map, String serverUrl, String cmd) {
    try {
      DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
      //1.计算签名
      //1.1请求头
      Map<String, String> headers = new HashMap();
      //用户key
      headers.put("clientid", CLIRNT_ID);
      //用户ips
      headers.put("ip", "127.0.0.1");
      //请求唯一标识，36位
      headers.put("guid", UUID.randomUUID().toString());
      headers.put("sendtime", df.format(new Date()));
      //1.2获得签名参数
      String sign = AuthUtils.getSign(headers, SECRET_KEY);
      headers.put("sign", sign);

      String url = serverUrl + cmd;
      String json = null;
      //2构造请求地址和参数
      switch (cmd) {
        case "getUserList":
          //取得用户信息列表
          json = "{\"username\":\"" + map.get("username") + "\",\"mobile\":\"" + map.get("mobile")
              + "\",\"groupId\":\"" + map.get("groupId") + "\"}";
          break;
        case "getUserByUserId":
          //根据指定用户名取得用户信息
          json = "{\"userId\":\"" + map.get("userId") + "\"}";
          break;
        case "getUserByGroupId":
          //根据组织机构ID获取用户信息
          json = "{\"groupId\":\"" + map.get("groupId") + "\"}";
          break;
        case "getGroupById":
          //根据ID取得组织机构
          json = "{\"groupId\":\"" + map.get("groupId") + "\"}";
          break;
        case "getRelatedGroup":
          //根据用户ID获取组织机构信息
          json = "{\"userPkId\":\"" + map.get("userPkId") + "\"}";
          break;
      }
      String result = post(url, headers, json, "application/json");
      return result;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }


  private static String get(String url, Map<String, String> headers) {
    String result = null;
    HttpURLConnection connection = null;
    try {
      URL get = new URL(url);
      connection = (HttpURLConnection) get
          .openConnection();
      //需要输出
      connection.setDoOutput(true);
      //需要输入
      connection.setDoInput(true);
      //不允许缓存
      connection.setUseCaches(false);
      connection.setConnectTimeout(3000);
      connection.setReadTimeout(3000);
      connection.setRequestMethod("GET");
      for (Map.Entry<String, String> entry : headers.entrySet()) {
        connection.setRequestProperty(entry.getKey(), entry.getValue());
      }

      connection.connect();
      InputStream ins = connection.getInputStream();

      BufferedReader reader = new BufferedReader(new InputStreamReader(ins, "utf-8"));
      StringBuffer buffer = new StringBuffer();

      String line = null;
      while ((line = reader.readLine()) != null) {
        buffer.append(line);
        buffer.append("\r\n");
      }
      return buffer.toString();

    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }

  public static String post(String url, Map<String, String> headers, String json,
      String ContentType) {
    String result = null;
    HttpURLConnection connection = null;
    try {
      URL post = new URL(url);
      connection = (HttpURLConnection) post.openConnection();
      //需要输出
      connection.setDoOutput(true);
      //需要输入
      connection.setDoInput(true);
      //不允许缓存
      connection.setUseCaches(false);
      connection.setConnectTimeout(3000);
      connection.setReadTimeout(3000);
      connection.setRequestMethod("POST");
      for (Map.Entry<String, String> entry : headers.entrySet()) {
        connection.setRequestProperty(entry.getKey(), entry.getValue());
      }
      connection.setRequestProperty("Content-Type", ContentType);
      connection.connect();
      OutputStream dos = connection.getOutputStream();
      dos.write(json.getBytes());

      dos.flush();
      dos.close();
      InputStream ins = connection.getInputStream();

      BufferedReader reader = new BufferedReader(new InputStreamReader(ins, "utf-8"));
      StringBuffer buffer = new StringBuffer();

      String line = null;
      while ((line = reader.readLine()) != null) {
        buffer.append(line);
        buffer.append("\r\n");
      }
      return buffer.toString();

    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }

  public static String postform(String url, Map<String, String> headers, String json) {
    String result = null;
    HttpURLConnection connection = null;
    try {
      URL post = new URL(url);
      connection = (HttpURLConnection) post.openConnection();
      //需要输出
      connection.setDoOutput(true);
      //需要输入
      connection.setDoInput(true);
      //不允许缓存
      connection.setUseCaches(false);
      connection.setConnectTimeout(30000);
      connection.setReadTimeout(30000);
      connection.setRequestMethod("POST");
      for (Map.Entry<String, String> entry : headers.entrySet()) {
        connection.setRequestProperty(entry.getKey(), entry.getValue());
      }

      connection.setRequestProperty("Accept", "*/*");
      connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
      connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
      connection.setRequestProperty("Connection", "keep-alive");
      connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
      connection.setRequestProperty("Range", "bytes=" + "");
      connection.connect();
      OutputStream dos = connection.getOutputStream();
      dos.write(json.getBytes(StandardCharsets.UTF_8));
      dos.flush();
      dos.close();
      InputStream ins = connection.getInputStream();

      BufferedReader reader = new BufferedReader(new InputStreamReader(ins, "utf-8"));
      StringBuilder buffer = new StringBuilder();

      String line;
      while ((line = reader.readLine()) != null) {
        buffer.append(line);
      }
      return buffer.toString();

    } catch (Exception e) {
      PrintLogUtils.printErrorLogInfo(e);
      return "";
    }
  }
}
