<template>
	<el-dialog v-model="visible" :title="title" width="600" append-to-body>
		<div style="text-align: center; margin-bottom: 20px">
			<el-button type="success" :icon="Download" @click="handleDownloadTemplate">下载模板</el-button>
		</div>

		<el-upload
			class="upload-demo"
			:action="uploadUrl"
			:headers="headers"
			:accept="'.xls,.xlsx'"
			:on-success="handleUploadSuccess"
			:on-error="handleAvatarError"
			:limit="1"
			drag
		>
			<el-icon class="el-icon--upload"><upload-filled /></el-icon>
			<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
			<template #tip>
				<div class="el-upload__tip">只能上传 .xls 或 .xlsx 格式的 Excel 文件</div>
			</template>
		</el-upload>
	</el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { ElNotification } from 'element-plus';
import { Download, UploadFilled } from '@element-plus/icons-vue';
import { Session } from '/@/utils/storage';
import { downBlobFile } from '/@/utils/other';

const title = ref('');
// 响应式数据
const visible = ref(false);

// 计算属性
const headers = computed(() => {
	return {
		Authorization: 'Bearer ' + Session.getToken(),
    TENANT_ID: Session.getTenant()
	};
});

const uploadUrl = ref('')
const currentType = ref('')
const titleMap: Record<string, string> = {
	planMajor: '计划专业导入'
}
// 方法
const init = (type: any) => {
	currentType.value = type
	uploadUrl.value = '/professional/file/importTeacherOtherInfo?type=' + type
	title.value = titleMap[type] || '信息导入'
	visible.value = true
}

// Emits
const emit = defineEmits<{
  (e: 'refreshData'): void
}>()

const handleUploadSuccess = () => {
	visible.value = false;
	ElNotification({
		title: '成功',
		message: '导入成功',
		type: 'success',
	});

  emit('refreshData')
};

const handleAvatarError = (err: any) => {
	const result = JSON.parse(err.message);
	if (result.code == '1') {
		ElNotification.error({
			title: '错误',
			message: result.msg,
			duration: 30000,
		});
	}
};

const handleDownloadTemplate = () => {
	downBlobFile('/recruit/file/exportRecruitTemplate', { type: currentType.value || 'planMajor' }, title.value+'模板.xlsx')
}

// 暴露方法给父组件
defineExpose({
	init
});
</script>

<style scoped lang="scss">
.upload-demo {
	:deep(.el-upload-dragger) {
		width: 100%;
	}
}
</style>
