import { DataOutput } from "@/model/DataOutput";
import { HeaderType } from "@/constants/enum/header-type.enum";
import { CoreConfig } from "@/model/CoreConfig";
import Vue from "vue";

class ApiService {
  /**
   * @description: 获取全局配置
   * @author ChenRui
   * @date 2020/12/17 16:16
   */
  get coreConfig(): Partial<CoreConfig> {
    if (Vue.prototype.$ec != null) {
      return Vue.prototype.$ec;
    }
    return {};
  }

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

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

  /**
   * @description: 普通请求
   * @author ChenRui
   * @date 2020/12/17 15:35
   */
  fetch(path: string, query: any, body: 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
      }
    );
  }

  /**
   * @description:  通用请求
   * @author ChenRui
   * @date 2020/12/17 15:39
   */
  general(api: any, query?: any | undefined, params?: any | undefined, requestConfig?: any | any): Promise<DataOutput<any>> {
    const url = this.coreConfig ? (this.coreConfig.baseApi || "") + api.url : "";
    if (!!api.url && !!api.method) {
      if (requestConfig == null) {
        switch (api.header) {
          case HeaderType.BASE.code:
            requestConfig = this.createBasicHeaders();
            break;
          case HeaderType.AUTH.code:
            requestConfig = this.createAuthHeaders();
            break;
        }
      }
    }
    return this.fetch(url, query, params, api.method, requestConfig);
  }

  /**
   * @description: 参数序列化
   * @author ChenRui
   * @date 2020/12/17 15:34
   */
  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;
