<template>
	<div class="auxiliary-import-file-container layout-pd">
		<el-card shadow="never" v-loading="loading">
			<el-alert class="mb20">
				<template #title>
					<span
						>请先下载模板，按照模板格式填写数据（注意在来源中填写对应的数据来源（中文））如：{{
							importTypeList.map((item) => item.value).join(',')
						}}等，然后上传。</span
					>
				</template>
			</el-alert>
			<el-button type="primary" @click="downloadTemplate" :loading="btnLoading"><SvgIcon name="ele-Download" class="mr3" /> 下载模板 </el-button>
			<el-upload
				class="mt20"
				drag
				v-model:file-list="fileList"
				action="#"
				:multiple="false"
				ref="uploadListRef"
				name="file"
				:http-request="httpRequest"
				:show-file-list="false"
				v-loading="loading"
			>
				<SvgIcon class="el-icon--upload" name="ele-UploadFilled" size="52px" />
				<div class="el-upload__text">将模板文件拖到此处，或<em>点击上传</em></div>
				<template #tip>
					<div class="el-upload__tip"></div>
				</template>
			</el-upload>
			<div v-if="resultObj" class="result-content">
				<p>
					导入条数：<span class="color-primary">{{ resultObj.count }}</span> 条
				</p>
				；
				<p>
					添加成功：<span class="color-success">{{ resultObj.addCount }}</span> 条
				</p>
				；
				<p>
					修改成功：<span class="color-warning">{{ resultObj.modifyCount }}</span> 条
				</p>
				；
				<p>
					导入失败：<span class="color-danger">{{ resultObj.errorCount }}</span> 条
				</p>
				；
			</div>
		</el-card>
	</div>
</template>
<script setup lang="tsx" name="auxiliaryImportFile">
import { onMounted, ref } from 'vue';
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';
import { fileImport, fileTemplateDownload, fileTemplateType } from '@/api/public/file';
const importTypeList = ref<any[]>([]);
const btnLoading = ref<boolean>(false);
// 下载模板
const downloadTemplate = () => {
	ElMessageBox.confirm(`确定要下载模板，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			btnLoading.value = true;
			fileTemplateDownload()
				.then((res: any) => {
					let blob: Blob = new Blob([res], { type: res.type }); // 创建blob 设置blob文件类型 data 设置为后端返回的文件(例如mp3,jpeg) type:这里设置后端返回的类型 为 mp3
					let down: HTMLAnchorElement = document.createElement('a'); // 创建A标签
					let href: string = window.URL.createObjectURL(blob); // 创建下载的链接
					down.href = href; // 下载地址
					down.download = '导入模板'; // 下载文件名
					document.body.appendChild(down);
					down.click(); // 模拟点击A标签
					document.body.removeChild(down); // 下载完成移除元素
					window.URL.revokeObjectURL(href); // 释放blob对象
					btnLoading.value = false;
				})
				.catch(() => {
					btnLoading.value = false;
				});
		})
		.catch(() => {
			btnLoading.value = false;
		});
};
const fileList = ref<EmptyArrayType>([]);
const uploadListRef = ref<RefType>(); // 上传组件ref
const loading = ref<boolean>(false);
const resultObj = ref<EmptyObjectType>();
const httpRequest = async (file: any) => {
	loading.value = true;
	let fileObj = file.file; // 相当于input里取得的files
	let fd = new FormData(); // FormData 对象
	fd.append('file', fileObj); // 文件对象
	try {
		const { result } = await fileImport(fd);
		loading.value = false;
		if(result.errorMessage){
			ElMessage.error(result.errorMessage);
			return;
		}
		ElNotification({
			title: '导入完成',
			message: `导入条数：${result.count}条，添加成功：${result.addCount}条，修改成功：${result.modifyCount}条，导入失败：${result.errorCount}条`,
			type: 'success',
			duration: 1000 * 10,
		});
		resultObj.value = result;
	} catch (e) {
		console.log(e);
		loading.value = false;
	}
};
onMounted(() => {
	// 获取数据
	fileTemplateType().then((res) => {
		importTypeList.value = res.result?.source ?? [];
	});
});
</script>
<style scoped lang="scss">
.result-content {
	margin-top: 20px;
	display: flex;
	align-items: center;
	flex-wrap: wrap;
}
</style>
