<template>
	<block>
		<el-upload style="display: inline-block; margin: 0 10px;" :action="upload_host" :data="dataObj" :multiple="false" :before-upload="beforeUpload" :on-success="handleUploadSuccess" :file-list="importFileList">
			<el-button @click="upload" size="small" type="primary" :loading="importLoading">{{ importLoading ? '导入中...' : title }}</el-button>
		</el-upload>
		<el-dialog title="错误提示" :visible.sync="isShowMsg" width="50%" :close-on-click-modal="false" :destroy-on-close="true">
			<div class="html" v-html="html"></div>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="isShowMsg = false">确定</el-button>
			</div>
		</el-dialog>
	</block>
</template>
<script>
import request from '@/utils/request';
import SparkMD5 from 'spark-md5'
export default {
	name: 'importUploadPhp',
	props: {
		requestUrl: {
			type: String,
			default: ''
		},
		title: {
			type: String,
			default: '导入'
		},
		batch_month: {
			type: String,
			default: ''
		},
	},
	data() {
		return {
			importFileList: [],
			importLoading: false,
			timer: '',
			aliosstoken: '',
			upload_host: '',
			dataObj: {
				policy: '',
				signature: '',
				key: '',
				ossaccessKeyId: '',
			},
			md5: '',
			isShowMsg: false,
			html: ''
		};
	},
	created() {
		
	},
	methods: {
		getAliOssToken(){
			const that = this;
			request({
				url: '/qviKHUYsyN.php/index/getAliOssToken',
				method: 'get',
				params: {}
			}).then(res => {
				that.aliosstoken = res.data.aliosstoken;
				that.upload_host = res.data.upload_host
			});
		},
		close(){
			this.isShowMsg = false
		},
		emitInput(val) {
			this.$emit('input', val);
		},
		upload(){
			this.getAliOssToken()
		},
		beforeUpload(file) {
			const that = this;
			return new Promise((resolve, reject) => {
				var fileReader = new FileReader();
				//此处打印file可看到file下的raw为文件属性
				let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice
				var spark = new SparkMD5.ArrayBuffer();
				//获取文件二进制数据
				fileReader.readAsArrayBuffer(file)
						
				//异步执行函数
				fileReader.onload = function(e){
					spark.append(e.target.result);
					var md5 = spark.end()
					that.md5 = md5
					console.log(md5)
					request({
						url: '/addons/alioss/index/params',
						method: 'post',
						data: {
							method: 'POST',
							md5: md5,
							name: md5 + file.name.substring(file.name.lastIndexOf(".")),
							type: file.type,
							size: file.size,
							aliosstoken: that.aliosstoken
						}
					})
						.then(res => {
							that.dataObj = res.data;
							resolve(true);
						})
						.catch(err => {
							reject(false);
						});
				}
			});
		},
		handleUploadSuccess(res, file, fileList) {
			this.getNotify(file)
			this.toLead()
		},
		toLead() {
			let params = {
				file: this.dataObj.key.replace('${filename}')
			}
			request({
				url: this.requestUrl,
				method: 'post',
				params
			}).then(res => {
				if(res.data.key){
					this.timer = setInterval(()=> {
						this.$message({
							type: 'success',
							message: '导入中，请等待...'
						});
						this.getCache(res.data.key)
					},3000)
				}else if(res.data.length > 0){
					this.$emit('importSuccess',res.data)
				} else {
					this.$message.error(res.msg);
				}
				this.importLoading = false;
				this.importFileList = [];
			})
		},
		getNotify(file){
			request({
				url: '/addons/alioss/index/notify',
				method: 'post',
				data: {
					method: 'POST',
					url: this.dataObj.key.replace('${filename}'),
					md5: this.md5,
					name: this.md5 + file.name.substring(file.name.lastIndexOf(".")),
					type: file.type,
					size: file.size,
					aliosstoken: this.aliosstoken
				}
			}).then(res => {
				resolve(true);
			}).catch(err => {
				reject(false);
			});
		},
		getCache(key){
			let params = {
				key: key
			}
			if(this.batch_month){
				params.batch_month = this.batch_month
			}
			request({
				url: '/qviKHUYsyN.php/index/getCache',
				method: 'get',
				params
			}).then(res => {
				if(res.data.import_bool){
					clearInterval(this.timer)
					this.$emit('importSuccess')
					this.$message({
						type: 'success',
						message: '导入成功!'
					});
				}else if(res.code != 1){
					clearInterval(this.timer)
					// let html = ''
					// let arr = res.msg.split('<br />\n')
					// arr.forEach(item => {
					// 	html += `<div>${item}</div>`
					// })
					this.html = res.msg
					this.isShowMsg = true
					if(res.msg.length < 500){
						setTimeout(() => {
							this.isShowMsg = false
						},5000)
					}
				}
			});
		},
	}
};
</script>
<style type="text/css" scoped="scoped">
	.html{
		font-size: 16px;
		line-height: 20px;
	}
</style>