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

    <el-alert
        v-if="currentType=='R10003'"
        type="warning"
        :closable="false"
        show-icon
        style="margin-bottom: 20px;">
      <template #title>
        <span> 请从中招平台导出数据后导入</span>
      </template>
    </el-alert>


    <el-upload
			ref="uploadRef"
			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, nextTick } 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 uploadRef = ref<{ clearFiles?: () => void }>()
const titleMap: Record<string, string> = {
  R10001: '计划专业导入',
  R10002: '地区分数导入',
  R10003: '中招平台数据导入',
  R10004: '学校维护导入',
}
// 方法
const init = (type: any) => {
	currentType.value = type
	uploadUrl.value = '/api/recruit/file/importRecruitInfo?type=' + type
	title.value = titleMap[type] || '信息导入'
	visible.value = true
	nextTick(() => {
		uploadRef.value?.clearFiles()
	})
}

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

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

  emit('refreshDataList')
};

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>
