import OSS from 'ali-oss'
import store from '@/store'
import { Message } from 'element-ui'

let client = new OSS({
	region: store.state.oss.region,
	accessKeyId: store.state.oss.accessKeyId,
	accessKeySecret: store.state.oss.accessKeySecret,
	bucket: store.state.oss.bucket
})

//  上传
const CooOss = function (file) {
	if (this instanceof CooOss) {
		let objectKey = store.state.oss.folder + '/' + file.lastModified + '_' + getFileNameUUID()
		return new Promise((resolve, reject) => {
			client
				.multipartUpload(objectKey, file, {
					progress: function (p) {
						store.commit('oss/SET_PROGRESS', p * 100)
					}
				})
				.then((result) => {
					resolve({
						code: 200,
						url: objectKey,
						msg: 'ok'
					})
				})
				.catch((err) => {
					Message.error('上传出错了')
					reject({ code: 500, url: '', objectKey: '', msg: '上传出错了' })
				})
		})
	} else {
		return new CooOss(file)
	}
}

// 下载
export const download = function (key, filename = '') {
	const url = client.signatureUrl(key, {
		response: {
			'content-disposition': `attachment; filename=${encodeURIComponent(filename)};expires: 7200`
		}
	})
	window.location.href = url
}
/**
 *
 * @param {上传是设置文件key 一般是文件名} obecjtKey
 */
CooOss.prototype.getOssFileUrl = (obecjtKey) => {
	if (!obecjtKey) return new Error('object key 必须传')
	return 'https://' + bucket + '.' + region + '.aliyuncs.com/' + obecjtKey
}
const getFileNameUUID = () => {
	function rx() {
		return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
	}
	return `${+new Date()}_${rx()}${rx()}`
}
export default CooOss
