<template>
	<el-dialog v-model="state.dialogVisible" draggable destroy-on-close :show-close="false" width="80%" :before-close="closeDialog">
        <template #header="{ close, titleId, titleClass }">
            <div class="topContent">
                <div class="titleBox">
                    <span class="title">自我练习</span>
                </div>
                <div class="submitBox">
				    <el-button type="info" @click="closeDialog">关 闭</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="{'select': questionsItem.id == state.selQuestionID, 'right': questionsItem.isRight, 'error': !questionsItem.isRight}" 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 }}</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.practiceQuestionOptionsDtos" style="margin-bottom: 10px;">
                                    <el-radio :label="item.content" :value="item.questionOptionId" disabled />
                                </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.practiceQuestionOptionsDtos" style="margin-bottom: 10px;">
                                    <el-checkbox :label="item.content" :value="item.questionOptionId" disabled />
                                </el-form-item>
                            </el-checkbox-group>
                        </div>
                    </div>
                </div>
                <div class="referenceAnswer" v-if="state.questionDetail">
                    <span>参考答案：</span>
                    <p>{{state.questionDetail.answerDesc || '略'}}</p>
                </div>
                <div class="referenceAnswer" v-if="state.questionDetail && state.questionDetail.practiceQuestionKnowladgeDtos.length > 0">
                    <span>关联知识：</span>
                    <p v-for="item in state.questionDetail.practiceQuestionKnowladgeDtos" @click="onKnowladgeTo(item)">{{item.title}}</p>
                </div>
                <div class="referenceAnswer" v-if="state.questionDetail && state.questionDetail.practiceQuestionSourcewareDtos.length > 0">
                    <span>关联课件：</span>
                    <p v-for="item in state.questionDetail.practiceQuestionSourcewareDtos" @click="onSourcewareTo(item)">{{item.name}}</p>
                </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 { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { excludeSelfById } from '@/utils/tools';
import other from '@/utils/other';
import { fileDownloadByUrl } from '@/api/public/file';
import {getViewPracticeQuestions, getPracticeView} from '@/api/examTrain/practice';

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

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false, // 弹窗
	loading: false, // 加载
    practiceId: '', // 用户练习id
	questionTypeData: [] as any[], // 试卷题型数据
    questionsData: [] as any[], // 试题集合
    selQuestionID: '', // 选择的问题id
    questionDetail: null, // 选择的问题明细
    selRadioValue: '', // 单选题选择的值
    selCheckboxValue: [] as any[], // 多选题选择的值
});
// 打开弹窗
const openDialog = async (rows: any) => {
    state.dialogVisible = true;
    state.practiceId = rows.id;
	state.loading = true;
    getQuestionsData();
};
const getQuestionsData = async () => {
    try {
		const { result } = await getViewPracticeQuestions(state.practiceId);
        let sortIndexNum = 1;
        result.forEach(item => {
            switch(item.questionType){
				case 0: item.questionTypeDesc = '单选题'; break;
				case 1: item.questionTypeDesc = '多选题'; break;
				case 2: 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 = []; 
};
// 上一题下一题
const onLastQuestion = () => {
    let index:number = state.questionsData.findIndex(it => it.id == state.selQuestionID);
    index = (index - 1) == -1 ? state.questionsData.length - 1 : 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;
    onGetQuestionDetail(value);
}
const onGetQuestionDetail = async (value) => {
    // 初始化选择选择/填写的答案
    state.selRadioValue = '';  
    state.selCheckboxValue = []; 
    // 请求下一道题
    state.selQuestionID = value;
    try {
		const { result } = await getPracticeView(state.selQuestionID);
		state.questionDetail = result;
        let answerDesc = '';
        state.questionDetail.practiceQuestionOptionsDtos.forEach(it => {it.isAnswer && (answerDesc += it.label)});
        state.questionDetail.answerDesc = answerDesc;
        if ([0,2].includes(state.questionDetail.questionType)){
            let obj = state.questionDetail.practiceQuestionOptionsDtos.find((x: any) => x.isSelected === true);
            state.selRadioValue = obj ? obj.questionOptionId : '';
        }else if (state.questionDetail.questionType == 1){
            let arr = [] as any[];
            state.questionDetail.practiceQuestionOptionsDtos.forEach(it => {if (it.isSelected) arr.push(it);})
            state.selCheckboxValue = arr ? arr.map((x: any) => x.questionOptionId) : [];
        }
        state.loading = false;
	} catch (error) {
		// 打印错误信息
		console.error(error);
	}
}
// 跳转知识详情页面
const onKnowladgeTo = (row: any) => {
	router.push({
		name: 'knowledgePreview',
		params: {
			id: row.knowladgeId,
			isAddPv: 'isAddPv',
			tagsViewName: row.title,
		},
	});
};
// 课件预览下载
const onSourcewareTo = (row: any) => {
    ElMessageBox.confirm(`您确定要下载课件，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			fileDownloadByUrl({
				Source: 'hotline',
				Id: row.attachmentId,
			}).then((res: any) => {
				let blob: Blob = new Blob([res.data], { type: res.data.type }); // 创建blob 设置blob文件类型 data 设置为后端返回的文件(例如mp3,jpeg) type:这里设置后端返回的类型 为 mp3
				let down: HTMLAnchorElement = document.createElement('a'); // 创建A标签
				let href: string = window.URL.createObjectURL(blob); // 创建下载的链接
				down.href = href; // 下载地址
				down.download = row.name // 下载文件名
				document.body.appendChild(down);
				down.click(); // 模拟点击A标签
				document.body.removeChild(down); // 下载完成移除元素
				window.URL.revokeObjectURL(href); // 释放blob对象
			});
		})
		.catch(() => {});
}
// 暴露变量
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 .right::after{content: " ";width: 5px;height: 5px;position: absolute;top: 2px;right: 3px;background-color: #009688;border-radius: 50%;}
    .examListContent .examList .error::after{content: " ";width: 5px;height: 5px;position: absolute;top: 2px;right: 3px;background-color: #FF5722;border-radius: 50%;}
    .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;}
    .referenceAnswer{background-color: #ebf9ff;margin: 15px 40px 15px 30px;padding: 10px;}
    .referenceAnswer span{display: block;}
    .referenceAnswer p{width: calc(100% - 80px);display: block;margin-top: 10px;color: #1890ff;cursor: pointer;}
</style>