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

import { Tag } from '../../common'
import OpenApp from './OpenApp'
import { http,api } from '@/utils'

export default class Examination extends PureComponent {

    constructor(props) {
        super(props)
        this.state = {
            isShowAnswer: false,
            questionData: {}
        }
    }

    componentDidMount() {
        http.get(`${API.home}/m/dailyQuestion`)
            .then(res => {
                this.setState({
                    questionData: res.data.data
                })
            })
    }

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

    render() {
        let {
            questionData: {
                ques, type_id, options, analysis, category
            },
            isShowAnswer
        } = this.state
        return (
            <div className='examination'>
                <div className="question-container">
                    <div className="topic">
                        <Tag className='category-tag'>{category}</Tag>
                        {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>
            <p className='content'>
                {content}
            </p>
        </div>
    )
})
