import {
	uploadImg,
	finishUpload
} from '@/api/common.js';
import crypto from 'crypto-js';
import {
	Base64
} from 'js-base64';

export const upload = function(r,operate) {
	return new Promise((resolve,reject)=>{
		let suffix = r.url.split('.')[1]
		uploadImg({
			"fineName":  r.url.split('/')[3] + '.' + suffix,
			operate
		}).then(res => {
			if (res.state == 'Success') {
				const date = new Date();
				date.setHours(date.getHours() + 1);
				const policyText = {
					expiration: date.toISOString(), // 设置policy过期时间。
					conditions: [
						// 限制上传大小。
						["content-length-range", 0, 1024 * 1024 * 1024],
					],
				};


				let fileName = r.name
				const host = 'https://' + res.content.bucket + '.' + res.content.endPoint;
				const policy = Base64.encode(JSON.stringify(policyText));
				const signature = crypto.enc.Base64.stringify(crypto.HmacSHA1(policy, res.content.token
					.accessKeySecret));;
				const filePath = r.url; // 待上传文件的文件路径。
				let paths = res.content.paths[0]
				// paths.pop()
				
				uni.uploadFile({
					url: host, // 开发者服务器的URL。
					filePath: filePath,
					name: 'file', // 必须填file。
					formData: {
						key: paths.join('/'),
						policy,
						success_action_status: '200', //让服务端返回200,不然，默认会返回204
						OSSAccessKeyId: res.content.token.accessKeyId,
						signature,
						'x-oss-security-token': res.content.token.securityToken // 使用STS签名时必传。
					},
					success: (res1) => {
						if (res1.statusCode === 200) {
							console.log('上传成功');
							// 告知服务器上传成功地址
							finishUpload(
								[{
									path: res.content.paths[0],
								}]).then(msg => {
									resolve(host + '/' + paths.join('/'))
							})
						}
					},
					fail: err => {
						console.log(err);
					}
				});


			}
		})
	})
}