<template>
<el-drawer title="批量导出" v-model="visible" :size="600" destroy-on-close @closed="$emit('closed')">
	<el-main>
		<el-form :model="form" label-width="120px">
			<el-form-item label="导出数量">
				<el-input v-model="form.num" clearable placeholder="导出数量" />
			</el-form-item>
			<el-form-item label="导出字段">
				<el-checkbox-group v-model="form.field">
					<el-checkbox v-for="(item, index) in outData.column" :key="index" :label="index" checked >{{ item }}</el-checkbox>
				</el-checkbox-group>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="onSubmit">确人导出</el-button>
			</el-form-item>
		</el-form>
		<el-card>
			<template #header>导出日志</template>
			<div style="padding: 5px 0;" v-for="(item, index) in logList" :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:{
		outData: {
			type: [Object, Array],
			default: () => {
				return {apiObj: '', column: {}, filename: '导出文件'}
			}
		}
	},
	data() {
		return {
			loading: false,
			form: {num: 30, field: []},
			search: {},
			visible: false,
			disabled: false,
			outDataList: [],
			logList: []
		}
	},
	methods: {
		async onSubmit(){
			let key = this.form.field || Object.keys(this.outData.title)
			let title = {}

			key.map(item => {
				title[item] = this.outData.column[item]
			})
			this.search.limit = this.form.num
			this.search.page = this.search.page ? this.search.page : 1
			this.search.outxls = 1
			this.search

			this.setLog('开始导出，请等待！');
			await this.getOutXlsData(this.outData.apiObj, this.search, title, key, this.outData.filename);

		},
		async getOutXlsData(apiObj, params, title, key, filename){
			let res = await apiObj.get(this.search)
			if(res.code == 1){
				res.data.data.map(item => {
					this.outDataList.push(excel.get_key_data(item, key));
				})
				this.setLog('正在导出第'+res.data.current_page+'页，总共'+res.data.total+'条'+res.data.last_page+'页，请等待！');
				if(res.data.current_page < res.data.last_page){
					params.page = params.page+1;
					this.getOutXlsData(apiObj, params, title, key, filename);
				}else if(res.data.current_page == res.data.last_page){
					filename = filename + Date.parse(new Date());
					excel.export_json_to_excel({data:this.outDataList, title: title, key: key, filename: filename, autoWidth: true});
					this.outDataList = [];
				}
			}else{
				this.setLog('导出失败！', 'error')
			}
		},
		setLog(message, type = 'success'){
			this.logList.push({label: message, type: type})
		},
		//显示
		open(){
			this.visible = true;
			return this;
		},
		//表单注入数据
		setData(data){
			this.loading = true
			this.search = {page: 1}
			this.search = data
		}
	}
}
</script>

<style>
</style>
