import React, { Component } from "react"
import { getParam, http } from "src/utils"
import "./camp.scss"
import { connect } from "react-redux"
import { Header, CampTitle, TestItem, ChangeQuestion } from "./common/common"
import { Toast } from "antd-mobile"

class CampTest extends Component {
  constructor(props) {
    super(props)
    this.state = {
      examList: [], // 问题列表
      currentExam: {}, // 当前要展示的问题
      currentQuestionOption: {}, // 切换题目时 用来存储当前问题的选项
      questionIndex: 1, // 第几个问题
      numberList: [], // 答题的题号
      qtitle: "",
      useTime: "00:00",
      showCard: false,
    }
  }
  componentDidMount() {
    this.keshi_id = getParam("keshi_id")
    this.qidP = getParam("qid")
    let _this = this
    // 获取问题列表
    http
      .get(`${API.home}/m/aist/get_questions/${this.keshi_id}/${this.qidP}`)
      .then((res) => {
        if (res.data.code === 4040) {
          Toast.info(res.data.msg, 2, () => {
            this.props.history.push("/passport")
          })
          return
        } else if (res.data.code !== 200) {
          Toast.info(res.data.msg, 2, () => {
            this.props.history.push("/")
          })
          return
        }
        let data = res.data.data
        this.qid = data.id
        this.course_id = data.course_id
        this.setState({
          examList: data.list,
          qtitle: data.qtitle,
          currentExam: data.list[0],
        })
        _this.answerList = []
        data.list.forEach((item) => {
          let obj = {}
          obj.questionId = item.id
          obj.answerId = 0
          _this.answerList.push(obj)
        })
        _this.time = 0
        _this.useTimeInterval = setInterval(function () {
          _this.time += 1
          // _this.useTime = _this.getUseTime(_this.time);
          _this.setState({
            useTime: _this.getUseTime(_this.time),
          })
        }, 1000)
      })
  }
  // 关闭按钮
  close = () => {
    let isShow = this.state.showCard
    if (isShow) {
      this.setState({
        showCard: false,
      })
      this.body = document.getElementsByTagName("body")[0]
      this.body.style.position = "static"
    } else {
      const {
        history,
        location: { state = {} },
      } = this.props
      let to = ""
      if (state.from && state.from.indexOf("video") !== -1) {
        to = "detail"
      }
      if (state.from && state.from.indexOf("detail") !== -1) {
        to = "classify"
      }
      // console.log(this.props);
      history.push(`${state.from}`, {
        to,
      })
    }
  }
  // 选择答案
  checkOption = (checkItem) => {
    let list = this.state.numberList
    this.answerList.map(function (item) {
      if (Number(item.questionId) === Number(checkItem.ques_id)) {
        item.answerId = checkItem.opt_id
      }
      return item
    })
    list.push(checkItem.ques_id)
    this.setState({
      currentQuestionOption: checkItem.opt_id,
      numberList: list,
    })
  }
  // 上一题
  preQuestion = () => {
    let index = this.state.questionIndex
    if (index === 1) {
      return
    }
    this.setState({
      questionIndex: index - 1,
      currentExam: this.state.examList[index - 2],
      currentQuestionOption: this.answerList[index - 2].answerId,
    })
  }
  // 下一题
  nextQuestion = () => {
    let index = this.state.questionIndex
    if (index === this.state.examList.length) {
      this.setState({
        showCard: true,
      })
      return
    }
    this.setState({
      questionIndex: index + 1,
      currentExam: this.state.examList[index],
      currentQuestionOption: this.answerList[index].answerId,
    })
  }
  // 通过答题卡的卡号跳转到对应的题目
  jumpItem = (item, index) => {
    this.setState({
      showCard: false,
      questionIndex: index + 1,
      currentExam: this.state.examList[index],
      currentQuestionOption: this.answerList[index].answerId,
    })
  }
  // 提交
  commit = () => {
    let data = {}
    data.video_id = this.keshi_id
    data.qid = this.qid
    data.cost_time = this.time
    data.uid = this.props.user.data.uid
    data.answer_record = this.answerList
    http.post(`${API.home}/m/aist/submit`, data).then((res) => {
      if (res.data.code === 200) {
        this.body = document.getElementsByTagName("body")[0]
        this.body.style.position = "static"
        this.props.history.push(
          `/campResolve?keshi_id=${this.keshi_id}&qid=${this.qid}`,
          { from: this.props.location.state.from }
        )
      } else {
        Toast.info(res.data.msg, 2)
      }
    })
  }
  // 显示答题卡
  showCard = () => {
    this.setState({
      showCard: true,
    })
    this.body = document.getElementsByTagName("body")[0]
    this.body.style.position = "fixed"
  }
  // 答题用时的格式化
  getUseTime = (date) => {
    let hours = 0,
      minutes = 0,
      seconds = 0
    hours = `${parseInt(date / (60 * 60))}`.padStart(2, 0)
    minutes = `${parseInt((date - hours * 3600) / 60)}`.padStart(2, 0)
    seconds = `${parseInt(date - hours * 3600 - minutes * 60)}`.padStart(2, 0)
    if (date === 3600 * 24) {
      clearInterval(this.useTimeInterval)
      this.useTimeInterval = null
    } else {
      if (date < 3600) {
        return `${minutes}:${seconds}`
      } else {
        return `${hours}:${minutes}:${seconds}`
      }
    }
  }

  render() {
    let {
      qtitle,
      currentExam,
      currentQuestionOption,
      questionIndex,
      examList,
      useTime,
      showCard,
      numberList,
    } = this.state
    return (
      <div className="camp-test-container">
        <div className={"fixed_container"}>
          {/*关闭按钮 时间 答题卡*/}
          <Header
            time={useTime}
            showCardEve={this.showCard}
            close={this.close}
            showCard={showCard}
          />

          {/*课后练习题 当前题目 题目总数*/}
          <CampTitle
            qtitle={qtitle}
            questionIndex={questionIndex}
            examList={examList}
          />
        </div>

        {/*题目*/}
        <TestItem
          questionIndex={questionIndex}
          checkOption={this.checkOption}
          currentExam={currentExam}
          currentQuestionOption={currentQuestionOption}
        />
        {/*切换题目*/}
        <ChangeQuestion
          preQuestion={this.preQuestion}
          nextQuestion={this.nextQuestion}
          questionIndex={questionIndex}
        />
        {/* 答题卡 */}
        {showCard && (
          <div className="test-card-container">
            <p>{`课后练习：${qtitle}`}</p>
            <ul className={"test-item"}>
              {examList.map((item, index) => {
                return (
                  <li
                    key={item.id}
                    onClick={() => {
                      this.jumpItem(item, index)
                    }}
                    className={`layout-flex-center ${
                      numberList.includes(item.id) ? "answered" : ""
                    }`}
                  >
                    {index + 1}
                  </li>
                )
              })}
            </ul>
            <div className={"bottom_commit"}>
              <div
                onClick={this.commit}
                className={"commit_answer layout-flex-center"}
              >
                提交并查看结果
              </div>
            </div>
          </div>
        )}
      </div>
    )
  }
}

export default connect((state) => ({ user: state.user }), null)(CampTest)
