import axios from 'axios';
import Api from '../http/api';
import { postRequest } from '../http'
import { ElMessage } from 'element-plus'

export const uploadFile = async (file: any) => {
    let imgInfo = await getImgInfo(file);
    let status = await upload(imgInfo, file);
    if (status) {
        return imgInfo
    } else {
        return false;
    }
}

const getImgInfo = (file: any) => {
    return new Promise((resolve) => {
        let type = file.type || 'image/jpg';
        postRequest(Api.mediaUpload, {
            params: {
                bizType: 2,
                contentType: type,
                fileSuffix: type.split('/')[1],
                fileType: 1,
            }
        }).then(res => {
            let { code, data } = res;
            if ( code === 0 ) {
                resolve(data)
            }
        }).catch(error => {
            ElMessage({
                type: 'error',
                message: 'network error!'
            })
        })
    })
}
 
const upload = (params: any, file: any) => {
    let type = file.type || 'image/jpg';
    return new Promise((resolve) => {
        axios({
            method: 'PUT',
            url: params.url,
            data: new Blob([file]),
            headers: {
                'Authorization': params.authorization,
                'x-amz-date': params.date,
                'Content-Type': type,
            }
        }).then(res => {
            let { status } = res
            if (status == 200) {
                resolve(true)
            } else {
                ElMessage({
                    type: 'error',
                    message: 'upload error!'
                })
            }
        }).catch(error => {
            ElMessage({
                type: 'error',
                message: 'upload error!'
            })
        })
    })
}