import { DataInput } from "@/components/model/DataInput";
import { DataOutput } from "@/components/model/DataOutput";

class ApiService {
  createBasicHeaders() {
    return {
      "Content-Type": "application/json",
      Accept: "application/json"
    };
  }

  createAuthHeaders() {
    return {
      "Content-Type": "application/json",
      Accept: "application/json"
    };
  }

  fetch(path: string, query: any, body: DataInput<any> | undefined, method: string, header: any): Promise<DataOutput<any>> {
    path = query != null ? this.urlQueryConvert(path, query) : path;
    return fetch(path, {
      method: method ? method : "GET",
      headers: header,
      body: this.serialize(body)
    }).then(
      function(response) {
        response.status; //=> number 100–599
        response.statusText; //=> String
        response.headers; //=> Headers
        response.url; //=> String

        return response.json();
      },
      function(error) {
        error.message; //=> String
      }
    );
  }

  serialize(data: any): string | undefined {
    if (data) {
      try {
        return JSON.stringify(data);
      } catch (e) {
        console.log(e);
      }
    }
    return;
  }

  /**
   * @description: url请求参数组装
   * @author ChenRui
   * @date 2020/8/28 15:21
   */
  urlQueryConvert(url: string, query: any) {
    let connectiveSymbol = "";
    if (url.indexOf("?") !== -1) {
      connectiveSymbol = "&";
    } else {
      connectiveSymbol = "?";
    }
    if (query) {
      Object.keys(query).forEach((key, idx) => {
        const val = query[key];
        if (idx === 0) {
          if (val != null && val !== "null" && val !== "undefined") {
            url += connectiveSymbol + key + "=" + val;
          } else {
            url += connectiveSymbol + key + "=";
          }
        } else {
          if (val != null && val !== "null" && val !== "undefined") {
            url += "&" + key + "=" + val;
          } else {
            url += "&" + key + "=";
          }
        }
      });
    }
    return url;
  }
}
const apiService = new ApiService();
export default apiService;
