import http from './http.js'

function upload(files, callback) {
    const uploadResults = [];
    let count = files.length;

    files.forEach(file => {
        http.get("/oss/get", {}, (res) => {
            console.log('get', res);
            const sign = res.data;
            doUpload(sign, file.path, (result) => {
                uploadResults.push(result);
                count--;
                if (count === 0) {
                    callback(uploadResults);
                }
            });
        });
    });
}

function doUpload(sign, filePath, callback, module = 'upload') {
    const key = `${module}/${new Date().getTime()}.png`;
    const prk = sign.host + "/" + key;
    uni.uploadFile({
        url: sign.host,
        filePath,
        name: 'file',
        formData: {
            key,
            policy: sign.policy,
            OSSAccessKeyId: sign.accessKeyId,
            signature: sign.signature,
            success_action_status: '200'
        },
        success: (res) => {
            console.log('oss', prk);
            callback(prk);
        },
        fail: (err) => {
            console.log('oss', err);
            callback({ error: err });
        }
    });
}

// 调用示例
//upload(files, (uploadUrls) => {
//    console.log('All upload URLs:', uploadUrls);
//});

export default {
	upload: upload
}

 