import { httpApp } from "@/plugins/axiosApp";
import router from "@/router";
import { AxiosResponse } from "axios";

// 下载文件
export async function downloadFileURL(url: string,data: Record<string, any> = {}) {
  return httpApp
    .get(url, { responseType: "blob" ,params:data})
    .then((res) => {
      return responseToFile(res);
    })
    .catch((err) => console.log(err));
}

export async function responseToFile(response: AxiosResponse) {
  return new Promise(() => {
    const { data, headers } = response;
    const fileName = headers["content-disposition"].replace(
      /\w+;\s*filename=(.*)/,
      "$1"
    );
    //Here, when the JSON file is returned, the JSON.stringify Processing, other types of files do not need to be processed
    //const blob = new Blob([JSON.stringify(data)], ...)
    const blob = new Blob([data], { type: headers["content-type"] });
    const dom = document.createElement("a");
    const url = window.URL.createObjectURL(blob);
    dom.href = url;
    dom.download = decodeURI(fileName);
    dom.style.display = "none";
    document.body.appendChild(dom);
    dom.click();
    dom.parentNode?.removeChild(dom);
    window.URL.revokeObjectURL(url);
  });
}
// 返回
export function goBack() {
  router.back();
}
