<template>
	<div>
		<div style="margin-bottom: 10px">
			<!-- <a-button type="primary" @click="chooseFile" :disabled="coverFileList.length > 0 && isedit">选择图片</a-button> -->
			<a-button
				type="primary"
				@click="chooseFile"
				:disabled="isedit ? coverFileList.length > 0 && isedit : coverFileList.length > 0"
				>选择图片</a-button
			>
			<span style="margin-left: 10px">仅支持上传jpg/png格式文件，单个文件不能超过500kb</span>
		</div>
		<a-upload
			ref="upload"
			:before-upload="beforeUploadCover"
			accept=".jpg,.png,.bmp,.jpeg"
			:remove="handleRemoveCover"
			:headers="headers"
			:action="action"
			:on-change="handleChangeCover"
			@preview="handlePreview"
			:file-list="coverFileList"
		>
		</a-upload>
		<div class="preview-area" v-if="previewImageUrl">
			<a-image
				:width="200"
				:src="previewImageUrl"
				:preview="{
					src: previewImageUrl
				}"
			/>
		</div>
	</div>
</template>

<script setup>
	import { ref, reactive, watch } from 'vue'
	import { Modal, Upload, message } from 'ant-design-vue'
	import tool from '@/utils/tool'
	const emit = defineEmits(['handleRemoveCover', 'handleChangeCover'])
	const headers = ref({
		token: tool.data.get('TOKEN')
	})
	import sysConfig from '@/config/index'
	const props = defineProps({
		coverImageId: {
			type: Number,
			required: true,
			default: null
		},
		imageUrl: {
			type: String,
			required: true,
			default: null
		},
		isedit: {
			type: Boolean,
			required: true,
			default: false
		}
	})

	const action = ref('/api/webapp/dev/file/uploadMinioReturnId')
	// 封面文件列表
	const coverFileList = ref([])
	const previewImageUrl = ref('')
	const coverImageId = ref(null)
	watch(
		() => props.imageUrl,
		(newVal) => {
			if (newVal) {
				previewImageUrl.value = sysConfig.FILE_URL + newVal
				coverImageId.value = props.coverImageId
			} else {
				previewImageUrl.value = ''
				coverImageId.value = null
			}
		},
		{ immediate: true } // 立即执行一次
	)
	// 上传封面前的钩子函数
	const beforeUploadCover = (file) => {
		// 允许的文件扩展名
		const allowedExtensions = ['.jpg', '.png', '.bmp', '.jpeg']
		// 获取文件扩展名
		const fileExtension = file.name.slice(file.name.lastIndexOf('.')).toLowerCase()
		console.log(file, fileExtension, 'filefilefilefile')

		// 验证文件类型
		const isFileTypeAllowed = allowedExtensions.includes(fileExtension)

		if (!isFileTypeAllowed) {
			message.error(`不支持的文件格式: ${fileExtension}，请上传以下格式: ${allowedExtensions.join(', ')}`)
			return false
		}

		// 验证文件大小（500KB限制）
		const isLt500K = file.size / 1024 < 500
		if (!isLt500K) {
			message.error('文件大小不能超过500KB!')
			return false
		}

		return isFileTypeAllowed && isLt500K
	}
	// 移除封面文件
	const handleRemoveCover = (file) => {
		const index = coverFileList.value.indexOf(file)
		const newFileList = coverFileList.value.slice()
		newFileList.splice(index, 1)
		coverFileList.value = newFileList
		previewImageUrl.value = ''
		// 如果移除的是当前封面文件，则清空coverImageId
		if (coverImageId.value === file.id) {
			coverImageId.value = null
			emit('handleRemoveCover')
		}
	}
	// 封面文件状态改变时的处理函数
	const handleChangeCover = ({ file, fileList: newFileList }) => {
		if (file.status === 'done') {
			// 上传成功，获取文件ID
			const fileId = file.response?.data || file.id
			console.log('上传成功，获取文件ID', fileId)
			if (fileId) {
				coverImageId.value = fileId
				emit('handleChangeCover', fileId)
				// 生成预览URL
				if (file.originFileObj) {
					previewImageUrl.value = URL.createObjectURL(file.originFileObj)
				} else if (file.url) {
					previewImageUrl.value = file.url
				}
			}
		}
		if (file.status === 'error') {
			// 延迟移除，确保用户能看到错误提示
			setTimeout(() => {
				coverFileList.value = coverFileList.value.filter((f) => f.uid !== file.uid)
			}, 1500)
		}
		coverFileList.value = newFileList
	}

	// 选择文件按钮点击事件
	const chooseFile = () => {
		document.querySelector('.ant-upload input').click()
	}
</script>

<style lang="less">
</style>
