<template>
	<el-dialog v-model="state.dialogVisible" draggable append-to-body destroy-on-close :show-close="false" width="80%" :before-close="closeDialog">
        <template #header="{ close, titleId, titleClass }">
            <div class="topContent">
                <div class="surplusBox" v-if="state.examType == 0">
                    <el-countdown title="剩余时间：" :value="state.surplusTime" @finish="onSurplusTimeFinish" />
                </div>
                <div class="titleBox">
                    <span class="title">统一考试</span>
                </div>
                <div class="submitBox">
				    <el-button type="info" @click="closeDialog">关 闭</el-button>
                    <el-button type="primary" @click="onSubmit" :loading="state.loading">交 卷</el-button>
                </div>
            </div>
        </template>
        <el-row :gutter="10" v-loading="state.loading">
            <el-col :xs="6" :sm="6" :md="6" :lg="6" :xl="6">
                <div class="examListContent" v-for="(item) in state.questionTypeData">
                    <p class="examType">{{item.questionTypeDesc}}</p>
                    <ul class="examList">
                        <li class="examListItem" :class="questionsItem.id == state.selQuestionID ? 'select' : ''" v-for="(questionsItem) in item.questions" @click="onSelQuestion(questionsItem.id)">{{questionsItem.sortIndex}}</li>
                    </ul>
                </div>
            </el-col>
            <el-col :xs="18" :sm="18" :md="18" :lg="18" :xl="18">
                <div class="questionBox" v-if="state.questionDetail">
                    <p class="questionTitle">题干：{{ state.questionDetail.title }}（{{ state.questionDetail.score }}分）</p>
                    <div class="questionAnswer">
                        <div v-if="[0,2].includes(state.questionDetail.questionType)">
							<el-radio-group style="display: block;" v-model="state.selRadioValue">
                                <el-form-item :label="item.label + '. '" v-for="item in state.questionDetail.questionOptions" style="margin-bottom: 10px;">
                                    <el-radio :label="item.content" :value="item.id" />
                                </el-form-item>
                            </el-radio-group>
                        </div>
                        <div v-else-if="state.questionDetail.questionType == 1">
                            <el-checkbox-group v-model="state.selCheckboxValue">
                                <el-form-item :label="item.label + '. '" v-for="item in state.questionDetail.questionOptions" style="margin-bottom: 10px;">
                                    <el-checkbox :label="item.content" :value="item.id" />
                                </el-form-item>
                            </el-checkbox-group>
                        </div>
                        <!-- <div v-else-if="state.questionDetail.questionType == 2"></div> -->
                        <div v-else-if="state.questionDetail.questionType == 3">
                            <el-form-item label="答：">
                                <el-input type="textarea" v-model="state.answerValue" :rows="3" placeholder="请输入答案，如果有多个请依照顺序用英文 , 隔开" clearable></el-input>
                            </el-form-item>
                        </div>
                        <div v-else-if="state.questionDetail.questionType == 4">
                            <el-form-item label="答：">
                                <el-input type="textarea" v-model="state.answerValue" :rows="3" placeholder="请输入答案" clearable></el-input>
                            </el-form-item>
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>
		<template #footer>
			<span class="dialog-footer" v-if="state.selQuestionID">
				<el-button type="primary" @click="onLastQuestion" :loading="state.loading">上一题</el-button>
				<el-button type="primary" @click="onNextQuestion" :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 { excludeSelfById } from '@/utils/tools';
import other from '@/utils/other';
import {startUserExam, getExamQuestionGroup, getExamQuestion, answerUserExam, submitUserExam } from '@/api/examTrain/userExam';

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

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false, // 弹窗
	loading: false, // 加载
    userExamId: '', // 用户考试id
    examId: '', // 考试id
    examType: null, // 考试类型
    surplusTime: '00:00:00', // 剩余时间
	questionTypeData: [] as any[], // 试卷题型数据
    questionsData: [] as any[], // 试题集合
    selQuestionID: '', // 选择的问题id
    questionDetail: null, // 选择的问题明细
    selRadioValue: '', // 单选题选择的值
    selCheckboxValue: [] as any[], // 多选题选择的值
    answerValue: '', // 填空问答填写的值
});
// 打开弹窗
const ruleFormRef = ref<any>(); // 表单ref
const openDialog = async (row: any) => {
    state.dialogVisible = true;
    state.userExamId = row.id;
    state.examId = row.examId;
    state.examType = row.examType;
	state.loading = true;
    startUserExam({
        id: state.userExamId
    }).then((res) => {
        if (onStateControl(res.result)){
            getQuestionsData();
        }else {
            closeDialog();
	        state.loading = false;
        }
    }).catch((error) => {
		console.error(error);
    });
};
const onStateControl = (obj) => {
    console.log(obj);
    if (!obj.isStart){
        ElMessage.warning('考试尚未开始！')
        return false;
    }else if (obj.isCompleted){
        ElMessage.warning('考试已经结束！')
        return false;
    }else if (!obj.isJoin){
        ElMessage.warning('您不用参加此考试！')
        return false;
    }else{
        if (state.examType == 0){
            state.surplusTime = new Date(obj.startTime).getTime() + obj.timeSpan * 60 * 1000;
            if (state.surplusTime <= new Date().getTime()){
                ElMessage.warning('考试已经结束！')
                return false;
            }else {
                return true;
            }
        }else {
            return true;
        }
    }
};
const onSurplusTimeFinish = () => {
    ElMessage.warning('考试已经结束！')
    closeDialog();
}
const getQuestionsData = async () => {
    try {
		const { result } = await getExamQuestionGroup(state.examId);
        let sortIndexNum = 1;
        result.forEach(item => {
            switch(item.questionType){
				case 0: item.questionTypeDesc = '单选题'; break;
				case 1: item.questionTypeDesc = '多选题'; break;
				case 2: item.questionTypeDesc = '判断题'; break;
				case 3: item.questionTypeDesc = '填空题'; break;
				case 4: item.questionTypeDesc = '问答题'; break;
				default: break;
			}
            item.questions.forEach(it => {
                it.sortIndex = sortIndexNum;
                it.questionType = item.questionType;
                state.questionsData.push(it)
                sortIndexNum++ ;
            });
        })
		state.questionTypeData = result;
        state.loading = false;
	} catch (error) {
		// 打印错误信息
		console.error(error);
	}
}
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
    state.questionTypeData = []; 
    state.questionsData = []; 
    state.selQuestionID = ''; 
    state.questionDetail = null; 
    state.selRadioValue = ''; 
    state.selCheckboxValue = []; 
    state.answerValue = '';
};
// 上一题下一题
const onLastQuestion = () => {
    let index:number = state.questionsData.findIndex(it => it.id == state.selQuestionID);
    index = (index - 1) == -1 ? state.questionsData.length : index - 1;
    onSelQuestion(state.questionsData[index].id);
}
const onNextQuestion = () => {
    let index:number = state.questionsData.findIndex(it => it.id == state.selQuestionID);
    index = (index + 1) == state.questionsData.length ? 0 : index + 1;
    onSelQuestion(state.questionsData[index].id);
}
// 选择的问题id 提交当前试题答案，再请求下一道题详情 value: 请求下一题详情id
const onSelQuestion = async (value: any) => {
	state.loading = true;
    if (state.questionDetail){
        // 保存当前题目选项
        const selQuestionItem = state.questionsData.find(it => it.id == state.selQuestionID);
        const submitObj = {
            userExamId: state.userExamId,
            questionId: selQuestionItem.id,
            questionType: selQuestionItem.questionType,
            userExamItemOptionDtos: [] as any[],
            answer: ''
        };
        if ([0,2].includes(state.questionDetail.questionType)){
            if (state.selRadioValue){
                submitObj.userExamItemOptionDtos.push({questionOptionId: state.selRadioValue})
            }
        }else if (state.questionDetail.questionType == 1){
            if (state.selCheckboxValue.length > 0){
                state.selCheckboxValue.forEach(it => {
                    submitObj.userExamItemOptionDtos.push({questionOptionId: it})
                })
            }
        }else if ([3,4].includes(state.questionDetail.questionType)){
            submitObj.answer = state.answerValue;
        }
        answerUserExam(submitObj)
            .then((res) => {
                if (onStateControl(res.result)){
                    onGetQuestionDetail(value);
                }else {
                    closeDialog();
                }
            })
            .catch(() => {
                state.loading = false;
            });
    }else {
        onGetQuestionDetail(value);
    }
}
const onGetQuestionDetail = async (value) => {
    if (!value){
        state.loading = false;
        return;
    }
    // 初始化选择选择/填写的答案
    state.selRadioValue = '';  
    state.selCheckboxValue = []; 
    state.answerValue = '';
    // 请求下一道题
    state.selQuestionID = value;
    try {
		const { result } = await getExamQuestion(state.selQuestionID, state.examId);
		state.questionDetail = result;
        if ([0,2].includes(state.questionDetail.questionType)){
            let obj = state.questionDetail.questionOptions.find((x: any) => x.isSelected === true);
            state.selRadioValue = obj ? obj.id : '';
        }else if (state.questionDetail.questionType == 1){
            let arr = [] as any[];
            state.questionDetail.questionOptions.forEach(it => {if (it.isSelected) arr.push(it);})
            console.log(arr);
            state.selCheckboxValue = arr ? arr.map((x: any) => x.id) : [];
            console.log(state.selCheckboxValue);
        }else {
            state.answerValue = state.questionDetail.answer || '';
        }
        state.loading = false;
	} catch (error) {
		// 打印错误信息
		console.error(error);
	}
}
// 结束考试
const onSubmit = async () => {
    state.loading = true;
    await onSelQuestion('');
	submitUserExam({
        isSubmit: 1
    }).then(() => {
        emit('updateList');
        state.loading = false;
        closeDialog(); // 关闭弹窗
        ElMessage.success('操作成功');
    }).catch(() => {
        state.loading = false;
    });
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
<style lang="scss">
    .topContent{padding: 10px 30px;display: flex;justify-content: space-between;align-items: center;}
    .topContent .surplusBox{text-align: center;}
    .topContent .surplusBox .surplus{font-size: 18px;color: #000000;}
    .topContent .titleBox{text-align: center;}
    .topContent .titleBox .title{font-size: 20px;font-weight: bold;letter-spacing: 1px;color: #000000;}
    .topContent .submitBox{text-align: right;vertical-align: top;}
    .examListContent .examType{font-weight: bold;color: #000000;}
    .examListContent .examList{padding: 5px 0 10px;}
    .examListContent .examList .examListItem{display: inline-block;margin: 5px 10px 5px 0;text-align: center;width: 50px;height:35px;line-height: 35px;cursor: pointer;position: relative;border: #f2f2f2 1px solid;}
    .examListContent .examList .marked::after{content: "*";width: 5px;height: 5px;position: absolute;top: -3px;right: 4px;color: #FF5722;font-size: 25px;}
    .examListContent .examList .select{background-color: #1890ff;color: #fff;}
    .questionBox{padding: 20px 10px 0;}
    .questionBox .questionTitle{margin-bottom: 10px;font-size: 16px;}
    .questionBox .questionAnswer{padding: 0 20px;}
    .questionBox .questionAnswer .answerItem{width:calc(100%);}
    .questionBox .questionAnswer .answerItem .optionIndex{vertical-align: sub;font-size: 16px;display: inline-block;}
</style>