<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="code" :rules="[{ required: true, message: '请填写规则编号', trigger: 'blur' }]">
						<el-input v-model="state.ruleForm.code" 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="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="ruleType" :rules="[{ required: true, message: '请选择规则类型', trigger: 'change' }]">
						<el-radio-group v-model="state.ruleForm.ruleType">
							<el-radio :value="0">正式</el-radio>
							<el-radio :value="1">模拟</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
				<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="抽题设置" class="w100 tableFormItem">
						<vxe-table
							border
							:loading="state.tableLoading"
							:data="state.ruleForm.tagQuestionDtos"
							:column-config="{ resizable: true }"
							:row-config="{ height: 50, useKey: true }"
							ref="tableRef"
							height="300"
							auto-resize
							show-overflow
							:print-config="{}"
							:scrollY="{ enabled: true, gt: 100 }"
							id="extractRule"
							:custom-config="{ storage: true }"
							showHeaderOverflow
							:merge-cells=mergeCells
						>
							<vxe-column field="tag" title="标签名称" width="200"></vxe-column>
							<vxe-column title="试题类型" min-width="250">
								<template #default="scope">
									<el-form-item :label="scope.row.questionTypeDes">
									<!-- <el-form-item :label="scope.row.questionTypeDes" :prop="`tagQuestionDtos.` + scope.$rowIndex+ `.count`" :rules="[{ validator: vaildateTable, trigger: 'blur', totalCount: scope.row.totalCount }]">
										<el-input type="number" v-model="scope.row.count" placeholder="请填写" clearable></el-input>
										<template #append>共{{scope.row.totalCount}}题</template> -->
										<el-input-number v-model="scope.row.count" :min="0" :max="scope.row.totalCount" >
											<template #suffix>
												<span>共{{scope.row.totalCount}}题</span>
											</template>
										</el-input-number>
									</el-form-item>
								</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="remark">
						<el-input type="textarea" :rows="3" v-model="state.ruleForm.remark" 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>
	</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 {editExtractRule, getTagQuestionCount, getExtractRuleDetail} from '@/api/examTrain/extractRule';

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

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false, // 弹窗
	ruleForm: {
		code: '', // 规则编号
		name: '', // 规则名称
		ruleType: null, // 规则类型
		questionTagIds: '', // 抽题标签ids
		ruleTagDtos: [], // 规则标签
		tagQuestionDtos: [], // 标签试题数
		remark: '', // 备注
	},
	tagData: [], // 标签数据
	loading: false, // 加载
	tableLoading: false, // 表格加载
});
// 打开弹窗
const ruleFormRef = ref<any>(); // 表单ref
// 打开弹窗
const openDialog = async (row: any) => {
	state.dialogVisible = true;
	try {
		getTagData();
		const { result } = await getExtractRuleDetail(row.id);
		state.ruleForm = result;
		state.ruleForm.questionTagIds = state.ruleForm.ruleTagDtos.map(it => it.tagId);
	} catch (error) {
		console.log(error);
		state.loading = false;
	}
};
const close = () => {
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
// 选择标签
const treeSelectRef = ref<RefType>();
const mergeCells = ref<any>(); // 行合并
const selQuestionTag = async (value: any) => {
	state.tableLoading = true;
	state.ruleForm.ruleTagDtos = [];
	mergeCells.value = [];
	try {
		const { result } = await getTagQuestionCount({tagIds: state.ruleForm.questionTagIds});
		state.ruleForm.questionTagIds.forEach(item => {
			let tagObj = Other.deepClone(treeSelectRef.value.getNode(item).data);
			state.ruleForm.ruleTagDtos.push({tagId: tagObj.id});
			result.forEach(it => {if (it.tagId == tagObj.id) it.tag = tagObj.name} )
			let arrResult = Other.deepClone(result);
			let rowNum = result.findIndex(it => it.tagId == tagObj.id);
			let rowspanNum = arrResult.filter(it => it.tagId == tagObj.id).length;
			mergeCells.value.push({ row: rowNum, col: 0, rowspan: rowspanNum, colspan: 1 })
		});
		result.forEach(item => {
			let obj = state.ruleForm.tagQuestionDtos.find(it => (item.tagId == it.tagId && item.questionType == it.questionType))
			if (obj){
				item.count = obj.count;
			} else {
				item.count = 0;
			}
			switch(item.questionType){
				case 0: item.questionTypeDes = '单选题'; break;
				case 1: item.questionTypeDes = '多选题'; break;
				case 2: item.questionTypeDes = '判断题'; break;
				case 3: item.questionTypeDes = '填空题'; break;
				case 4: item.questionTypeDes = '问答题'; break;
				default: break;
			}
		});
		state.ruleForm.tagQuestionDtos = result ?? [];
		state.tableLoading = false;
	} catch (error) {
		state.tableLoading = false;
	}
}
// 验证表格input值
// const vaildateTable = (rule: any, value: any, callback: any) => {
// 	if (value > rule.totalCount) {
//     callback(new Error('填写的数字不能大于标签题型最大数量'))
//   } else {
//     callback()
//   }
// };
// 新增
const onSubmit = async (formEl: FormInstance | undefined) => {
	console.log(state.ruleForm);
	if (!formEl) return;
	// 表单额外验证
	let blog = false;
	state.ruleForm.tagQuestionDtos.forEach(it => {
		if (it.count > 0){
			blog = true;
		}
	});
	if (!blog){
		ElMessage.warning('请至少选择一道题！')
		return;
	}
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		editExtractRule(state.ruleForm)
			.then(() => {
				emit('updateList');
				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>