import React, { Component } from 'react';
import './index.scss'
import Container from '../container'
import classnames from 'classnames'
import { html } from "@/utils"

class SingleAnswerQuestion extends Component {

  icon = 'https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/interactive_tutorial/study/single-answer-icon.png'

  state = {
    correct: '',
    wrong: '',
    replies: [],
    selectable: false,
  }

  handleSelect = (info, index) => {
    if (!this.state.selectable) {
      return
    }

    const {question: {unit_questions}, updatePosition, resetStatus} = this.props
    const userSelect = unit_questions[index]
    this.setState({
      wrong: userSelect.is_ans ? '' : index,
      correct: userSelect.is_ans ? index : '',
      replies: info,
      selectable: false,
    }, () => {
      updatePosition()
      resetStatus()
    })
  }

  componentDidMount() {
    const {user_answer: userAnswer, unit_questions: options} = this.props.question
    if (userAnswer && userAnswer.answer) {
      const userSelectId = userAnswer.answer
      const userSelectIndex = options.findIndex(item => item.unit_id == userSelectId)
      const isUserCorrect = options[userSelectIndex].is_ans
      this.setState({
        correct: isUserCorrect ? userSelectIndex : '',
        wrong: isUserCorrect ? '' : userSelectIndex,
        replies: options[userSelectIndex].unit_info,
        selectable: false,
      })
    } else {
      this.setState({
        selectable: true,
      })
    }
  }


  render() {
    const {correct, wrong, replies} = this.state
    const {user, topic, img, question: {unit_questions: options}} = this.props
    return (
      <>
        <Container
          user={this.icon}
          content={
            <div className={'single-answer-question'}>
              <div className="topic" dangerouslySetInnerHTML={html(topic)}></div>
              {img && <img src={img} alt=""/>}
              <ul>
                {
                  options && !!options.length && options.map((item, index) => {
                    return <li
                      className={classnames(['option', {'correct': index === correct, 'wrong': index === wrong}])}
                      key={index}
                      onClick={this.handleSelect.bind(this, item.unit_info, index)}>{item.des}</li>
                  })
                }
              </ul>
            </div>
          }
        />
        {
          !!replies.length && replies.map(item => <Container key={item.info_id} content={item.content}/>)
        }
      </>
    );
  }
}

export default SingleAnswerQuestion;