<template>
    <view class="erercises-detail">
        <view class="erercises-detail-section" v-if="info.question_info.title">
            <view class="li">
                <view class="top">
                    <view class="tag">
                        <text>{{teamIndex}}/{{count}}</text>
                    </view>

                    <view class="time" v-if="type != 1">
                        <image :src="staticUrl('/static/icon-clock.png')"></image>
                        <u-count-down :time="start_time" format="HH:mm:ss" autoStart @change="onChange">
                            <view class="time">
                                <view class="time__custom">
                                    <text
                                        class="time__custom__item">{{timeData.hours>10?timeData.hours:'0'+(timeData.hours?timeData.hours:0)}}</text>
                                </view>
                                <text class="time__doc">:</text>
                                <view class="time__custom">
                                    <text
                                        class="time__custom__item">{{timeData.minutes>10?timeData.minutes:'0'+(timeData.minutes?timeData.minutes:0)}}</text>
                                </view>
                                <text class="time__doc">:</text>
                                <view class="time__custom">
                                    <text
                                        class="time__custom__item">{{timeData.seconds>10?timeData.seconds:'0'+(timeData.seconds?timeData.seconds:0)}}</text>
                                </view>
                            </view>
                        </u-count-down>
                    </view>
                </view>
                <view class="tit" :style="{'fontSize': fontSize+'rpx', 'fontWeight': fontWeight?'normal':'bold'}">
                    {{teamIndex}}、<view class="content" v-html="info.question_info.title"></view>
                </view>
                <view class="title_img" v-if="info.question_info.title_img">
                    <image mode="widthFix" :src="info.question_info.title_img"></image>
                </view>
                <view class="title_video" v-if="info.question_info.title_video">
                    <video :src="info.question_info.title_video"></video>
                </view>
                <view class="con" v-for="(a,index) in info.question_info.choice" :key="index"
                    :class="a.isSelect?'right':a.isErrow?'wrong':''" :style="{'fontSize': fontSize+'rpx'}"
                    @click="toSelect(index)">
                    {{a.name}}.{{a.value}}
                    <view class="mark">
                        <image v-if="a.isSelect" :src="staticUrl('/static/icon-study-right.png')"></image>
                        <template v-else>
                            <image v-if="a.isErrow" :src="staticUrl('/static/icon-study-wrong.png')"></image>
                            <image v-if="current_question_choice && info.question_info.correct == a.name"
                                :src="staticUrl('/static/icon-study-right.png')"></image>
                        </template>
                    </view>
                </view>
            </view>
            <view class="btns">
                <view class="btn" @click="getInfo(0)">上一题</view>
                <view class="btn" @click="updateFont(1)">放大</view>
                <view class="btn" @click="updateFont(2)">缩小</view>
                <view class="btn" @click="updateFont(3)">{{fontWeight?'加粗':'恢复'}}</view>
                <view class="btn" @click="getInfo(1)">下一题</view>
            </view>
            <view class="analysis" v-if="current_question_choice">
                <view class="answer">
                    答案： <text>{{info.question_info.correct}}</text>
                </view>
                <view class="line">
                    <u-divider text="答案解析" textSize="14" textColor="#3e3e3e"></u-divider>
                </view>
                <view class="msg" :style="{'fontSize': fontSize1+'rpx'}" v-html="info.question_info.prompt"></view>
            </view>
			<view class="btns" v-if="current_question_choice">
				<view class="btn" style="flex: 1;" @click="updateFont1(1)">放大</view>
				<view class="btn" @click="updateFont1(2)" style="flex: 1;margin-left: 20rpx; margin-right: 20rpx;">缩小</view>
			</view>
        </view>
        <view class="erercises-detail-section" v-if="info.question_info.length == 0 && count >= 0">
            <view class="empty" style="margin-top: 200rpx;" v-if="count == 0">
                <u-empty mode="data" text="暂无相关信息">
                </u-empty>
            </view>
            <template v-else>
                <view class="empty" style="margin-top: 200rpx; margin-bottom: 100rpx;">
                    <u-empty mode="data" text="当前真题全部答完">
                    </u-empty>
                </view>
                <u-button color="#2080F9" @click="openPage(8)">返回上一页</u-button>
            </template>
        </view>
        <view class="erercises-detail-bottom" v-if="info.question_info.title"
            :style="{ 'padding-bottom': safeBottom + 'px' }">
            <view class="check" @click="isShowCard = true">
                <view class="a">
                    <image :src="staticUrl('/static/icon-study-yes.png')"></image>{{successNum}}
                </view>
                <view class="b">
                    <image :src="staticUrl('/static/icon-study-no.png')"></image>{{errorNum}}
                </view>
            </view>
            <view class="listen" v-if="info.question_info.speech" @click="toPlayAudio(info.question_info.speech)">
                <image v-if="isPlay == false" :src="staticUrl('/static/icon-listen.png')"></image>
                <image v-else :src="staticUrl('/static/icon-listen-on.png')"></image>
                <text :class="isPlay?'on':''">听题</text>
            </view>
            <view class="btns">
                <template v-if="type != 1">
                    <view class="hand" v-if="type != 1" @click="openPage(2)">
                        交卷
                    </view>
                </template>
            </view>
        </view>
        <u-popup :show="isShowCard" round="10" @close="isShowCard=false" :closeable="true">
            <view class="pop-card">
                <view class="card-title">
                    <text>答题卡</text>
                    <view class="a">
                        <image :src="staticUrl('/static/icon-study-yes.png')"></image>{{successNum}}
                    </view>
                    <view class="b">
                        <image :src="staticUrl('/static/icon-study-no.png')"></image>{{errorNum}}
                    </view>
                </view>
                <view class="card-content">
                    <view v-for="(item,index) in list" class="item"
                        :class="{'correct':correctArr.indexOf(item) >=0,'error': errorArr.indexOf(item) >=0}">
                        {{index + 1}}
                    </view>
                </view>
            </view>
        </u-popup>

    </view>
</template>

<script>
    export default {
        data() {
            return {
                playType: 1,
                isShowCard: false,
                start_time: 100000,
                answer: "",
                category_id: "",
                teamIndex: 0,
                successNum: 0,
                errorNum: 0,
                type: 0,
                count: 0,
                list: [],
                resultList: [],
                fontSize: 30,
                fontSize1: 26,
                fontWeight: true,
                info: {
                    question_info: []
                },
                timeData: {},
                log_id: 0,
                page: 1,
                innerAudioContext: null,
                isPlay: false,
                current_question_id: "", //当前题目ID
                next_question_id: "", //下一题ID
                current_question_choice: "", //current_question_choice
                safeBottom: '',
                correctArr: [],
                errorArr: []

            };
        },
        onLoad(o) {
            const {
                safeAreaInsets
            } = uni.getSystemInfoSync()
            this.safeBottom = safeAreaInsets?.bottom
            this.category_id = o.id ? o.id : ''
            this.innerAudioContext = uni.createInnerAudioContext({
                useWebAudioImplement: false // 默认关闭。对于短音频、播放频繁的音频建议开启此选项
            });
            this.getZhengTiList()
        },

        methods: {
            updateFont(type) {
                if (type == 1) {
                    this.fontSize < 70 ? this.fontSize++ : this.fontSize
                } else if (type == 2) {
                    this.fontSize > 20 ? this.fontSize-- : this.fontSize
                } else if (type == 3) {
                    this.fontWeight = !this.fontWeight
                }
            },
			updateFont1(type){
			    if (type == 1) {
			        this.fontSize1 < 70 ? this.fontSize1++ : this.fontSize1
			    } else if (type == 2) {
			        this.fontSize1 > 20 ? this.fontSize1-- : this.fontSize1
			    }
			},
            openPage(index) {
                const that = this;
                if (index == 2) {
                    if (that.teamIndex == that.count) {
                        uni.showModal({
                            title: "交卷确认",
                            content: "你确定要交卷吗？",
                            confirmText: "确认",
                            cancelText: "取消",
                            confirmColor: "#2080F9",
                            success(res) {
                                if (res.confirm) {
                                    uni.showModal({
                                        title: "再次确认",
                                        content: "你确定要交卷吗？",
                                        confirmText: "确认",
                                        cancelText: "取消",
                                        confirmColor: "#2080F9",
                                        success(res) {
                                            if (res.confirm) {
                                                that.getInfo(2)
                                            }
                                        }
                                    })
                                }
                            }
                        })
                    } else {
                        uni.showModal({
                            title: "请确认",
                            content: "你确定要交卷吗？",
                            confirmText: "继续答题",
                            cancelText: "确认",
                            confirmColor: "#2080F9",
                            success(res) {
                                if (res.cancel) {
                                    uni.showModal({
                                        title: "再次确认",
                                        content: "你确定要交卷吗？",
                                        confirmText: "确认",
                                        cancelText: "取消",
                                        confirmColor: "#2080F9",
                                        success(res) {
                                            if (res.confirm) {
                                                that.getInfo(3)
                                            }
                                        }
                                    })

                                }
                            }
                        })
                    }
                } else {
                    uni.navigateBack({
                        delta: 1
                    })
                }

            },
            onChange(e) {
                this.timeData = e;
                if (this.count > 0 && e.days == 0 && e.hours == 0 && e.milliseconds == 0 && e.minutes == 0 && e
                    .seconds == 0) {
                    uni.showModal({
                        title: "温馨提示",
                        content: "当前刷题时间已结束，请返回上一页",
                        showCancel: false,
                        confirmColor: "#2080F9",
                        success(res) {
                            if (res.confirm) {
                                uni.navigateBack({
                                    delta: 1
                                })
                            }
                        }
                    })
                }
            },
            //播发试题
            toPlayAudio(src) {
                console.log(src)
                if (this.isPlay == false) {
                    if (this.playType == 1) {
                        this.innerAudioContext.src = src;
                        this.innerAudioContext.play();
                        this.playType = 2
                    } else {
                        this.innerAudioContext.play();
                    }
                    this.isPlay = true;
                } else {
                    this.isPlay = false;
                    this.innerAudioContext.pause();
                }
                this.innerAudioContext.onPlay(() => {
                    console.log('开始播放');
                });
                this.innerAudioContext.onEnded(() => {
                    this.isPlay = false
                });
            },
            //选择答案
            toSelect(index) {
                if (this.info.question_info.isDisable == true) {
                    return;
                }
                this.info.question_info.isDisable = true;
                this.info.question_info.choice.map(a => {
                    a.isSelect = false
                })
                const questionId = this.list[this.teamIndex - 1]
                if (this.info.question_info.choice[index].name == this.info.question_info.correct) {
                    this.info.question_info.choice[index].isSelect = true
                    this.info.question_info.choice[index].isErrow = false
                    this.successNum++
                    this.correctArr.push(questionId)
                } else {
                    this.info.question_info.choice[index].isSelect = false
                    this.info.question_info.choice[index].isErrow = true
                    this.errorNum++
                    this.errorArr.push(questionId)
                }
                this.info.question_info.value = this.info.question_info.choice[index]
                this.current_question_choice = this.info.question_info.choice[index].name
            },
            //交卷
            async toSumbit() {
                const that = this;
                let arr = [];
                const {
                    code,
                    data,
                    msg
                } = await this.$api.freeSubPaper({
                    log_id: this.log_id
                })
                if (code == 200) {
                    uni.showToast({
                        title: "提交成功"
                    })
                    setTimeout(() => {
                        uni.setStorageSync("shareImg1", data.img)
                        uni.redirectTo({
                            url: "/pages/exercises/complete?score=" + data.score + "&error_num=" +
                                data.error_num + "&correct_num=" + this.successNum + "&use_time=" +
                                data.use_time + "&type=99" + "&logId=" + this.log_id
                        })
                    }, 2000)
                }
            },
            //获取列表
            async getZhengTiList() {
                const that = this;
                const {
                    code,
                    data,
                    msg
                } = await this.$api.freeQuestionList({
                    category_id: this.category_id,
                    page: this.page
                })
                if (code == 200) {
                    this.list = data.list;
                    this.log_id = data.log_id,
                        this.count = data.count;
                    this.successNum = data.correct_num ? data.correct_num : 0;
                    this.errorNum = data.error_num ? data.error_num : 0;
                    this.start_time = data.start_time * 1000;
                    this.resultList = data.result
                    if (data.result?.length > 0) {
                        const errArr = data.result.filter(item => item.is_correct == 1)
                        const correctArr = data.result.filter(item => item.is_correct == 2)
                        if (errArr?.length > 0) {
                            that.errorArr = errArr.map(errItem => errItem.id + '')
                        }
                        if (correctArr?.length > 0) {
                            that.correctArr = correctArr.map(correctItem => correctItem.id + '')
                        }
                    }
                    if (this.count > 0) {
                        if (data.current_question_id == 0) {
                            that.teamIndex = 0
                            this.next_question_id = data.list[0];
                        } else {
                            this.next_question_id = data.current_question_id;
                            if (data.list && data.list.length > 0) {
                                data.list.map((a, idx) => {
                                    if (a == data.current_question_id) {
                                        that.teamIndex = idx
                                    }
                                })
                            }

                        }
                        this.getInfo();
                    }

                } else {
                    uni.showToast({
                        icon: "none",
                        title: msg
                    })
                }
            },

            //获取详情
            async getInfo(type) {
                let that = this
                if (type == 1) {
                    if (!that.current_question_choice) {
                        uni.showToast({
                            icon: "none",
                            title: "请选择答案！"
                        })
                        return;
                    }
                    if (that.teamIndex >= that.count) return
                    // 下一题 首先判断下一题是否打过，打过直接取

                    that.current_question_id = that.teamIndex > that.count ? '' : that.list[that.teamIndex - 1];
                    that.next_question_id = that.teamIndex > that.count ? '' : that.list[that.teamIndex];
                    that.isPlay = false;
                    that.playType = 1;
                    that.innerAudioContext.pause();
                } else if (type == 0) {
                    // 上一题
                    if (that.teamIndex <= 1) return
                    that.next_question_id = that.teamIndex > that.count ? '' : that.list[that.teamIndex - 2];
                    that.isPlay = false;
                    that.playType = 1;
                    that.innerAudioContext.pause();
                } else if (type == 2) {
                    // 最后一道题
                    that.next_question_id = 0
                    that.current_question_id = that.list[that.list.length - 1]
                } else if (type == 3) {
                    // 当前题 没有选择答案时直接提交  否则调一下下一题接口上传答案后再提交
                    if (that.current_question_choice) {
                        that.current_question_id = that.teamIndex > that.count ? '' : that.list[that.teamIndex - 1];
                        that.next_question_id = that.teamIndex > that.count ? '' : that.list[that.teamIndex];
                        that.isPlay = false;
                        that.playType = 1;
                        that.innerAudioContext.pause();
                    } else {
                        this.toSumbit();
                        return;
                    }
                }
                uni.showLoading({
                    title: "加载中"
                })
                const params = type == 0 ? {
                    next_question_id: this.next_question_id
                } : {
                    next_question_id: this.next_question_id,
                    current_question_id: this.current_question_id,
                    current_question_choice: this.current_question_choice,
                    is_error: this.type == 1 ? 1 : 0,
                    log_id: this.log_id ? this.log_id : 0
                }
                const {
                    code,
                    data,
                    msg
                } = await this.$api.freeQuestionInfo(params)
                if (code == 200) {
                    uni.hideLoading();
                    if (type == 2 || type == 3) {
                        this.toSumbit();
                        return;
                    } else if (type == 0 || type == 1 || typeof type == 'undefined') {
                        // 上一题  下一题 先查找题答案
                        const foundItem = that.resultList && that.resultList.find(item => item.id == that.next_question_id);
                        if (foundItem && foundItem.your_answer) {
                            let arr = data
                            arr.question_info.value = {}
                            arr.question_info.isDisable = true
                            if (arr.question_info && arr.question_info.choice) {
                                arr.question_info.choice.map(a => {
                                    a.isSelect = foundItem.is_correct == 2 && a.name.toLowerCase() ==
                                        foundItem
                                        .your_answer
                                    a.isErrow = foundItem.is_correct == 1 && a.name.toLowerCase() ==
                                        foundItem
                                        .your_answer
                                })
                            }
                            type == 0 && that.teamIndex--;
                            type != 0 && that.teamIndex++;
                            that.current_question_choice = foundItem.your_answer
                            that.info = arr
                        } else {
                            // 把用户选项放入resultList
                            that.resultList && that.resultList.forEach(item => {
                                if (item.id == that.current_question_id) {
                                    item.your_answer = that.current_question_choice.toLowerCase()
                                    item.is_correct = data.current_question_is_correct ? 2 : 1
                                }
                            })
                            let arr = data
                            arr.question_info.value = {}
                            arr.question_info.isDisable = false
                            if (arr.question_info && arr.question_info.choice) {
                                arr.question_info.choice.map(a => {
                                    a.isSelect = false
                                    a.isErrow = false
                                })
                            }
                            that.teamIndex++;
                            that.current_question_choice = ""
                            that.info = arr
                        }

                    }
                } else {
                    uni.hideLoading();
                    uni.showToast({
                        icon: "none",
                        title: msg
                    })
                }
            },
        },

        onUnload() {
            this.innerAudioContext.src = ""
            this.innerAudioContext.stop()
            this.innerAudioContext.destroy();
        },
        destroyed() {
            this.innerAudioContext.src = ""
            this.innerAudioContext.stop()
            this.innerAudioContext.destroy();
        }
    }
</script>

<style lang="scss" scoped>
    .pop-card {
        height: 600rpx;
        display: flex;
        flex-direction: column;

        .card-title {
            display: flex;
            padding: 30rpx;

            .a {
                display: flex;
                align-items: center;
                margin: 0 30rpx;
                font-size: 30rpx;
                color: #37C594;
            }

            .b {
                display: flex;
                align-items: center;
                font-size: 30rpx;
                color: #F01B1B;
            }

            image {
                width: 44rpx;
                height: 44rpx;
                margin-right: 10rpx;
            }
        }

        .card-content {
            flex: 1;
            display: flex;
            flex-wrap: wrap;
            overflow-y: auto;

            .item {
                margin: 20rpx;
                width: 80rpx;
                height: 80rpx;
                text-align: center;
                line-height: 80rpx;
                border: 1px solid rgba(0, 0, 0, 0.2);
                color: rgba(0, 0, 0, 0.6);
                border-radius: 50%;

                &.correct {
                    color: #49c99c;
                    background-color: #f3f8f6;
                }

                &.error {
                    color: #fa6e6e;
                    background-color: #fff3f3;
                }
            }
        }
    }

    .erercises-detail {
        padding-bottom: 140rpx;
        overflow: hidden;

        &-section {
            width: 100%;
            padding: 0 25rpx 20rpx;
            overflow: hidden;
            box-sizing: border-box;

            .li {
                width: 90%;
                margin: 20rpx auto 0;
                padding: 30rpx;
                background: #FFFFFF;
                border-radius: 20rpx;
                box-shadow: 0rpx 5rpx 10rpx 0rpx rgba(32, 79, 156, 0.06);
                border-radius: 20rpx;

                .top {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    margin-bottom: 20rpx;

                    .tag {
                        height: 50rpx;
                        margin-left: -30rpx;
                        padding-left: 30rpx;
                        padding-right: 30rpx;
                        background: url('../../static/icon-tag-bg.png') no-repeat;
                        background-size: 100% 100%;
                        font-size: 1rpx;
                        line-height: 50rpx;
                        color: #ffffff;

                        text {
                            font-size: 30rpx;
                        }
                    }

                    .time {
                        font-size: 24rpx;
                        color: #3e8ff9;
                        display: flex;
                        align-items: center;

                        image {
                            width: 25rpx;
                            height: 25rpx;
                            margin-right: 10rpx;
                        }
                    }
                }

                .tit {
                    overflow: hidden;
                    padding-bottom: 10rpx;
                    color: #333333;
                    display: flex;
                    align-items: flex-start;
                }

                .title_img {
                    width: 100%;

                    image {
                        width: 100%;
                    }
                }

                .title_video {
                    width: 100%;
                    height: 300rpx;

                    video {
                        width: 100%;
                        height: 100%;
                    }
                }

                .con {
                    overflow: hidden;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    margin-top: 20rpx;
                    padding: 30rpx 60rpx 30rpx 30rpx;
                    background: #F6F6F6;
                    color: #333333;
                    line-height: 50rpx;
                    position: relative;

                    &.right {
                        color: #49c99c;
                        background-color: #f3f8f6;
                    }

                    &.wrong {
                        color: #fa6e6e;
                        background-color: #fff3f3;
                    }

                    .mark {
                        width: 60rpx;
                        height: 60rpx;
                        position: absolute;
                        right: 10rpx;
                        top: 50%;
                        margin-top: -30rpx;
                        z-index: 2;

                        image {
                            width: 100%;
                            height: 100%;
                        }
                    }
                }
            }

            .btns {
                padding: 25rpx;
                box-sizing: border-box;
                margin-top: 20rpx;
                display: flex;
                justify-content: space-between;

                .btn {
                    padding: 0 20rpx;
                    line-height: 80rpx;
                    border-radius: 10rpx;
                    text-align: center;
                    background-color: #2080F9;
                    font-size: 28rpx;
                    color: #fff;
                }
            }

            .analysis {
                width: 90%;
                margin: 20rpx auto 0;
                padding: 30rpx;
                background: #FFFFFF;
                border-radius: 20rpx;
                box-shadow: 0rpx 5rpx 10rpx 0rpx rgba(32, 79, 156, 0.06);
                border-radius: 20rpx;

                .answer {
                    overflow: hidden;
                    padding: 20rpx 30rpx;
                    line-height: 50rpx;
                    background-color: #f3f8f6;

                    text {
                        color: #49c99c;
                    }
                }

                .line {
                    width: 70%;
                    margin: 0 auto;
                }

                .msg {
                    line-height: 1.5;
                    letter-spacing: 1rpx;
                    color: #6b6b6b;
                }
            }

        }

        &-bottom {
            position: fixed;
            bottom: 0;
            z-index: 99;
            width: 100%;
            height: 100rpx;
            background: #FFFFFF;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .check {
                margin-left: 20rpx;
                line-height: 30rpx;

                .a {
                    float: left;
                    display: flex;
                    align-items: center;
                    margin-right: 30rpx;
                    font-size: 30rpx;
                    color: #37C594;
                }

                .b {
                    float: left;
                    display: flex;
                    align-items: center;
                    font-size: 30rpx;
                    color: #F01B1B;
                }

                image {
                    width: 44rpx;
                    height: 44rpx;
                    margin-right: 10rpx;
                }
            }

            .listen {
                display: flex;
                align-items: center;
                font-size: 26rpx;
                line-height: 30rpx;
                color: #666666;

                image {
                    width: 44rpx;
                    height: 44rpx;
                    margin-right: 12rpx;
                }
            }

            .btns {
                margin-right: 20rpx;

                .hand {
                    float: left;
                    width: 140rpx;
                    margin-right: 10rpx;
                    font-size: 28rpx;
                    line-height: 57rpx;
                    color: #FFFFFF;
                    text-align: center;
                    background: #2080F9;
                    border: 1px solid #2080F9;
                    border-radius: 29rpx;
                }

                .btn {
                    float: right;
                    width: 140rpx;
                    font-size: 28rpx;
                    line-height: 57rpx;
                    color: #2080F9;
                    text-align: center;
                    background: #FFFFFF;
                    border: 1px solid #2080F9;
                    border-radius: 29rpx;
                }
            }
        }
    }
</style>
