<template>
	<a-form
		:model="formState"
		:rules="rules"
		ref="formRef"
		layout="horizontal"
		:label-col="{ span: 2 }"
		:wrapper-col="{ span: 12 }"
	>
		<a-form-item label="教室名称" name="courseName">
			<a-input v-model:value="formState.courseName" placeholder="输入教室名称" />
		</a-form-item>

		<a-form-item label="授课教师" name="teacherId">
			<a-select
				v-model:value="formState.teacherId"
				:fieldNames="{ label: 'name', value: 'id' }"
				:options="teacherOptions"
				placeholder="请选择授课教师"
			/>
		</a-form-item>

		<a-form-item label="课程分类" name="courseType">
			<a-select v-model:value="formState.courseType" :options="courseClass" placeholder="选择课程分类" />
		</a-form-item>

		<a-form-item label="上传封面" name="coverImageId">
			<coverUpload
				:coverImageId="formState.coverImageId"
				:imageUrl="coverImagePath"
				@handleChangeCover="handleChangeCover"
				@handleRemoveCover="handleRemoveCover"
			></coverUpload>
		</a-form-item>

		<a-form-item label="院系" name="collegeId">
			<a-cascader
				v-model:value="majorIdName"
				:options="collegeMajorOptions"
				:fieldNames="{ label: 'name', value: 'id', children: 'children' }"
				placeholder="请选择院系"
				changeOnSelect
				@change="changeCollegeMajor"
			/>
		</a-form-item>
		<a-form-item label="专业" name="majorId">
			<a-select
				v-model:value="formState.majorId"
				:fieldNames="{ label: 'majorName', value: 'majorCode' }"
				:options="majorOptions"
				placeholder="请选择专业"
			/>
		</a-form-item>

		<a-form-item label="教室描述" name="courseDesc">
			<quill-editor
				ref="quillEditorRef"
				placeholder="请输入教室描述"
				v-model:content="formState.courseDesc"
				style="height: 200px"
				contentType="html"
				theme="snow"
			/>
		</a-form-item>

		<a-form-item :wrapper-col="{ offset: 5, span: 12 }">
			<a-button
				type="primary"
				v-if="!courseInfoId"
				style="margin-right: 10px"
				@click="() => formRef.validate().then(handleSubmit)"
				>提交</a-button
			>
			<a-button type="primary" v-if="courseInfoId" @click="() => formRef.validate().then(handleEdit)"
				>编辑提交</a-button
			>
		</a-form-item>
	</a-form>
</template>

<script setup>
	import { reactive, ref, onMounted } from 'vue'
	import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue'
	import { QuillEditor } from '@vueup/vue-quill'
	import '@vueup/vue-quill/dist/vue-quill.snow.css'
	import resourceAuditApi from '@/api/resourceAudit.js'
	import courseCenterApi from '@/api/courseCenter/courseinfo.js'
	import coverUpload from '@/views/myResources/coverUpload/index.vue'
	import sysConfig from '@/config/index'

	const emit = defineEmits(['nextStep'])
	import tool from '@/utils/tool'
	const props = defineProps({
		//课程id
		courseInfoId: {
			type: Number,
			required: true,
			default: null
		}
	})
	const formState = reactive({
		courseName: null,
		teacherId: null,
		courseType: null,
		courseDesc: null,
		collegeId: null, //院校一级id
		collegeTwoId: null, //院校二级id
		collegeThreeId: null, //院校三级id
		majorId: null, //专业
		coverImageId: null //封面id
	})
	const rules = {
		courseName: [{ required: true, message: '请输入教室名称', trigger: 'blur' }],
		teacherId: [{ required: true, message: '请选择授课教师', trigger: 'change' }],
		courseType: [{ required: true, message: '请选择课程分类', trigger: 'change' }],
		courseDesc: [{ required: true, message: '请输入教室描述', trigger: 'change' }],
		collegeId: [{ required: true, message: '请选择院系', trigger: 'change' }],
		majorId: [{ required: true, message: '请选择专业', trigger: 'change' }],
		coverImageId: [{ required: true, message: '请上传封面', trigger: 'change' }]
	}
	const loading = ref(false)
	const formRef = ref(null)
	const courseInfoId = ref(null) //课程表单添加成功id
	const collegeMajorOptions = ref([]) //院系
	const majorIdName = ref([]) //院系回显
	const majorOptions = ref([]) //专业
	const courseOptions = ref([]) //课程
	const teacherOptions = ref([]) //教师
	const coverImagePath = ref() // 预览回显
	const quillEditorRef = ref(null) // 预览回显
	const courseClass = tool.dictList('COURSE_TYPE')

	const handleSubmit = () => {
		console.log('表单数据:', formState)
		// 这里添加实际提交逻辑，例如：
		// let params = {
		// 	current: pagination.pageNum,
		// 	size: pagination.pageSize,
		// 	verifyStatus: formState.verifyStatus,
		// 	fileName: formState.fileName
		// }

		// courseDesc.ops
		formState.courseDesc = toRaw(quillEditorRef.value).getHTML()
		courseCenterApi
			.add(formState)
			.then((res) => {
				console.log(res.data, '表单添加')
				courseInfoId.value = res.data.courseId
				//表单添加成功保存ID
				localStorage.setItem('courseInfoId', res.data.courseId)
				emit('nextStep')
			})
			.catch((err) => {
				console.log(err)
			})
	}
	const handleEdit = () => {
		console.log('表单编辑数据:', formState)
		// collegeId
		formState.courseDesc = toRaw(quillEditorRef.value).getHTML()
		courseCenterApi
			.edit({ ...formState, courseId: courseInfoId.value })
			.then((res) => {
				console.log(res.data, '表单编辑')
			})
			.catch((err) => {
				console.log(err)
			})
	}
	// 封面文件id
	const handleChangeCover = (fileId) => {
		formState.coverImageId = fileId
	}

	// 移除封面文件
	const handleRemoveCover = () => {
		formState.coverImageId = null
	}
	//获取教师人员
	const getlecturerListSelector = () => {
		courseCenterApi
			.lecturerList()
			.then((res) => {
				console.log(res.data, '获取教师下拉数据')
				teacherOptions.value = res.data
			})
			.catch((err) => {
				console.log(err)
			})
	}
	//院系组织查询
	const getOrgTreeSelector = () => {
		resourceAuditApi
			.orgTreeSelector()
			.then((res) => {
				console.log(res.data, '获取组织树选择器')
				collegeMajorOptions.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 getCollegeMajor = (id) => {
		resourceAuditApi
			.zyselect({ collegeId: id })
			.then((res) => {
				console.log(res.data, '专业下拉数据')
				majorOptions.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 getDetail = () => {
		courseInfoId.value = props.courseInfoId
		courseCenterApi.detail({ courseId: props.courseInfoId }).then((res) => {
			console.log(res.data, '课程信息详情')
			formState.courseName = res.data.courseName
			formState.teacherId = res.data.teacherId
			formState.collegeId = res.data.collegeId
			majorIdName.value = res.data.collegeAllId?.split(',')
			getCollegeMajor(majorIdName.value[majorIdName.value.length - 1])
			formState.courseType = res.data.courseType
			formState.courseDesc = res.data.courseDesc
			toRaw(quillEditorRef.value).setHTML(formState.courseDesc)
			formState.coverImageId = res.data.coverImageId
			coverImagePath.value = res.data.coverImagePath
			formState.majorId = res.data.majorId
		})
	}
	//  const quill = toRaw(myQuillEditor.value).getQuill()
	//   if (myQuillEditor.value) {
	//     quill.getModule('toolbar').addHandler('image', imgHandler)
	//   }

	// ————————————————

	//                             版权声明：本文为博主原创文章，遵循 CC 4.0 BY-SA 版权协议，转载请附上原文出处链接和本声明。

	// 原文链接：https://blog.csdn.net/moanuan/article/details/128240291
	onMounted(() => {
		// toRaw(quillEditorRef.value).setHTML(props.value)
		// formState.courseDesc = '<p>默认内容</p>'
		getOrgTreeSelector()
		getCourseAllList()
		getlecturerListSelector()
		if (props.courseInfoId) {
			getDetail()
		}
	})
</script>

<style scoped>
	.avatar-uploader > .ant-upload {
		width: 128px;
		height: 128px;
	}
	.ant-upload-select-picture-card i {
		font-size: 32px;
		color: #999;
	}

	.ant-upload-select-picture-card .ant-upload-text {
		margin-top: 8px;
		color: #666;
	}

	/* 调整表单间距 */
	.ant-form-item {
		margin-bottom: 16px;
	}
</style>
