<template>
	<el-dialog v-model="state.dialogVisible" width="50%" draggable title="知识导入" destroy-on-close append-to-body @close="close">
		<p class="flex-center-align">步骤一：点击 <el-link type="primary" @click="onDownload">下载模板</el-link>，并按格式填写</p>
		<p class="flex-center-align mt20">步骤二：上传编辑好的文件</p>
		<el-upload
			v-model:file-list="fileList"
			action="#"
			:multiple="false"
			ref="uploadListRef"
			name="file"
			:http-request="onImport"
			:show-file-list="false"
			class="mt10"
			:disabled="state.loading"
		>
			<el-button type="primary" :loading="state.loading"> <SvgIcon name="ele-Upload" class="mr5" /> 导入知识 </el-button>
		</el-upload>
		<vxe-tip title="注意" status="error" class="mt10">
			<p>1、如需导入分类，请先在分类管理中创建好分类再导入；</p>
			<p>2、导入可能需要一段时间，请耐心等待（数据越多越久）；</p>
      <!--			<p>3、文件大小不超过xxM，导入知识内容不超过xx条</p>-->
		</vxe-tip>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElNotification } from 'element-plus';
import { downloadFileByStream } from '@/utils/tools';
import { knowledgeImport, knowledgeTemplate } from '@/api/knowledge';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false,
	ruleForm: {
		systemAreaId: null, // 所属区域
		systemAreaName: null, // 所属区域名称
		street: null, // 所属镇/街
		name: null, // 姓名
		phoneNumber: null, // 联系方式
		gender: 1, // 性别
	},
	loading: false,
});
// 打开弹窗
const ruleFormRef = ref<RefType>();
const openDialog = () => {
	state.dialogVisible = true;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const close = () => {
	ruleFormRef.value?.resetFields();
	ruleFormRef.value?.resetFields();
};
// 模板下载
const onDownload = () => {
	state.loading = true;
	knowledgeTemplate()
		.then((res: any) => {
			state.loading = false;
			downloadFileByStream(res);
		})
		.catch(() => {
			state.loading = false;
		});
};
// 导入
const fileList = ref<EmptyArrayType>([]);
const uploadListRef = ref<RefType>(); // 上传组件ref
const onImport = async (file: any) => {
	state.loading = true;
	let fileObj = file.file; // 相当于input里取得的files
	let fd = new FormData(); // FormData 对象
	fd.append('file', fileObj); // 文件对象
	try {
		const { result } = await knowledgeImport(fd);
		ElNotification({
			title: '导入完成',
			message: result,
			type: 'success',
		});
		closeDialog();
		emit('updateList');
		state.loading = false;
	} catch (e) {
		console.log(e);
		state.loading = false;
	}
};
defineExpose({
	openDialog,
	closeDialog,
});
</script>
