import { api } from 'common/api'

const _getFileTypeByBase64 = (base64) => {
    let arr = base64.split(','),
        fileType = arr[0].match(/:(.*?);/)[1]
    return fileType
}

/**
 * ArrayBuffer转Base64
 * @param {*} arrayBuffer 
 * @returns 
 */
export const ArrayBufferToBase64 = async (arrayBuffer) => {
    const blob = ArrayBufferToBlob(arrayBuffer)
    const base64 = await BlobToBase64(blob)
    return base64
}

/**
 * ArrayBuffer转Blob
 * @param {*} arrayBuffer 
 * @returns 
 */
export const ArrayBufferToBlob = (arrayBuffer) => {
    return new Blob([arrayBuffer])
}

/**
 * Base64转Blob
 * @param {*} base64 
 * @returns 
 */
export const Base64ToBlob = (base64) => {
    let arr = base64.split(','),
        fileType = _getFileTypeByBase64(base64),
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)

    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    return new Blob([u8arr], { type: fileType })
}

/**
 * Blob转文件
 * @param {*} blob 
 * @param {*} fileName 
 * @param {*} fileType 
 * @returns 
 */
export const BlobToFile = (blob, fileName, fileType) => {
    blob.lastModifiedDate = new Date()
    blob.name = fileName
    const file = new File([blob], fileName, { type: fileType })
    return file
}

/**
 * Base64转文件
 * @param {*} base64 
 * @param {*} fileName 
 * @returns 
 */
export const Base64ToFile = (base64, fileName) => {
    const blob = Base64ToBlob(base64)
    const fileType = _getFileTypeByBase64(base64)
    const file = BlobToFile(blob, fileName, fileType)
    return file
}

/**
 * Blob转Base64
 * @param {*} blob 
 * @returns 
 */
export const BlobToBase64 = async (blob) => {
    return new Promise(resolve => {
        const reader = new FileReader()
        reader.readAsDataURL(blob)
        reader.onload = (e) => {
            resolve(e.target.result)
        }
    })
}

export const GetFileName = (disposition) => {
    const dispositionSplit = disposition.split(';')
    const fileName = decodeURI(
        dispositionSplit[1].split('=')[1],
        dispositionSplit[2].match(/(?<=\*=).*?(?=')/)[0]
    )
    return fileName
}

export const PreviewFileResponse = async (id) => {
    return api.sysFileInfoPreview({ id }).then((res) => {
        return res
    })
}

export const PreviewFileArrayBuffer = async (id) => {
    const response = await PreviewFileResponse(id)
    return response.data
}

export const PreviewFileBase64 = async (id) => {
    const file = await PreviewFile(id)
    if (!file) return
    const base64 = await BlobToBase64(file)
    return base64
}

export const PreviewFile = async (id) => {
    const response = await PreviewFileResponse(id)
    const arrayBuffer = response.data
    const blob = ArrayBufferToBlob(arrayBuffer)
    const disposition = response.headers['content-disposition']
    if (!disposition) return
    const fileName = GetFileName(disposition)
    const file = BlobToFile(blob, fileName, response.headers['content-type'])
    return file
}