import React, { PureComponent } from "react"
import "./examination.scss"
import classnames from "classnames"

import { HeaderBar, Tag } from "../../common"
import OpenApp from "./OpenApp"
import { http } from "src/utils"
import { Object } from "core-js"

export default class Examination extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      isShowAnswer: false,
      questionData: {},
    }
  }

  componentDidMount() {
    http.get(`${API.home}/m/dailyQuestion`).then((res) => {
      const {
        data: { data, code },
      } = res
      if (code === 200) {
        const newData = Object.assign(data, {
          analysis: data.analysis.length > 0 ? data.analysis.split("\n") : [],
        })
        this.setState({
          questionData: newData,
        })
      }
    })
  }

  showAnswer = () => {
    this.setState({ isShowAnswer: !this.state.isShowAnswer })
  }

  render() {
    let {
      questionData: { ques, type_id, options, analysis, category },
      isShowAnswer,
    } = this.state
    return (
      <div className="examination">
        <HeaderBar title="每日一题" arrow={true} cart={false}></HeaderBar>
        <div className="question-container">
          <div className="topic">
            <Tag className="category-tag">{category}</Tag>
            <span dangerouslySetInnerHTML={{ __html: ques }} />
          </div>
          {type_id === 1 && (
            <MultiChoice
              className="options"
              options={options}
              showCorrect={this.state.isShowAnswer}
            />
          )}
          {!isShowAnswer && (
            <div className="show-answer" onClick={this.showAnswer}>
              <span>
                查看解析<i className="iconfont iconiconfront-69"></i>
              </span>
            </div>
          )}
        </div>
        {isShowAnswer && <Answer content={analysis} isShowAnswer />}
        <OpenApp />
      </div>
    )
  }
}

const MultiChoice = React.memo(({ options, showCorrect }) => {
  return (
    <ul className="options">
      {options.map((item, index) => (
        <li
          key={index}
          className={classnames("option", {
            active: item.is_ans === 1 && showCorrect,
          })}
        >
          <span className="alphabet">{String.fromCharCode(65 + index)}</span>
          {item.des}
        </li>
      ))}
    </ul>
  )
})

const Answer = React.memo(({ content, isShowAnswer }) => {
  return (
    <div className={classnames("answer", { scale: isShowAnswer })}>
      <p className="legend">解析</p>
      {content.length > 0 &&
        content.map((item, index) => (
          <p
            key={index}
            className="content"
            dangerouslySetInnerHTML={{ __html: item }}
          />
        ))}
    </div>
  )
})
