<template>
	<!-- 上传资源模态框 -->
	<a-modal
		:title="isState == 0 ? '发布课程' : '编辑课程'"
		style="width: 800px"
		v-model:visible="uploadModalVisible"
		@ok="handleUploadOk"
		@cancel="handleUploadCancel"
	>
		<a-form :model="uploadForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
			<!-- <a-form-item label="资源名称" name="resourceName">
				<a-input v-model:value="uploadForm.resourceName" placeholder="请输入资源名称" />
			</a-form-item> -->

			<a-form-item label="资源类型" name="resourceType">
				<a-select v-model:value="uploadForm.resourceType" placeholder="请选择资源类型">
					<a-select-option value="type1">类型1</a-select-option>
					<a-select-option value="type2">类型2</a-select-option>
				</a-select>
			</a-form-item>

			<a-form-item label="课程名称" name="courseName">
				<a-input v-model:value="uploadForm.courseName" placeholder="请输入课程名称" />
			</a-form-item>

			<a-form-item label="课程介绍" name="courseDesc">
				<a-textarea v-model:value="uploadForm.courseDesc" placeholder="请输入课程介绍" :rows="4" />
			</a-form-item>

			<a-form-item label="上传封面" name="coverImageId">
				<div style="margin-bottom: 10px">
					<a-button type="primary" @click="chooseFile" :disabled="coverFileList.length > 0">选择图片</a-button>
					<span style="margin-left: 10px">仅支持上传jpg/png格式文件，单个文件不能超过500kb</span>
				</div>
				<a-upload
					ref="upload"
					:before-upload="beforeUploadCover"
					:file-list="coverFileList"
					:remove="handleRemoveCover"
					:headers="headers"
					:action="action"
					:on-change="handleChangeCover"
					list-type="picture-card"
				>
					<div v-if="coverFileList.length < 1">
						<plus-outlined />
						<div class="ant-upload-text">上传图片</div>
					</div>
				</a-upload>
			</a-form-item>
		</a-form>

		<!-- 文件上传状态展示 -->
		<ul v-if="fileList.length">
			<li v-for="(file, index) in fileList" :key="index" class="file-item">
				<span>{{ file.name }}</span>
				<a-progress :percent="file.percent || 0" />
				<span v-if="file.status === 'done'">已完成</span>
				<span v-else-if="file.status === 'error'">上传失败</span>
				<span v-else-if="file.status === 'uploading'">上传中...</span>
			</li>
		</ul>
	</a-modal>
</template>

<script setup>
	import { ref, reactive } from 'vue'
	import { Modal, Upload } from 'ant-design-vue'
	import { PlusOutlined } from '@ant-design/icons-vue'
	import tool from '@/utils/tool'
	const props = defineProps({
		isState: {
			type: Number,
			required: true,
			default: 0
		}
	})
	const headers = ref({
		token: tool.data.get('TOKEN')
	})
	const action = ref('http://192.168.31.80:9003/api/webapp/dev/file/uploadMinioReturnId')
	const emit = defineEmits(['close', 'confirm'])

	// 表单数据
	const uploadForm = reactive({
		// resourceName: null,
		resourceType: null,
		courseName: null,
		courseDesc: null,
		coverImageId: null
	})

	// 封面文件列表
	const coverFileList = ref([])
	const fileList = ref([])

	const uploadModalVisible = ref(true)

	// 显示上传模态框
	// const showUploadModal = () => {
	//   uploadModalVisible.value = true
	// }

	// 关闭模态框
	const handleUploadCancel = () => {
		uploadModalVisible.value = false
		Object.assign(uploadForm, {
			// resourceName: null,
			resourceType: null,
			courseName: null,
			courseDesc: null,
			coverImageId: null
		})
		fileList.value = []
		coverFileList.value = []
		emit('close')
	}

	// 确认上传
	const handleUploadOk = () => {
		// 这里可以添加实际的上传逻辑
		console.log('Upload confirmed:', uploadForm.fileId, fileList.value, coverFileList.value)
		emit('confirm', uploadForm)
		uploadModalVisible.value = false
		Object.assign(uploadForm, {
			// resourceName: null,
			resourceType: null,
			courseName: null,
			courseDesc: null,
			coverImageId: null
		})
		fileList.value = []
		coverFileList.value = []
	}

	// 上传封面前的钩子函数
	const beforeUploadCover = (file) => {
		const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
		if (!isJpgOrPng) {
			Modal.error({ content: '仅支持上传jpg/png格式文件!' })
		}
		const isLt500K = file.size / 1024 < 500
		if (!isLt500K) {
			Modal.error({ content: '单个文件不能超过500kb!' })
		}
		return isJpgOrPng && isLt500K
	}

	// 移除封面文件
	const handleRemoveCover = (file) => {
		const index = coverFileList.value.indexOf(file)
		const newFileList = coverFileList.value.slice()
		newFileList.splice(index, 1)
		coverFileList.value = newFileList
		// 如果移除的是当前封面文件，则清空coverImageId
		if (uploadForm.coverImageId === file.id) {
			uploadForm.coverImageId = null
		}
	}

	// 封面文件状态改变时的处理函数
	const handleChangeCover = ({ file, fileList: newFileList }) => {
		if (file.status === 'done') {
			// 上传成功，获取文件ID
			const fileId = file.response?.data || file.id
			console.log('上传成功，获取文件ID', fileId)
			if (fileId) {
				uploadForm.coverImageId = fileId
			}
		}
		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 scoped>
	.upload-area {
		border: 2px dashed #3ca9f5;
		padding: 40px;
		text-align: center;
	}

	.upload-area p {
		margin: 10px 0;
	}

	.file-item {
		display: flex;
		align-items: center;
		margin: 10px 0;
	}

	.file-item .ant-progress {
		flex: 1;
		margin: 0 10px;
	}
</style>
