import axios from 'axios';
import store from '@/store';

const ajax = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 100000,
});
const token = store.getters['user/token'];
ajax.interceptors.request.use(
  config => {
    config.headers = {
      token: token,
      // OrgId: auth.getUser().orgId,
      // UserId: auth.getUser().id,
    };
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);

const downloadFile = async (url, options) => {
  await ajax
    .get(url, { responseType: 'arraybuffer' })
    .then(resp => download(resp, options));
};
const downloadPostFile = async (url, options) => {
  await ajax
    .post(url, { responseType: 'arraybuffer' })
    .then(resp => download(resp, options));
};
const getFile = async (url, options) => {
  await ajax
    .get(url, { responseType: 'blob' })
    .then(resp => download(resp, options));
};

const download = (resp, options) => {
  const blob = new Blob([resp.data], {
    type: options.fileType ? options.fileType : 'application/octet-binary',
  });
  //创建下载的链接
  const href = window.URL.createObjectURL(blob);
  downloadBlob(href, options.fileName);
};

const downloadBlob = (blobUrl, fileName, revokeObjectURL) => {
  const downloadElement = document.createElement('a');
  downloadElement.href = blobUrl;
  //下载后文件名
  downloadElement.download = fileName;
  document.body.appendChild(downloadElement);
  //点击下载
  downloadElement.click();
  //下载完成移除元素
  document.body.removeChild(downloadElement);
  if (revokeObjectURL == null || revokeObjectURL) {
    //释放掉blob对象
    window.URL.revokeObjectURL(blobUrl);
  }
};

const getDownloadFileUrl = async (url, fileType) => {
  let blob;
  await ajax.get(url, { responseType: 'blob' }).then(resp => {
    blob = new Blob([resp.data], {
      type: fileType ? fileType : 'application/octet-binary',
    });
  });
  return window.URL.createObjectURL(blob);
};

const getDownloadFileUrlByPost = async (url, data, fileType) => {
  let blob;
  await ajax.post(url, data, { responseType: 'blob' }).then(resp => {
    blob = new Blob([resp.data], {
      type: fileType ? fileType : 'application/octet-binary',
    });
  });
  return window.URL.createObjectURL(blob);
};

const getDownloadFileBlob = async (url, fileType) => {
  let blob;
  await ajax.get(url, { responseType: 'blob' }).then(resp => {
    blob = new Blob([resp.data], {
      type: fileType ? fileType : 'application/octet-binary',
    });
  });
  return blob;
};

export default {
  ajax,
  downloadFile,
  getFile,
  getDownloadFileUrl,
  downloadPostFile,
  getDownloadFileUrlByPost,
  getDownloadFileBlob,
  downloadBlob,
};
