

import Common from './Common';

export const ajaxApiGet = (url, datas) => {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: Common.getApiURL(url),
      type: 'get',
      contentType: 'application/json',
      beforeSend: function (request) {
        Common.addTokenToRequest(request);
      },

      success: function (data) {
        resolve(data);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        reject(XMLHttpRequest);
      },
    });
  });
};

export const ajaxApiPost = (url, datas) => {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: Common.getApiURL(url),
      type: 'post',
      contentType: 'application/json',
      data: JSON.stringify(datas),
      beforeSend: function (request) {
        Common.addTokenToRequest(request);
      },
      success: function (data) {
        resolve(data);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        reject(XMLHttpRequest);
      },
    });
  });
};


export const ajaxApiFile = (url, datas) => {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: Common.getApiURL(url),
      type: 'post',
      data: datas,
      processData: false,
      contentType: false,
      beforeSend: function (request) {
        Common.addTokenToRequest(request);
      },

      success: function (data) {
        resolve(data);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        reject(XMLHttpRequest);
      },
    });
  });
};

// 下载文件
export const download = url => {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: url,
      method: 'GET',

      xhrFields: {
        responseType: 'blob',
      },
      success: function (data) {
        resolve(data);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        reject(XMLHttpRequest);
      },
    });
  });
};

export const debounce = (fn, delay = 500) => {
  let timer = null;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};