<template>
	<el-dialog title="编辑培训模板" v-model="state.dialogVisible" draggable append-to-body destroy-on-close @close="close" width="800px">
		<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="name" :rules="[{ required: true, message: '请填写模板名称', trigger: 'blur' }]">
						<el-input v-model="state.ruleForm.name" placeholder="请填写模板名称" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<el-form-item label="培训资料" prop="trainKnowladges" class="w100 tableFormItem" :rules="[{ required: true, message: '请选择培训资料', trigger: 'change' }]">
                        <vxe-toolbar
                            ref="toolbarRef"
                            custom
                        >
                            <template #buttons>
                                <el-button type="primary" @click="onAddKnowladgesTable">
                                    <SvgIcon name="ele-Plus" class="mr10" />新增
                                </el-button>
                            </template>
                        </vxe-toolbar>
                        <vxe-table
                            border
                            :data="state.ruleForm.trainKnowladges"
                            :column-config="{ resizable: true }"
                            :row-config="{ height: 50, useKey: true }"
                            ref="tableRef"
                            height="300"
                            auto-resize
                            show-overflow
                            :scrollY="{ enabled: true, gt: 100 }"
                            id="knowladgesTable"
                            :custom-config="{ storage: true }"
                            showHeaderOverflow
                        >
                            <vxe-column field="title" title="知识标题" min-width="100"></vxe-column>
                            <vxe-column title="操作" fixed="right" width="80" align="center" :show-overflow="false">
                                <template #default="{ row }">
                                    <el-button link type="danger" @click="onRowDelKnowladgesTable(row)" title="删除">
                                        删除
                                    </el-button>
                                </template>
                            </vxe-column>
                        </vxe-table>
                    </el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<el-form-item label="包含习题" prop="isContainsPractice" :rules="[{ required: true, message: '请选择是否包含习题', trigger: 'change' }]">
						<el-radio-group v-model="state.ruleForm.isContainsPractice">
							<el-radio :value="true">是</el-radio>
							<el-radio :value="false">否</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="state.ruleForm.isContainsPractice == true">
					<el-form-item label="选择习题" prop="trainPracticeDtos" class="w100 tableFormItem" :rules="[{ required: true, message: '请选择习题', trigger: 'change' }]">
                        <vxe-toolbar
                            ref="toolbarRef"
                            custom
                        >
                            <template #buttons>
                                <el-button type="primary" @click="onAddQuestionsTable">
                                    <SvgIcon name="ele-Plus" class="mr10" />新增
                                </el-button>
                            </template>
                        </vxe-toolbar>
                        <vxe-table
                            border
                            :data="state.ruleForm.trainPracticeDtos"
                            :column-config="{ resizable: true }"
                            :row-config="{ height: 50, useKey: true }"
                            ref="tableRef"
                            height="300"
                            auto-resize
                            show-overflow
                            :scrollY="{ enabled: true, gt: 100 }"
                            id="questionsTable"
                            :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="100"></vxe-column>
                            <vxe-column title="操作" fixed="right" width="80" align="center" :show-overflow="false">
                                <template #default="{ row }">
                                    <el-button link type="danger" @click="onRowDelQuestionsTable(row)" title="删除">
                                        删除
                                    </el-button>
                                </template>
                            </vxe-column>
                        </vxe-table>
                    </el-form-item>
				</el-col>
				<!-- <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
					<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>
				</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>

        <!-- 关联知识库 -->
		<question-knowledge ref="QuestionKnowledgeRef" @choose="chooseKnowledge" />
        <!-- 自选试题页面 -->
		<template-optional ref="TemplateOptionalRef" @choose="chooseQuestion" />
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, defineAsyncComponent } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import Other from '@/utils/other';
import {getTrainTemplateDetail, editTrainTemplate} from '@/api/examTrain/trainTemplate';

// 引入组件
const QuestionKnowledge = defineAsyncComponent(() => import('@/views/examTrain/questionBank/components/Question-knowledge.vue')); // 关联知识
const TemplateOptional = defineAsyncComponent(() => import('@/views/examTrain/train/template/components/Template-optional.vue')); // 自选试题页面

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

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false, // 弹窗
	ruleForm: {
		name: '', // 模板名称
		trainKnowladges : [], // 培训资料
		isContainsPractice: null, // 是否包含习题
		trainPracticeDtos: [], // 习题
	},
	loading: false, // 加载
	tableLoading: false, // 表格加载
});
// 打开弹窗
const ruleFormRef = ref<any>(); // 表单ref
// 打开弹窗
const openDialog = async (row: any) => {
	state.dialogVisible = true;
	try {
		const { result } = await getTrainTemplateDetail(row.id);
		state.ruleForm = result;
	} catch (error) {
		console.log(error);
		state.loading = false;
	}
};
const close = () => {
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
	state.ruleForm.trainKnowladges = [];
	state.ruleForm.trainPracticeDtos = [];
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
	state.ruleForm.trainKnowladges = [];
	state.ruleForm.trainPracticeDtos = [];
};
// 选择知识
const QuestionKnowledgeRef = ref<RefType>();
const onAddKnowladgesTable = () => {
	QuestionKnowledgeRef.value.openDialog(state.ruleForm.trainKnowladges);
};
// 确定选择了知识库
const chooseKnowledge = (data: any) => {
    state.ruleForm.trainKnowladges = Other.deepClone(data);
};
// 删除知识
const onRowDelKnowladgesTable = (row: any) => {
	state.ruleForm.trainKnowladges = state.ruleForm.trainKnowladges.filter(it => it.knowladgeId !== row.knowladgeId );
    ElMessage.success('删除成功');
};
// 选择试题新增
const TemplateOptionalRef = ref<RefType>();
const onAddQuestionsTable = () => {
	if (state.ruleForm.trainKnowladges.length > 0){
		TemplateOptionalRef.value.openDialog(state.ruleForm.trainKnowladges, state.ruleForm.trainPracticeDtos);
	}else {
		ElMessage.warning('请选择培训资料');
	}
};
// 确定选择试题
const chooseQuestion = (data: any) => {
    state.ruleForm.trainPracticeDtos = Other.deepClone(data);
};
// 删除试题
const onRowDelQuestionsTable = (row: any) => {
	state.ruleForm.trainPracticeDtos = state.ruleForm.trainPracticeDtos.filter(it => it.questionId !== row.questionId );
    ElMessage.success('删除成功');
};
// 新增
const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
	    console.log(state.ruleForm);
        const submitObj = Other.deepClone(state.ruleForm);
		if (!submitObj.isContainsPractice){
			submitObj.trainPracticeDtos = [];
		}
		editTrainTemplate(submitObj)
			.then(() => {
				emit('updateList');
				closeDialog(); // 关闭弹窗
				ElMessage.success('操作成功');
				state.loading = false;
			})
			.catch(() => {
				state.loading = false;
			});
	});
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
<style lang="scss">
	.tableFormItem .el-form-item__content{
		display: block;
	}
</style>