import { getNewMistake, postQuestion } from '../../../../service/match'

import Utils from '../../../../util/utils'
import { isLogin } from '../../../../util/login'

class errorScene extends scene {
    constructor(scope) {
        super(scope);
        this.quesIndex = 0;
        this.quesLength = 0;
        this.questionList = [];
        this.requestId = undefined;
        this.courseId = undefined;
        this.lessonId = undefined;
        this.wareId = undefined;
        this.target = undefined;
        this.category = 'CHINESE';
        this.pageNum = 1;
        this.pageSize = 5;
        this.hasNext = false; // 是否还有下一页
        this.startTime = new Date(); // 页面开始时间

    }

    onCreate(data) {
        Utils.setBg('#8E53D9')
        Utils.setBack(false, '.52')
        this.setContentView(require('../../../../res/tpl/match/errorbook.tpl'), {}, 'errorbook', {
            containerId: 'root'
        }, () => {
            // 获取数据
            if (data && data.type) {
                this.type = data.type;
                this.changeCategory(this.type)
            }
        });
    }

    changeCategory(type) {
        document.getElementById('scroll_analysis').style.display = 'none';
        this.type = type;
        this.getMistakeList(true)
    }

    getMistakeList(ifChange) {
        getNewMistake({
            grade: Utils.readLocalstorage('class'),
            pageNum: this.pageNum,
            pageSize: this.pageSize
            }).success(res => {
            this.getData(res, ifChange)
        })
    }
    getData(res, ifChange) {
        if (this.hasNext && !ifChange) {
            console.log('加载下一页')
            res.data.list.forEach(item => {
                this.questionList.push(item)
            })
            this.quesLength = this.questionList.length;
            this.hasNext = res.data.hasNext;
        } else {
            this.quesLength = res.data.list.length;
            if (res.data.list.length === 0) {
                // 没有错题，显示图片
                this.showImg(true)
                this.questionList = [];
            } else {
                this.showImg(false)
                this.questionList = res.data.list;
                this.quesIndex = 0;
                this.renderQues(this.quesIndex);
                if (res.data.hasNext) {
                    this.hasNext = true
                }
            }
        }
    }
    showImg(isShow) {
        // return
        if (isShow) {
            document.getElementById('no_ques').style.display = 'block';
            document.getElementById('text_area').style.display = 'none';
            document.getElementById('answer_area').style.display = 'none';
            document.getElementById('analysis').style.display = 'none';
        } else {
            document.getElementById('no_ques').style.display = 'none';
            document.getElementById('text_area').style.display = 'block';
            document.getElementById('answer_area').style.display = 'flex';
        }

    }
    onResume() {
        Utils.setBack(false, '.52')
        Utils.setBg('#8E53D9')
    }
    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;
                const questionListIndex = this.questionList[this.quesIndex];
                if (questionListIndex.isAnswered || (questionListIndex.question && questionListIndex.question.isAnswered)) break;
                this.chooseAnswer(e.target.con.dataset.answer, e.target.con.dataset.index);
                break;
            case 'prev':
                // 上一题
                clickMp3();
                this.touchBtn('prev')
                if (this.quesIndex - 1 < 0) {
                    this.showTip('已经到头啦！')
                    return;
                }
                this.quesIndex--;
                this.renderQues(this.quesIndex)

                break;
            case 'next':
                // 下一题
                clickMp3();
                this.touchBtn('next')
                if (this.quesIndex + 2 === this.quesLength) {
                    if (this.hasNext) {
                        // 还有下一页
                        this.pageNum++;
                        this.getMistakeList()
                        // return
                    }
                } else if (this.quesIndex + 1 === this.quesLength) {
                    console.log('没有更多了！！！')
                    // 提交回答
                    this.submitRecord()
                    this.pageNum = 1;
                    this.showTip('已经到最后，没有更多啦！')
                    return
                }
                this.quesIndex++;
                this.renderQues(this.quesIndex)
                break;
            case 'analysis':
                clickMp3();
                if (this.analysisShow) {
                    this.renderQues(this.quesIndex)
                } else {
                    this.showAnalysis();
                }
                break;
            case 'back':
                clickMp3();
                this.hideScene();
                break;
        }
    }

    onBack(e) {
        Utils.setBack(true)
        clearTimeout(this.prevTime)
        clearTimeout(this.nextTime)
        clearTimeout(this.tipTime)
        let hideTime = new Date() - this.startTime;
    }

    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) {
        console.log('加载题目')
        clearTimeout(this.changingAnswer)

        this.analysisShow = false
        let obj = this.questionList[index];
        // 兼容知识竞赛错题本返回数据不同
        obj = obj.answer ? obj : obj.question;
        if (obj === undefined) return;
        this.target = obj.target;
        this.questionId = obj.id;
        document.getElementById('analysis').style.display = 'none';
        document.getElementById('text_area').style.display = 'block'
        this.hideAnswerIcon();

        if (obj.type === 'PICTURE') {
            document.getElementById('text_area').innerHTML = `
              <img src=${obj.image} class="ques_img" />
            `
        } else if(obj.type === 'BIG_PICTURE' || this.type === '2') {
          document.getElementById('text_area').innerHTML = `
            <img src=${obj.image} class="ques_big_img" />
          `
        } else {
            document.getElementById('text_area').innerHTML = obj.content;
        }
        // 删除已选答案
        this.removeClass();
        if(obj.type === 'BIG_PICTURE' || this.type === '2') {
          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: .1rem;left: 1.2rem;'
            if (index == 1) {
              item.querySelector('.right_wrong').style.left = '1.1rem'
            }
            if (index == 2) {
              item.querySelector('.right_wrong').style.left = '1.6rem'
            }
          })
          Utils.$('.text_area').style.height = '8rem'
          Utils.$('.answer_area').style = 'display: flex;width: 70%;margin: -1.8rem auto;'

        } else {
          this.answerA = obj.options.A;
          this.answerB = obj.options.B;
          this.answerC = obj.options.C;
          Array.from(document.querySelectorAll('.answer_item')).forEach(item => {
            item.style = '';
            item.querySelector('.answer_icon').style = '';
            item.querySelector('.right_wrong').style = '';
            item.querySelector('.answer_text').style = ''
          })
          Utils.$('.text_area').style.height = '5.8rem'
          Utils.$('.answer_area').style = 'display: flex;';
          document.getElementById('answer_a_text').innerHTML = this.wrapDiv(this.answerA);
          document.getElementById('answer_b_text').innerHTML = this.wrapDiv(this.answerB);
          document.getElementById('answer_c_text').innerHTML = this.wrapDiv(this.answerC);
        }
        this.analysisA = obj.analysisA;
        this.analysisB = obj.analysisB;
        this.analysisC = obj.analysisC;
        // 没有答过的题要刷新状态
        if (obj.answer === 'A') {
            document.getElementById('right_wrong_a').src = 'assets/mobile/correct.png';
        } else if (obj.answer === 'B') {
            document.getElementById('right_wrong_b').src = 'assets/mobile/correct.png';
        } else {
            document.getElementById('right_wrong_c').src = 'assets/mobile/correct.png';
        }

        let scrollImg = document.getElementById('scroll_analysis')

        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'
            }

            scrollImg.style.display = 'block'

            // 答过以后不允许再闪烁
            this.moye.root.getWidgetById('answer_a').disable();
            this.moye.root.getWidgetById('answer_b').disable();
            this.moye.root.getWidgetById('answer_c').disable();
        } else {
            // 答案弹出后只允许点击一次
            // this.answerOnceOnly = false;
            this.moye.root.getWidgetById('answer_a').enable();
            this.moye.root.getWidgetById('answer_b').enable();
            this.moye.root.getWidgetById('answer_c').enable();
            scrollImg.style.display = 'none'
        }
        scrollImg.style.left = null;
        scrollImg.style.right = '.5rem';
        scrollImg.style.background = "url('http://asxx-img.ai160.com/images/asxx/assets/pre/scroll_ana.gif') 0 0 / 100% 100% no-repeat";

        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();

    }

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

    onTouch(e) {}
    onTouchStart(e) {
        this.touchXStart = e.changedTouches[0].clientX
        this.touchYStart = e.changedTouches[0].clientY
    }
    onTouchEnd(e) {
        // 当前滑动手势，在黑板区域时，才会切换页面
        // 遍历e的路径，如果在黑板区域时就跳出遍历
        // 如果遍历不到就结束
        let myContinue = false;
        try {
            e.path.forEach(item => {
                if (item.className === 'lesson_main') {
                    throw new Error('go')
                } else {
                    return
                }
            })
        } catch (ee) {
            if (ee.message === 'go') {
                myContinue = true;
            }
        }
        if (!myContinue) return;
        // if (e.target.className !== 'text_area' && e.target.className !== 'ques_img' && e.target.className !== 'lesson_main' && e.target.className !== 'analysis_main') return;

        this.touchXEnd = e.changedTouches[0].clientX
        this.touchYEnd = e.changedTouches[0].clientY
        let xDistance = this.touchXEnd - this.touchXStart;
        let yDistance = this.touchYEnd - this.touchYStart;
        let XorY = Math.abs(xDistance) - Math.abs(yDistance);
        if (XorY > 0) {
            // 横轴移动
            let leftOrRight = this.touchXEnd - this.touchXStart;
            if (Math.abs(leftOrRight) < 200) return;
            if (leftOrRight < 0) {
                // 向右滑屏 切换解析
                this.showAnalysis();
            } else {
                // 向左滚屏 切换题目
                this.renderQues(this.quesIndex);

            }
        } else {
            // 竖轴移动
            let upOrDown = this.touchXEnd - this.touchXStart;

            if (Math.abs(upOrDown) < 200) return;
            if (upOrDown < 0) {
                // 向上滑屏
                console.log('向上滚屏')

            } else {
                // 向下滚屏
                console.log('向下')

            }
        }
    }
    onTouchMove(e) {
        console.log("onTouchMove", e.changedTouches[0].clientX)
    }

    // 记题板
    // 记录这道题是否答过，答对答错
    // type：是否作答
    // answerType： 答对答错
    // userOption: 用户作答选项
    recordHandler(type, answerType, userOption) {
        let currentQues = this.questionList[this.quesIndex]
        if(this.type === '2') {
            currentQues.question.isAnswered = type;
            currentQues.question.isCorrect = answerType;
            currentQues.question.userOption = userOption;
            let postData = {
                questionId: this.questionId,
                "questionAnswer": userOption,
            }
            postQuestion(postData).success(res => {
                console.log('发送答案', res)
                this.hasPostAnswer = true;
            })
        } else {
            currentQues.isAnswered = type;
            currentQues.isCorrect = answerType;
            currentQues.userOption = userOption;
            let postData = {
                "target": this.target,
                "answer": userOption,
                "lessonId": currentQues.lessonId,
            }
            // LessonApi.postMistakeAnswer(postData).success(res => {
            //     console.log('发送答案', res)
            // })
        }
    }
    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 || this.questionList[this.quesIndex].question.answer;
        if (option === correctAnswer) {
            // 答对逻辑
            // 记录答对答错
            rightMp3()
            this.recordHandler(true, true, option)
        } else {
            // 答错逻辑
            wrongMp3()
            this.recordHandler(true, false, option)
        }
        document.getElementById('scroll_analysis').style.display = 'block'
    }


    // 提交本次记录
    submitRecord() {
        // LessonApi.reviewSubmit({
        //     wareId: this.wareId,
        //     requestId: this.requestId
        // }).success(res => {
        //     console.log('提交', res)
        // })
    }
    // 隐藏答案图片
    hideAnswerIcon() {
        let list = Array.from(document.getElementsByClassName('right_wrong'));
        list.forEach(item => {
            item.src = 'assets/mobile/wrong.png'
            item.style.display = 'none'

        })
    }

    // 切换解析
    showAnalysis() {

        let obj = this.questionList[this.quesIndex]
        // 兼容知识竞赛错题本返回数据不同
        obj = obj.answer ? obj : obj.question;
        if (!obj.isAnswered) return
        if (this.analysisShow) return;
        this.analysisShow = true

        let scrollImg = document.getElementById('scroll_analysis')
        scrollImg.style.left = '.2rem';
        scrollImg.style.background = "url('http://asxx-img.ai160.com/images/asxx/assets/pre/scroll_que.gif') 0 0 / 100% 100% no-repeat";

        document.getElementById('text_area').style.display = 'none'
        document.getElementById('answer_area').style.display = 'none'
        document.getElementById('analysis').style.display = 'block';
        document.getElementById('user_answer').innerHTML = obj.userOption.toUpperCase();
        document.getElementById('correct_answer').innerHTML = obj.answer.toUpperCase();

        let objA = obj.commentA && JSON.parse(obj.commentA)
        let ifPictrue = false
        let imgBox = document.getElementById('analysis_img')
        let textBox = document.getElementById('analysis_con')
        if ((objA && objA.bgImg) || obj.analysis) {
          imgBox.style = `
          width: 13.3rem;
          height: 7.48rem;
          display: block;
          margin: 0px auto;`
          Utils.$('.answer_line').style = 'display: none;';
          Utils.$('.analysis_main').style = 'display: none;';

          imgBox.style.display = 'block';
          imgBox.style.margin = '0 auto';
          console.log(obj.userOption)
          if (this.type === '2') {
            imgBox.src = obj.analysis;
          } else {
            switch (obj.userOption) {
                case 'A':
                  imgBox.src = objA.bgImg;
                    break;
                case 'B':
                  imgBox.src = JSON.parse(obj.commentB).bgImg;
                    break;
                case 'C':
                  imgBox.src = JSON.parse(obj.commentC).bgImg;
                    break;
                default:
                    break;
            }
          }
        }else {
          imgBox.style = `
          width: 16.9rem;
          height: 5.52rem;
          display: block;
          margin: 0px auto;`
          Utils.$('.answer_line').style = '';
          Utils.$('.analysis_main').style = '';
          document.getElementById('user_answer').innerHTML = obj.userOption.toUpperCase();
          document.getElementById('correct_answer').innerHTML = obj.answer.toUpperCase();
          if (objA.img) {
              imgBox.style.display = 'block'
              document.getElementById('analysis_main').style.display = 'none';
              ifPictrue = true;
          } else {
              imgBox.style.display = 'none'
              document.getElementById('analysis_main').style.display = 'block';
          }
          // 播放解析语音
          console.log(obj.userOption)
          console.log(JSON.parse(obj.commentA))
          console.log(JSON.parse(obj.commentB))
          console.log(JSON.parse(obj.commentC))
          switch (obj.userOption) {
              case 'A':
                  ifPictrue ? imgBox.src = objA.img : textBox.innerHTML = objA.text
                  break;
              case 'B':
                  ifPictrue ? imgBox.src = JSON.parse(obj.commentB).img : textBox.innerHTML = JSON.parse(obj.commentB).text
                  break;
              case 'C':
                  ifPictrue ? imgBox.src = JSON.parse(obj.commentC).img : textBox.innerHTML = JSON.parse(obj.commentC).text

                  break;
              default:
                  break;
          }
        }
        // 是否显示按钮
        // if (obj.feature) {
        //     document.getElementById('analysis_btn').style.display = 'block';
        // }

    }

    aiHandle(name, slots) {

    }

    touchBtn(type) {
        if (type === 'next') {
            document.getElementById('next_final').className = 'next tap'
            clearTimeout(this.nextTime)

            this.nextTime = setTimeout(() => {
                document.getElementById('next_final').className = 'next'
            }, 210)
        } else {
            document.getElementById('prev_first').className = 'prev tap'
            clearTimeout(this.prevTime)
            this.prevTime = setTimeout(() => {
                document.getElementById('prev_first').className = 'prev'
            }, 210)
        }
    }
    showTip(text) {
        document.getElementById('tip_modal').innerText = text
        document.getElementById('tip_modal').style.display = 'block'
        clearTimeout(this.tipTime)
        this.tipTime = setTimeout(() => {
            document.getElementById('tip_modal').style.display = 'none'

        }, 1000)

    }
}

module.exports = errorScene;
