import { request } from '@umijs/max';

/** MimeType */
export enum MimeType {
  XLSX = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  ZIP = 'application/zip',
  JSON = 'application/json',
}

/**
 * 解析blob响应内容并下载
 * @param res - blob响应内容
 * @param mimeType - MIME类型
 */
export function resolveBlob(res: any, mimeType: string, specifiedFileName: string = 'file') {
  const aLink = document.createElement('a');
  const blob = new Blob([res.data], { type: mimeType });
  // 从response的headers中获取filename,
  // 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*');
  // console.log(res);
  const contentDisposition = decodeURI(res.headers['content-disposition']);
  const result = patt.exec(contentDisposition);
  let fileName = result ? result[1] : specifiedFileName;
  fileName = fileName.replace(/"/g, '');
  aLink.style.display = 'none';
  aLink.href = URL.createObjectURL(blob);
  aLink.setAttribute('download', fileName); // 设置下载文件名称
  document.body.appendChild(aLink);
  aLink.click();
  URL.revokeObjectURL(aLink.href); // 清除引用
  document.body.removeChild(aLink);
}

/**
 * 下载 Zip 文件
 * @param url - url 地址
 * @param options - 请求参数
 */
export function downLoadZip(url: string, params?: any) {
  request(url, {
    method: 'GET',
    params,
    responseType: 'blob',
    getResponse: true,
  }).then((res) => {
    resolveBlob(res, MimeType.ZIP);
  });
}

/**
 * 下载 XLSX 文件
 * @param url - url 地址
 * @param method - 请求方式
 * @param options - 请求选项
 */
export async function downloadXlsx(
  url: string,
  method: string = 'GET',
  options?: Record<string, any>,
) {
  return request(url, {
    method: method,
    ...options,
    responseType: 'blob',
    getResponse: true,
  }).then((res) => {
    resolveBlob(res, MimeType.XLSX);
  });
}

/**
 * 下载文本文件
 * @param url - url 地址
 * @param type - mime-type
 * @param fileName - 文件名
 * @param method - 请求方法
 * @param options - 请求选项
 */
export function downloadCommonFile(
  url: string,
  type: string,
  fileName: string = 'file',
  method: string = 'GET',
  options?: Record<string, any>,
) {
  request(url, {
    method: method,
    headers: {
      isToken: false,
    },
    skipValidating: true,
    ...options,
    responseType: 'blob',
    getResponse: true,
  }).then((res) => {
    resolveBlob(res, type, fileName);
  });
}
