<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="12" :lg="12" :xl="12">
                        <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-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-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" @change="selMode">
                                        <el-radio :value="0">正式考试</el-radio>
                                        <el-radio :value="1">模拟考试</el-radio>
                                    </el-radio-group>
								</el-form-item>
							</template>
						</el-skeleton>
                        <div v-if="[0].includes(state.ruleForm.examType)">
                            <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="count" :rules="[{ validator: vaildateInt, trigger: 'blur'},{ required: true, message: '请输入可考次数', trigger: 'blur' }]">
                                        <el-input-number v-model="state.ruleForm.count" :min="0" class="w100" ></el-input-number>
                                    </el-form-item>
                                </template>
                            </el-skeleton>
                            <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="timeSpan" :rules="[{ validator: vaildateInt, trigger: 'blur'}, { required: true, message: '请输入可考次数', trigger: 'blur' }]">
                                        <el-input-number v-model="state.ruleForm.timeSpan" :min="0" class="w100" >
                                            <template #suffix>
                                                <span>分钟</span>
                                            </template>
                                        </el-input-number>
                                    </el-form-item>
                                </template>
                            </el-skeleton>
                            <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="rangeTime" :rules="[{ required: true, message: '请选择考试时间', trigger: 'change' }]">
                                        <el-date-picker v-model="state.ruleForm.rangeTime" type="datetimerange" class="w100" value-format="YYYY-MM-DD[T]HH:mm:ss" range-separator="-" start-placeholder="请选择考试开始时间" end-placeholder="请选择考试结束时间" :disabled-date="disabledDate" popper-class="no-atTheMoment" />
                                    </el-form-item>
                                </template>
                            </el-skeleton>
                        </div>
                        <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" @change="selMode">
                                        <el-radio :value="0">统一试卷</el-radio>
                                        <el-radio :value="1">随机抽题</el-radio>
                                    </el-radio-group>
								</el-form-item>
							</template>
						</el-skeleton>
                        <el-skeleton :loading="state.loading" animated>
							<template #template>
								<el-form-item :label="state.ruleForm.mode == 0 ? '选择试卷' : '抽题规则'">
									<el-skeleton-item variant="h1" />
								</el-form-item>
							</template>
							<template #default>
								<el-form-item :label="state.ruleForm.mode == 0 ? '选择试卷' : '抽题规则'" prop="testPaperId" :rules="[{ required: true, message: state.ruleForm.mode == 0 ? '请选择试卷' : '请选择抽题规则', trigger: 'change' }]">
                                    <el-select v-model="state.ruleForm.testPaperId" clearable filterable :placeholder="state.ruleForm.mode == 0 ? '请选择试卷' : '请选择抽题规则'" @change="selTestPaper">
                                        <el-option v-for="item in state.testPaperData" :key='item.id' :label="item.name" :value="item.id"  />
                                    </el-select>
                                </el-form-item>
							</template>
						</el-skeleton>
                        <el-skeleton :loading="state.loading" animated v-if="state.ruleForm.mode == 0">
							<template #template>
                                <el-form-item label="试题顺序">
                                    <el-skeleton-item variant="h1" />
                                </el-form-item>
							</template>
							<template #default>
                                <el-form-item label="试题排序" prop="questionSort" :rules="[{ required: true, message: '请选择试题排序', trigger: 'change' }]" >
                                    <el-radio-group v-model="state.ruleForm.questionSort">
                                        <el-radio :value="0">顺序</el-radio>
                                        <el-radio :value="1">乱序</el-radio>
                                    </el-radio-group>
                                </el-form-item>
							</template>
						</el-skeleton>
                        <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="optionSort" :rules="[{ required: true, message: '请选择选项排序', trigger: 'change' }]" >
                                    <el-radio-group v-model="state.ruleForm.optionSort">
                                        <el-radio :value="0">顺序</el-radio>
                                        <el-radio :value="1">乱序</el-radio>
                                    </el-radio-group>
                                </el-form-item>
							</template>
						</el-skeleton>
                        <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" :rules="[{ required: false, message: '请输入备注', trigger: 'blur' }]">
                                    <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="12" :lg="12" :xl="12">
                        <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="examQuestionScoreDtos" class="w100 tableFormItem" :rules="[{ required: true, message: '请输入题型分数', trigger: 'change' }]">
									<vxe-table
										border
										:data="state.ruleForm.examQuestionScoreDtos"
										:column-config="{ resizable: true }"
										:row-config="{ height: 50, useKey: true }"
										ref="tableRef"
										height="300"
										auto-resize
										show-overflow
										:scrollY="{ enabled: true, gt: 100 }"
										id="countTable"
										:custom-config="{ storage: true }"
										showHeaderOverflow
									>
										<vxe-column field="questionTypeDesc" title="题型" width="100"></vxe-column>
                                        <vxe-column title="题型分数" min-width="250">
                                            <template #default="scope">
                                                <el-form-item :prop="`examQuestionScoreDtos.` + scope.$rowIndex+ `.score`" :rules="[{ validator: vaildateInt, trigger: 'blur'}]">
                                                    <el-input-number v-model="scope.row.score" :min="0" class="w100" @change="onScoreChange" >
                                                        <template #suffix>
                                                            <span>分/题  共{{scope.row.count}}题</span>
                                                        </template>
                                                    </el-input-number>
                                                </el-form-item>
                                            </template>
                                        </vxe-column>
									</vxe-table>
								</el-form-item>
							</template>
						</el-skeleton>
						<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="cutoffScore" :rules="[{ required: true, message: '请输入合格分数', trigger: 'blur' }]">
                                    <el-input-number v-model="state.ruleForm.cutoffScore" :min="0" :max="state.ruleForm.totalScore" class="w100" >
                                        <template #suffix>
                                            <span>总分：{{state.ruleForm.totalScore}}</span>
                                        </template>
                                    </el-input-number>
								</el-form-item>
							</template>
						</el-skeleton>
                        <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="userExamDtos" class="w100 tableFormItem" :rules="[{ required: true, message: '请选择参考人员', trigger: 'change' }]">
                                    <vxe-toolbar
                                        ref="toolbarRef"
                                        custom
                                    >
                                        <template #buttons>
                                            <el-button type="primary" @click="onAddUserTable">
                                                <SvgIcon name="ele-Plus" class="mr10" />新增
                                            </el-button>
                                        </template>
                                    </vxe-toolbar>
									<vxe-table
										border
										:data="state.ruleForm.userExamDtos"
										:column-config="{ resizable: true }"
										:row-config="{ height: 50, useKey: true }"
										ref="tableRef"
										height="300"
										auto-resize
										show-overflow
										:scrollY="{ enabled: true, gt: 100 }"
										id="userTable"
										:custom-config="{ storage: true }"
										showHeaderOverflow
									>
										<vxe-column field="name" title="姓名" min-width="100"></vxe-column>
										<vxe-column field="fullOrgName" 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="onRowDelUserTable(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" 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>

		<!-- 选择参考人员 -->
		<examManage-users ref="ExamManageUsersRef" @choose="chooseUsers" />
	</div>
</template>

<script setup lang="ts" name="questionEdit">
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 {getExtractRuleAllList} from '@/api/examTrain/extractRule';
import {getTestPaperAllList} from '@/api/examTrain/testPaper';
import { addExamManage, editExamManage, getExamManageDetail, getTestPaperQuestionCount } from '@/api/examTrain/examManage';
// 引入组件
const ExamManageUsers = defineAsyncComponent(() => import('@/views/examTrain/exam/examManage/components/ExamManage-users.vue')); // 选择参考人员

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false,
	ruleForm: {
		code: '', // 考试编号
		name: '', // 考试标题
		examType: 0, // 考试类型
		mode: 0, // 考核方式
        testPaperId: '', // 试卷||抽题规则id
		count: 0, // 可考次数
		timeSpan: 0, // 考试时长
        startTime: '', // 考试开始时间
        endTime: '', // 考试结束时间
        rangeTime: [], // 考试时间范围
		questionSort: 0, // 试题顺序
		optionSort: 0, // 选项顺序
		remark: '', // 备注
        cutoffScore: 0, // 合格分数
        totalScore: 0, // 总分
		examQuestionScoreDtos: [], // 题型分数
		userExamDtos: [], // 参考人员数据
	},
	loading: false,
    testPaperData: [], // 试题或者抽题规则数据
    paperData: [], // 试题数据
    ruleData: [], // 抽题规则数据
});

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

// 切换考核方式
const selMode = () => {
    state.ruleForm.testPaperId = '';
    if (state.ruleForm.mode == 0){
        state.testPaperData = other.deepClone(state.paperData.filter(it => it.examType == state.ruleForm.examType));
    }else if (state.ruleForm.mode == 1) {
        state.testPaperData = other.deepClone(state.ruleData.filter(it => it.examType == state.ruleForm.examType));
    }
}
// 选择试卷||抽题规则
const selTestPaper = async (value: any) => {
	try {
        const testPaperId = state.ruleForm.mode == 0 ? state.ruleForm.testPaperId : '';
        const extractRuleId = state.ruleForm.mode == 1 ? state.ruleForm.testPaperId : '';
		const { result } = await getTestPaperQuestionCount(testPaperId, extractRuleId);
		state.ruleForm.examQuestionScoreDtos = result ?? [];
        state.ruleForm.examQuestionScoreDtos.forEach(it => {it.score = 0})
        state.ruleForm.cutoffScore = 0;
        state.ruleForm.totalScore = 0;
	} catch (error) {
        console.log(error);
	}
};
// 设置考试开始时间选择范围
const disabledDate = (time: Date) => {
	return time.getTime() < Date.now() - 8.64e7; // - 8.64e7是今天可以选
};
// 分数变化
const onScoreChange = (value: any) => {
    state.ruleForm.totalScore = 0;
    state.ruleForm.examQuestionScoreDtos.forEach(it => state.ruleForm.totalScore += (it.score * it.count));
}
// 选择参考人员
const ExamManageUsersRef = ref<RefType>();
const onAddUserTable = () => {
	ExamManageUsersRef.value.openDialog(state.ruleForm.userExamDtos);
};
// 删除参考人员
const onRowDelUserTable = (row: any) => {
	state.ruleForm.userExamDtos = state.ruleForm.userExamDtos.filter(it => it.userId !== row.userId );
    ElMessage.success('删除成功');
};
// 确定选择了参考人员
const chooseUsers = (data: any) => {
    state.ruleForm.userExamDtos = [];
	if (data) {
		data.forEach(it => state.ruleForm.userExamDtos.push({userId: it.userId, name: it.name, fullOrgName: it.fullOrgName}));
	}
};
// 验证input值>0
const vaildateInt = (rule: any, value: any, callback: any) => {
	if (value <= 0) {
    callback(new Error("请输入大于0的整数"))
  } else {
    callback()
  }
};
// 保存提交
const onSave = throttle(async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		const submitObj = other.deepClone(state.ruleForm);
        if (submitObj.examType == 0){
		    submitObj.startTime = submitObj.rangeTime[0];
            submitObj.endTime = submitObj.rangeTime[1];
		    Reflect.deleteProperty(submitObj, 'rangeTime');
        }else if (submitObj.examType == 1){
		    Reflect.deleteProperty(submitObj, 'rangeTime');
		    Reflect.deleteProperty(submitObj, 'startTime');
		    Reflect.deleteProperty(submitObj, 'endTime');
		    Reflect.deleteProperty(submitObj, 'count');
		    Reflect.deleteProperty(submitObj, 'timeSpan');
        }
        if (submitObj.mode == 1){
		    Reflect.deleteProperty(submitObj, 'questionSort');
        }
		console.log(submitObj)
		if (route.params.id) {
			editExamManage(submitObj)
				.then(handleSuccess)
				.catch(() => {
					state.loading = false;
				});
		} else {
			// 新增
			addExamManage(submitObj)
				.then(handleSuccess)
				.catch(() => {
					state.loading = false;
				});
		}
	});
}, 300);
// 取消
const onCancel = () => {
	state.loading = true;
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
	mittBus.emit('clearCache', 'examManage');
	router.push({
		path: '/examTrain/exam/examManage',
	});
	state.loading = false;
};
const handleSuccess = () => {
	state.loading = false;
	ElMessage.success('操作成功');
	// 关闭当前 tagsView
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
	mittBus.emit('clearCache', 'examManage');
	router.push({
		path: '/examTrain/exam/examManage',
	});
};
// 获取统一试卷数据
const getPaperData = async () => {
	state.loading = true;
	try {
		const { result } = await getTestPaperAllList();
		state.paperData = result ?? [];
		state.loading = false;
	} catch (error) {
		state.loading = false;
	}
};
// 获取抽题规则数据
const getRuleData = async () => {
	state.loading = true;
	try {
		const { result } = await getExtractRuleAllList();
		state.ruleData = result ?? [];
		state.loading = false;
	} catch (error) {
		state.loading = false;
	}
};
const getDetail = async () => {
	if (state.ruleForm.mode == 0){
        	state.testPaperData = other.deepClone(state.paperData.filter(it => it.examType == state.ruleForm.examType));
	}else if (state.ruleForm.mode == 1) {
		state.testPaperData = other.deepClone(state.ruleData.filter(it => it.examType == state.ruleForm.examType));
	}
	if (route.params.id) {
		const res: any = await getExamManageDetail(route.params.id);
		state.ruleForm = res.result ?? {};
		state.ruleForm.rangeTime = [state.ruleForm.startTime, state.ruleForm.endTime];
	}
};
onMounted(async () => {
	await getPaperData();
	await getRuleData();
	await getDetail();
});
</script>
<style lang="scss">
.vtree-tree-drop__wrapper {
	width: 100%;
}
.tableFormItem .el-form-item__content{
	display: block;
}
</style>