import React, { Component } from 'react';
import './index.scss'
import { HeaderBar } from "src/common/index"
import Question from "src/components/ai-test/common/question"
import { html, http, browser } from "src/utils"
import { Toast } from "antd-mobile";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import Recommends from "src/components/ai-test/common/recommends"
import classnames from 'classnames'
import storage from 'store2'


class Assist extends Component {

  store = storage.namespace('aiTestAssist')

  state = {
    question: this.store.session.get('question'),
    answer: this.store.session.get('answer'),
    result: null,
    rightAnswer: '',
    userAnswer: '',
  }

  componentDidMount() {
    if (!this.store.session.get('question')) {
      this.getData()
    }
  }

  getData = () => {
    http.get(`${API.home}/sys/aitest/assist`)
      .then(res => {
        const {code, msg, data} = res.data
        if (code === 200) {
          const answer = {
            [data.id]: 0,
          }
          this.store.session.set('question', data)
          this.store.session.set('answer', answer)
          this.setState({
            question: data,
            answer,
          });
        } else {
          Toast.fail(msg, 2, null, false)
        }
      })
  }

  selectAnswer = (question, optionId) => {
    this.setState({
      answer: {
        [question.id]: optionId,
      },
    });
  }

  submit = () => {
    const {history, user} = this.props
    if (user.hasError) {
      if (browser.isWeixin) {
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx23dac6775ac82877&redirect_uri=${encodeURIComponent(`${window.location.origin}${location.pathname}?aa=bb`)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
      } else {
        history.push('/passport')
      }
      return
    }
    const {question, answer} = this.state
    if (!answer[question.id]) {
      Toast.info('请选择后进提交', 2, null, false)
      return
    }
    http.post(`${API.home}/sys/aitest/assistSubmit`, {
      code: this.props.match.params.assistCode,
      question_id: question.id,
      answer_id: answer[question.id],
    }).then(res => {
      const {code, msg, data} = res.data
      if (answer[question.id] === data.correct_answer) {
        Toast.info('回答正确', 2, null, false)
      } else {
        Toast.info('回答错误', 2, null, false)
      }
      this.setAnswer(data.correct_answer)
      if (code === 200) {
        this.setState({
          result: data,
        });
        this.store.session.clearAll()
      } else {
        Toast.fail(msg, 2, null, false)
      }
    })
  }

  setAnswer = (rightAnswerId) => {
    this.setState(state => {
      let rightAnswer = '', userAnswer = ''
      const question = {
        ...state.question, ...{
          options: state.question.options.map((item, index) => {
            if (item.id === rightAnswerId) {
              item.is_ans = 1
              rightAnswer = String.fromCharCode(65 + index)
            }
            if (item.id === state.answer[state.question.id]) {
              userAnswer = String.fromCharCode(65 + index)
              item.user_select = 1
            }
            return item
          }),
        },
      }
      return {
        question,
        rightAnswer,
        userAnswer,
      }
    });
  }

  render() {
    const {question, answer, result, rightAnswer, userAnswer} = this.state
    return (
      <div className={'assist'}>
        <HeaderBar title={'AI水平测试'} arrow={true}/>
        {
          question &&
          <Question question={question} category={'机器学习'} answer={answer} selectAnswer={!result && this.selectAnswer}/>
        }
        <div style={{height: '8px', backgroundColor: '#f5f5f5'}}></div>
        {
          result && <div className="content">
            <div
              className={'info'}>您的选择是{userAnswer}，正确答案是{rightAnswer} 回答{userAnswer === rightAnswer ? '正确' : '错误'}</div>
            <div className="head">
              <i className="icon"></i>
              <span>解析</span>
            </div>
            <div className="analysis-content" dangerouslySetInnerHTML={html(result.analysis)}></div>
          </div>
        }
        {
          result && question.commend_course && question.commend_course.length && <>
            <Recommends recommends={question.commend_course}/>
          </>
        }

        <div className="btns">
          {
            result && <div className={classnames(['status', {
              end: result.status === 6,
              success: result.status === 1,
              error: result.status === 2 || result.status === 3 || result.status === 4 || result.status === 5,
            }])}>
              {result.desc}
            </div>
          }
          {
            !result && <button className={'submit'} onClick={this.submit}>提交</button>
          }
          {
            result && (result.status === 6
              ? <Link to={'/'} className={'home'}>返回首页</Link>
              : <Link to={'/ai-test/scores'} className={'test'}>我也要测试</Link>)
          }
        </div>
      </div>
    );
  }
}

export default connect(
  ({user}) => ({user}),
  null,
)(Assist)