<template>
    <view class="backView">
        <Examine :index="3">
            <view class="bottom-padding">
                <view class="title-view">
                    <view :class="['title-text', {'radio': currentItem.question ? currentItem.question.answerType == 1 : true}]">
                        <text>{{ titleText[Math.max(0, currentItem.question ? currentItem.question.answerType - 1 : 0)] }}</text>
                    </view>
                    <view class="title-right-view">
                        <image class="timeIcon" :src="time1Image" mode=""></image>
                        <text class="timeText">倒计时：</text><text class="time-count-down">{{currentTime}}</text>
                    </view>
                </view>
                <view class="topicView">
                    <text class="topicText">{{currentItem.question.content}}</text>
                </view>

                <view :class="['itemView',item.isSelect ? 'active':'']" v-for="(item,ikey) in currentItem.answerList" :key="ikey" @click="itemClick(item,ikey)">
                    <view :class="item.isSelect ? 'itemIndexView' : 'itemIndexView grayBorder' ">
                        <text :class="item.isSelect ? 'itemIndexText whiteColor selectBackColor' : 'itemIndexText gray-color' ">
                            {{alphaArr[ikey]}}
                        </text>
                    </view>
                    <view :class="item.isSelect ? 'itemText selectedColor' : 'itemText defaultColor' ">{{contentFilter(item.content)}}</view>
                </view>
            </view>

            <!-- </template> -->
            <template v-slot:bottom>
                <view class="answerBottomView">
                    <view class="bottom-left-view">
                        <!-- <image class="bottom-icon" :src="timuImage" mode=""></image> -->
                        <text class="numberText">{{progress}}</text>
                    </view>
                    <view class="bottomRightView">
                        <view :class="isSelect ? 'nextBtn selectBackColor' : 'nextBtn defaultBackColor' " @click="handleClick()">
                            <text class="bottomTitle">{{bottomTitle}}</text>
                        </view>
                    </view>

                </view>
            </template>
        </Examine>
        <view class="mask" v-show="isComplete">
            <view class="box">
                <image class="icon" :src="chenggongImage"></image>
                <view class="txt">您已成功完成考试</view>
                <button class="btn" @click="toSubmit()">
                    去提交
                </button>
            </view>
        </view>
    </view>
</template>

<script>
import Examine from "@/components/settle/examine.vue";
import utils from "@/utils/util.js";
const globalUrl = process.uniEnv || {};
const systemApiUrl = globalUrl.systemUrl.apiUrl;
const ucenterApiUrl = globalUrl.ucenterUrl.apiUrl;
export default {
    components: {
        Examine,
    },
    data() {
        return {
            examId: null,
            userExamId: null,
            userAnswerIds: "",
            isStart: true,
            currentNumber: 1,
            currentItem: {
                question: {
                    answerType: 1,
                    content: ""
                },
                answerList: {}
            },
            isSelect: false,
            timeDefine: {
                "time-id-2": 1800,
                "time-id-3": getApp().globalData.questionTime * 4,
                "time-id-4": getApp().globalData.questionTime * 5,
            },
            endTime: 0,
            currentTime: 100,
            everyTime: 20,
            progress: "",
            bottomTitle: "下一题",
            isStop: false,
            clock_url: "https://qn-static.banshouhui.com/clock_exam.png",
            examScore: 0,
            alphaArr: ["A", "B", "C", "D", "E"],
            timer: null,
            isComplete: false, // 是否已经考试完成判定
            examInfo: null,
            isLoadQuestion: true,
            isOnLoad: true
        };
    },
    computed: {
        titleText() {
            return ["单选", "多选", "问答"];
        },
        time1Image() {
            return process.uniEnv.qn_base_url + "time1.png";
        },
        chenggongImage() {
            return process.uniEnv.qn_base_url + "chenggong.png";
        },
        timuImage() {
            return process.uniEnv.qn_base_url + "timu-new.png";
        },
    },
    onLoad(e) {
		getApp().trackPage('学习考试答题页')
        this.examId = e.examId;
        this.userExamId = e.userExamId;
        this.getUserExamInfo();
        // this.getNext();
    },
    onUnload() {
        clearTimeout(this.timer);
        let key = 'exma-' + this.examId;
        uni.setStorageSync(key, this.endTime);
    },
    methods: {
        formatTimeToMini(timestamp) {
            let result = timestamp;
            let h =
                Math.floor(result / 3600) < 10
                    ? "0" + Math.floor(result / 3600)
                    : Math.floor(result / 3600);
            let m =
                Math.floor((result / 60) % 60) < 10
                    ? "0" + Math.floor((result / 60) % 60)
                    : Math.floor((result / 60) % 60);
            let s =
                Math.floor(result % 60) < 10
                    ? "0" + Math.floor(result % 60)
                    : Math.floor(result % 60);

            let res = "";
            if (h !== "00") res += `${h}:`;
            if (m !== "00") res += `${m}:`;
            res += `${s}`;
            if (this.endTime == 0) res = "00:00";
            return res;
        },
        toSubmit() {
            //判断是否通过，通过去成功页，失败去失败页
            let examInfo = this.examInfo;
            let status = examInfo.examLevelResult == "已通过";
            let url = '';
            if (status) {
                url = "/pages/learn/exam-pass?userExamId=" +
                        this.userExamId +
                        "&examId=" +
                        this.examId;
            } else {
                url = "/pages/learn/result?userExamId=" +
                        this.userExamId +
                        "&examId=" +
                        this.examId
            }
            wx.redirectTo({
                url: url,
            });
        },
        contentFilter(txt) {
            if (!txt) {
                return txt;
            }
            let reg = /\w+\.?/;
            const result = txt.replace(reg, "");
            return result;
        },
        gotoLogin() {
            uni.navigateTo({
                url: "/pages/login/index",
            });
            return;
        },
        //获取考试信息
        getUserExamInfo: function () {
            uni.showLoading({
                title: "请稍候",
            });

            let that = this;
            let examId = that.examId;
            this.$u.api.getExamResult(examId)
            .then((res) => {
                uni.hideLoading();
                if (!res.data) {
                    return;
                }
                if (res.code == 200) {
                    //examStatus 用户考试状态 0考试中 1考试完成 2未参与
                    if (that.isOnLoad && (res.data.examStatus == 1 || res.data.examStatus == 2)) {
                        //刚进来是考试完成和未参与，直接申请考试
                        that.isOnLoad = false;
                        that.applyExam();
                        return;
                    }
                    that.isOnLoad = false;
                    
                    if (res.data.examStatus == 1) {
                        that.isComplete = true;
                        that.examScore = res.data.examScore;
                        return;
                    }
                    if (res.data.examStatus == 0) {
                        that.userExamId = res.data.id;
                        
                        let key = 'exma-' + this.examId;
                        let limitTime = uni.getStorageSync(key);
                        if(limitTime <= 0 || limitTime == ""){
                            let time = parseInt(
                                that.timeDefine["time-id-" + that.examId]
                            );
                            that.endTime = time;
                            that.currentTime = parseInt(time * 1000);
                        }else{
                            that.endTime = parseInt(limitTime);
                            that.currentTime = parseInt(limitTime * 1000);
                        }
                        that.getNext();
                    }
                } else {
                    uni.showToast({
                        icon: "none",
                        title: res.data.message,
                    });
                }
            })
            // .catch((err) => {
            //     uni.hideLoading();
            //     uni.showToast({
            //         icon: "none",
            //         title: err,
            //     });
            // });
        },

        //申请考试
        applyExam: function () {
            uni.showLoading({
                title: "请稍候",
            });

            let that = this;
            let examId = this.examId;
            this.$u.api.applyExam(examId)
            .then((res) => {
                uni.hideLoading();
                if (res.code == 200) {
                    if (res.data.userExamId) {
                        that.userExamId = res.data.userExamId;
                
                        //申请完考试设置倒计时总时间
                        let time = parseInt(
                            this.timeDefine["time-id-" + this.examId]
                        );
                        this.endTime = time;
                        // let timestamp = new Date().getTime();
                        // this.endTime = timestamp + time * 1000;
                        this.currentTime = parseInt(time * 1000); //this.formatTimeToMini(timestamp);//endTime-currentTime再格式化时间显示
                        that.getNext();
                    }
                } else {
                    uni.showToast({
                        icon: "none",
                        title: res.data.message,
                    });
                }
            })
            // .catch((err) => {
            //     uni.hideLoading();
            //     uni.showToast({
            //         icon: "none",
            //         title: "获取考试信息失败",
            //     });
            // });
        },

        //获取下一题
        getNext: function () {
            var questionId = "";
            if (
                this.currentItem &&
                this.currentItem.question &&
                this.currentItem.question.id
            ) {
                questionId = this.currentItem.question.id;
            }

            uni.showLoading({
                title: "请稍候",
            });

            let that = this;
            
            this.$u.api.getNextQuestion(this.userExamId, questionId, this.userAnswerIds)
            .then((res) => {
                uni.hideLoading();
                if (res.code == 200) {
                    that.currentItem = res.data;
                    that.progress = res.data.progress;
                    // if(this.isLoadQuestion){
                    //     this.isLoadQuestion = false;
                    //     if(!res.data.isQuestion){
                    //         this.applyExam()
                    //         return
                    //     }
                    //     let key = 'exma-' + this.examId;
                    //     let limitTime = uni.getStorageSync(key);
                    //     console.log(limitTime);
                    //     // let limitTime = this.getLimitTime(that.progress);
                    //     // console.log(limitTime);
                    //     this.endTime = parseInt(limitTime);
                    //     this.currentTime = parseInt(limitTime * 1000);
                    // }
                    if (res.data.isQuestion) {
                        let str = res.data.question.content;
                        var wz = str.indexOf(".");
                        let str1 = str.substring(wz + 1);
                        that.currentItem.question.content = str1.replace('*', '');
                    }
                    if (res.data.answerList) {
                        that.handleData();
                        // that.currentTime = 100
                        this.everyTime = getApp().globalData.questionTime; //每道题100s
                        that.isSelect = false;
                        clearTimeout(this.timer);
                        that.startCounting();
                    } else {
                        that.isSelect = true;
                        that.getUserExamInfo();
                        clearTimeout(this.timer);
                        this.isComplete = true;
                        //用来考完试判断跳转
                        this.examInfo = that.currentItem;
                        // that.bottomTitle = '完成考试，现在签约'
                    }
                    // debugger
                } else {
                    uni.showToast({
                        icon: "none",
                        title: res.data.message,
                    });
                }
            })
            // .catch((err) => {
            //     uni.hideLoading();
            //     uni.showToast({
            //         icon: "none",
            //         title: "获取考试信息失败",
            //     });
            // });
        },
        getLimitTime(progress){
            let arr = progress.split('/');
            let how = arr[0].replace(/[^0-9]/ig,"");
            let total = arr[1].replace(/[^0-9]/ig,"");
            return (total - how + 1) * this.currentTime;
        },
        handleData: function () {
            this.currentItem.answerList.forEach((item, index) => {
                item.isSelect = false;
                this.$set(this.currentItem.answerList, index, item);
            });
        },

        startCounting: function () {
            if (this.isStop) {
                return;
            }

            this.endTime = this.endTime - 1;
            this.currentTime = this.formatTimeToMini(this.endTime);

            this.everyTime = this.everyTime - 1;

            if (this.everyTime > 0) {
                this.timer = setTimeout(this.startCounting, 1000);
            } else {
                clearTimeout(this.timer);
                this.everyTime = 90;
                this.nextClick();
            }
        },

        itemClick: function (currentItem, ikey) {
            this.isSelect = true;
            //answerType 题目类型，1单选，2多选，3简答
            for (let i = 0; i < this.currentItem.answerList.length; i++) {
                var item = this.currentItem.answerList[i];

                if (this.currentItem.question.answerType == 2) {
                    //多选
                    if (ikey == i) {
                        item.isSelect = !item.isSelect;
                    }
                } else {
                    //单选/简答
                    if (ikey == i) {
                        item.isSelect = !item.isSelect;
                    } else {
                        item.isSelect = false;
                    }
                }

                this.$set(
                    this.currentItem.answerList[i],
                    isSelect,
                    item.isSelect
                );
            }

            var isSelect = false;
            this.currentItem.answerList.forEach((item) => {
                if (item.isSelect) {
                    isSelect = true;
                }
            });

            //有选答案
            this.isSelect = isSelect;
        },
        // 点击下一步
        handleClick() {
            // 判断有没有选
            if (!this.isSelect) {
                return;
            }
            this.nextClick();
        },

        //下一题
        nextClick: function () {
            clearTimeout(this.timer);
            this.currentNumber = this.currentNumber + 1;
            this.handleAnswer();
        },
        //所选答案
        handleAnswer: function () {
            //每次清空，多选题时id按从小到大排序，并英文逗号,分隔；
            this.userAnswerIds = "";
            this.currentItem.answerList.forEach((item) => {
                if (item.isSelect) {
                    //answerType 题目类型，1单选，2多选，3简答，
                    if (this.currentItem.question.answerType == 2) {
                        //多选
                        if (this.userAnswerIds.length == 0) {
                            this.userAnswerIds = item.id + ',';
                        } else {
                            this.userAnswerIds = this.userAnswerIds + item.id + ",";
                        }
                    } else {
                        //单选
                        this.userAnswerIds = item.id + ',';
                    }
                }
            });
            this.getNext();
        },
    },
};
</script>

<style lang="scss">
.backView {
    background-color: #f4f5f7;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    overflow-y: auto;
}

.noticeView {
    margin-top: 100rpx;
    width: 100%;
    display: flex;
}

.noticeText {
    font-size: 32rpx;
    color: #555555;
    padding-left: 40rpx;
    padding-right: 40rpx;
}

.numberView {
    margin-top: 40rpx;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.numberText {
    color: #333333;
    font-size: 28rpx;
    font-weight: bold;
}

.topicView {
    margin-top: 40rpx;
    width: 100%;
    display: flex;
    align-items: center;
    margin-bottom: 40rpx;
}

.topicText {
    color: #333333;
    font-size: 32rpx;
    line-height: 48rpx;
    font-weight: bold;
}

.itemView {
    margin-top: 30rpx;
    background-color: #f4f5f7;
    width: 100%;
    padding: 40rpx 30rpx;
    display: flex;
    align-items: flex-start;
    border-radius: 12rpx;
    border: 2rpx solid transparent;
    font-size: 28rpx;
    &.active {
        background-color: #ffffff;
        border: 2rpx solid #2272ff;
    }
}

.itemIndexView {
    width: 40rpx;
    height: 40rpx;
    border-radius: 8rpx;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.grayBorder {
    border: 2rpx solid #999999;
}

.gray-color {
    color: #999999;
}

.itemIndexText {
    border-radius: 8rpx;
    width: 36rpx;
    height: 36rpx;
    display: block;
    line-height: 36rpx;
    text-align: center;
    font-size: 28rpx;
}

.itemText {
    margin-left: 20rpx;
    font-size: 28rpx;
}

.bottomView {
    background-color: #ffffff;
    width: 100%;
    height: 140rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    bottom: 0;
}

.bottomBtn {
    background-color: #007aff;
    width: 60%;
    height: 80rpx;
    border-radius: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.bottomTitle {
    font-size: 32rpx;
    color: #ffffff;
}

.title-view {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 30rpx;

    .title-text {
        border-radius: 8rpx;
        background-color: #ff930d;
        font-size: 20rpx;
        color: #ffffff;
        width: 72rpx;
        height: 40rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        &.radio {
            background-color: #2272ff;
        }
    }

    .title-right-view {
        display: flex;
        flex-direction: row;
        align-items: center;

        .timeIcon {
            margin-right: 12rpx;
            width: 32rpx;
            height: 32rpx;
        }

        .timeText {
            font-size: 28rpx;
            color: #333333;
        }

        .time-count-down {
            width: 50rpx;
            text-align: right;
        }
    }
}

.bottomRightView {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-right: 30rpx;
}

.nextBtn {
    width: 300rpx;
    height: 104rpx;
    border-radius: 52rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.defaultColor {
    color: #333333;
}

.defaultBackColor {
    background-color: #d1d4d4;
}

.selectedColor {
    color: #2272ff;
}

.whiteColor {
    color: #ffffff;
}

.selectBackColor {
    background-color: #2272ff;
}

.bottom-padding {
    // margin-bottom: 188rpx;
    background-color: #ffffff;
    border-radius: 12rpx;
    padding: 40rpx 30rpx 40rpx 30rpx;
}

.answerBottomView {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .bottom-left-view {
        display: flex;
        align-items: center;
        margin-left: 30rpx;
        .bottom-icon {
            width: 44rpx;
            height: 44rpx;
        }

        .numberText {
            color: #666666;
            font-size: 32rpx;
            margin-left: 30rpx;
        }
    }
}

.mask {
    position: fixed;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    background: rgba(0, 0, 0, 0.5);
}

.box {
    width: 660rpx;
    height: 696rpx;
    padding: 0 70rpx;
    border-radius: 12rpx;
    background-color: #fff;

    .icon {
        margin: 80rpx auto 0;
        display: block;
        width: 224rpx;
        height: 224rpx;
    }

    .txt {
        margin-top: 20rpx;
        margin-bottom: 98rpx;
        font-weight: bold;
        font-size: 40rpx;
        line-height: 66rpx;
        color: #2272ff;
        text-align: center;
    }

    .btn {
        line-height: 104rpx;
        border-radius: 52rpx;
        background: #2272ff;
        font-size: 32rpx;
        color: #fff;
    }
}
</style>
