/**
 * 封装axios的类
 * nh 2021.12.23
 */

import axios from "axios";
import vueStore from "@/store";
import { logicConfig } from "@/logicConfig";

var CancelToken = axios.CancelToken;
var cancel;

// 创建axios实例
const axiosservice = axios.create({
  timeout: 3000000, // 请求超时时间
  cancelToken: new CancelToken(function executor(c) {
    // executor 函数接收一个 cancel 函数作为参数
    cancel = c;
  }),
});

axiosservice.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

axiosservice.interceptors.response.use(
  function (res) {
    //在这里对返回的数据进行处理
    let resp = res.data;
    return res;
  },
  function (err) {
    console.log("axios interceptors err = ", err);
    return Promise.reject(err);
  }
);

export class axiosUtils {
  /**
   * get请求
   * @param url
   * @param data
   * @returns
   */
  protected async getRequest(url: string, data: any) {
    try {
      var urlArr = url.split("?");
      var urlPrefix = urlArr[0];
      var urlParamStr = urlArr[1] || "";

      var paramKeyArr = Object.keys(data || {});
      paramKeyArr.forEach(_key => { 
        urlParamStr = _key + '=' + data[_key] + '&' + urlParamStr;
      });

      var newUrl = urlPrefix + '?' + urlParamStr;

      let response = await this.customRequest(newUrl, {}, {}, "get");
      return response;
    } catch (err) {
      throw err;
    }
  }

  /**
   * post请求
   * @param url
   * @param data
   * @returns
   */
  protected async postRequest(url: string, data: any) {
    try {
      let response = await this.customRequest(url, {}, data, "post");
      return response;
    } catch (err) {
      throw err;
    }
  }

  /**
   * 自定义请求
   * @param url
   * @param headers
   * @param data
   * @param method get | post  默认post
   * @returns
   */
  protected async customRequest(
    url: string,
    headers: any,
    data: any,
    method: string = "post"
  ) {
    try {
      //headers里放入 groupCode、projectId  为了兼顾老ADM的写法，以后可删除
      headers = headers || {};
      headers.groupCode =
        headers.groupCode || vueStore.state.selectProject.groupCode;
      headers.projectId = headers.projectId || vueStore.state.selectProject.id;

      var urlArr = url.split("?");
      var urlPrefix = urlArr[0];
      var urlParamStr = urlArr[1] || "";
      if (urlParamStr.indexOf("projectId=") == -1) {
        urlParamStr =
          "projectId=" + vueStore.state.selectProject.id + "&" + urlParamStr;
      }

      if (urlParamStr.indexOf("groupCode=") == -1) {
        urlParamStr =
          "groupCode=" +
          vueStore.state.selectProject.groupCode +
          "&" +
          urlParamStr;
      }

      url = urlPrefix + "?" + urlParamStr;

      let response = await axiosservice({
        url,
        headers: headers || {},
        data,
        method: method == "post" ? "post" : "get",
      });
      return response.data;
    } catch (err) {
      // throw err;
      console.error(err);
      return {
        result: logicConfig.resultObj.failure,
        reason: '请求异常'
      };
    }
  }
}
