<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="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>
				</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 { addPractice, getTagQuestionCount } from '@/api/examTrain/practice';

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

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false, // 弹窗
	ruleForm: {
		questionTagIds: [], // 选中的标签id
		practiceTagDtos: [], // 试题标签
		count: 0, // 出题数量
	},
	tagData: [], // 试题标签数据
    totalCount: 0, // 满足条件试题总数量
	loading: false, // 加载
});
// 打开弹窗
const ruleFormRef = ref<any>(); // 表单ref
const openDialog = () => {
	state.dialogVisible = true;
	getTagData();
};
// 获取标签数据
const getTagData = async () => {
	state.loading = true;
	try {
		const { result } = await examTagTreeList();
		state.tagData = result ?? [];
		state.loading = false;
	} catch (error) {
		state.loading = false;
	}
};
const close = () => {
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
    state.totalCount = 0;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
    state.totalCount = 0;
};
// 选择试题标签
const treeSelectRef = ref<RefType>();
const selQuestionTag = async (value: any) => {
	state.ruleForm.practiceTagDtos = [];
	state.ruleForm.questionTagIds.forEach(item => {
		let tagObj = other.deepClone(treeSelectRef.value.getNode(item).data);
		state.ruleForm.practiceTagDtos.push({tagId: tagObj.id});
	})
	try {
		const { result } = await getTagQuestionCount({
			tagIds: state.ruleForm.questionTagIds
		});
		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;
		addPractice(state.ruleForm)
			.then((res) => {
				console.log(res);
				emit('choose', res.result);
				closeDialog(); // 关闭弹窗
				ElMessage.success('操作成功');
				state.loading = false;
			})
			.catch(() => {
				state.loading = false;
			});
	});
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
