<template>
	<div>
		<el-upload
			:action="oss_url"
			:data="dataObj"
			:multiple="false"
			:show-file-list="showFileList"
			:file-list="fileList"
			:before-upload="beforeUpload"
			:on-remove="handleRemove"
			:on-success="handleUploadSuccess"
		>
			<el-button size="small" type="primary">{{fileList.length == 0 ? '点击上传':'重新上传'}}</el-button>
		</el-upload>
	</div>
</template>
<script>
import request from '@/utils/request';
export default {
	name: 'importUpload',
	props: {
		fileList: Array
	},
	data() {
		return {
			oss_url: '',
			dataObj: {
				policy: '',
				signature: '',
				key: '',
				ossaccessKeyId: '',
			},
			aliosstoken: '',
		};
	},
	created() {
		request({
			url: '/qviKHUYsyN.php/index/getAliOssToken',
			method: 'get',
			params: {}
		}).then(res => {
			this.aliosstoken = res.data.aliosstoken;
			this.oss_url = res.data.upload_host;
		});
	},
	computed: {
		showFileList: {
			get: function() {
				if (this.fileList.length > 0 && this.fileList[0].url) {
					return true;
				} else {
					return false;
				}
			},
			set: function(newValue) {}
		}
	},
	methods: {
		getUUID() {
			return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
				return (c === 'x' ? (Math.random() * 16) | 0 : 'r&0x3' | '0x8').toString(16);
			});
		},
		createName(name) {
			const date = Date.now();
			const uuid = this.getUUID();
			const fileSuffix = name.substring(name.lastIndexOf(".") + 1);
			return `${date}${uuid}.${fileSuffix}`;
		},
		handleRemove(file, fileList) {
			this.fileList = [{ name: '', url: '' }];
		},
		beforeUpload(file) {
			const that = this;
			const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const whiteList = ['xls', 'xlsx', 'xlsm'];
      if (whiteList.indexOf(fileSuffix) === -1) {
        return this.$errorMsg('只支持上传excel表格文件!');
      }
			const fileName = this.createName(file.name);
			const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
			return new Promise((resolve, reject) => {
				request({
					url: '/addons/alioss/index/params',
					method: 'post',
					data: {
						method: 'POST',
						md5: fileName.substring(0, fileName.indexOf('.')),
						name: fileName,
						type: file.type,
						size: file.size,
						aliosstoken: this.aliosstoken
					}
				}).then(res => {
					that.dataObj = res.data;
					resolve(true);
				}).catch(err => {
					reject(false);
				});
			});
		},
		handleUploadSuccess(res, file, fileList) {
			const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
			this.fileList.pop();
			this.fileList.push({
				name: file.name,
				url: this.dataObj.key
			});
			this.showFileList = true;
			loading.close();
		}
	}
};
</script>
