<template>
	<el-dialog v-model="state.dialogVisible" width="50%" draggable title="数据导入-区域从业人员" destroy-on-close append-to-body @close="close">
		<vxe-tip title="注意" status="error">
			<p>1、导入文件的格式必须为Excel 97-2003(.xls)，手动修改文件的后缀名无效；</p>
			<p>2、导入数据的单元格必须为文本格式，重点注意身份证、手机号、日期的单元格格式；</p>
			<p>3、导入可能需要一段时间，请耐心等待（数据越多越久）；</p>
			<p class="flex-center-align">4、模版下载 <el-link type="primary" @click="onDownload">区域从业人员</el-link></p>
		</vxe-tip>
		<el-upload
			v-model:file-list="fileList"
			action="#"
			:multiple="false"
			ref="uploadListRef"
			name="file"
			:http-request="onImport"
			:show-file-list="false"
			class="mt20"
			:disabled="state.loading"
		>
			<el-button type="primary" :loading="state.loading"> <SvgIcon name="ele-Upload" class="mr5" /> 导入</el-button>
		</el-upload>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElNotification } from 'element-plus';
import { externalCitizenImport, externalCitizenTemplate } from '@/api/auxiliary/externalCitizen';
import { downloadFileByStream } from '@/utils/tools';
// 定义子组件向父组件传值/事件
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 = () => {
	externalCitizenTemplate()
		.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 externalCitizenImport(fd);
		ElNotification({
			title: '导入完成',
			message: `总条数：${result.count}条，新增：${result.addCount}条，失败：${result.errorCount}条`,
			type: 'success',
		});
		closeDialog();
		emit('updateList');
		state.loading = false;
	} catch (e) {
		console.log(e);
		state.loading = false;
	}
};
defineExpose({
	openDialog,
	closeDialog,
});
</script>
