<template>
	<div class="knowledge-edit-container layout-pd">
		<el-card shadow="never" style="padding: 0 50px">
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="120px" scroll-to-error>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
						<el-skeleton :loading="state.loading" animated>
							<template #template>
								<el-form-item label="试题类型">
									<el-skeleton-item variant="h1" />
								</el-form-item>
							</template>
							<template #default>
								<el-form-item label="试题类型" prop="questionType" :rules="[{ required: true, message: '请选择试题类型', trigger: 'change' }]" >
                                    <el-radio-group v-model="state.ruleForm.questionType">
                                        <el-radio :value="0">单选题</el-radio>
                                        <el-radio :value="1">多选题</el-radio>
                                        <el-radio :value="2">判断题</el-radio>
                                        <el-radio :value="3">填空题</el-radio>
                                        <el-radio :value="4">问答题</el-radio>
                                    </el-radio-group>
								</el-form-item>
							</template>
						</el-skeleton>
                        <el-skeleton :loading="state.loading" animated>
							<template #template>
								<el-form-item label="试题标签">
									<el-skeleton-item variant="h1" />
								</el-form-item>
							</template>
							<template #default>
								<el-form-item label="试题标签" prop="questionTagIds" :rules="[{ required: true, message: '请选择试题标签', trigger: 'change' }]">
									<el-tree-select
										v-model="state.ruleForm.questionTagIds"
										:data="state.tagData"
										node-key="id"
										:props="{ label: 'name' }"
										filterable
										multiple
										collapse-tags
										collapse-tags-tooltip
										:max-collapse-tags="2"
										:render-after-expand="false"
										style="width: 100%"
										ref="treeSelectRef"
										@change="selQuestionTag"
									/>
								</el-form-item>
							</template>
						</el-skeleton>
                        <el-skeleton :loading="state.loading" animated>
							<template #template>
								<el-form-item label="难度级别">
									<el-skeleton-item variant="h1" />
								</el-form-item>
							</template>
							<template #default>
								<el-form-item label="难易程度" prop="difficultyLevel" :rules="[{ required: true, message: '请选择难易程度', trigger: 'change' }]">
                                    <el-select v-model="state.ruleForm.difficultyLevel" clearable placeholder="请选择难易程度">
                                        <el-option key='0' label="容易" :value="0" />
                                        <el-option key='1' label="适中" :value="1" />
                                        <el-option key='2' label="困难" :value="2" />
                                    </el-select>
								</el-form-item>
							</template>
						</el-skeleton>
                        <el-skeleton :loading="state.loading" animated>
							<template #template>
								<el-form-item label="正式可用">
									<el-skeleton-item variant="h1" />
								</el-form-item>
							</template>
							<template #default>
								<el-form-item label="正式可用" prop="formalEnable" :rules="[{ required: true, message: '请选择是否正式可用', trigger: 'change' }]">
                                    <el-radio-group v-model="state.ruleForm.formalEnable">
                                        <el-radio :value="true">是</el-radio>
                                        <el-radio :value="false">否</el-radio>
                                    </el-radio-group>
								</el-form-item>
							</template>
						</el-skeleton>
                        <el-skeleton :loading="state.loading" animated>
							<template #template>
								<el-form-item label="模拟可用">
									<el-skeleton-item variant="h1" />
								</el-form-item>
							</template>
							<template #default>
								<el-form-item label="模拟可用" prop="simulateEnable" :rules="[{ required: true, message: '请选择是否模拟可用', trigger: 'change' }]">
                                    <el-radio-group v-model="state.ruleForm.simulateEnable">
                                        <el-radio :value="true">是</el-radio>
                                        <el-radio :value="false">否</el-radio>
                                    </el-radio-group>
								</el-form-item>
							</template>
						</el-skeleton>
                        <el-skeleton :loading="state.loading" animated>
                            <template #template>
                                <el-form-item label="关联知识">
                                    <el-skeleton-item variant="h1" />
                                </el-form-item>
                            </template>
                            <template #default>
								<el-form-item label="关联知识" prop="knowledgeTitle" :rules="[{ required: false, message: '请选择关联知识', trigger: 'change' }]">
									<div class="flex-center-align w100">
										<el-input v-model="state.ruleForm.knowledgeTitle" placeholder="请选择关联知识" style="flex: 1" clearable readonly>
											<template #append>
												<el-button @click="onKnowledgeTo">选择知识</el-button>
											</template>
										</el-input>
										<el-button class="ml10" @click="clearKnowledge" type="danger">清空</el-button>
									</div>
								</el-form-item>
                            </template>
                        </el-skeleton>
                        <el-skeleton :loading="state.loading" animated>
                            <template #template>
                                <el-form-item label="关联课件">
                                    <el-skeleton-item variant="h1" />
                                </el-form-item>
                            </template>
                            <template #default>
								<el-form-item label="关联课件" prop="courseTitle" :rules="[{ required: false, message: '请选择关联课件', trigger: 'change' }]">
									<div class="flex-center-align w100">
										<el-input v-model="state.ruleForm.courseTitle" placeholder="请选择关联课件" style="flex: 1" clearable readonly>
											<template #append>
												<el-button @click="onCourseTo">选择课件</el-button>
											</template>
										</el-input>
										<el-button class="ml10" @click="clearCourse" type="danger">清空</el-button>
									</div>
								</el-form-item>
                            </template>
                        </el-skeleton>
					</el-col>
					<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
						<el-skeleton :loading="state.loading" animated>
							<template #template>
								<el-form-item label="题干">
									<el-skeleton-item variant="h1" />
								</el-form-item>
							</template>
							<template #default>
								<el-form-item label="题干" prop="title" :rules="[{ required: true, message: '请输入题干', trigger: 'blur' }]">
                                    <el-input type="textarea" :rows="3" v-model="state.ruleForm.title" placeholder="请输入题干" clearable></el-input>
								</el-form-item>
							</template>
						</el-skeleton>
                        <div v-if="[0].includes(state.ruleForm.questionType)">
							<el-radio-group v-model="state.ruleForm.radioKey" style="display: block;">
								<el-skeleton :loading="state.loading" animated v-for="(item, index) in state.ruleForm.questionOptionsDtos" :key="item.temp">
									<template #template>
										<el-form-item label="选项">
											<el-skeleton-item variant="h1" />
										</el-form-item>
									</template>
									<template #default>
										<el-form-item label="选项" :prop="`questionOptionsDtos.${index}.content`" :rules="[{required: true, message: '请输入选项', trigger: 'blur' }]">
											<el-row :gutter="0" justify="space-between" style="width: 100%;">
												<el-col :span="17">
													<el-input v-model="item.content" placeholder="请输入选项" clearable>
													<template #append>
														<el-radio label="答案" :value="item.temp" />
													</template>
												</el-input>
												</el-col>
												<el-col :span="7" style="text-align: right">
													<el-button type="primary" size="small" v-if="index == 0" @click="addOption"> <SvgIcon name="ele-Plus" class="mr5" /> </el-button>
													<el-button size="small" class="default-button" @click="deleteOption(item.temp)" > <SvgIcon name="ele-Delete" class="mr5" /></el-button>
												</el-col>
											</el-row>
										</el-form-item>
									</template>
								</el-skeleton>
							</el-radio-group>
                        </div>
						<div v-else-if="[1].includes(state.ruleForm.questionType)">
							<el-checkbox-group v-model="state.ruleForm.checkBoxKey">
								<el-skeleton :loading="state.loading" animated v-for="(item, index) in state.ruleForm.questionOptionsDtos" :key="item.temp">
									<template #template>
										<el-form-item label="选项">
											<el-skeleton-item variant="h1" />
										</el-form-item>
									</template>
									<template #default>
										<el-form-item label="选项" :prop="`questionOptionsDtos.${index}.content`" :rules="[{required: true, message: '请输入选项', trigger: 'blur' }]">
											<el-row :gutter="0" justify="space-between" style="width: 100%;">
												<el-col :span="17">
													<el-input v-model="item.content" placeholder="请输入选项" clearable>
														<template #append>
															<el-checkbox label="答案" :value="item.temp" />
														</template>
													</el-input>
												</el-col>
												<el-col :span="7" style="text-align: right">
													<el-button type="primary" size="small" v-if="index == 0" @click="addOption"> <SvgIcon name="ele-Plus" class="mr5" /> </el-button>
													<el-button size="small" class="default-button" @click="deleteOption(item.temp)"> <SvgIcon name="ele-Delete" class="mr5" /></el-button>
												</el-col>
											</el-row>
										</el-form-item>
									</template>
								</el-skeleton>
							</el-checkbox-group>
                        </div>
                        <div v-else-if="[2].includes(state.ruleForm.questionType)">
                            <el-skeleton :loading="state.loading" animated>
								<template #template>
									<el-form-item label="答案">
										<el-skeleton-item variant="h1" />
									</el-form-item>
								</template>
								<template #default>
									<el-form-item label="答案" prop="judgeKey" :rules="[{ required: true, message: '请选择答案', trigger: 'change' }]">
										<el-radio-group v-model="state.ruleForm.judgeKey">
											<el-radio label="错误" :value="false"></el-radio>
											<el-radio label="正确" :value="true"></el-radio>
										</el-radio-group>
									</el-form-item>
								</template>
							</el-skeleton>
                        </div>
                        <div v-else-if="[3,4].includes(state.ruleForm.questionType)">
                            <el-skeleton :loading="state.loading" animated>
								<template #template>
									<el-form-item label="答案">
										<el-skeleton-item variant="h1" />
									</el-form-item>
								</template>
								<template #default>
									<el-form-item label="答案" :prop="`questionAnswerDto.answer`" :rules="[{ required: true, message: '请输入答案', trigger: 'blur' }]">
										<el-input type="textarea" :rows="3" v-model="state.ruleForm.questionAnswerDto.answer" placeholder="请输入答案" clearable></el-input>
									</el-form-item>
								</template>
							</el-skeleton>
                        </div>
                        <el-skeleton :loading="state.loading" animated>
							<template #template>
								<el-form-item label="备注">
									<el-skeleton-item variant="h1" />
								</el-form-item>
							</template>
							<template #default>
								<el-form-item label="备注" prop="remark">
                                    <el-input type="textarea" :rows="3" v-model="state.ruleForm.remark" placeholder="请输入备注" clearable></el-input>
								</el-form-item>
							</template>
						</el-skeleton>
						<el-skeleton :loading="state.loading" animated>
                            <template #template>
                                <el-form-item label="排序">
                                    <el-skeleton-item variant="h1" />
                                </el-form-item>
                            </template>
                            <template #default>
                                <el-form-item label="排序" prop="weight" :rules="[{ required: true, message: '请填写排序', trigger: 'blur' }]">
                                    <el-input v-model="state.ruleForm.weight" placeholder="请填写排序" clearable></el-input>
                                </el-form-item>
                            </template>
                        </el-skeleton>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" style="text-align: center;">
						<el-button type="primary" @click="onSave(ruleFormRef)" :loading="state.loading">保存</el-button>
						<el-button class="default-button" @click="onCancel" :loading="state.loading">取消 </el-button>
					</el-col>
				</el-row>
			</el-form>
		</el-card>

		<!-- 关联课件 -->
		<question-course ref="QuestionCourseRef" @choose="chooseCourse" />
		<!-- 关联知识库 -->
		<question-knowledge ref="QuestionKnowledgeRef" @choose="chooseKnowledge" />
	</div>
</template>

<script setup lang="ts" name="questionEdit">
import { defineAsyncComponent, nextTick, onMounted, reactive, ref } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElMessage } from 'element-plus';
import mittBus from '@/utils/mitt';
import { useRoute, useRouter } from 'vue-router';
import { Local } from '@/utils/storage';
import other from '@/utils/other';
import { throttle, transformFile, guid } from '@/utils/tools';
import { removeDuplicate } from '@/utils/arrayOperation';
import { VTreeDrop } from '@wsfe/vue-tree';
import { examTagTreeList } from '@/api/examTrain/tag';
import {getCoursewareData} from '@/api/courseware/index';
import { addQuestion, editQuestion, getQuestionDetail } from '@/api/examTrain/questionBank';
// 引入组件
const QuestionCourse = defineAsyncComponent(() => import('@/views/examTrain/questionBank/components/Question-course.vue')); // 关联课件
const QuestionKnowledge = defineAsyncComponent(() => import('@/views/examTrain/questionBank/components/Question-knowledge.vue')); // 关联知识

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false,
	ruleForm: {
		title: '', // 题干
		questionType: 0, // 题型
		difficultyLevel: null, // 难易程度
		formalEnable: false, // 正式可用
		simulateEnable: false, // 模拟可用
		remark: '', // 备注
		weight: '', // 排序
		questionTagIds: [], // 选中的标签id
		questionTagDtos: [], // 试题标签
		questionAnswerDto: {
			answer: ''
		}, // 填空、问答答案
		questionOptionsDtos: [], // 单选、多选、判断 选项
		courseTitle: '', // 选择的课件标题
		questionSourcewareDtos: [], // 关联课件
		knowledgeTitle: '', // 选择的知识库标题
		questionKnowladgeDtos: [], // 关联知识库
		radioKey: '', // 单选答案id
		checkBoxKey: [], // 多选答案id
		judgeKey: false, // 判断答案value
	},
	loading: false,
    tagData: [], // 试题标签初始化数据
});

const route = useRoute(); // 获取路由
const router = useRouter(); // 路由跳转
const ruleFormRef = ref<any>(); // 表单ref

// 选择试题标签
const treeSelectRef = ref<RefType>();
const selQuestionTag = (value: any) => {
	state.ruleForm.questionTagDtos = [];
	state.ruleForm.questionTagIds.forEach(item => {
		let tagObj = other.deepClone(treeSelectRef.value.getNode(item).data);
		state.ruleForm.questionTagDtos.push({tagId: tagObj.id});
	})
}
// 增加单选多选选项
const addOption = () => {
	if ([0,1].includes(state.ruleForm.questionType)){
		state.ruleForm.questionOptionsDtos.push({temp: guid(), content: '', isAnswer: false})
	}
};
// 删除单选多选选项
const deleteOption = (id: any) => {
	if ([0,1].includes(state.ruleForm.questionType)){
		state.ruleForm.questionOptionsDtos = state.ruleForm.questionOptionsDtos.filter(it => it.temp !== id );
		if ([0].includes(state.ruleForm.questionType)){
			state.ruleForm.radioKey = state.ruleForm.radioKey.filter(it => it.temp !== id )
		}else {
			state.ruleForm.checkBoxKey = state.ruleForm.checkBoxKey.filter(it => it.temp !== id )
		}
	}
}
// 选择知识
const QuestionKnowledgeRef = ref<RefType>();
const onKnowledgeTo = () => {
	QuestionKnowledgeRef.value.openDialog(state.ruleForm.questionKnowladgeDtos);
};
// 清除选择的知识
const clearKnowledge = () => {
	state.ruleForm.questionKnowladgeDtos = [];
	state.ruleForm.knowledgeTitle = '';
};
// 确定选择了知识库
const chooseKnowledge = (data: any) => {
	clearKnowledge();
	if (data) {
		data.forEach(it => state.ruleForm.questionKnowladgeDtos.push({knowladgeId: it.knowladgeId, title: it.title}));
		state.ruleForm.knowledgeTitle = data.map(it => it.title).join(',');
	}
};
// 选择课件
const QuestionCourseRef = ref<RefType>();
const onCourseTo = () => {
	QuestionCourseRef.value.openDialog(state.ruleForm.questionSourcewareDtos);
};
// 清除选择的课件
const clearCourse = () => {
	state.ruleForm.questionSourcewareDtos = [];
	state.ruleForm.courseTitle = '';
};
// 确定选择了课件
const chooseCourse = (data: any) => {
	clearCourse();
	if (data) {
		data.forEach(it => state.ruleForm.questionSourcewareDtos.push({sourcewareId: it.sourcewareId, name: it.name}));
		state.ruleForm.courseTitle = data.map(it => it.name).join(',');
	}
};
// 保存提交
const onSave = throttle(async (formEl: FormInstance | undefined) => {
	// 表单额外验证
	if (state.ruleForm.questionType == 0){
		if (!state.ruleForm.radioKey){
			ElMessage.warning('请指定正确选项！')
			return;
		};
	}else if (state.ruleForm.questionType == 1){
		if (state.ruleForm.checkBoxKey.length == 0){
			ElMessage.warning('请指定正确选项！')
			return;
		};
	}
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		const submitObj = other.deepClone(state.ruleForm);
		if ([0,1,2].includes(state.ruleForm.questionType)){
			submitObj.questionAnswerDto = null;
			if (submitObj.questionType == 0){
				submitObj.questionOptionsDtos.forEach(item => {
					if (item.temp == submitObj.radioKey){
						item.isAnswer = true;
					}else {
						item.isAnswer = false;
					}
				})
			}else if (submitObj.questionType == 1){
				submitObj.questionOptionsDtos.forEach(item => {
					if (submitObj.checkBoxKey.indexOf(item.temp) != -1){
						item.isAnswer = true;
					}else {
						item.isAnswer = false;
					}
				})
			}else {
				submitObj.questionOptionsDtos = [
					{temp: guid(), content: '错误', isAnswer: !submitObj.judgeKey},
					{temp: guid(), content: '正确', isAnswer: submitObj.judgeKey}
				];
			}
		}else{
			submitObj.questionOptionsDtos = [];
		}
		Reflect.deleteProperty(submitObj, 'radioKey');
		Reflect.deleteProperty(submitObj, 'checkBoxKey');
		Reflect.deleteProperty(submitObj, 'judgeKey');
		Reflect.deleteProperty(submitObj, 'questionTagIds');
		Reflect.deleteProperty(submitObj, 'knowledgeTitle');
		Reflect.deleteProperty(submitObj, 'courseTitle');
		console.log(submitObj)
		if (route.params.id) {
			editQuestion(submitObj)
				.then(handleSuccess)
				.catch(() => {
					state.loading = false;
				});
		} else {
			// 新增
			addQuestion(submitObj)
				.then(handleSuccess)
				.catch(() => {
					state.loading = false;
				});
		}
	});
}, 300);
// 取消
const onCancel = () => {
	state.loading = true;
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
	mittBus.emit('clearCache', 'questionBank');
	router.push({
		path: '/examTrain/questionBank',
	});
	state.loading = false;
};
const handleSuccess = () => {
	state.loading = false;
	ElMessage.success('操作成功');
	// 关闭当前 tagsView
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
	mittBus.emit('clearCache', 'questionBank');
	router.push({
		path: '/examTrain/questionBank',
	});
};
// 获取标签数据
const getTagData = async () => {
	state.loading = true;
	try {
		const { result } = await examTagTreeList();
		state.tagData = result ?? [];
		state.loading = false;
	} catch (error) {
		state.loading = false;
	}
};
const getDetail = async () => {
	if (route.params.id) {
		const res: any = await getQuestionDetail(route.params.id); // 试题详情
		state.ruleForm = res.result ?? {};
		state.ruleForm.questionTagIds = state.ruleForm.questionTagDtos.map(it => it.tagId);
		state.ruleForm.knowledgeTitle = state.ruleForm.questionKnowladgeDtos.map(it => it.title).join(',');
		state.ruleForm.courseTitle = state.ruleForm.questionSourcewareDtos.map(it => it.name).join(',');
		state.ruleForm.radioKey = '';
		state.ruleForm.checkBoxKey = [];
		state.ruleForm.judgeKey = false;
		if ([0,1,2].includes(state.ruleForm.questionType)){
			state.ruleForm.questionOptionsDtos.forEach(item => {
				item.temp = item.id;
				if (item.isAnswer){
					if (state.ruleForm.questionType == 0){
						state.ruleForm.radioKey = item.id;
					}else if (state.ruleForm.questionType == 1){
						state.ruleForm.checkBoxKey.push(item.id);
					}else if (state.ruleForm.questionType == 2){
						item.content == '正确' ? state.ruleForm.judgeKey = true : state.ruleForm.judgeKey = false
					}
				}
			});
		}
		if (!state.ruleForm.questionAnswerDto){
			state.ruleForm.questionAnswerDto = {answer: ''};
		}
	}else {
		for(let num = ref(0); num.value < 3; num.value++){
			state.ruleForm.questionOptionsDtos.push({temp: guid(), content: '', isAnswer: false});
		}
	}
};
onMounted(async () => {
	await getTagData();
	await getDetail();
});
</script>
<style lang="scss">
.vtree-tree-drop__wrapper {
	width: 100%;
}
</style>