<template>
	<div class="w100">
		<slot name="head"> </slot>
		<el-upload
			class="file-upload w100"
			v-model:file-list="fileList"
			:action="action"
			:multiple="true"
			accept="*"
			:on-exceed="handleExceed"
			ref="uploadListRef"
			name="fileData"
			:on-change="handleChangeFile"
			:on-success="updateData"
			:disabled="props.readonly"
			:on-error="onUploadError"
		>
			<template v-if="!props.readonly">
				<el-button> <SvgIcon name="ele-Upload" /> {{ props.name }} </el-button>
			</template>
			<template v-else>
				<el-button v-if="fileList && fileList.length" disabled> {{ props.name }} </el-button>
				<el-button v-else disabled> 暂无附件 </el-button>
			</template>
			<slot> </slot>
			<template #file="{ file }">
				<div class="el-upload-list__item-info">
					<a class="el-upload-list__item-name">
						<SvgIcon class="mr5" :name="fileType(checkFile(file.name))" size="14px" @click="onPreview(file)" />
						<span class="el-upload-list__item-file-name" :title="file.name" @click="onPreview(file)">{{ file.name }}</span>
						<span @click.stop="" v-if="!props.readonly">
							<el-switch
								class="ml20 mr10"
								v-model="file.publicity"
								active-text="公开"
								inactive-text="不公开"
								inline-prompt
								:active-value="1"
								:inactive-value="0"
								@change="updateData"
							/>
						</span>
					</a>
				</div>
				<SvgIcon name="ele-Download" size="14px" class="el-icon--close mr20" title="下载文件" @click="handleDownload(file)" />
				<SvgIcon name="ele-Close" class="el-icon--close" size="14px" title="删除文件" @click="handleRemove(file)" v-if="!props.readonly" />
			</template>
			<template #tip v-if="!props.readonly">
				<div class="el-upload__tip">大小限制：20M</div>
			</template>
		</el-upload>
		<slot name="footer"> </slot>
	</div>
</template>
<script setup lang="ts" name="annexList">
import { computed, ref, watch } from 'vue';
import { checkFile, downloadFile, fileType } from '@/utils/tools';
import { ElButton, ElMessage, ElMessageBox } from 'element-plus';
import Other from '@/utils/other';
const emit = defineEmits(['update:modelValue', 'update:format']);
const props = defineProps({
	name: {
		// 上传按钮名称
		type: String,
		default: '上传附件',
	},
	fileLimit: {
		// 限制上传数量
		type: Number,
		default: 5,
	},
	fileSize: {
		// 限制上传大小(M)
		type: Number,
		default: 20,
	},
	businessId: {
		// 业务id
		type: String,
		default: '',
	},
	readonly: {
		// 只读（详情查看）
		type: Boolean,
		default: false,
	},
	classify: {
		// 附件分类
		type: String,
		required: true,
		default: '',
	},
	modelValue: {
		// 附件数据
		type: Array,
		default: () => [],
	},
});

const action = computed(() => {
	return import.meta.env.VITE_API_UPLOAD_URL + '/file/upload?source=hotline';
});
// 上传成功
const fileList = ref<EmptyArrayType>([]);
const uploadListRef = ref<RefType>(); // 上传组件ref
// 更新数据
const updateData = () => {
	emit('update:modelValue', fileList.value);
	const data = formatData(Other.deepClone(fileList.value));
	emit('update:format', data);
};
// 格式化数据
const formatData = (data: any) => {
	return data.map((v: any) => {
		return {
			additions: v?.response?.result.id,
			name: v?.response?.result?.fileName?.substring(0, v.response.result?.fileName?.lastIndexOf('.')),
			type: v?.response?.result?.fileName?.split('.').pop(),
			path: v?.response?.result?.path,
			publicity: v?.publicity ? 1 : 0,
			classify: props.classify,
			key: props.businessId,
		};
	});
};
//文件限制
const handleExceed = (files: any, fileList: any) => {
	ElMessage.warning(`当前限制选择 ${props.fileLimit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
};
//限制文件大小
const handleChangeFile = (file: any, fileList: any) => {
	//限制上传文件大小
	updateData();
	if (!file) return;
	const isLt2M = file.size / 1024 / 1024 < props.fileSize;
	if (!isLt2M) {
		const currIdx = fileList.indexOf(file);
		fileList.splice(currIdx, 1);
		ElMessage.warning(`文件超过了最大限度 ${props.fileSize} MB!`);
		return false;
	}
};
// 上传失败
const onUploadError = (error: Error) => {
	console.log(error);
	ElMessage.error('上传失败');
};
// 删除
const handleRemove = (uploadFile: any) => {
	ElMessageBox.confirm(`确定要删除？`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			uploadListRef.value.handleRemove(uploadFile);
			updateData();
		})
		.catch(() => {});
};
// 下载
const handleDownload = (uploadFile: any) => {
	const path = uploadFile.path ? uploadFile.path : uploadFile.response.result.path ? uploadFile.response.result.path : '';
	if (!path) {
		ElMessage.error('附件不存在');
		return;
	}
	// 确定是否下载
	ElMessageBox.confirm('确定要下载附件？', '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
	})
		.then(() => {
			const fileName = uploadFile.name;
			const url = import.meta.env.VITE_FILE_PREFIX + path;
			downloadFile(url, fileName);
		})
		.catch(() => {});
};
// 预览
const onPreview = (file: any) => {
	if (!file.response?.result?.path) {
		ElMessage.error('附件不存在');
		return;
	}
	const type = file.response?.result?.fileName?.split('.').pop();
	// 图片预览
	if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'BMP', 'mpg', 'MPG', 'mpeg', 'MPEG', 'svg', 'tis'].includes(type)) {
		const url = import.meta.env.VITE_FILE_PREFIX + file.response?.result?.path;
		/*		viewerApi({ images: [] });*/
		window.open(url);
		return;
	}
};
watch(
	() => props.modelValue,
	(n: any) => {
		fileList.value = n;
		emit('update:modelValue', fileList.value);
		const data = formatData(Other.deepClone(fileList.value));
		emit('update:format', data);
	},
	{ deep: true, immediate: true }
);
</script>
<style lang="scss">
.file-upload {
	.el-upload__tip {
		margin-top: 0 !important;
	}
	.el-upload-list {
		margin-top: 10px !important;
		display: flex !important;
		flex-wrap: wrap;
		.el-upload-list__item {
			max-width: 300px !important;
		}
	}
}
</style>
