<template>
    <view class="paperQuestionInfo-container">
        <template v-if="currentQuestion.questionId">
            <view class="box-body">

                <view style=" background: #fff; padding: 30rpx 32rpx;">
                    <view class="head">
                        <view class="tit">{{ currentQuestion.typeName }}（{{ currentQuestion.questionScore }}分）</view>
                        <view class="count">{{ currentIndex + 1 }}/{{ questionList.length }}</view>
                    </view>
                    <view class="item-content">
                        {{ currentQuestion.name }}
                    </view>

                    <view class="option">
                        <!-- 复选 -->
                        <u-checkbox-group
                            v-model="currentQuestion.useAnswer"
                            v-if="currentQuestion.type === 2"
                            :disabled="isExplain"
                            placement="column"
                            @change="checkboxChange">
                            <u-checkbox
                                :customStyle="{ marginBottom: '16px' }"
                                v-for="(item, index) in currentQuestionOption"
                                :key="index"
                                :label="item.label"
                                :name="item.value">
                            </u-checkbox>
                        </u-checkbox-group>
                        <!-- 单选 -->
                        <u-radio-group
                            v-model="currentQuestion.useAnswer"
                            v-else
                            placement="column"
                            :disabled="isExplain"
                            @change="checkboxChange">
                            <u-radio
                                :customStyle="{ marginBottom: '16px' }"
                                v-for="(item, index) in currentQuestionOption"
                                :key="index"
                                :label="item.label"
                                :name="item.value">
                            </u-radio>
                        </u-radio-group>

                    </view>
                </view>
                <view style=" background: #fff; padding: 30rpx 32rpx;margin-top: 20rpx;" v-if="isExplain">
                    <view class="head">
                        <view class="tit">答题解析</view>
                    </view>
                    <!-- 解析 -->
                    <view class="explain">
                        <!-- <view class="explain-content">你的选择：{{ getanswer(currentQuestion.useAnswer) }}</view> -->
                        <view class="explain-title">正确答案：{{ getanswer(currentQuestion.answer) }}</view>
                        <view class="explain-content">得分：{{ currentQuestion.score }}分</view>
                    </view>

                </view>

            </view>



            <!-- 底部 -->
            <view class="operation">
                <u-button text="上一题" :disabled="currentIndex === 0" @click="previousQuestion"></u-button>
                <u-button text="答题卡" @click="show = true"></u-button>
                <u-button text="下一题" @click="nextQuestion"
                    v-if="currentIndex < questionList.length - 1"></u-button>
                <u-button type="primary" @click="saveUserPaper"
                    v-if="currentIndex === questionList.length - 1 && !isExplain" text="立即交卷"></u-button>
            </view>
        </template>
        <!-- 答题卡 -->
        <u-popup :show="show" @close="close" @open="open" v-if="!isExplain">
            <view class="answer-cardsheet">
                <view class="item-box" v-for="(item, index) in questionList">
                    <view class="item" @click="toCurrentIndex(index)"
                        :class="{ 'item1': item.useAnswer, 'item2': index === currentIndex }" :key="index">{{ index + 1
                        }}
                    </view>
                </view>
                <view class="button-box">
                    <u-button text="继续答题" @click="close"></u-button>
                    <u-button type="primary" @click="saveUserPaper" text="立即交卷"></u-button>
                </view>
            </view>
        </u-popup>

        <!-- 解析答题卡 -->
        <u-popup :show="show" @close="close" @open="open" v-if="isExplain">
            <view class="answer-cardsheet">
                <view class="item-box" v-for="(item, index) in questionList">
                    <view class="item" @click="toCurrentIndex(index)"
                        :class="{ 'item1': item.status === 1, 'item3': item.status === 0 }" :key="index">{{ index + 1
                        }}
                    </view>
                </view>
                <view class="button-box">
                    <u-button type="primary" @click="close" text="关闭"></u-button>
                </view>
            </view>
        </u-popup>
        <!-- 确认提示框 -->
        <u-popup :show="warnShow" @close="warnShow = false" @open="warnShow = true">
            <view class="answer-cardsheet">
                <view class="is-sub">
                    <u-icon type="warn" class="error-circle-fill" name="error-circle-fill" size="24"
                        color="#fb6547"></u-icon>
                    <view class="warn">
                        <span v-if="notReach">您有{{ notReach }}道题未答，确定提交吗？</span>
                        <span v-else>试卷提交后不可更改，确定提交吗？</span>
                    </view>
                </view>
                <view class="button-box">
                    <u-button text="取消" @click="warnShow = false"></u-button>
                    <u-button type="primary" @click="saveUserPaper(true)" text="确定"></u-button>
                </view>
            </view>
        </u-popup>
        <!-- 结果 -->
        <u-popup :show="resultShow" mode="center" :closeOnClickOverlay="false" @close="resultShow = false"
            @open="resultShow = true">
            <view class="answer-cardsheet">
                <view class="is-sub">
                    <!-- 通过 -->
                    <template v-if="resultData.viaStatus === 1">
                        <image
                            class="result-img"
                            src="@/static/icon/pass.png"
                            style="width: 300rpx;height: 300px;"
                            mode="widthFix"></image>
                        <view style="font-size: 48rpx;color: red;">
                            恭喜您通过考试!
                        </view>
                    </template>
                    <!-- 不通过 -->
                    <template v-if="resultData.viaStatus === 0">
                        <image
                            class="result-img"
                            src="@/static/icon/not.png"
                            style="width: 300rpx;height: 300px;"
                            mode="widthFix"></image>
                        <view style="font-size: 48rpx;color: red;">
                            未通过考试!
                        </view>
                    </template>

                    <view style="font-size: 48rpx;color: brown;margin-top: 10rpx;">
                        {{ resultData.score }}分
                    </view>
                    <view style="margin-top: 30rpx;">
                        总分：{{ resultData.totalScore }}分&nbsp;&nbsp;&nbsp;&nbsp;答对：<span style="color: red;">{{
                            resultData.answerNum
                            }}</span>/{{ resultData.totalQuestion }}
                    </view>
                </view>
                <view class="button-box">
                    <u-button text="查看解析" @click="userExaminationRecord"></u-button>
                    <template>
                        <u-button type="primary" v-if="resultData.useNum === resultData.limitNum" @click="navigateBack"
                            text="返回"></u-button>
                        <u-button type="primary" @click="getData" v-else text="再考一次"></u-button>
                    </template>

                </view>
            </view>
        </u-popup>
		<!-- 人脸校验 -->
		<tq-face ref="faceRef" 
			@success="faceSuccess"
			@close="faceClose"
		></tq-face>
    </view>
</template>
<script>
import { paperQuestionInfo, saveUserPaper, userExaminationRecord, recordByPaperId } from "@/api/learnMobile/index";
export default {
    paperQuestionInfo: '',
    data() {
        return {
            oldData: {},
            id: '',
            recordId: '',
            show: false,
            warnShow: false,

            cardsheet: [],
            currentIndex: 0,//当前题下标
            currentQuestion: {},
            questionList: [],
            options: [
                // {
                //     name: '苹果',
                //     disabled: false
                // },
                // {
                //     name: '香蕉',
                //     disabled: false
                // },
                // {
                //     name: '橙子',
                //     disabled: false
                // }, {
                //     name: '榴莲',
                //     disabled: false
                // }
            ],
            startTime: '',
            notReach: 0,
            isPass: false,
            resultShow: false,
            resultData: {}, //考试结果
            isExplain: false ,//是否是解析状态
			isValidFace: false, //是否检验人脸
        }
    },
    //计算属性得到当前的题目
    computed: {
        currentQuestionOption() {
            let item = this.questionList[this.currentIndex]
            if (item.type === 3) {//判断
                return [{
                    label: '对',
                    value: '1',
                }, {
                    label: '错',
                    value: '0',
                }]
            } else {
                return item.option.map(e => {
                    return {
                        ...e,
                        label: e.optionKey + ' ' + e.optionValue,// 
                        value: e.optionKey
                    }
                })
            }
        },
        isAllUseAnswer() {
            //判断questionList数组的所有选项都有useAnswer参数值
            return this.questionList.every(question => question.useAnswer);
        }
    },
    watch: {
        currentIndex: {
            handler(newVal) {
                let item = this.questionList[newVal]
                this.$nextTick(() => {
                    console.log('用户答案', item.useAnswer)
                    this.currentQuestion = item
                })
            }
        }
    },
    onLoad({ id, recordId, paperStatus }) {
        this.id = id
        if (!this.recordId) {
            this.recordId = recordId
        }
        let status = paperStatus * 1
        if (status === 0) { //未作答
            this.getData()
        } else if (status === 1) { //已作答
            this.recordByPaperId()
        } else {
            this.userExaminationRecord()
        }
        // this.getData();
        // this.userExaminationRecord();
        // this.recordByPaperId()
        this.startTime = this.dayjs().format('YYYY-MM-DD HH:mm:ss')
    },
    methods: {
        /**获取结果 */
        async recordByPaperId() {
            let { data, code } = await recordByPaperId({
                paperId: this.id
            })
            if (code == '0') {
                this.resultShow = true
                this.resultData = data
            }
        },
        getanswer(e) {
            if (e === '0') return '错'
            if (e === '1') return '对'
            return e
        },
        /**查看考试记录信息(试题解析) */
        async userExaminationRecord() {
            let { data, code } = await userExaminationRecord({
                recordId: this.recordId
            })
            if (code == '0') {
                this.questionList = data.questionList.map(e => {
                    return {
                        ...e,
                        useAnswer: e.type === 2 ? e.useAnswer.split(',') : e.useAnswer
                    }
                })
                this.currentQuestion = this.questionList[0]
                this.currentIndex = 0
                this.resultShow = false
                this.isExplain = true
            }
        },
        navigateBack() {
            uni.navigateBack()
        },
        async saveUserPaper(is) { //提交试卷
		
            this.show = false
            if (!is) { //非直接提交 判断
                this.notReach = this.questionList.filter(e => !e.useAnswer).length
                return this.warnShow = true //提示框
            }
            this.warnShow = false
            let datas = this.questionList.map(e => {
                return {
                    ...e,
                    useAnswer: e.useAnswer ? e.useAnswer.toString() : ''
                }
            })
			
			if(!this.isValidFace) {
				this.openFace()
			}
			
            let { data, code } = await saveUserPaper({
                ...this.oldData,
                questionList: datas,
                startTime: this.startTime,

            })
            if (code == '0') {
                this.resultShow = true
                this.resultData = data
                this.recordId = data.recordId
            }
        },
        previousQuestion() {
            this.currentIndex--
        },
        nextQuestion() {
            this.currentIndex++
        },
        async getData() {
            let { data, code } = await paperQuestionInfo({
                id: this.id
            })
            if (code == '0') {
                this.questionList = data.questionList
                this.currentQuestion = this.questionList[0]
                this.oldData = data
                this.resultShow = false
            }
        },
        toCurrentIndex(e) {
            this.currentIndex = e
        },
        checkboxChange(e) {
            console.log('选择', e)
        },
        open() {
            // console.log('open');
        },
        close() {
            this.show = false
            // console.log('close');
        },
		
		openFace() {	
			this.$refs.faceRef.show()
		},
		faceClose() {
			uni.navigateBack()
		},
		faceSuccess() {
			this.isValidFace = true
			this.saveUserPaper(true)
		}
    }
}
</script>
<style lang="scss" scoped>
.paperQuestionInfo-container {

    .head {
        border-left: solid 10rpx #2979FF;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding-left: 20rpx;

        .tit {
            font-size: 36rpx;
            font-weight: bolder;
            color: #333;
        }
    }

    .box-body {



        .item-content {
            padding: 40rpx 0 20rpx 0;
            color: #333;
        }
    }

    .operation {
        display: flex;
        position: fixed;
        bottom: 0;
        width: 100%;
        left: 0;
    }

    .answer-cardsheet {
        display: flex;
        flex-wrap: wrap;
        padding-top: 20rpx;
        max-height: 400px;
        overflow-y: auto;

        // justify-content: space-between;
        .item-box {
            display: flex;
            justify-content: center;
            width: 20%;

            .item {
                width: 80rpx;
                height: 80rpx;
                border: 1px solid #9e9b9b;
                border-radius: 50%;
                flex-shrink: 0;
                display: flex;
                align-items: center;
                justify-content: center;
                margin: 20rpx 0;
            }

            .item1 {
                //已答 正确
                background: rgba(60, 156, 255, 0.4);
                border: 1px solid rgba(60, 156, 255, 0.4);
                color: #2979FF;
            }

            .item2 {
                //当前
                background: #fff;
                color: #2979FF;
                border: 1px solid rgba(60, 156, 255, 0.4);
            }

            .item3 {
                //错误
                background: rgba(217, 159, 159, 0.5);
                border: 1px solid rgba(217, 159, 159, 0.5);
                color: rgba(255, 25, 25, 0.337);
            }
        }

        .button-box {
            margin-top: 20rpx;
            display: flex;
            width: 100%;
        }
    }

    .is-sub {
        display: flex;
        justify-content: center;
        flex-direction: column;
        padding: 40rpx 0;
        width: 100%;
        text-align: center;

        .error-circle-fill {
            margin: 0 auto;
        }

        .warn {
            font-size: 32rpx;
            margin-top: 12rpx;
        }

        .result-img {
            margin: 0 auto;
        }
    }

    .explain {
        margin-top: 20px;
    }
}
</style>