import saveAs from 'file-saver'
import httpRequest from "~/service/index";
// 验证是否为blob格式
export async function blobValidate(data: any) {
  try {
    const text = await data.text();
    JSON.parse(text);
    return false;
  } catch (error) {
    return true;
  }
}
export function download(url: string, params: object, filename: string) {
  const downloadLoadingInstance = ElLoading.service({ text: "Downloading", background: "rgba(0, 0, 0, 0.7)", })
  const isLogin2 = useCookie('tokenKey')
  return httpRequest.post<Blob>(url, params, {
    responseType: 'blob',
  }).then(async (data:any) => {
    const isLogin = await blobValidate(data);
    if (isLogin) {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      ElMessage.error(rspObj.msg);
    }
    downloadLoadingInstance.close();
  }).catch((r:any) => {
    console.error(r)
    ElMessage.error('下载异常！')
    downloadLoadingInstance.close();
  })
}