import { RcFile } from 'antd/lib/upload';
/** 判断是否是图片 */
const checkIsImage = (name: string): boolean => {
    let imgType = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff']
    if (name && name?.indexOf('/') !== -1) {
        let type = name?.split('/')[1]
        if (imgType?.indexOf(type) !== -1) {
            return true
        }
    } else {
        return false
    }
    return true
}

/** base64转File */
export const dataURLtoFile = (dataurl: any, filename: any) => {
    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);
    }
    return new File([u8arr], filename, { type: mime });
}

/* 获取图片宽高*/
export const imgMessage = (imgs: string[]): Promise<{ width: number, height: number }[]> => {
    return new Promise((resolve, reject) => {
        if (imgs.length > 0) {
            let imgsAll = imgs?.map((item: string) => {
                return new Promise((resolve) => {
                    let img: any = new Image();
                    img.onload = function (e: any) {
                        resolve({ width: this.width, height: this.height })
                    }
                    img.src = item;
                })
            })
            Promise.all(imgsAll).then((res: any) => {
                resolve(res)
            })
        } else {
            reject([])
        }
    })
};

/* 获取视频宽高*/
export const videoMessage = (videos: RcFile[]): Promise<{ width: number, height: number, videoLength: number }[]> => {
    return new Promise((resolve, reject) => {
        if (videos.length > 0) {
            let videoAll = videos?.map((item: RcFile) => {
                return new Promise((resolve) => {
                    var videoUrl = URL.createObjectURL(item);
                    var videoObj = document.createElement("video");
                    videoObj.onloadedmetadata = function (evt) {
                        URL.revokeObjectURL(videoUrl);
                        // 执行上传的方法，获取外网路径，上传进度等
                        resolve({ width: videoObj.videoWidth, height: videoObj.videoHeight, videoLength: videoObj.duration })
                    };
                    videoObj.src = videoUrl;
                    videoObj.load();
                })
            })
            Promise.all(videoAll).then((res: any) => {
                resolve(res)
            })
        } else {
            reject([])
        }
    })
};

/** 
 * blob 转 base64
 * @param blob 图片2进制流
 */
export const blobToBase64 = (blob: Blob) => {
    return new Promise((resolve, reject) => {
        const fileReader = new FileReader();
        fileReader.onload = (e: any) => {
            resolve(e.target.result);
        };
        // readAsDataURL
        fileReader.readAsDataURL(blob);
        fileReader.onerror = () => {
            reject(new Error('blobToBase64 error'));
        };
    });
}