import { useMessage } from "@/hooks/useMessage";

const { createMessage } = useMessage()
/**
 * 打开winodw的方式
 * @param url url链接
 * @param opt 
 */
function openWindow(
    url: string,
    opt?: { target?: TargetContext | string; noopener?: boolean; noreferrer?: boolean },
) {
    const { target = '__blank', noopener = true, noreferrer = true } = opt || {};
    const feature: string[] = [];

    noopener && feature.push('noopener=yes');
    noreferrer && feature.push('noreferrer=yes');

    window.open(url, target, feature.join(','));
}

/**
 * 根据后台文件流下载
 * @param {*} data 数据
 * @param {*} filename 下载名称
 * @param {*} mime 类型
 * @param {*} bom
 */
export function downloadByData(data: BlobPart, filename: string, mime?: string, bom?: BlobPart) {
    const blobData = typeof bom !== 'undefined' ? [bom, data] : [data];
    const blob = new Blob(blobData, { type: mime || 'application/octet-stream' });

    const blobURL = window.URL.createObjectURL(blob);
    const tempLink = document.createElement('a');
    tempLink.style.display = 'none';
    tempLink.href = blobURL;
    tempLink.setAttribute('download', filename);
    if (typeof tempLink.download === 'undefined') {
        tempLink.setAttribute('target', '_blank');
    }
    document.body.appendChild(tempLink);
    tempLink.click();
    document.body.removeChild(tempLink);
    window.URL.revokeObjectURL(blobURL);
}

/**
 * 根据文件地址下载文件
 * @param url 下载的链接
 * @param target 下载的跳转方式
 * @param fileName 自定义下载文件名
 * @returns 
 */
export function downloadByUrl({
    url,
    target = '_blank',
    fileName,
}: {
    url: string;
    target?: TargetContext;
    fileName?: string;
}): boolean {
    // 浏览器的兼容性
    const isChrome = window.navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    const isSafari = window.navigator.userAgent.toLowerCase().indexOf('safari') > -1;

    if (/(iP)/g.test(window.navigator.userAgent)) {
        createMessage.error('您的浏览器不支持下载！')
        return false;
    }
    if (isChrome || isSafari) {
        // 创建a标签模拟下载
        const link = document.createElement('a');
        link.href = url;
        link.target = target;

        if (link.download !== undefined) {
            link.download = fileName || url.substring(url.lastIndexOf('/') + 1, url.length);
        }

        if (document.createEvent) {
            const e = document.createEvent('MouseEvents');
            e.initEvent('click', true, true);
            link.dispatchEvent(e);
            return true;
        }
    }
    if (url.indexOf('?') === -1) {
        url += '?download';
    }

    openWindow(url, { target });
    return true;
}
