<template>
<el-drawer :title="title" v-model="visible" :size="400" destroy-on-close @closed="$emit('closed')">
	<el-main>
		<slot name="extra"></slot>
		<el-upload v-model="file" accept=".xls, .xlsx" :disabled="disabled" :before-upload="handleBeforeUpload" :on-remove="handleRemove">
			<el-button type="primary">选择导入文件</el-button>
			<template #tip>
				<div style="padding: 10px 0;">
					<el-alert title="请按照导入模版导入" type="success" :closable="false" />
				</div>
			</template>
		</el-upload>
		<el-card>
			<template #header>操作记录</template>
			<div style="padding: 5px 0;" v-for="(item, index) in insertLog" :key="index"><el-alert :title="item.label" :type="item.type" /></div>
		</el-card>
	</el-main>
</el-drawer>
</template>
<script>
import excel from '@/utils/excel'

export default {
	emits: ['success', 'closed', 'update-data'],
	props: {
		title: {
			type: String,
			default: '批量导入'
		}
	},
	data() {
		return {
			loading: false,
			form: {},
			visible: false,
			disabled: false,
			insertLog: []
		}
	},
	methods: {
		handleBeforeUpload (file) {
			this.setLog('已选择导入文件！')
			this.disabled = true
			const fileExt = file.name.split('.').pop().toLocaleLowerCase()
			if (fileExt === 'xlsx' || fileExt === 'xls') {
				this.readFile(file)
				this.file = file
			} else {
				this.setLog('文件类型错误，文件：' + file.name + '不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。', 'error')
			}
			return false
		},
		// 读取文件
		readFile (file) {
			this.setLog('正在解析文件数据……')
			const reader = new FileReader()
			reader.readAsArrayBuffer(file)
			reader.onloadstart = () => {
			}
			reader.onprogress = e => {
				this.progressPercent = Math.round(e.loaded / e.total * 100)
			}
			reader.onerror = () => {
				this.setLog('文件读取出错')
			}
			reader.onload = e => {
				this.setLog('文件读取成功')
				const data = e.target.result
				const { header, results } = excel.read(data, 'array')
				// const tableTitle = header.map(item => { return { title: item, key: item } })
				console.log(header)
				this.updateData(results)
			}
		},
		updateData: function(data){
			this.$emit('update-data', data);
		},
		setLog(message, type = 'success'){
			this.insertLog.push({label: message, type: type})
		},
		//显示
		open(){
			this.visible = true;
			return this;
		},
		//表单注入数据
		setData(data){
			this.loading = true
			this.form = data
		}
	}
}
</script>

<style>
</style>
