import React, { Component } from 'react';
import './index.scss'
import { HeaderBar } from "@common/index"
import storage from 'store2'
import { Toast } from "antd-mobile";
import { http } from "@/utils"
import classnames from 'classnames'
import { Link } from "react-router-dom";
import { isEmpty } from 'lodash'


class SubmitAnswer extends Component {

  store = storage.namespace('aiTestExam')
  timer = null

  state = {
    time: this.store.get('time') || {d: 0, h: 0, m: 0, s: 0},
    answer: this.store.get('answer'),
    recordId: this.store.get('recordId'),
    analysis: [],
    results: [],
    elapsed: this.store.get('elapsed'),
  }

  componentDidMount() {
    this.setCounter()
    if (isEmpty(this.state.answer) || !this.state.recordId) {
      this.props.history.replace('/ai-test')
    }
  }

  componentWillUnmount() {
    clearInterval(this.timer)
  }


  setCounter = () => {
    this.timer = setInterval(() => {
      this.setState(state => {
        const s = state.elapsed + 1
        return {
          time: {
            d: Math.floor(s / (60 * 60 * 24)),
            h: Math.floor(s / (60 * 60)) % 24,
            m: Math.floor(s / 60) % 60,
            s: s % 60,
          },
          elapsed: s,
        }
      })
    }, 1000)
  }


  submit = () => {
    const {answer, recordId} = this.state
    http.post(`${API.home}/sys/submit_answer`, {
      answer: JSON.stringify(answer),
      cost_time: this.state.elapsed,
      record_id: recordId,
    }).then(res => {
      const {code, msg, data} = res.data
      if (code === 200) {
        this.store.clearAll()
        this.store.set('submitted', true)
        clearInterval(this.timer)
        this.getAnalysis()
      } else {
        Toast.fail(msg, 2, null, false)
      }
    })
  }

  getAnalysis = () => {
    http.post(`${API.home}/sys/get_analysis`, {
      record_id: this.state.recordId,
    }).then(res => {
      const {code, msg, data} = res.data
      if (code === 200) {
        this.setState({
          analysis: data,
        });
      } else {
        Toast.fail(msg, 2, null, false)
      }
    })
  }

  render() {
    const {time, answer, analysis, recordId} = this.state
    return (
      <div className={'submit-answer'}>
        <HeaderBar title={'提交试卷'} arrow={true}/>
        <div className="content">
          <div className="cost">用时：
            <span>
              {
                !!time.d && time.d
              }
              {
                !!time.h && <>{time.h && time.h.toString().padStart(2, '0')}:</>
              }
              {time.m.toString().padStart(2, '0')}:
              {time.s.toString().padStart(2, '0')}
            </span>
          </div>
          {
            analysis.length
              ? <>
                <ul className={'answers'}>
                  {
                    analysis.map((item, index) => {
                      const userSelectIndex = item.options.findIndex(item => item.user_select)
                      const rightAnswerIndex = item.options.findIndex(item => item.is_ans)
                      return <li key={item.id}
                                 className={classnames({
                                   correct: userSelectIndex === rightAnswerIndex,
                                   wrong: userSelectIndex >= 0 && userSelectIndex !== rightAnswerIndex,
                                   unselect: userSelectIndex < 0,
                                 })}>{index + 1}</li>
                    })
                  }
                </ul>
                {
                  !!analysis.length && <div className={'score'}>总分：{analysis[0].score}分</div>
                }
                <Link to={`/ai-test/analysis/${recordId}`}>
                  <button>查看解析</button>
                </Link>
              </>
              : <>
                <ul className={'answers'}>
                  {
                    answer && !!Object.keys(answer).length && Object.keys(answer).map((item, index) => {
                      return <li key={item} className={answer[item] ? 'selected' : ''}>{index + 1}</li>
                    })
                  }
                </ul>
                <button onClick={this.submit}>提交</button>
              </>
          }
        </div>
      </div>
    );
  }
}

export default SubmitAnswer;