/**
 * 加载远程 script
 */
function getScript(url, callback) {
    const script = document.createElement('script');
    script.src = url;
    script.async = 'async';
    if (callback) {
        script.onload = callback;
    }
    document.head.appendChild(script);
}

 

/**
 * 下载图片
 */
function async openDownload(imgUrl, name) {
    const link = imgUrl;
    const files = link.split('.');
    const type = files[files.length - 1];

    // 初始化 XMLHttpRequest
    const x = new XMLHttpRequest();

    if (['jpg', 'png', 'jpeg', 'gif'].includes(type)) {
        // 图片
        const image = await this.getBase64Image(link);
        x.open('GET', image, true);
    } else {
        // 非图片
        x.open('GET', link, true);
    }

    x.responseType = 'blob';
    x.onload = function() {
        const url = window.URL.createObjectURL(x.response);
        const a = document.createElement('a');
        a.href = url;
        a.download = name || '';
        a.click();
    };
    x.send();
},

function getBase64Image(img) {
    return new Promise((resolve, reject) => {
        if (!img) {
            reject(new Error(null));
        }

        const canvas = document.createElement('canvas');
        const image = new Image();
        image.setAttribute('crossOrigin', 'anonymous');
        image.src = `${img}?v=${Math.random()}`;
        image.onload = () => {
            canvas.width = image.width;
            canvas.height = image.height;
            const ctx = canvas.getContext('2d');
            ctx.drawImage(image, 0, 0, image.width, image.height);
            const ext = image.src
                .substring(image.src.lastIndexOf('.') + 1)
                .toLowerCase();
            resolve(canvas.toDataURL(`image/${ext}`));
        };
        image.error = () => {
            reject(new Error(null));
        };
    });
},

 

/**
 * 姓名脱敏
 */
function desensitizeName(num) {
    const pat = /.(?=[\u4e00-\u9fa5])/;
    return num.replace(pat, '*');
}

/**
 * 手机号脱敏
 */
function desensitizePhone(num) {
    const pat = /(\d{3})\d*(\d{4})/;
    return num.replace(pat, '$1****$2');
}