import {Component, 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/appHttpService";
import {LearningResultPage} from "../learning-result/learning-result";
import {LearnService} from "../learn.service";
import {DatePipe} from "@angular/common";
import {CommonService} from "../../../../service/common.service";
import {ReviewResultPage} from "../review-result/review-result";

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

    type;   //是否重做
    title;  // 问卷标题
    recordId;  //试卷记录ID
    testId;   //试卷ID
    clock;  //倒计时的定时器
    list = [];
    timeText = '00:00:00';
    totalTime;
    index = 0;  //当前题目的序号
    useTime = 0;  //用时
    constructor(public navCtrl: NavController, public navParams: NavParams, private learnSer: LearnService, public commonSer: CommonService,
                public toastCtrl: ToastController, public appService: AppService, public datePipe: DatePipe) {
    }

    ionViewDidLoad() {
        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.nav.swipeBackEnabled = true;
        this.index = 1;
        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)
    }

    //上一题
    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)
        }
    }

    //左划右划
    slideChanged() {
        this.index = this.slides.getActiveIndex();
    }

    //多选
    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();
        })
    }

    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", {
                        result: res.data,
                        title: this.title
                    })
                } else {
                    this.navCtrl.push("LearningResultPage", {
                        testId: this.testId,
                        title: this.title
                    })
                }
            }
        )

    }

}
