<template>
	<div style="width: 100%">
		<!--  accept=".pdf" -->
		<el-upload
			ref="uploadView"
			class="avatar-uploader"
			style="width: 100%"
			:data="uploadData"
			v-loading="loading"
			:http-request="uploadAction"
			:headers="uploadHeader"
			drag
			:limit="limit"
			:accept="wordFlag ? '.pdf,.docx' : '.pdf'"
			v-model:file-list="fileList"
			:on-success="handleAvatarSuccess"
			:before-upload="onBeforeUpload"
			:on-exceed="handleExceed"
			:on-progress="onProgress"
			:on-change="onChange"
			:show-file-list="false"
		>
			<div class="el-upload__text">
				<img :src="iconFile" />
				<div class="upload_text_one">将文件拖拽至此处</div>
				<div>或</div>
				<ZButton btn-width="112px" btn-height="32px">
					<img :src="iconFileWhite" style="width: 12px; height: 13px; margin-right: 5px" />
					<text style="font-family: 'Alip-Regular'">选择文件</text>
				</ZButton>
			</div>
		</el-upload>
	</div>
</template>

<script setup lang="ts" name="upload">
import { ref, onBeforeMount, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { Session } from '/@/utils/storage';
import ZButton from '/@/components/ZButton/index.vue';
import iconFile from '/@/assets/images/icon_file_big.png';
import iconFileWhite from '/@/assets/images/icon_file.png';
import { getUploadUrl, doUploadErrorLog, getWordFlag } from '/@/api/api';
import { uuid } from 'vue-uuid';
// import { getToken } from '@/utils/auth';
import ObsClient from 'esdk-obs-browserjs/src/obs';
import axios from 'axios';
import SparkMD5 from 'spark-md5';

const fileList = ref([]);

// const limit = ref(Session.get('roleName') == 'Director' || Session.get('roleName') == 'subCenter' || Session.get('roleName') == 'operate' ? 60 : 1);
const limit = ref(1);
const showView = ref(true);
const uploadUrl = ref(import.meta.env.VITE_API_URL + '/report/upload');
const props = defineProps({
	model: {
		type: Object,
	},
	fileListEx: {
		type: Array,
	},
});
const emit = defineEmits(['handleAvatarSuccess', 'onProgress', 'onChange', 'onFileChoose']);

watch(
	() => props.fileListEx,
	(val) => {
		if (val && val.length > 0) {
			fileList.value = val;
		}
	}
);

watch(
	() => fileList.value,
	(val) => {
		if (val.length > 0) {
			emit('onFileChoose', val);
		}
	}
);

const uploadData = ref({});
const uploadHeader = ref({
	'auth-token': `${Session.get('userData').token}`,
	phone: `${Session.get('userData').phone}`,
});

const loading = ref(false);
function uploadAction(param) {
	console.log('🚀 ~ uploadAction ~ param:', param);

	loading.value = true;
	getUploadUrl({
		fileName: param.file.name,
	})
		.then((res1) => {
			loading.value = false;
			if (res1.code == 200) {
				let rData = res1;
				var reopt = {
					method: 'PUT',
					url: res1.data.url,
					withCredentials: false,
					headers: {
						'Content-Type': 'application/octet-stream',
						// Host: 'financial-report-test.obs.cn-east-3.myhuaweicloud.com:443',
					},
					validateStatus: function (status) {
						return status >= 200;
					},
					timeout: 600000,
					maxRedirects: 0,
					responseType: 'text',
					data: param.file,
				};
				loading.value = true;
				axios
					.request(reopt)
					.then(function (response) {
						console.log('🚀 ~ response:', response);
						loading.value = false;
						if (response.status < 300) {
							emit('onProgress', 100);
							emit('handleAvatarSuccess', {
								fileName: param.file.name,
								fileMd5: fileMd5.value,
								title: res1.data.title,
								filePath: res1.data.filePath,
								status: 'success',
							});
						} else {
							ElMessage.error('上传失败');
							loading.value = false;

							doUploadErrorLog({
								errorMsg: JSON.stringify(response),
							});
							uploadView.value.clearFiles();

							emit('onProgress', 0);
							emit('handleAvatarSuccess', {
								fileName: param.file.name,
								fileMd5: fileMd5.value,
								title: res1.data.title,
								filePath: res1.data.filePath,
								status: 'fail',
							});
						}
						// console.log(response.data);
						// console.log('\n');
					})
					.catch(function (err) {
						doUploadErrorLog({
							errorMsg: JSON.stringify(err),
						});

						ElMessage.error('上传失败');
						console.log('Creating object using temporary signature failed!');
						console.log(err);
						console.log('\n');
						loading.value = false;

						emit('onProgress', 0);
						emit('handleAvatarSuccess', {
							fileName: param.file.name,
							fileMd5: fileMd5.value,
							title: res1.data.title,
							filePath: res1.data.filePath,
							status: 'fail',
						});
					});
			} else {
				ElMessage.error(res1.msg);
				loading.value = false;
				uploadView.value.clearFiles();
			}
		})
		.catch((e) => {
			loading.value = false;
			uploadView.value.clearFiles();
		});
}

function handleExceed() {
	//提示最多只能
	ElMessage.error('最多上传' + limit.value + '个文件！');
}

async function onBeforeUpload(res) {
	console.log('🚀 ~ onBeforeUpload ~ res:', res);
	let suffixName = res.name.substring(res.name.lastIndexOf('.') + 1);
	// let canGo = true;
	let canGo = false;
	if (suffixName == 'pdf' || suffixName == 'PDF' || suffixName == 'docx') {
		canGo = true;
	} else {
		canGo = false;
		ElMessage.error('请上传PDF或docx文件');
	}

	// let { code, data } = await getWordFlag({});
	// if (code == 200) {
	// 	if (data == 0 && suffixName == 'docx') {
	// 		canGo = false;
	// 		ElMessage.error('尚未开通上传word文件权限，请联系中证报经营人员开通权限');
	// 	}
	// }

	return canGo;
}

function isFileWithExtension(filename, extension) {
	const fileExtension = filename.split('.').pop();
	return fileExtension === extension;
}
const fileMd5 = ref();
function onChange(res) {
	emit('onChange', res.name);

	let fileReader = new FileReader();
	let Spark = new SparkMD5.ArrayBuffer();
	fileReader.readAsArrayBuffer(res.raw);
	fileReader.onload = function (e) {
		Spark.append(e.target.result);
		let md5 = Spark.end();
		console.log(md5);
		fileMd5.value = md5;
	};
	if (res.name) {
		showView.value = false;
	} else {
		showView.value = true;
	}
}

function onProgress(res) {
	emit('onProgress', res.percent);
}

function handleAvatarSuccess(res: any) {
	if (res.code == 200) {
		emit('handleAvatarSuccess', res.data);
	} else {
		ElMessage.error(res.msg);
	}
}

const uploadView = ref(null);
function clearFile() {
	uploadView.value.clearFiles();
}

const wordFlag = ref(false);
onBeforeMount(async () => {
	let { code, data } = await getWordFlag({});
	if (code == 200) {
		if (data == 1) {
			wordFlag.value = true;
		}
	}
});

defineExpose({
	clearFile,
});
</script>

<style scoped lang="scss">
:deep(.el-upload-dragger) {
	border: 1px solid #f0f2f5;
}

.el-upload__text {
	display: flex;
	flex-direction: column;
	text-align: center;
	justify-content: center;
	align-items: center;

	// font-weight: bold;
	img {
		width: 48px;
		height: 48px;
	}

	.upload_text_one {
		color: #19213d;
		text-align: center;
		font-size: 14px;
		font-style: normal;
		font-weight: bold;
		line-height: 18.2px;
		margin-top: 10px;
	}
}
</style>
