import React, { Component } from "react"
import "./index.scss"
import { HeaderBar } from "src/common/index"
import storage from "store2"
import { Toast } from "antd-mobile"
import { http } from "src/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.session.get("time") || { d: 0, h: 0, m: 0, s: 0 },
    answer: this.store.session.get("answer"),
    recordId: this.store.session.get("recordId"),
    analysis: [],
    results: [],
    elapsed: this.store.session.get("elapsed"),
  }

  componentDidMount() {
    if (isEmpty(this.state.answer) || !this.state.recordId) {
      this.props.history.replace("/ai-test")
      this.store.session.remove("submitted")
    }
    if (this.store.session.get("submitted")) {
      this.getAnalysis()
    } else {
      this.setCounter()
    }
  }

  componentWillUnmount() {
    clearInterval(this.timer)
  }

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

  submit = () => {
    const { answer, recordId } = this.state
    http
      .post(`${API.home}/sys/submit_answer`, {
        answer: JSON.stringify(answer),
        cost_time: this.state.elapsed * 10,
        record_id: recordId,
      })
      .then((res) => {
        const { code, msg } = res.data
        if (code === 200) {
          this.store.session.set("submitted", true)
          this.store.session.set("elapsed", this.state.elapsed)
          this.store.session.set("time", this.state.time)
          clearInterval(this.timer)
          this.props.history.push("/ai-test/report")
        } 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
