import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './index.less';
import { Checkbox, Icon as AntDIcon } from 'antd';
import Assets from '@src/components/Assets';
import { formatSeconds, formatMinuteSecond, getMap } from '@src/services/Tools';
import Icon from '../../../../components/Icon';
import Button from '../../../../components/Button';
import Navigation from '../../../../components/Navigation';
import Answer from '../../../../components/Answer';
import Calculator from '../../../../components/Calculator';
import AnswerSelect from '../../../../components/AnswerSelect';
import AnswerTable from '../../../../components/AnswerTable';
import Editor from '../../../../components/Editor';
import { QuestionType, ExaminationOrder } from '../../../../../Constant';

const QuestionTypeMap = getMap(QuestionType, 'value');

export default class extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showTime: true,
      showNo: true,
      showCalculator: false,
      disorder: false,
      order: [],
      step: 0,
      answer: {},
      modal: null,
    };
  }

  onChangeQuestion(index, value) {
    const { question } = this.props;
    const { content } = question;
    const { answer = {} } = this.state;
    const type = content.type === 'double' ? 'double' : 'single';
    if (!answer.questions) {
      answer.questions = content.questions.map(() => {
        return {};
      });
    }
    answer.questions[index] = { [type]: value };
    console.log(answer);
    this.setState({ answer });
  }

  onChangeAwa(value) {
    const { answer = {} } = this.state;
    answer.awa = value;
    this.setState({ answer });
  }

  showConfirm(title, desc, width, cb) {
    this.showModal('confirm', title, desc, width, cb);
  }

  showToast(title, desc, width, cb) {
    this.showModal('toast', title, desc, width, cb);
  }

  showModal(type, title, desc, width, cb) {
    this.setState({ modal: { type, title, desc, width, cb } });
  }

  timeOut(cb) {
    this.showToast('Time Expired', 'Time has expired for this section. \n Click OK to continue.', 440, cb);
  }

  checkAnswer() {
    const { question } = this.props;
    const { answer } = this.state;
    let result = null;
    if (!answer) return this.showToast('Answer Required', 'You can not continue with this question unanswered. ', 430);
    if (question.questionType === 'awa' && !answer.awa) result = 'Please answer the question first.';
    if (result) return this.showToast(null, result);
    return true;
  }

  hideModal(b) {
    if (b) {
      const { modal = {} } = this.state;
      if (modal.cb) modal.cb();
    }
    this.setState({ modal: null });
  }

  formatStrem(text) {
    if (!text) return '';
    const { question = { content: {} } } = this.props;
    const { table = {}, questions = [] } = question.content;
    text = text.replace(/#select#/g, "<span class='#select#' />");
    text = text.replace(/#table#/g, "<span class='#table#' />");
    setTimeout(() => {
      const selectList = document.getElementsByClassName('#select#');
      const tableList = document.getElementsByClassName('#table#');
      for (let i = 0; i < selectList.length; i += 1) {
        if (!questions[i]) break;
        ReactDOM.render(
          <AnswerSelect list={questions[i].select} type={'single'} onChange={v => this.onChangeQuestion(i, v)} />,
          selectList[i],
        );
      }
      if (table.row && table.col && table.header) {
        const columns = table.header.map((title, index) => {
          return { title, key: index };
        });
        for (let i = 0; i < tableList.length; i += 1) {
          ReactDOM.render(<AnswerTable list={columns} columns={columns} data={table.data} />, tableList[i]);
        }
      }
    }, 1);
    return text;
  }

  next() {
    const { flow } = this.props;
    const { answer } = this.state;
    if (this.checkAnswer()) {
      this.showConfirm('Answer Confirmation', 'Click Yes to confirm your answer and continue to the next \n question. ', 560, () => {
        flow.submit(answer).then(() => {
          flow.next();
        });
      });
    }
  }

  render() {
    const { modal } = this.state;
    const { scene, paper } = this.props;
    let content = null;
    switch (scene) {
      case 'start':
        content = paper.paperModule === 'examination' ? this.renderExaminationStart() : this.renderExerciseStart();
        break;
      case 'relax':
        content = this.renderRelax();
        break;
      default:
        content = this.renderDetail();
        break;
    }
    return (
      <div id="paper-process-base">
        {content}
        {modal ? this.renderModal() : ''}
      </div>
    );
  }

  renderContent() {
    const { question = { content: {} } } = this.props;
    const { step } = this.state;
    const { steps = [] } = question.content;
    return (
      <div className="block block-content">
        {steps.length > 0 && (
          <Navigation
            theme="process"
            list={question.content.steps}
            active={step}
            onChange={v => this.setState({ step: v })}
          />
        )}
        <div
          className="text"
          dangerouslySetInnerHTML={{ __html: this.formatStrem(steps.length > 0 ? steps[step].stem : question.stem) }}
        />
      </div>
    );
  }

  renderAnswer() {
    const { question = { content: {} } } = this.props;
    const { questions = [], type } = question.content;
    if (type === 'inline') return '';
    return (
      <div className="block block-answer">
        {question.questionType === 'awa' && <Editor onChange={v => this.onChangeAwa(v)} />}
        {questions.map((item, index) => {
          return (
            <div>
              <div className="text m-b-2" dangerouslySetInnerHTML={{ __html: item.description }} />
              <Answer
                list={item.select}
                type={type}
                first={item.first}
                second={item.second}
                direction={item.direction}
                onChange={v => this.onChangeQuestion(index, v)}
              />
            </div>
          );
        })}
      </div>
    );
  }

  renderDetail() {
    const { paper, userQuestion, question = { content: {} }, singleTime, stageTime, flow } = this.props;
    if (!userQuestion.id) return null;
    const { showCalculator, showTime, showNo } = this.state;
    const { typeset = 'one' } = question.content;
    return (
      <div className="layout">
        <div className="fixed">
          {QuestionTypeMap[question.questionType].long}
          {question.questionType === 'ir' && (
            <Assets
              className="calculator-icon"
              name="calculator_icon"
              onClick={() => this.setState({ showCalculator: !showCalculator })}
            />
          )}
          {/* <Assets className="collect-icon" name="collect_icon" onClick={() => {
            flow.toggleCollect();
          }} /> */}
          <div className="collect-icon">
            <Icon name="star" active={userQuestion.collect} onClick={() => flow.toggleCollect()} />
          </div>
        </div>
        <Calculator show={showCalculator} />
        <div className="layout-header">
          <div className="title">{paper.title}</div>
          <div className="right">
            <div
              className="block"
              onClick={() => {
                this.setState({ showTime: !showTime });
              }}
            >
              <Assets name="timeleft_icon" />
              {showTime && stageTime && `Time left ${formatMinuteSecond(stageTime)}`}
              {showTime && !stageTime && singleTime && `Time cost ${formatMinuteSecond(singleTime)}`}
            </div>
            <div
              className="block"
              onClick={() => {
                this.setState({ showNo: !showNo });
              }}
            >
              <Assets name="subjectnumber_icon" />
              {showNo && `${userQuestion.no} of ${paper.questionNumber}`}
            </div>
          </div>
        </div>
        <div className={'layout-body'}>
          <div className={typeset}>
            {this.renderContent()}
            {this.renderAnswer()}
          </div>
        </div>
        <div className="layout-footer">
          <div className="help">
            <Assets name="help_icon" />
            Help
          </div>
          <div className="full">
            <Assets name="fullscreen_icon" onClick={() => flow.toggleFullscreen()} />
          </div>
          <div className="next" onClick={() => this.next()}>
            Next
            <Assets name="next_icon" />
          </div>
        </div>
      </div>
    );
  }

  renderExaminationStart() {
    // const { paper, userQuestion, singleTime, stageTime, flow } = this.props;
    const { showTime } = this.state;
    const { paper, flow, startTime } = this.props;
    return (
      <div className="layout">
        <div className="fixed" />
        <div className="layout-header">
          <div className="title">{paper.title}</div>
          <div className="right">
            <div
              className="block"
              onClick={() => {
                this.setState({ showTime: !showTime });
              }}
            >
              <Assets name="timeleft_icon" />
              {showTime && startTime && `Time left ${formatMinuteSecond(startTime)}`}
            </div>
            {/* <div
              className="block"
              onClick={() => {
                this.setState({ showNo: !showNo });
              }}
            >
              <Assets name="subjectnumber_icon" />
              {showNo && `${userQuestion.no} of ${paper.questionNumber}`}
            </div> */}
          </div>
        </div>
        <div className={'layout-body'}>{paper.isAdapt > 1 ? this.renderExaminationStartCAT() : this.renderExaminationStartDefault()}</div>
        <div className="layout-footer">
          <div className="help">
            <Assets name="help_icon" />
            Help
          </div>
          <div className="full">
            <Assets name="fullscreen_icon" onClick={() => flow.toggleFullscreen()} />
          </div>
          <div className="next" onClick={() => this.next()}>
            Next
            <Assets name="next_icon" />
          </div>
        </div>
      </div>
    );
  }

  renderExerciseStart() {
    const { paper, flow, setting } = this.props;
    const { disorder } = setting;
    return (
      <div className="start">
        <div className="bg" />
        <div className="fixed-content">
          <div className="title">{paper.title}</div>
          <div className="desc">
            <div className="block">
              <div className="desc-title">
                <Assets name="subject_icon" />
                题目总数
              </div>
              <div className="desc-info">{paper.questionNumber}</div>
            </div>
            <div className="block">
              <div className="desc-title">
                <Assets name="time_icon" />
                建议用时
              </div>
              <div className="desc-info">{formatSeconds(paper.time)}</div>
            </div>
          </div>
          {paper.finishTimes > 0 && <div className="tip">
            <Checkbox className="m-r-1" checked={!disorder} onChange={() => flow.setSetting({ disorder: !!disorder })} />
            题目选项乱序显示
          </div>}
          <div className="submit">
            <Button size="lager" radius onClick={() => flow.start({ disorder: paper.finishTimes > 0 ? !disorder : false })}>
              开始练习
            </Button>
          </div>
        </div>
      </div>
    );
  }

  renderExaminationStartCAT() {
    const { paper, flow, setting } = this.props;
    const { disorder, order, orderIndex } = setting;
    return (
      <div className="exercise-start default">
        <div className="title">Section Ordering</div>
        <div className="desc">Select the order in which the exam sections are to be administered.</div>
        <div className="desc tip">
          NOTE: You have 1 minutes to make your selection. If you do not make your selection within 1 minutes, the first
          option listed will be selected and you will view the exam in the following order: Analytical Writing
          Assessment, Integrated Reasoning, Quantitative, Verbal.
        </div>
        <div className="desc">
          Once you select your section order, you must view ALL questions in each section, in the order you have
          selected, before moving on to the next section. You will NOT be able to return to this screen.
        </div>
        <div className="block-list">
          {ExaminationOrder.map((row, index) => {
            return <div className="block-item">
              <div className="block-title" onClick={() => {
                flow.setSetting({ order: row.value, orderIndex: index });
              }}>
                <div className="block-title-border">
                  {orderIndex === index && <AntDIcon type="check" />}
                  <span>{row.label}</span>
                </div>
              </div>
              {row.list.map((r, i) => {
                return <div className="block-text">{i + 1}.{r.label} </div>;
              })}
            </div>;
          })}
        </div>
        <div className="bottom">
          {paper.finishTimes > 0 && <div className="text">
            <Checkbox checked={!disorder} onChange={() => flow.setSetting({ disorder: !!disorder })} /> 题目选项乱序显示
          </div>}
          <div className="text">
            Click{' '}
            <div className="next" onClick={() => flow.start({ disorder: paper.finishTimes > 0 ? !disorder : false, order })}>
              Next
              <Assets name="next_icon" />
            </div>{' '}
            button to start the exam. You will begin the GMAT exam on the next screen.{' '}
          </div>
        </div>
      </div>
    );
  }

  renderExaminationStartDefault() {
    const { paper, flow, setting } = this.props;
    const { disorder, order, orderIndex } = setting;
    return (
      <div className="exercise-start cat">
        <div className="title">Section Ordering</div>
        <div className="block-list">
          {ExaminationOrder.map((row, index) => {
            return <div className="block-item" onClick={() => {
              this.setState({ order: row.value, orderIndex: index });
            }}>
              <div className={orderIndex === index ? 'block-item-body active' : 'block-item-body'}>
                {orderIndex === index && <AntDIcon type="check" style={{ color: '#fff' }} />}
                {row.list.map((r, i) => {
                  return <div className="block-text" onClick={() => {
                    if (order.indexOf(r.value) > 0) {
                      // 取消
                      order[i] = '';
                    } else {
                      // 选中
                      order[i] = r.value;
                    }
                    flow.setSetting({ order });
                  }}>
                    <Checkbox checked={orderIndex === index ? order.indexOf(r.value) >= 0 : false} /> {r.label}{' '}
                  </div>;
                })}
              </div>
            </div>;
          })}
        </div>
        <div className="bottom">
          {paper.finishTimes > 0 && <div className="text">
            <Checkbox checked={!disorder} onChange={() => flow.setSetting({ disorder: !!disorder })} /> 题目选项乱序显示
          </div>}
          <div className="text">
            Click{' '}
            <div className="next" onClick={() => flow.start({ disorder: paper.finishTimes > 0 ? !disorder : false, order: order.filter(row => row) })}>
              Next
              <Assets name="next_icon" />
            </div>{' '}
            button to start the exam. You will begin the GMAT exam on the next screen.{' '}
          </div>
          <div className="text tip">*实战可选择考试顺序但无法选择考试内容。</div>
        </div>
      </div>
    );
  }

  renderRelax() {
    const { paper, stageTime, flow } = this.props;
    const { showTime } = this.state;
    return (
      <div className="layout">
        <div className="layout-header">
          <div className="title">{paper.title}</div>
          <div className="right">
            <div
              className="block"
              onClick={() => {
                this.setState({ showTime: !showTime });
              }}
            >
              <Assets name="timeleft_icon" />
              {showTime && stageTime && `Time left ${formatMinuteSecond(stageTime)}`}
              {/* {showTime && singleTime && `Time cost ${formatMinuteSecond(singleTime)}`} */}
            </div>
            {/* <div
              className="block"
              onClick={() => {
                this.setState({ showNo: !showNo });
              }}
            >
              <Assets name="subjectnumber_icon" />
              {showNo && `${userQuestion.no} of ${paper.questionNumber}`}
            </div> */}
          </div>
        </div>
        <div className={'layout-body'}>
          <div className="relax">
            <div className="title">
              Optional Break <Icon name="question" />
            </div>
            <div className="time" dangerouslySetInnerHTML={{ __html: formatMinuteSecond(stageTime).split(':').map(row => row.replace(/([0-9])/g, '<div class="block">$1</div>')).join('<div class="div">:</div>') }} />
          </div>
        </div>
        <div className="layout-footer">
          <div className="help">
            <Assets name="help_icon" />
            Help
          </div>
          <div className="full">
            <Assets name="fullscreen_icon" onClick={() => flow.toggleFullscreen()} />
          </div>
          <div className="next" onClick={() => this.next()}>
            Next
            <Assets name="next_icon" />
          </div>
        </div>
      </div>
    );
  }

  renderModal() {
    const { modal } = this.state;
    return (
      <div className="modal">
        <div className="mask" />
        <div style={{ width: modal.width }} className="body">
          <div className="title">{modal.title}</div>
          <div className="desc">{modal.desc}</div>
          {modal.type === 'confirm' ? (
            <div className="btn-list">
              <div className="btn" onClick={() => this.hideModal(true)}>
                <span className="t-d-l">Y</span>es
              </div>
              <div className="btn" onClick={() => this.hideModal(false)}>
                <span className="t-d-l">N</span>o
              </div>
            </div>
          ) : (<div className="btn-list">
            <div className="btn" onClick={() => this.hideModal(true)}>
              <span className="t-d-l">O</span>k
              </div>
          </div>)}
        </div>
      </div>
    );
  }
}