import React from 'react';
import Fullscreen from 'react-fullscreen-crossbrowser';
import './index.less';
import Page from '@src/containers/Page';
import { randomList, sortListWithOrder, resortListWithOrder } from '@src/services/Tools';
import { Question } from '../../../stores/question';
import Base from './base';
import Sentence from './sentence';
import { Main } from '../../../stores/main';
import { My } from '../../../stores/my';

export default class extends Page {
  init() {
    this.singleTime = null;
    this.singleInterval = null;

    this.stages = {};
    this.stage = '';
    this.stageInterval = null;
    this.stageTime = 0;
    this.stageNumber = 0;
    this.stageProcess = { number: 0, time: 0 };
    this.relaxProcess = { time: 0 };
  }

  initState() {
    return {
      setting: {},
      report: {},
      question: {},
      userQuestion: {},
      paper: {},
    };
  }

  initData() {
    const { type, id } = this.params;
    // type 是获取基础paper的表信息
    // 等同于PaperOrigin
    Question.getPaper(type, id).then(paper => {
      this.setState({ paper });
      let handler = null;
      if (paper.paperModule === 'examination') {
        // 模考获取配置信息
        handler = Main.getExaminationNumber().then((result) => {
          Object.keys(result).forEach((key) => {
            result[key].time = Number(result[key].time);
            result[key].number = Number(result[key].number);
          });
          this.stages = result;
          this.relaxProcess = { time: 8 * 60 };
        });
      } else {
        handler = Promise.resolve();
      }
      const { r } = this.state.search;
      if (r) {
        handler.then(() => {
          this.continue(r);
        });
      } else if (paper.paperModule === 'sentence') {
        // 长难句没有设置,直接开始
        handler.then(() => {
          this.start({});
        });
      } else {
        this.setState({ scene: 'start' });
      }
      handler.catch(() => {
        goBack();
      });
    });
  }

  start(setting) {
    const { type, id } = this.params;
    return Question.start(type, id, setting).then(report => {
      if (report.isFinish) {
        return this.finish();
      }
      this.setState({ report, scene: 'question' });
      // 开始统计做题进度
      if (report.paperModule === 'examination') {
        const { order } = setting;
        this.initStage(order[0], 0, 0);
      }
      return this.next();
    });
  }

  continue(reportId) {
    return Question.continue(reportId).then(report => {
      if (report.isFinish) {
        throw new Error('做题结束,请先重置');
      }
      this.setState({ report, scene: 'questionn' });
      // 更新当前做题进度
      if (report.paperModule === 'examination') {
        const { stage, time, number } = report.setting;
        this.initStage(stage, time[stage], number[stage]);
      }
      return this.next();
    }).catch(() => {
      Question.reportLink({ report: { id: reportId } });
    });
  }

  next() {
    const { report, scene } = this.state;
    const { setting = {} } = report;
    if (scene === 'relax') {
      this.nextStage();
    }
    return Question.next(report.id).then(userQuestion => {
      const questionSetting = {};
      if (setting.disorder) {
        const { questions } = userQuestion.question.content;
        if (questions) {
          // 乱序显示选项
          questionSetting.questions = [];
          questions.forEach((q) => {
            const order = randomList(q.select.length);
            q.select = sortListWithOrder(q.select, order);
            questionSetting.questions.push(order);
          });
        }
      }
      this.setState({
        userQuestion,
        question: userQuestion.question,
        questionSetting,
        scene: 'question',
      });
      this.singleQuestionTime();
      return true;
    }).catch((err) => {
      if (err.message === 'finish') {
        // 考试结束
        return this.finish();
      }
      return false;
    });
  }

  submit(answer) {
    const { report, userQuestion, questionSetting, singleTime } = this.state;
    const { setting = {} } = report;
    if (setting.disorder) {
      const { questions } = answer;
      if (questions) {
        // 还原乱序选项
        questions.forEach((q, index) => {
          const order = questionSetting.questions[index];
          Object.keys(q).forEach((k) => {
            if (q[k]) q[k] = resortListWithOrder(q[k], order);
          });
        });
      }
    }
    return Question.submit(userQuestion.id, answer, singleTime, questionSetting).then(() => {
      this.singleQuestionTime(true);
      // 更新模考做题进度
      if (report.paperModule === 'examination') {
        this.stageNumber += 1;
        if (this.stageNumber >= this.stageProcess.number) {
          // 进入休息
          this.relaxStage();
        }
      }
    });
  }

  stage() {
    const { report } = this.state;
    return Question.stage(report.id).then(() => {
      return this.next();
    }).then(() => {
      this.stageQuestionTime();
    });
  }

  finish() {
    const { report } = this.state;
    return Question.finish(report.id).then(() => {
      // 跳转到报告页
      Question.reportLink({ report });
      // this.setState({ scene: 'finish' });
    }).catch(() => {
      Question.reportLink({ report });
    });
  }

  singleQuestionTime(stop) {
    if (this.singleInterval) {
      clearInterval(this.singleInterval);
      this.singleInterval = null;
    }
    if (!stop) {
      this.singleTime = 0;
      this.singleInterval = setInterval(() => {
        this.singleTime += 1;
        this.setState({ singleTime: this.singleTime });
      }, 1000);
    }
  }

  stageQuestionTime(initTime) {
    if (this.stageInterval) {
      clearInterval(this.stageInterval);
      this.stageInterval = null;
      this.stageTime = initTime;
    }
    this.stageInterval = setInterval(() => {
      this.stageTime += 1;
      if (this.stageTime >= this.stageProcess.number) {
        this.nextStage();
      }
      this.setState({ stageTime: this.targetProcess.time - this.stageTime });
    }, 1000);
  }

  nextStage() {
    const { report } = this.state;
    // 进入下一阶段
    const { order } = report.setting;
    this.stage = order[order.indexOf(this.stage) + 1];
    this.stageProcess = this.stages[this.stage];
    this.stageNumber = 0;
    this.stageQuestionTime(0);
  }

  relaxStage() {
    this.stageProcess = this.relaxProcess;
    this.stageNumber = 0;
    this.stageQuestionTime(0);
    this.setState({
      scene: 'relax',
    });
  }

  initStage(stage, time, number) {
    this.stage = stage;
    this.stageProcess = this.stages[stage];
    this.stageTime = time;
    this.stageNumber = number;
    this.stageQuestionTime(time);
  }

  toggleFullscreen() {
    const { isFullscreenEnabled } = this.state;
    this.setState({ isFullscreenEnabled: !isFullscreenEnabled });
  }

  toggleCollect() {
    const { userQuestion = {} } = this.state;
    if (!userQuestion.collect) {
      My.addQuestionCollect(userQuestion.questionModule, userQuestion.questionNoId).then(() => {
        userQuestion.collect = true;
        this.setState({ userQuestion });
      });
    } else {
      My.delQuestionCollect(userQuestion.questionModule, userQuestion.questionNoId).then(() => {
        userQuestion.collect = false;
        this.setState({ userQuestion });
      });
    }
  }

  renderView() {
    return <Fullscreen
      enabled={this.state.isFullscreenEnabled}
      onChange={isFullscreenEnabled => this.setState({ isFullscreenEnabled })}
    >
      {this.renderDetail()}
    </Fullscreen>;
  }

  renderDetail() {
    const { scene, paper, userQuestion } = this.state;
    if (!paper.id || !scene) return null;
    switch (paper.paperModule) {
      case 'sentence':
        return <Sentence key={userQuestion.id} {...this.state} flow={this} />;
      default:
        return <Base key={userQuestion.id} {...this.state} flow={this} />;
    }
  }
}