import { HeaderType } from "../constants/enum/header-type.enum";
import { CoreConfig } from "../model/CoreConfig";
import Vue from "vue";
import { tokenStore } from "../stores/token.store";

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

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

  createAuthHeaders() {
    return {
      "Content-Type": "application/json",
      Accept: "application/json",
      Authorization: "bearer " + tokenStore.token?.access_token,
      "user-identity": tokenStore.token?.jti,
    };
  }

  createMultipartAuthHeaders() {
    return {
      accessToken: tokenStore.token?.access_token,
    };
  }

  /**
   * @description: 创建上传认证消息头
   * @author ChenRui
   * @date 2021/4/6 11:17
   */
  createFileUploadAuthorizationHeader() {
    return {
      Accept: "application/json",
      Authorization: "bearer " + tokenStore.token?.access_token,
      "user-identity": tokenStore.token?.jti,
    };
  }

  /**
   * @description: 创建认证下载消息头
   * @author ChenRui
   * @date 2020/8/28 15:18
   */
  createFileDownloadAuthorizationHeader() {
    return {
      "Content-Type": "application/json",
      Authorization: "bearer " + tokenStore.token?.access_token,
      "user-identity": tokenStore.token?.jti,
    };
  }

  /**
   * @description: 普通请求
   * @author ChenRui
   * @date 2020/12/17 15:35
   */
  fetch(path: string, query: any, body: any | undefined, method: string, header: any): Promise<any> {
    path = query != null ? this.urlQueryConvert(path, query) : path;
    return fetch(path, {
      method: method ? method : "GET",
      headers: header,
      body: body instanceof FormData ? body : this.serialize(body),
    }).then(
      (response: Response) => {
        response.status; //=> number 100–599
        response.statusText; //=> String
        response.headers; //=> Headers
        response.url; //=> String
        return response.json();
      },
      (error) => {
        error.message; //=> String
      }
    );
  }

  /**
   * @description:  通用请求
   * @author ChenRui
   * @date 2020/12/17 15:39
   */
  general(api: any, query?: any | undefined, params?: any | undefined, requestConfig?: any): Promise<any> {
    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;
          case HeaderType.UPLOAD_AUTH.code:
            requestConfig = this.createFileUploadAuthorizationHeader();
            break;
          case HeaderType.DOWNLOAD_AUTH.code:
            requestConfig = this.createFileDownloadAuthorizationHeader();
            break;
          case HeaderType.MULTIPART.code:
            requestConfig = this.createMultipartAuthHeaders();
            break;
        }
      }
    }
    return this.fetch(api.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: json格式转表单格式
   * @author ChenRui
   * @date 2020/8/28 15:20
   */
  jsonToFormData(params: any) {
    if (params != null) {
      const formData = new FormData();
      Object.keys(params).forEach((key) => {
        formData.append(key, params[key]);
      });
      return formData;
    }
  }

  /**
   * @description: url请求参数组装
   * @author ChenRui
   * @date 2020/8/28 15:21
   */
  urlQueryConvert(url: string, query: any): string {
    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 { apiService };
