// import { getEnv } from '@/lib/utils/env/index.ts'
import { request } from '@/utils/request/index.ts';



// 创建一个a标签，并做点击下载事件
export function downloadFile(hrefUrl:any, fileName:any){
    console.log('downloadFile',hrefUrl,fileName);
    const a = document.createElement('a')
    a.href = hrefUrl
    a.target = '_blank' // 新窗口打开 20250320 yjc 新增
    a.download = fileName // 下载后文件名
    document.body.appendChild(a)
    a.click() // 点击下载
    document.body.removeChild(a) // 下载完成移除元素
}
// 封装blob对象
function dataURLToBlob(base64Str:any, mimeTypeStr:any) {
    const bstr = window.atob(base64Str); // 解码 base-64 编码的字符串，base-64 编码使用方法是 btoa()
    let length = bstr.length;
    const u8arr = new Uint8Array(length); // 创建初始化为0的，包含length个元素的无符号整型数组
    while (length--) {
        u8arr[length] = bstr.charCodeAt(length); // 返回在指定的位置的字符的 Unicode 编码
    }
    return new Blob([u8arr], { type: mimeTypeStr }); // 返回一个blob对象
}

// 后端返回base64公共导出
export function downloadFileByBase64(base64Str:any, mimeTypeStr:any, fileName:any){
    const myBlob = dataURLToBlob(base64Str, mimeTypeStr)
    const myUrl = window.URL.createObjectURL(myBlob)
    downloadFile(myUrl, fileName)
}
// 后端返回文件流公共导出
export function downloadFileByFileFlow(blobData:any, mimeTypeStr:any, fileName:any) {
    const blob = new Blob([blobData], { type: mimeTypeStr })
    const hrefUrl = window.URL.createObjectURL(blob) // 创建下载的链接
    downloadFile(hrefUrl, fileName);
}

//将base64转换为文件
export function base64Tofile(dataurl:any,fileName:any){
    console.log(dataurl,fileName);
    // debugger;
    let arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    const blob =new Blob([u8arr], { type: mime });
    // @ts-ignore
    blob.lastModifiedDate = new Date();
    // @ts-ignore
    blob.name = fileName;

    console.log(blob,'blob');
    download(blob)
    // window.location.replace(blobUrl)

    return blob;
}


export function download(downfile:any, fileName?: string) {
    const tmpLink = document.createElement("a");
    const objectUrl = URL.createObjectURL(downfile);

    tmpLink.href = objectUrl;
    tmpLink.target = '_blank' // 新窗口打开 20250320 yjc 新增
    tmpLink.download = fileName || downfile.name;
    document.body.appendChild(tmpLink);
    tmpLink.click();

    document.body.removeChild(tmpLink);
    URL.revokeObjectURL(objectUrl);
}

// 生成唯一的uuid
export function getUUID(randomLength:any) {
    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    return ("p"+S4() + S4()  + S4()  + S4()  + S4()  + S4() + S4() + S4())
}

export function downloadWav(base64Data:any,name:any) {
    // const tmpLink = document.createElement("a");
    // const objectUrl = URL.createObjectURL(downfile);

    // tmpLink.href = objectUrl;
    // tmpLink.download = downfile.name;
    // document.body.appendChild(tmpLink);
    // tmpLink.click();

    // document.body.removeChild(tmpLink);
    // URL.revokeObjectURL(objectUrl);
    const downloadLink = document.createElement('a');
    downloadLink.href = base64Data; // 这里的 base64Data 是之前转换得到的 Base64 字符串
    downloadLink.download = name; // 设置下载文件的名称
    downloadLink.click(); // 模拟点击下载链接
  }

export function saveDatatoJson(data:any, filename:any) {
    if (!data) {
        console.error('Console.save: No data')
        return;
    }
    if (!filename) filename = 'console.json'
    if (typeof data === "object") {
        data = JSON.stringify(data, undefined, 4)
    }
    const blob = new Blob([data], {
            type: 'text/json'
        }),
        e = document.createEvent('MouseEvents'),
        a = document.createElement('a')
    a.download = filename
    a.href = window.URL.createObjectURL(blob)
    a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
    e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
    a.dispatchEvent(e)
}
// file 文件转 base64
export function fileToBase64(file:any) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
            resolve(reader.result);
        };
        reader.onerror = (error) => {
            reject(error);
        };
    });
}
// file 文件转换成 字节流
export function fileToBytes(file:any) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsArrayBuffer(file);
        reader.onload = () => {
            resolve(reader.result);
        };
        reader.onerror = (error) => {
            reject(error);
        };
    });
}

// base64转文件
export function base64ToFile(base64Data: string, fileName: string, mimeType?: string): File {
    // 从base64字符串中提取数据部分和MIME类型
    let dataType = '';
    let base64Content = '';

    if (base64Data.includes(';base64,')) {
      const parts = base64Data.split(';base64,');
      dataType = parts[0].split(':')[1];
      base64Content = parts[1];
    } else {
      // 如果base64字符串不包含MIME信息，则使用传入的mimeType
      dataType = mimeType || 'application/octet-stream';
      base64Content = base64Data;
    }

    // 解码base64
    const byteCharacters = atob(base64Content);
    const byteArrays = [];

    // 将字符串转换为字节数组
    for (let i = 0; i < byteCharacters.length; i++) {
      byteArrays.push(byteCharacters.charCodeAt(i));
    }

    // 创建Uint8Array
    const uint8Array = new Uint8Array(byteArrays);

    // 创建Blob对象
    const blob = new Blob([uint8Array], { type: dataType });

    // 创建File对象
    return new File([blob], fileName, { type: dataType, lastModified: new Date().getTime() });
}

