import { getRaceInfo, postQuestion, postQuestionSubmit } from '../../../../service/match';

import Utils from '../../../../util/utils'
class answerScene extends scene {
    constructor(scope) {
        super(scope);
        this.quesIndex = 0;
        this.quesLength = 0;
        this.questionList = [];
        this.requestId = undefined;
        this.wareId = undefined;
        this.target = undefined;
        this.hasPostAnswer = false;
        this.startTime = new Date(); // 页面开始时间

    }

    onCreate(data) {
        Utils.setBack(false, '.42')
        Utils.setBg('#3156AB')
        // 保存单次请求Id
        this.requestId = data.requestId;
        this.wareId = data.wareId;
        this.raceId = data.raceId;
        this.setContentView(require('../../../../res/tpl/match/answer.tpl'), {}, 'answer', {
            containerId: 'root'
        }, () => {
            // 渲染答题
            this.getRaceInfoData(this.raceId)
        });
    }

    getRaceInfoData(id) {
        getRaceInfo(id).success(res => {
            this.questionList = res.data.questions;
            this.quesLength = this.questionList.length
            this.raceId = res.data.race.id;
            this.renderNumber(this.quesLength);
            this.renderQues(this.quesIndex)
            Utils.$('.anser_title').innerHTML = res.data.race.title;
            const time = res.data.race.duration * 60
            this.countdown(time)
        })
    }
    onResume() {
        Utils.setBack(false, '.42')
        Utils.setBg('#3156AB')
    }
    onOK(e) {
        const flag = e.target.con.attributes['data-event'].nodeValue;
        switch (flag) {
            case 'cancle':
                clickMp3();
                this.hideScene()
                break;
            case 'answer':
                if (this.answerOnceOnly) break;
                this.answerOnceOnly = true;
                this.chooseAnswer(e.target.con.dataset.answer, e.target.con.dataset.index);
                break;
            case 'prev':
                // 上一题
                clickMp3();
                const prevInd = this.quesIndex - 1
                if ( prevInd < 0) return
                console.log(this.quesIndex - 9)
                if (this.quesIndex - 9 < this.quesLength && this.quesIndex >= 9) {
                    document.querySelector('.number_menu').scrollTo((this.quesIndex - 9) * 120 ,0)
                }
                this.quesIndex--;
                this.renderQues(this.quesIndex)

                break;
            case 'next':
                // 下一题
                clickMp3();

                const index = this.quesIndex + 1
                if ( index === this.quesLength) {
                    // 提交回答
                    clearTimeout(this.countDownTime);
                    this.submitRecord().then(res => {
                        console.log(res);
                        this.showScene(require('./matchDialogScene.js'), {
                            bg: 'assets/match/baogao_bg.png',
                            type: 'report',
                            reportCon: res,
                            raceId: this.raceId
                        })
                    })
                    return
                }
                if (index >= 9) {
                    document.querySelector('.number_menu').scrollTo((index - 9) * 120,0)
                }
                this.quesIndex++;
                this.renderQues(this.quesIndex)
                break;
            case 'number':
                const quesIndex = e.target.con.attributes['data-index'].nodeValue
                this.quesIndex = parseInt(quesIndex);
                console.log(111111111, this.quesIndex)
                this.renderQues(this.quesIndex)
                break;
            case 'back':
                clickMp3();
                this.showScene(require('./matchDialogScene.js'), {
                    bg: 'assets/match/quit_bg.png',
                    type: 'quit',
                    raceId: this.raceId,
                    reportCon: {}
                })
                break;
            // 交卷
            case 'submitAnswer':
                clearTimeout(this.countDownTime);
                // 提交回答
                this.submitRecord().then(res => {
                    console.log(res);
                    this.showScene(require('./matchDialogScene.js'), {
                        bg: 'assets/match/baogao_bg.png',
                        type: 'report',
                        reportCon: res,
                        raceId: this.raceId
                    })
                })
                break;
        }
    }

    onBack(e) {
        Utils.setBack(true)
        clearTimeout(this.prevTime)
        clearTimeout(this.nextTime)
        clearTimeout(this.countDownTime);
    }
    renderNumber(length) {
        for (let i = 0; i < length; i++) {
            let number = document.createElement('div');
            number.className = 'number'
            number.setAttribute('fe-role', 'Widget')
            number.setAttribute('data-event', 'number')
            number.setAttribute('data-index', i)
            let numberText = document.createElement('span');
            numberText.innerHTML = i + 1;
            number.appendChild(numberText)
            document.getElementById('number_menu_wrapper').appendChild(number);
        }
        this.moye.root.reRender()
    }
    wrapDiv(str) {
        let list = str.split('<br/>');
        if (list.length > 1) {
            return `
                <div>${list[0]}</div>
                <div>${list[1]}</div>
            `
        } else {
            return str
        }
    }
    renderQues(index) {

        clearTimeout(this.changingAnswer)
        this.analysisShow = false
        document.getElementById('analysis').style.display = 'none';
        document.getElementById('analysis_btn').style.display = 'none';

        document.getElementById('text_area').style.display = 'block'
        document.getElementById('answer_area').style.display = 'flex'
        this.hideAnswerIcon();
        this.renderCurrentNumber();
        let obj = this.questionList[index];
        // 最后一题
        if (index + 1 === this.quesLength) {
            document.getElementById('next_final').innerHTML = '提交'
        } else {
            document.getElementById('next_final').innerHTML = '下一题'
        }
        this.target = obj.target;
        document.getElementById('text_area').innerHTML = `
        <span class="ques_score">(${obj.score}分)</span>
        <img src=${obj.image} class="ques_big_img" />
        `
         // 删除已选答案
        this.removeClass();
        Array.from(document.querySelectorAll('.answer_item')).forEach((item, index) => {
            item.style = 'width: 3.7rem; height: 1rem;'
            item.querySelector('.answer_icon').style = 'display: none;'
            item.querySelector('.answer_text').style = 'display: none;'
            item.querySelector('.right_wrong').style = 'top: -.2rem;width: 3.62rem;height: 1.42rem;left: -.5rem'
        })
        Utils.$('.text_area').style = 'height: 7.1rem; transform: scale(1);top: 0;'
        Utils.$('.answer_area').style = 'display: flex;width: 70%;margin-top: -1.8rem; position: absolute;left: 3.4rem;'
        this.analysisA = obj.analysisA;
        this.analysisB = obj.analysisB;
        this.analysisC = obj.analysisC;
        // 没有答过的题要刷新状态
        if (obj.answer === 'A') {
            document.getElementById('right_wrong_a').src = 'assets/match/hand.png';
        } else if (obj.answer === 'B') {
            document.getElementById('right_wrong_b').src = 'assets/match/hand.png';
        } else {
            document.getElementById('right_wrong_c').src = 'assets/match/hand.png';
        }


        if (obj.isAnswered) {
            this.answerOnceOnly = true;
            Array.from(document.getElementsByClassName('right_wrong')).forEach(item => {
                item.style.display = 'none'
            })

            if (obj.userOption === 'A') {
                document.getElementById('answer_a_icon').className += ' choose';
                document.getElementsByClassName('right_wrong')[0].style.display = 'block'
            } else if (obj.userOption === 'B') {
                document.getElementById('answer_b_icon').className += ' choose';
                document.getElementsByClassName('right_wrong')[1].style.display = 'block'
            } else {
                document.getElementById('answer_c_icon').className += ' choose';
                document.getElementsByClassName('right_wrong')[2].style.display = 'block'
            }
        } else {
            // 答案弹出后只允许点击一次
            this.answerOnceOnly = false;
        }

        document.getElementById('lesson_main').style.display = 'block'

        // 让答案失去焦点 为了闪烁
        this.moye.root.getWidgetById('answer_a').blur();
        this.moye.root.getWidgetById('answer_b').blur();
        this.moye.root.getWidgetById('answer_c').blur();

    }
    // 给当前的题目序号标上边框
    renderCurrentNumber() {
        let list = Array.from(document.getElementsByClassName('number'));
        let reg = /current/g;
        let prevQuesIndex = 0;
        list.forEach((item, index) => {
            if (reg.test(item.className)) {
                prevQuesIndex = index
            }
        })
        list.forEach((item, index) => {
            if (index === this.quesIndex) {
                item.className = 'number current';
                this.moye.root.getWidgetById(item.id).focus()
            } else {
                item.className = item.className.replace('current', '')
            }

        })
    }
    // 修改样式
    removeClass() {
        document.getElementsByClassName('choose')[0] ? document.getElementsByClassName('choose')[0].classList.remove('choose') : '';
    }

    onTouch(e) {
        console.log("touch")
    }
    // 记题板
    // 记录这道题是否答过，答对答错
    // type：是否作答
    // answerType： 答对答错
    // userOption: 用户作答选项
    recordHandler(type, answerType, userOption, questionId) {
        let currentQues = this.questionList[this.quesIndex]
        currentQues.isAnswered = type;
        currentQues.isCorrect = answerType;
        currentQues.userOption = userOption;
        let postData = {
            questionId,
            "questionAnswer": userOption,
        }
        postQuestion(postData).success(res => {
            console.log('发送答案', res)
            this.hasPostAnswer = true;
        })
    }
    chooseAnswer(option, index) {
        option = option ? option.toUpperCase() : undefined;
        // 语音时也要闪烁
        switch (option) {
            case 'A':
                this.moye.root.getWidgetById('answer_a').focus();
                document.getElementById('answer_a_icon').className += ' choose';
                break;
            case 'B':
                this.moye.root.getWidgetById('answer_b').focus();
                document.getElementById('answer_b_icon').className += ' choose';

                break;
            case 'C':
                this.moye.root.getWidgetById('answer_c').focus();
                document.getElementById('answer_c_icon').className += ' choose';
                break;
            default:
                break;

        }
        if (option) {
            this.changingAnswer = setTimeout(() => {
                let answerList = Array.from(document.getElementsByClassName('right_wrong'));
                answerList.forEach((item) => {
                    item.style.display = 'none'
                });
                document.getElementsByClassName('right_wrong')[index].style.display = 'block'
            }, 600)
        }
        let correctAnswer = this.questionList[this.quesIndex].answer;
        const questionId = this.questionList[this.quesIndex].id;
        if (option === correctAnswer) {
            // 答对逻辑
            // rightMp3();
            // 记录答对答错
            this.recordHandler(true, true, option, questionId)
        } else {
            // 答错逻辑
            // wrongMp3();
            this.recordHandler(true, false, option, questionId)
        }
    }

    // 提交本次记录
    submitRecord() {
        return new Promise((resolve, reject) => {
            postQuestionSubmit({
                raceId: this.raceId
            }).success(res => {
                resolve(res.data)
                // this.hideScene();
            })
        })

    }
    // 隐藏答案图片
    hideAnswerIcon() {
        let list = Array.from(document.getElementsByClassName('right_wrong'));
        list.forEach(item => {
            item.src = 'assets/match/hand.png'
            item.style.display = 'none'

        })
    }

    aiHandle(name, slots) {

    }
  /**倒计时 */
  countdown(time) {
    if (time > 0) {
        this.countDownTime = setTimeout(() => {
            time--;
            // console.log('分', Math.floor(time / 60), '秒', time % 60)
            const h = Math.floor(time / 3600 % 24) < 10 ? '0' + Math.floor(time / 3600 % 24) : Math.floor(time / 3600 % 24)
            const m = Math.floor(time / 60 % 60) < 10 ? '0' + Math.floor(time / 60 % 60) : Math.floor(time / 60 % 60);
            const s = (time % 60) < 10 ?  '0' +  (time % 60) :  time % 60;
            if (h * 1 === 0) {
                Utils.$('.answer_time span').innerHTML = m + ':' + s
            } else {
                Utils.$('.answer_time span').innerHTML = h + ':' + m + ':' + s
            }
            this.countdown(time)
        }, 1000)
    } else {
        console.log('竞赛结束')
        // 提交回答
        this.submitRecord().then(res => {
            console.log(res);
            this.showScene(require('./matchDialogScene.js'), {
                bg: 'assets/match/end_bg.png',
                type: 'end',
                reportCon: res,
                raceId: this.raceId
            })
        })
    }
  }
}

module.exports = answerScene;
