<template>
	<div class="base-upload-container">
		<Upload multiple type="drag" action=""
			:before-upload="onBeforeUpload"
			:show-upload-list="false">
			<div style="padding: 40px 0">
				<Icon type="ios-cloud-upload" size="100" style="color: #a3a3a3;margin: 40px 0;"></Icon>
				<p style="color: #a3a3a3">选择或者拖拽文件到该区域进行上传</p>
			</div>
		</Upload>
		<div class="file-list-box">
			<div class="file-item" v-for="(item,index) in fileArr" :key="index">
				<p>
					<span>{{ item.name }}</span>
					<span class="tool-remove" v-if="isShowTool">
						<Icon type="md-close" @click="onRemoveFile(index)" />
					</span>
				</p>
				<Progress :percent="progressArr[index]" :stroke-width="12" />
			</div>
		</div>
		<Button type="success" @click="onConfirmUpload" style="width: 100%;height: 40px;" :loading="isLoading" class="modal-btn" :disabled="!fileArr.length"
			v-if="mode === 'modal'">确认上传</Button>
	</div>
</template>

<script>
	import excel from '@/utils/excel.js'
	import FileSaver from "file-saver";
	import BlobTool from '@/utils/blobTool.js'
	export default {
		props: {
			auth: {
				type: Object,
				default: () => {
					return {
						sas: '',
						url: '',
						name: ''
					}
				}
			},
			scope: {
				type: String,
				default: 'school'
			},
			prefix: {
				type: String,
				default: ''
			},
			mode: {
				type: String,
				default: 'modal'
			},
			maxSize: {
				type: Number,
				default: -1
			},
			acceptTypes: {
				type: Array,
				default: () => []
			}
		},
		data() {
			return {
				isLoading:false,
				isShowTool: true,
				containerClient: null,
				fileArr: [],
				progressArr: []
			}
		},
		created() {

		},
		methods: {
			

			onRemoveFile(index) {
				this.fileArr.splice(index, 1)
			},
			
			/* 转换size */
			getSizeByBytes(bytes) {
			    return bytes / 1024 < 1024 ? (bytes / 1024).toFixed(1) + 'KB' : bytes / 1024 / 1024 < 1024 ? (bytes / 1024 / 1024).toFixed(1) + 'M' : (bytes / 1024 / 1024 / 1024).toFixed(1) + 'G'
			},
			
			onBeforeUpload(file) {
				console.log(this.acceptTypes);
				console.log(file);
				console.log(file.type);
				
				if(this.maxSize > 0 && file.size > this.maxSize){
					this.$Message.warning('上传文件大小不能大于' + this.getSizeByBytes(this.maxSize) + '！');
					return false
				}
				if(this.acceptTypes.length && !this.acceptTypes.includes(file.type.split('/')[file.type.split('/').length - 1].toLowerCase()) && !this.acceptTypes.includes(file.name.split('.')[file.name.split('.').length - 1].toLowerCase())){
					this.$Message.warning('上传文件格式只能为' + this.acceptTypes.join(','));
					return false
				}
				
				if(this.mode === 'import'){
					let excelResult = []
					this.readExcel(file,data => {
						if(data.results.length){
							console.log(data);
							data.results.forEach(item => {
								excelResult.push({
									question:item.Question || '',
									answer:item.Answer ? (item.Type === 'multiple' ?  item.Answer.split(',') : [item.Answer]): [],
									type:item.Type,
									options:this.getItemOptions(item)
								})
							})
							console.log(excelResult);
							this.fileArr = []
							this.progressArr = []
							this.$emit('uploadFinish', excelResult)
							this.isLoading = false
						}
					})
					return false
				}
				file.progress = 0
				this.fileArr.push(file)
				this.progressArr.push(0)
				return false
			},
			
			/* 解析excel表格 */
			readExcel(file, callback) {
			    var reader = new FileReader();
			    reader.onload = function (e) {
			        var data = e.target.result;
			        var workbook = excel.read(data, 'binary');                
			        if (callback) callback(workbook);
			    };
			    reader.readAsBinaryString(file);
			},
			
			/* 获取表格解析试题的选项 */
			getItemOptions(item){
				let options = []
				let optionIndex = 0
				if(item.Type === 'judge'){
					return [{
						code:'A',
						value:'对'
					},{
						code:'B',
						value:'错'
					}]
				}else{
					for(let key in item){
						if(key.includes('Option')){
							options.push({
								code: String.fromCharCode(64 + parseInt(optionIndex + 1)),
								value:item[key]
							})
							optionIndex++
						}
					}
					return options
				}
			},

			async onConfirmUpload() {
				this.isShowTool = false
				this.isLoading = true
				let result = []
				let containerClient = this.containerClient
				let list = this.fileArr
				let that = this
				let path = this.prefix === '' ? `yxpt/${this.curStandard}/jyzx` : `yxpt/${this.curStandard}/jyzx/${this.prefix}`
				console.log(containerClient);
				for (let i = 0; i < list.length; i++) {
					let file = list[i]
					try {
						let blobFile = await containerClient.upload(file, path, {
							onProgress: function(e) {
								that.$set(that.progressArr, i, parseInt(e.loadedBytes * 100 / file.size))
							}
						});
						result.push(blobFile)
					} catch (e) {
						console.log(e)
						this.$Message.error(e)
						return
					}
				}
				this.fileArr = []
				this.progressArr = []
				this.$emit('uploadFinish', result)
				this.isLoading = false
			}
		},
		mounted() {
			if (this.auth.sas) {
				let n = this.auth
				this.containerClient = new BlobTool(n.url, n.name, n.sas, this.scope)
			}
		},
		computed:{
			curStandard(){
				return this.$store.state.user.schoolProfile.school_base.standard
			}
		},
		watch: {
			auth: {
				handler(n, o) {
					this.containerClient = new BlobTool(n.url, n.name, n.sas, this.scope)
				}
			}
		}
	}
</script>

<style lang="less">
	.base-upload-container {
		.file-list-box {
			margin: 20px 5px;
			width: 100%;
			max-height: 200px;
			overflow: auto;

			.file-item {
				margin: 10px 0;

				.tool-remove {
					color: #b3b3b3;
					margin-left: 15px;
					font-size: 14px;
					cursor: pointer;
				}
			}

			.ivu-progress {
				margin-top: 10px;
			}

			.ivu-progress-inner {
				background-color: #e1e1e1;
			}

			.ivu-progress-text-inner {
				color: #969696;
			}

			&::-webkit-scrollbar-thumb {
				background: #dadada !important;
			}
		}
	}
</style>
