<template>
	<!-- 上传资源模态框 -->
	<a-modal
		v-model:visible="uploadModalVisible"
		:title="isState == 0 ? '上传资源' : '编辑'"
		@ok="handleUploadOk"
		@cancel="handleUploadCancel"
		width="600px"
	>
		<a-form :model="formState" :rules="rules" ref="formRef">
			<a-form-item label="院系" name="collegeId" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
				<a-cascader
					v-model:value="majorIdName"
					:options="collegeMajorOptions"
					:fieldNames="{ label: 'name', value: 'id', children: 'children' }"
					placeholder="请选择院系"
					style="width: 300px"
					changeOnSelect
					@change="changeCollegeMajor"
				/>
			</a-form-item>
			<!-- <a-form-item label="专业" name="majorId" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
				<a-select
					v-model:value="formState.majorId"
					style="width: 200px"
					:fieldNames="{ label: 'majorName', value: 'majorCode' }"
					:options="majorOptions"
					placeholder="请选择专业"
				/>
			</a-form-item> -->
			<!-- <a-form-item label="课程" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
				<a-select
					v-model:value="formState.courseId"
					style="width: 200px"
					:fieldNames="{ label: 'courseName', value: 'courseId' }"
					:options="courseOptions"
					placeholder="请选择课程"
				/>
			</a-form-item> -->
			<a-form-item label="资源类型" name="resourceType" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
				<a-cascader
					style="width: 240px; margin-left: 8px"
					v-model:value="resourceName"
					:options="resourceTypeOptions"
					:fieldNames="{ label: 'name', value: 'id', children: 'children' }"
					placeholder="请选择资源类型"
					changeOnSelect
					@change="changeCollegeResource"
				/>
			</a-form-item>
			<a-form-item
				label="关键词(需添加2-5个关键词)"
				name="keywordValue"
				:label-col="{ span: 10 }"
				:wrapper-col="{ span: 18 }"
			>
				<div v-if="!formState.keywordValue.length" style="color: #ccc">请选择下方热门关键词</div>
				<div v-if="formState.keywordValue.length">
					<a-tag
						v-for="(keyword, index) in formState.keywordValue"
						:key="index"
						closable
						@close="handleRemoveKeyword(keyword, index)"
					>
						{{ keyword }}
					</a-tag>
				</div>
			</a-form-item>
			<a-form-item label="热门关键词" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
				<a-checkbox-group
					v-model:value="formState.keyword"
					:options="HotKeywordsOptions"
					@change="handleChangeKeyword"
				/>
			</a-form-item>
			<a-row>
				<a-col :span="5"></a-col>
				<a-col :span="8">
					<a-input v-model:value="newKeyword" placeholder="请输入关键词" @pressEnter="handleAddKeyword" />
				</a-col>
				<a-col :span="9" style="line-height: 30px"> 按回车Enter创建新关键词 </a-col>
			</a-row>
			<a-form-item label="资源是否公开" style="margin-top: 10px" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
				<div class="public-status-buttons">
					<button :class="['status-button', { active: formState.authType === '0' }]" @click="setPublicStatus('0')">
						公开
					</button>
					<button :class="['status-button', { active: formState.authType === '1' }]" @click="setPublicStatus('1')">
						部分人可见
					</button>
				</div>
			</a-form-item>
			<a-form-item label="是否热门" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
				<a-radio-group v-model:value="formState.isHot">
					<a-radio :value="0">否</a-radio>
					<a-radio :value="1">是</a-radio>
				</a-radio-group>
			</a-form-item>
			<a-form-item label="是否推荐" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
				<a-radio-group v-model:value="formState.isRecommend">
					<a-radio :value="0">否</a-radio>
					<a-radio :value="1">是</a-radio>
				</a-radio-group>
			</a-form-item>
			<a-form-item v-if="isState == 1 && isVerifyStatus != '0,3'" label="资源描述" name="resourceDesc">
				<a-textarea v-model:value="formState.resourceDesc" placeholder="请输入资源描述" :rows="4" />
			</a-form-item>
			<a-form-item v-if="isState == 1 && isVerifyStatus != '0,3'" label="上传封面" name="coverImage">
				<coverUpload
					:isedit="true"
					:coverImageId="formState.coverImage"
					:imageUrl="coverImagePath"
					@handleChangeCover="handleChangeCover"
					@handleRemoveCover="handleRemoveCover"
				></coverUpload>
			</a-form-item>
			<!-- 选择成员 -->
			<userSelection
				:visible="userReleaseVisible"
				:userRelateIds="userRelateIdss"
				@close="userReleaseVisible = false"
				@confirm="confirmUser"
			></userSelection>
		</a-form>
		<template v-if="isState == 0">
			<!-- 资源上传 -->
			<!-- <UploadModal @success="uploadSuccess"></UploadModal> -->
			<UpLoadBreakPoint @onSuccess="onSuccess"></UpLoadBreakPoint>
		</template>
	</a-modal>
</template>

<script setup>
	import { ref, reactive, onMounted } from 'vue'
	import { Modal, Upload, Form } from 'ant-design-vue'
	import resourceAuditApi from '@/api/resourceAudit.js'
	import userSelection from './userSelection.vue'
	import UploadModal from './UploadModal.vue'
	import coverUpload from './coverUpload/index.vue'
	import UpLoadBreakPoint from '@/components/UpLoadBreakPoint/index.vue'
	import { useMyResourceStore } from '@/store/myResource'
	const myResourceStore = useMyResourceStore()
	const { proxy } = getCurrentInstance()
	const props = defineProps({
		isState: {
			type: Number,
			required: true,
			default: 0
		},
		isVerifyStatus: {
			type: Number,
			required: true,
			default: 0
		},
		resourcesId: {
			type: Number,
			required: true,
			default: null
		}
	})
	const emit = defineEmits(['close', 'getList'])
	import tool from '@/utils/tool'
	const headers = ref({
		token: tool.data.get('TOKEN')
	})
	//课程类型
	const courseTypeOptions = tool.dictList('COURSE_TYPE')
	const action = ref('/api/webapp/dev/file/uploadMinioReturnId')
	const formState = reactive({
		userfileIds: null, //资源文件id
		coverImage: null, //封面id
		// courseId: null, //课程
		// majorType: null, //专业
		resourceType: null, //资源类型一级
		resourceTwoType: null, //资源类型二级
		collegeId: null, //院校一级id
		collegeTwoId: null, //院校二级id
		collegeThreeId: null, //院校三级id
		resourceDesc: null, //资源介绍
		// majorId: null, //专业id
		// courseTypeName: [], // 资源类型
		keywordValue: [], // 添加关键词
		keyword: [], // 热门关键词
		authType: '0', // 资源是否公开
		userRelateIds: null, //资源公开人员id
		isRecommend: 0, // 资源是否推荐
		isHot: 0 // 资源是否热门
	})
	const coverImagePath = ref() // 预览回显
	const formRef = ref() // 添加表单引用
	const collegeMajorOptions = ref([]) //院系
	const resourceTypeOptions = ref([]) //资源类型下拉数据
	const HotKeywordsOptions = ref([]) //热门关键词列表
	const majorIdName = ref([]) //院系回显
	const resourceName = ref([]) //资源回显
	const majorOptions = ref([]) //专业
	const courseOptions = ref([]) //课程
	const userRelateIdss = ref([])
	// 上传资源模态框
	const uploadModalVisible = ref(true)
	// 用户选择模态框
	const userReleaseVisible = ref(false)

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

	// 关闭模态框
	const handleUploadCancel = () => {
		emit('close')
		fileList.value = []
	}
	// 新增Set记录已处理ID
	// const processedIds = ref(new Set())
	//资源文件上传成功返回
	const uploadSuccess = async (idsArr) => {
		formState.userfileIds = idsArr.join(',')
		// const newIds = idsArr.filter((id) => !processedIds.value.has(id))
		// if (newIds.length === 0) return
		// //文件转换
		// try {
		// 	const requests = newIds.map((id) => resourceAuditApi.fileFormatConversion({ userFileId: id }))
		// 	await Promise.all(requests)
		// 	newIds.forEach((id) => processedIds.value.add(id))
		// 	newKeyword.value = ''
		// } catch (err) {
		// 	console.error('部分请求失败:', err)
		// }
	}
	const onSuccess = (uploadFileList) => {
		let list = []
		console.log('formState.userfileIds是数组：', uploadFileList)
		for (let i = 0; i < uploadFileList.length; i++) {
			if (uploadFileList[i].userFileId) {
				list.push(uploadFileList[i].userFileId)
			}
		}
		console.log('formState.userfileIds是：', list)
		formState.userfileIds = list.join(',')
	}

	// 自定义校验函数示例
	const validateKeywords = (rule, value, callback) => {
		if (value.length < 2) {
			callback(new Error('至少需要添加2个关键词'))
		} else if (value.length > 5) {
			callback(new Error('最多只能添加5个关键词'))
		} else {
			callback()
		}
	}
	// 封面文件id
	const handleChangeCover = (fileId) => {
		formState.coverImage = fileId
	}

	// 移除封面文件
	const handleRemoveCover = () => {
		formState.coverImage = null
	}
	const rules = {
		// courseTypeName: [{ required: true, message: '请选择资源类型', trigger: 'change' }],
		collegeId: [{ required: true, message: '请选择院系', trigger: 'blur' }],
		keywordValue: [
			{ required: true, message: '请选择关键词', trigger: 'blur' },
			{ validator: validateKeywords, trigger: 'blur' }
		],
		// coverImage: [{ required: true, message: '请上传封面', trigger: 'blur' }],
		resourceType: [{ required: true, message: '请选择资源类型', trigger: 'blur' }],
		resourceDesc: [
			{ required: true, message: '请输入资源描述', trigger: 'blur' },
			{ pattern: /^[\s\S]{10,500}$/, message: '描述长度应在10-500字符之间', trigger: 'blur' }
		]
	}
	const newKeyword = ref('') //关键词
	const handleAddKeyword = (e) => {
		const newKeywords = newKeyword.value.trim()
		resourceAuditApi
			.addHotKeywords({
				wordName: newKeywords,
				popular: 0
			})
			.then((res) => {
				console.log(res.data, '添加热门关键词')
				getHotKeywords()
				newKeyword.value = ''
			})
			.catch((err) => {
				console.log(err)
			})
		// if (newKeywords && !formState.keywordValue.includes(newKeywords)) {
		// 	formState.keywordValue.push(newKeywords)
		// }
	}

	const handleRemoveKeyword = (keywordName, index) => {
		console.log(keywordName, index)
		// 1. 从显示列表中删除
		formState.keywordValue = formState.keywordValue.filter((name) => name !== keywordName)
		// 2. 更新checkbox的绑定值
		formState.keyword = HotKeywordsOptions.value
			.filter((option) => formState.keywordValue.includes(option.label))
			.map((item) => item.value)
	}
	const getHotKeywords = () => {
		resourceAuditApi
			.HotKeywords()
			.then((res) => {
				console.log(res.data, '获取热门关键词')
				HotKeywordsOptions.value = res.data.map((it) => {
					return {
						value: it.id,
						label: it.wordName
					}
				})
			})
			.catch((err) => {
				console.log(err)
			})
	}
	//资源类型下拉查询
	const getResourceTypeTree = () => {
		resourceAuditApi
			.resourceTypeTree()
			.then((res) => {
				console.log(res.data, '资源类型下拉')
				resourceTypeOptions.value = res.data
			})
			.catch((err) => {
				console.log(err)
			})
	}
	const handleChangeKeyword = (checkedValues) => {
		formState.keyword = checkedValues
		formState.keywordValue = HotKeywordsOptions.value
			.filter((option) => checkedValues.includes(option.value))
			.map((item) => item.label)
	}
	const setPublicStatus = (status) => {
		formState.authType = status
		if (status === '1') {
			userReleaseVisible.value = true
		}
	}
	//院系组织查询
	const getOrgTreeSelector = () => {
		resourceAuditApi
			.orgTreeSelector()
			.then((res) => {
				console.log(res.data, '获取组织树选择器')
				collegeMajorOptions.value = res.data
			})
			.catch((err) => {
				console.log(err)
			})
	}
	//院系组织查询
	const getCourseAllList = () => {
		resourceAuditApi
			.courseAllList()
			.then((res) => {
				console.log(res.data, '获取全部课程')
				courseOptions.value = res.data
			})
			.catch((err) => {
				console.log(err)
			})
	}
	const changeCollegeMajor = (value, selectedOptions) => {
		console.log('Selected:', value, selectedOptions)
		if (!value) {
			majorIdName.value = ''
			return false
		}
		majorIdName.value = selectedOptions.map((it) => it.name).join('/')
		formState.collegeId = value[0] || null
		formState.collegeTwoId = value[1] || null
		formState.collegeThreeId = value[2] || null
		if (selectedOptions.length) {
			// 获取选中的最后一级
			const lastSelected = selectedOptions[selectedOptions.length - 1]
			// formState.selectedCollegeMajor = {
			// 	id: lastSelected.id,
			// 	name: lastSelected.name,
			// 	fullPath: selectedOptions.map((opt) => opt.name).join(' / ')
			// }
			console.log(lastSelected, '最后一级id')
			getCollegeMajor(lastSelected.id)
		}
	}
	const changeCollegeResource = (value, selectedOptions) => {
		console.log('Selected:', value, selectedOptions)
		if (!value) {
			resourceName.value = ''
			return false
		}
		resourceName.value = selectedOptions.map((it) => it.name).join('/')
		formState.resourceType = value[0] || null
		formState.resourceTwoType = value[1] || null
	}
	const getCollegeMajor = (id) => {
		resourceAuditApi
			.zyselect({ collegeId: id })
			.then((res) => {
				console.log(res.data, '专业下拉数据')
				majorOptions.value = res.data
			})
			.catch((err) => {
				console.log(err)
			})
	}
	const confirmUser = (userIds) => {
		console.log(userIds, '用户id')
		userReleaseVisible.value = false
		formState.userRelateIds = userIds.join(',')
	}
	// 确认上传
	const handleUploadOk = async () => {
		try {
			await formRef.value.validate()
			console.log('formState.userfileIds是：提交了', formState.userfileIds)
			if (!formState.userfileIds) {
				Modal.error({ content: '请先上传文件!' })
				return
			}
			if (props.isState == 1) {
				const formData = {
					id: props.resourcesId,
					userfileIds: formState.userfileIds,
					resourceType: formState.resourceType,
					resourceTwoType: formState.resourceTwoType,
					collegeId: formState.collegeId,
					collegeTwoId: formState.collegeTwoId,
					collegeThreeId: formState.collegeThreeId,
					keywordValue: formState.keywordValue.join(','),
					keyword: formState.keyword.join(','),
					resourceDesc: formState.resourceDesc,
					isHot: formState.isHot,
					isRecommend: formState.isRecommend,
					coverImage: formState.coverImage,
					publicStatus: formState.publicStatus,
					authType: formState.authType,
					userRelateIds: formState.authType == 1 ? formState.userRelateIds : null
				}
				resourceAuditApi
					.edit(formData)
					.then((res) => {
						emit('getList')
						Modal.success({ content: '资源编辑成功' })
					})
					.catch((err) => {
						Modal.success({ content: '资源编辑失败' })
						console.log(err)
					})
			} else {
				const formData = {
					userfileIds: formState.userfileIds,
					resourceType: formState.resourceType,
					resourceTwoType: formState.resourceTwoType,
					collegeId: formState.collegeId,
					collegeTwoId: formState.collegeTwoId,
					collegeThreeId: formState.collegeThreeId,
					keywordValue: formState.keywordValue.join(','),
					keyword: formState.keyword.join(','),
					resourceDesc: formState.resourceDesc,
					isHot: formState.isHot,
					isRecommend: formState.isRecommend,
					coverImage: formState.coverImage,
					publicStatus: formState.publicStatus,
					authType: formState.authType,
					userRelateIds: formState.authType == 1 ? formState.userRelateIds : null
				}
				console.log(formData, '上传数据')
				resourceAuditApi
					.add(formData)
					.then((res) => {
						emit('getList')
						Modal.success({ content: '资源上传成功' })
					})
					.catch((err) => {
						Modal.success({ content: '资源上传失败' })
						console.log(err)
					})
			}
		} catch (error) {
			if (error.errorFields) {
				// 表单验证错误
				Modal.error({ content: '请检查表单填写是否正确' })
			} else {
				// API错误
				Modal.error({ content: '资源上传失败' })
				console.error(error)
			}
		}
	}
	// 获取资源详情
	const getDetail = () => {
		resourceAuditApi.detail({ id: props.resourcesId }).then((res) => {
			console.log(res.data, '资源详情')
			formState.userfileIds = res.data.fileId
			formState.userRelateIds = res.data.userRelateIdList?.join(',')
			userRelateIdss.value = res.data.userRelateIdList
			formState.resourceType = res.data.resourceType
			formState.resourceTwoType = res.data.resourceTwoType
			formState.collegeId = res.data.collegeId
			formState.coverImage = res.data.coverImage
			coverImagePath.value = res.data.coverImagePath
			formState.collegeTwoId = res.data.collegeTwoId
			formState.collegeThreeId = res.data.collegeThreeId
			majorIdName.value = res.data.collegeAllId?.split(',')
			resourceName.value = res.data.resourceALLTypeName?.split(',')
			getCollegeMajor(majorIdName.value[majorIdName.value.length - 1])
			formState.resourceDesc = res.data.resourceDesc
			// formState.majorId = res.data.majorId
			formState.keywordValue = res.data.keywordValue?.split(',')
			formState.keyword = res.data.keyword.split(',').filter(Boolean).map(Number)
		})
	}
	// 获取历史添加表单
	const getformState = () => {
		resourceAuditApi.recentlyRecord().then((res) => {
			console.log(res.data, '历史表单数据')
			formState.resourceType = res.data.resourceType
			formState.userRelateIds = res.data.userRelateIdList?.join(',')
			userRelateIdss.value = res.data.userRelateIdList
			formState.resourceTwoType = res.data.resourceTwoType
			formState.collegeId = res.data.collegeId
			formState.collegeTwoId = res.data.collegeTwoId
			formState.collegeThreeId = res.data.collegeThreeId
			majorIdName.value = res.data.collegeAllId?.split(',')
			resourceName.value = res.data.resourceAllType?.split(',')
			getCollegeMajor(majorIdName.value[majorIdName.value.length - 1])
			formState.resourceDesc = res.data.resourceDesc
			// formState.majorId = res.data.majorId
			formState.keywordValue = res.data.keywordValue?.split(',')
			formState.keyword = res.data.keyword?.split(',').filter(Boolean).map(Number)
		})
	}
	// 上传前的钩子函数
	const beforeUpload = (file) => {
		const isLt2G = file.size / 1024 / 1024 / 1024 < 2
		if (!isLt2G) {
			Modal.error({ content: '文件大小不能超过 2GB!' })
		}
		return isLt2G
	}

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

	// 文件状态改变时的处理函数
	const handleChange = ({ file, fileList: newFileList }) => {
		if (newFileList.length > 1) {
			fileList.value = [newFileList[0]] // 只保留最新上传的文件
			Modal.error({ content: '只能上传一个文件!' })
			return
		}

		if (file.response?.code == 200) {
			// 上传成功，获取文件ID
			const fileId = file.response?.data || file.id
			console.log('上传成功，获取文件ID', fileId)
			if (fileId) {
				formState.userfileIds = fileId
			}
		}
		fileList.value = newFileList
		if (file.status === 'uploading') {
			file.percent = Math.floor(file.percent)
		}
		if (file.response?.code == 200) {
			file.percent = 100
			Modal.success({ content: '文件上传成功' })
		} else if (file.response?.code == 500) {
			Modal.error({ content: '文件上传失败' })
			file.percent = 0
		}
	}
	onMounted(() => {
		getOrgTreeSelector()
		getCourseAllList()
		getHotKeywords()
		getResourceTypeTree()
		if (props.isState == 1) {
			getDetail()
		} else {
			getformState()
		}
	})
</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;
	}

	/* 新增表单样式 */
	.ant-form-item {
		margin-bottom: 16px;
	}
	.public-status-buttons {
		display: flex;
	}

	.status-button {
		padding: 5px 10px;
		/* margin-right: 10px; */
		border: 1px solid #ccc;
		/* border-radius: 3px; */
		cursor: pointer;
		background-color: #fff;
	}

	.status-button.active {
		background-color: #40a9ff;
		color: #fff;
		border-color: #40a9ff;
	}
	.upload-area {
		border: 2px dashed #3ca9f5;
		padding: 40px;
		text-align: center;
		transition: border-color 0.3s; /* 平滑过渡效果 */
	}

	.upload-area.drag-over {
		border-color: #1890ff;
		background-color: rgba(24, 144, 255, 0.05);
	}
</style>
