import request from '@/requset/axios'

//文件上传
export function fileUpload(data: FormData) {
    return new Promise((resolve, reject) => {
        request
            .request({
                url: '/file/v1/fileUpload',
                method: 'post',
                data,
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            })
            .then((res) => resolve(res.data || {}))
            .catch((err) => reject(err))
    })
}

// 附件在线预览
export function onlinePreview(fileId = '') {
    return new Promise((resolve, reject) => {
        request
            .get(`/file/onlinePreviewController/v1/onlinePreview?fileId=${fileId}`)
            .then((res) => resolve(res.data || {}))
            .catch((err) => reject(err))
    })
}

// 获取图片可以预览的url
export const getImgUrlById = (fileId: string) => {
    return new Promise((resolve, reject) => {
        request
            .download('/file/v1/preview?fileId=' + fileId, 'get', undefined, 'blob')
            .then((res) => {
                if (res?.data?.size > 0) {
                    const blob = res.data
                    const reader = new FileReader()
                    reader.readAsDataURL(blob)
                    reader.onload = function (e) {
                        resolve(e.target?.result || '')
                    }
                } else {
                    resolve('')
                }
            })
            .catch((err: unknown) => {
                reject(err)
            })
    })
}
