<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="24" :lg="24" :xl="24">
						<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="code" :rules="[{ required: true, message: '请填写试卷编号', trigger: 'blur' }]" >
									<el-input v-model="state.ruleForm.code" placeholder="请输入试卷编号" clearable></el-input>
								</el-form-item>
							</template>
						</el-skeleton>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<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="name" :rules="[{ required: true, message: '请填写试卷标题', trigger: 'blur' }]" >
									<el-input v-model="state.ruleForm.name" placeholder="请输入试卷标题" clearable></el-input>
								</el-form-item>
							</template>
						</el-skeleton>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<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="examType" :rules="[{ required: true, message: '请选择试卷类型', trigger: 'change' }]" >
									<el-radio-group v-model="state.ruleForm.examType">
                                        <el-radio :value="0">正式</el-radio>
                                        <el-radio :value="1">模拟</el-radio>
                                    </el-radio-group>
								</el-form-item>
							</template>
						</el-skeleton>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<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="mode" :rules="[{ required: true, message: '请选择组卷方式', trigger: 'change' }]" >
                                    <el-radio-group v-model="state.ruleForm.mode">
                                        <el-radio :value="0">随机试题</el-radio>
                                        <el-radio :value="1">自选试题</el-radio>
                                    </el-radio-group>
								</el-form-item>
							</template>
						</el-skeleton>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<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="选择试题" class="w100 tableFormItem">
                                    <vxe-toolbar
                                        ref="toolbarRef"
                                        :loading="state.tableLoading"
                                        custom
                                    >
                                        <template #buttons>
                                            <el-button type="primary" @click="onAdd" :loading="state.tableLoading">
                                                <SvgIcon name="ele-Plus" class="mr10" />新增
                                            </el-button>
                                        </template>
                                    </vxe-toolbar>
									<vxe-table
										border
										:loading="state.tableLoading"
										:data="state.ruleForm.testPaperItemDtos"
										:column-config="{ resizable: true }"
										:row-config="{ height: 50, useKey: true }"
										ref="tableRef"
										height="300"
										auto-resize
										show-overflow
										:scrollY="{ enabled: true, gt: 100 }"
										id="extractRule"
										:custom-config="{ storage: true }"
										showHeaderOverflow
									>
										<vxe-column field="questionTypeDesc" title="题型" width="100"></vxe-column>
										<vxe-column field="difficultyLevelDesc" title="难度" width="100"></vxe-column>
										<vxe-column field="title" title="标题" min-width="250"></vxe-column>
                                        <vxe-column title="操作" fixed="right" width="120" align="center" :show-overflow="false">
                                            <template #default="{ row }">
                                                <el-button link type="danger" @click="onRowDel(row)" title="删除">
                                                    删除
                                                </el-button>
                                            </template>
                                        </vxe-column>
									</vxe-table>
								</el-form-item>
							</template>
						</el-skeleton>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<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-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>

		<!-- 随机试题页面 -->
		<testPaper-random ref="TestPaperRandomRef" @choose="chooseQuestion" />
		<!-- 自选试题页面 -->
		<testPaper-optional ref="TestPaperOptionalRef" @choose="chooseQuestion" />
	</div>
</template>

<script setup lang="ts" name="testPaperEdit">
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 { addTestPaper, editTestPaper, getTestPaperDetail } from '@/api/examTrain/testPaper';
// 引入组件
const TestPaperRandom = defineAsyncComponent(() => import('@/views/examTrain/exam/testPaper/components/TestPaper-random.vue')); // 随机试题页面
const TestPaperOptional = defineAsyncComponent(() => import('@/views/examTrain/exam/testPaper/components/TestPaper-optional.vue')); // 自选试题页面

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false,
	ruleForm: {
		code: '', // 编号
		name: '', // 标题
		examType: 0, // 试卷类型
		mode: 0, // 组卷方式
		remark: '', // 备注
		testPaperItemDtos: [], // 生成试题列表
	},
	loading: false,
});

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

// 选择随机、自主试题新增
const TestPaperRandomRef = ref<RefType>();
const TestPaperOptionalRef = ref<RefType>();
const onAdd = () => {
    if (state.ruleForm.mode == 0){
        TestPaperRandomRef.value.openDialog(state.ruleForm.testPaperItemDtos);
    }else if (state.ruleForm.mode == 1) {
        TestPaperOptionalRef.value.openDialog(state.ruleForm.testPaperItemDtos);
    }
};
// 确定选择试题
const chooseQuestion = (data: any) => {
	if (state.ruleForm.mode == 0){
		state.ruleForm.testPaperItemDtos = state.ruleForm.testPaperItemDtos.concat(data);
    }else if (state.ruleForm.mode == 1) {
		state.ruleForm.testPaperItemDtos = other.deepClone(data);
    }
};
// 删除试题
const onRowDel = (row: any) => {
	state.ruleForm.testPaperItemDtos = state.ruleForm.testPaperItemDtos.filter(it => it.questionId !== row.questionId );
    ElMessage.success('删除成功');
};
// 保存提交
const onSave = throttle(async (formEl: FormInstance | undefined) => {
	// 表单额外验证
	if (state.ruleForm.testPaperItemDtos.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);
		console.log(submitObj)
		if (route.params.id) {
			editTestPaper(submitObj)
				.then(handleSuccess)
				.catch(() => {
					state.loading = false;
				});
		} else {
			// 新增
			addTestPaper(submitObj)
				.then(handleSuccess)
				.catch(() => {
					state.loading = false;
				});
		}
	});
}, 300);
// 取消
const onCancel = () => {
	state.loading = true;
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
	mittBus.emit('clearCache', 'testPaper');
	router.push({
		path: '/examTrain/exam/testPaper',
	});
	state.loading = false;
};
const handleSuccess = () => {
	state.loading = false;
	ElMessage.success('操作成功');
	// 关闭当前 tagsView
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
	mittBus.emit('clearCache', 'testPaper');
	router.push({
		path: '/examTrain/exam/testPaper',
	});
};
const getDetail = async () => {
	if (route.params.id) {
		const res: any = await getTestPaperDetail(route.params.id); // 试题详情
		state.ruleForm = res.result ?? {};
	}
};
onMounted(async () => {
	await getDetail();
});
</script>
<style lang="scss">
.vtree-tree-drop__wrapper {
	width: 100%;
}
.tableFormItem .el-form-item__content{
	display: block;
}
</style>