<template>
	<el-dialog title="随机选题" v-model="state.dialogVisible" draggable append-to-body destroy-on-close @close="close" width="500px">
		<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="80px" v-loading="state.loading">
			<el-row :gutter="10">
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<el-form-item label="试题类型" prop="questionType" :rules="[{ required: true, message: '请选择试题类型', trigger: 'change' }]">
                        <el-select v-model="state.ruleForm.questionType" clearable placeholder="请选择试题类型" @change="onGetTagQuestionCount">
                            <el-option key='0' label="单选题" :value="0" />
                            <el-option key='1' label="多选题" :value="1" />
                            <el-option key='2' label="判断题" :value="2" />
                            <el-option key='3' label="填空题" :value="3" />
                            <el-option key='4' label="问答题" :value="4" />
                        </el-select>
                    </el-form-item>
				</el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<el-form-item label="试题标签" prop="tagIds" :rules="[{ required: false, message: '请选择试题标签', trigger: 'change' }]">
						<el-tree-select
							v-model="state.ruleForm.tagIds"
							: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="onGetTagQuestionCount"
						/>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<el-form-item label="试题难度" prop="difficultyLevel" :rules="[{ required: false, message: '请选择试题难度', trigger: 'change' }]">
                        <el-select v-model="state.ruleForm.difficultyLevel" clearable placeholder="请选择试题难度" @change="onGetTagQuestionCount">
                            <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>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<el-form-item label="试题数量" prop="count" :rules="[{ required: true, message: '请输入试题数量', trigger: 'blur' }]">
                        <el-input-number v-model="state.ruleForm.count" :min="0" :max="state.totalCount" class="w100" >
                            <template #suffix>
                                <span>共{{state.totalCount}}题</span>
                            </template>
                        </el-input-number>
                    </el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.loading">确 定 </el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import other from '@/utils/other';
import { examTagTreeList } from '@/api/examTrain/tag';
import { getTagQuestionCount, getSecondsetQuestions } from '@/api/examTrain/testPaper';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['choose']);

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false, // 弹窗
	ruleForm: {
		questionType: null, // 试题类型
		tagIds: [], // 试题标签ids
		difficultyLevel: null, // 试题难度
		count: null, // 试题数量
        questionIds: [], // 已选择的试题ids
	},
    totalCount: 0, // 满足条件试题总数量
	tagData: [], // 标签数据
	loading: false, // 加载
    selData: [], // 选择的数据ids
});
// 打开弹窗
const ruleFormRef = ref<any>(); // 表单ref
// 打开弹窗
const openDialog = async (selData: any[]) => {
	state.dialogVisible = true;
	try {
        if (selData) {
			state.selData = selData;
            state.ruleForm.questionIds = state.selData.map(it => it.questionId);
		} else {
			state.ruleForm.questionIds = [];
		}
		getTagData();
	} catch (error) {
		console.log(error);
		state.loading = false;
	}
};
const close = () => {
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
    state.totalCount = 0;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
    state.totalCount = 0;
};
const onGetTagQuestionCount = async () => {
	try {
		const { result } = await getTagQuestionCount(state.ruleForm);
		state.totalCount = result.totalCount ?? 0;
        if (state.ruleForm.count > state.totalCount){
            state.ruleForm.count = 0;
        }
	} catch (error) {
	}
};
// 新增
const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		getSecondsetQuestions(state.ruleForm)
			.then((res) => {
		        const submitObj = other.deepClone(res);
                submitObj.result.forEach(it => {
                    it.questionId = it.id;
		            Reflect.deleteProperty(it, 'id');
                });
				emit('choose', submitObj.result);
				closeDialog(); // 关闭弹窗
				ElMessage.success('操作成功');
				state.loading = false;
			})
			.catch(() => {
				state.loading = false;
			});
	});
};
// 获取标签下拉数据
const getTagData = async () => {
	state.loading = true;
	try {
		const { result } = await examTagTreeList();
		state.tagData = result ?? [];
		state.loading = false;
	} catch (error) {
		state.loading = false;
	}
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
<style lang="scss">
	.tableFormItem .el-form-item__content{
		display: block;
	}
</style>