/**
 * 压缩图片
 * @param file input获取到的文件
 */
export function compressFile(file) {
    return new Promise(resolve => {
        let fileObj = file;
        let reader = new FileReader();
        reader.readAsDataURL(fileObj); //转base64
        reader.onload = function (e) {
            let image = new Image(); //新建一个img标签（还没嵌入DOM节点)
            image.src = e.target.result;
            image.onload = function () {
                let canvas = document.createElement('canvas'), // 新建canvas
                    context = canvas.getContext('2d'),
                    imageWidth = image.width * 0.5,    //压缩后图片的大小
                    imageHeight = image.height * 0.5,
                    data = '';
                canvas.width = imageWidth;
                canvas.height = imageHeight;
                context.drawImage(image, 0, 0, imageWidth, imageHeight);
                data = canvas.toDataURL(file.type); // 输出压缩后的base64
                let arr = data.split(','), mime = arr[0].match(/:(.*?);/)[1], // 转成blob
                    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                let files = new window.File([new Blob([u8arr], {type: mime})], file.name, {type: file.type}) // 转成file
                resolve(files) // 回调
            }
        }
    })
}

// 保存字符串文本到文件
export function saveContentToFile(content, fileName) {
    let blob = new Blob([content]);
    saveBlobToFile(blob);
}

// 保存blob对象到文件
export function saveBlobToFile(blob, fileName) {
    let downLink = document.createElement('a');
    downLink.download = fileName;
    downLink.href = URL.createObjectURL(blob);
    document.body.appendChild(downLink);
    downLink.click();
    document.body.removeChild(downLink)
}

// 获取音频文件时长
export function getAudioDuration(file) {
    return new Promise((resolve, reject) => {
        let audio = new Audio()
        audio.src = URL.createObjectURL(file)
        audio.addEventListener('canplaythrough', () => {
            resolve(Math.round(audio.duration))
        })
    })
}

// 检查链接是否为图片
export function checkImgExists(imgurl) {
    return new Promise(function(resolve, reject) {
        const ImgObj = new Image()
        ImgObj.src = imgurl
        ImgObj.onload = function(res) {
            resolve(res)
        }
        ImgObj.onerror = function(err) {
            reject(err)
        }
    })
}
