import {Component, EventEmitter, Output, ViewChild} from '@angular/core';
import {IonicPage, Nav, Navbar, NavController, NavParams, Slides, ToastController} from 'ionic-angular';
import {message} from "../../../../app/main";
import {AppGlobal, AppService} from "../../../../service/http.service";
import {LearningResultPage} from "../learning-result/learning-result";
import {LearnService} from "../learn.service";
import {DatePipe} from "@angular/common";
import {CommonService} from "../../../../provide/common.service";
import {ReviewResultPage} from "../review-result/review-result";
import {EmitService} from "../../../../provide/emit.service";

@IonicPage()
@Component({
    selector: 'page-learning-do',
    templateUrl: 'learning-do.html',
})
export class LearningDoPage {
    @ViewChild(Slides) slides: Slides;
    @ViewChild(Navbar) navbar:Navbar;

    type;   //是否重做
    title;  // 问卷标题
    recordId;  //试卷记录ID
    testId;   //试卷ID
    clock;  //倒计时的定时器
    list = [];
    timeText = '00:00:00';
    totalTime;
    index = 0;  //当前题目的序号
    useTime = 0;  //用时
    error = false;
    errorContent;   //纠错内容


    constructor(public navCtrl: NavController, public navParams: NavParams, private learnSer: LearnService, public commonSer: CommonService,
                public toastCtrl: ToastController, public appService: AppService, public datePipe: DatePipe,public eventEmitSer:EmitService,
                private nav:Nav) {
    }

    ionViewDidLoad() {
        this.eventEmitSer.eventEmit.emit('true');
        this.navbar.backButtonClick = () => {
            this.commonSer.alert("是否退出当前测试，中途退出直接交卷？", (res)=>{
                this.submit()
            })
        };
    }

    ionViewDidEnter() {
        // this.nav.swipeBackEnabled = false;
        this.testId = this.navParams.get('testId');
        this.title = this.navParams.get('title');
        this.type = this.navParams.get('type');
        const data = {
            testId: this.testId
        };
        this.learnSer.startTest(data).subscribe(
            (res) => {
                this.list = res.data.detailVos;
                this.recordId = res.data.recordId;
                this.list.forEach(e => e.answer = '');
                this.totalTime = res.data.timeLimit;
                this.countTime();
            }
        )
    }

    //清楚定时器
    ionViewDidLeave() {
        this.index = 0;
        this.slides.slideTo(0);
        window.clearInterval(this.clock);
    }

    //倒计时
    countTime() {
        let totalTime = this.totalTime;
        this.clock = window.setInterval(() => {
            totalTime--;
            this.useTime++;
            let hourse = (Math.floor(totalTime / 3600)).toString();
            hourse = (hourse.length > 1 ? hourse : '0' + hourse);
            let minutes = Math.floor(totalTime / 60).toString();
            minutes = (minutes.length > 1 ? minutes : '0' + minutes);
            let seconds = Math.floor(totalTime % 60).toString();
            seconds = (seconds.length > 1 ? seconds : '0' + seconds);
            this.timeText = hourse + ":" + minutes + ":" + seconds;
            if (totalTime < 0) {
                this.useTime = this.totalTime;
                window.clearInterval(this.clock)
                this.timeText = "00:00:00";
                this.forceSubmit();
            }
        }, 1000)
    }

    slideChanged(){
        this.index = this.slides.realIndex;
    }

    //上一题
    prev() {
        if (this.index == 0) {
            const toast = this.toastCtrl.create(message);
            toast.setMessage('已经是第一题哦');
            toast.present();
        } else {
            this.index -= 1;
            this.slides.slideTo(this.index)
        }
    }

    //下一题
    next() {
        if (this.index == this.list.length - 1) {
            const toast = this.toastCtrl.create(message);
            toast.setMessage('已经是最后一题了哦');
            toast.present();
        } else {
            this.index += 1;
            this.slides.slideTo(this.index)
        }
    }

    //多选
    mutiSelect(i, option) {
        if (this.list[i].answer.includes(option)) {
            this.list[i].answer = this.list[i].answer.replace(option, '');
        } else {
            this.list[i].answer += option + ";";
        }
    }

    //强制交卷
    forceSubmit() {
        this.appService.alert("答题时间已到，交卷！");
        this.submit();
        let index = this.navCtrl.length() - 2;
        this.navCtrl.remove(2, index)
    }

    //交卷
    handleSubmit() {
        let message = "确定交卷吗？";   //提示信息
        let number = 0;  //有number题未答
        this.list.forEach(e => {
            if (e.answer.length == 0) {
                number++;
            }
        });

        if (number > 0) {
            message = "您有" + number + "题未作答，确定交卷吗？";
        }
        this.appService.alert(message, () => {
            this.submit();
        })
    }

    //纠错
     sure(){
        const data = {
            questionId:this.list[this.index].questionId,
            questionType:this.list[this.index].questionType,
            content:this.errorContent
        };
        this.commonSer.log(data);
        this.learnSer.questionCorrecting(data).subscribe(
            (res)=>{
                this.commonSer.toast("提交成功！")
                this.error = false;
                this.errorContent = "";
            }
        )

     }

     cancel(){
         this.error = false;
         this.errorContent = "";
     }

    submit() {
        const data = {
            listMap: this.list.map(e => {
                if (e.answer.length > 1 && e.questionType == 2) {
                    e.answer = e.answer.substr(0, e.answer.length - 1);
                    e.answer = e.answer.split(";").sort().join(";");
                }
                const d = {
                    questionId: e.questionId,
                    questionType: e.questionType,
                    answer: e.answer
                };
                return d;
            }),
            recordId: this.recordId,
            answerTime: this.useTime,
        };
        this.learnSer.submitPaper(data).subscribe(
            (res) => {
                this.commonSer.toast("提交成功");
                if (this.type == 'reset') {
                    this.navCtrl.push("ReviewResultPage", {
                        testId:this.testId,
                        result: res.data,
                        title: this.title
                    })
                } else {
                    this.navCtrl.push("LearningResultPage", {
                        testId: this.testId,
                        title: this.title
                    })
                }
                this.eventEmitSer.eventEmit.emit('false');
            }
        )

    }

}
