/* eslint-disable eqeqeq */
import React, { Component } from "react"
import "./index.scss"
import { Toast } from "antd-mobile"
import classnames from "classnames"
import { http } from "src/utils"
import { WithFullSize } from "src/HOCs"
import { Link } from "react-router-dom"
import { compose } from "redux"
import { connect } from "react-redux"
import {
  addData,
  ADD_RECOMMENDS,
  ADD_QUESTION,
  ADD_RESULT,
  REDO,
} from "./store/reducer"
import storage from "store2"

class Question extends Component {
  store = storage.namespace("anniversary2020")
  state = {
    question: {},
    result: {},
    recommends: [],
    selectedOptionId: 0,
    isShowConfirm: false,
    isResultConfirm: false,
    isTeamHead: this.props.match.params.isPractice == 1,
    isActivityEnd: false,
    is_correct: "",
    is_sign: "",
  }

  componentDidMount() {
    if (this.props.cache.recommends.length === 0) {
      this.getQuestion()
    }
  }

  getQuestion = () => {
    const isPractice = this.props.match.params.isPractice
    http
      .get(
        `${API.home}/activity/anniversary/get_question/${
          isPractice == 1 ? 1 : 2
        }`
      )
      .then((res) => {
        const { code, msg, data } = res.data
        if (code === 200) {
          this.props.addData({
            type: ADD_QUESTION,
            payload: data,
          })
        } else if (code === 25004) {
          const { history } = this.props
          let teamCode = this.store.session.get("team_code")
          if (teamCode) {
            history.push(`/anniversary_2020/invitation?team_code=${teamCode}`)
          } else {
            history.push(`/anniversary_2020`)
          }
        } else {
          Toast.info(msg)
        }
      })
  }

  select = (id) => {
    this.setState({
      selectedOptionId: id,
    })
  }

  submit = () => {
    const isPractice = this.props.match.params.isPractice
    const { selectedOptionId } = this.state
    http
      .post(`${API.home}/activity/anniversary/submit`, {
        type: isPractice == 1 ? 1 : 2,
        option_id: selectedOptionId,
        id: this.props.cache.question.id,
      })
      .then((res) => {
        const { code, msg, data } = res.data
        if (code === 200) {
          this.getRecommends(data.type_id)
          this.afterSubmitted(data)
          this.setState({
            isShowConfirm: false,
            isResultConfirm: isPractice != 1,
            selectedOptionId: undefined,
            is_correct: data.is_correct,
            is_sign: data.is_sign,
          })
          this.props.addData({
            payload: data,
            type: ADD_RESULT,
          })
        } else {
          Toast.info(msg)
        }
      })
  }

  resultFun = (e) => {
    const { history } = this.props
    let notNeedSign = e.target.getAttribute("data-sign") == 0
    console.log(notNeedSign)
    if (this.state.is_sign || notNeedSign) {
      history.push("/anniversary_2020#lottery")
    } else {
      http.get(`${API.home}/activity/anniversary/sign`).then((res) => {
        const { code, msg } = res.data
        if (code === 200) {
          Toast.info("签到成功 抽奖次数+1")
          history.push("/anniversary_2020")
        } else {
          Toast.info(msg)
        }
      })
    }
  }

  afterSubmitted = (result) => {
    const { isTeamHead } = this.state

    if (isTeamHead) {
      if (result.stage === 4) {
        this.setState({
          isActivityEnd: true,
        })
      } else {
        result.is_correct
          ? Toast.info("回答正确 抽奖次数+1")
          : Toast.info("很遗憾 回答错误")
      }
    }
  }

  getRecommends = (typeId) => {
    http
      .post(`${API.home}/sys/get_commend_course`, {
        type_id: typeId,
      })
      .then((res) => {
        const { code, data } = res.data
        if (code === 200) {
          this.props.addData({
            payload: data,
            type: ADD_RECOMMENDS,
          })
        }
      })
  }

  getOptionLabel = (index) => {
    return index >= 0 ? String.fromCharCode(65 + index) : "空"
  }

  redo = () => {
    this.props.addData({
      type: REDO,
    })
    this.getQuestion()
  }

  render() {
    const {
      selectedOptionId,
      isShowConfirm,
      isActivityEnd,
      isResultConfirm,
      isTeamHead,
    } = this.state

    const {
      cache: { question, result, recommends },
    } = this.props

    return (
      <div id={"question"}>
        <div className="banner"></div>
        <div className={"question"}>
          {question.ques && (
            <div
              className="topic"
              dangerouslySetInnerHTML={{ __html: question.ques }}
            ></div>
          )}
          <ul>
            {question.options &&
              !!question.options.length &&
              question.options.map((item, index) => {
                return (
                  <li
                    key={item.id}
                    className={classnames({
                      selected: selectedOptionId === item.id,
                      correct: result.right_id === item.id,
                      wrong:
                        !result.is_correct &&
                        parseInt(result.option_id) === item.id,
                    })}
                    onClick={this.select.bind(this, item.id)}
                  >
                    <span>{this.getOptionLabel(index)}</span>
                    {item.des}
                  </li>
                )
              })}
          </ul>
        </div>
        {result.analysis && (
          <div className="answered">
            <div className="analysis">
              <div className="estimate">
                您选择的是
                {this.getOptionLabel(
                  question.options.findIndex(
                    (item) => item.id == result.option_id
                  )
                )}
                ，正确答案是
                {this.getOptionLabel(
                  question.options.findIndex(
                    (item) => item.id === result.right_id
                  )
                )}{" "}
                回答{result.right_id == result.option_id ? "正确" : "错误 "}
              </div>
              <div className="analysis-content">
                <div className="title">
                  <i className={"icon"}></i>
                  解析
                </div>
                <div
                  className="content"
                  dangerouslySetInnerHTML={{ __html: result.analysis }}
                ></div>
              </div>
            </div>
            {!!recommends.length && (
              <Recommends recommends={recommends}></Recommends>
            )}
          </div>
        )}
        <div className="submit-bar">
          <BottomButton
            result={result}
            resultFun={this.resultFun}
            isTeamHead={isTeamHead}
            isActivityEnd={isActivityEnd}
            submit={() => {
              this.setState({
                isShowConfirm: true,
              })
            }}
            redo={this.redo}
          />
        </div>
        {isShowConfirm && (
          <Confirm
            submit={this.submit}
            cancel={() => {
              this.setState({
                isShowConfirm: false,
              })
            }}
          ></Confirm>
        )}
        {isResultConfirm && (
          <ResultConfirm
            resultFun={this.resultFun}
            is_correct={this.state.is_correct}
            is_sign={this.state.is_sign}
            close={() => {
              this.setState({ isResultConfirm: false })
            }}
          ></ResultConfirm>
        )}
      </div>
    )
  }
}

function ResultConfirm({ resultFun, is_correct, is_sign, close }) {
  return (
    <div className="modal-cover">
      <div className="modal">
        {is_correct === 1 && <div className="title">回答正确，抽奖次数+1</div>}
        {is_correct === 0 && (
          <div className="rusult-title">
            很遗憾，回答错误 <p>快去抽奖提提神吧</p>
          </div>
        )}

        <div className={"btm-button"}>
          <button onClick={resultFun} data-sign={(is_correct || is_sign) && 0}>
            {is_correct ? "去抽奖" : is_sign ? "去抽奖" : "签到领取抽奖机会"}
          </button>
        </div>
        <i className="close iconiconfront-2 iconfont" onClick={close}></i>
      </div>
    </div>
  )
}

function Confirm({ submit, cancel }) {
  return (
    <div className="modal-cover">
      <div className="modal">
        <div className="title">提交确认</div>
        <div className="btns">
          <button onClick={cancel}>取消</button>
          <button onClick={submit}>确认提交</button>
        </div>
      </div>
    </div>
  )
}

function BottomButton({
  resultFun,
  result,
  submit,
  isTeamHead,
  redo,
  isActivityEnd,
}) {
  if (result.stage === 4 || isActivityEnd) {
    return <button className={"activity-end"}>活动已结束</button>
  }
  if (isTeamHead) {
    if (result.analysis) {
      return result.practiceNum === 0 ? (
        <button className={"lottery-related"}>
          <Link to={`/anniversary_2020/invitation`}>组队答题抽奖</Link>
        </button>
      ) : (
        <button className={"submit"} onClick={redo}>
          继续答题
        </button>
      )
    } else {
      return (
        <button className={"submit"} onClick={submit}>
          提交
        </button>
      )
    }
  } else {
    if (result.analysis) {
      return !result.is_sign ? (
        <button className={"lottery-related"} onClick={resultFun}>
          签到领取抽奖机会
        </button>
      ) : (
        <button className={"submit"} onClick={resultFun} data-sign={"0"}>
          去抽奖
        </button>
      )
    }
    return (
      <button className={"submit"} onClick={submit}>
        提交
      </button>
    )
  }
}

function Recommends({ recommends }) {
  return (
    <div className="recommends">
      <div className="title">相关课程</div>
      <ul>
        {recommends &&
          !!recommends.length &&
          recommends.map((item) => {
            return (
              <li key={item.course_id}>
                <Link to={`/detail?id=${item.course_id}`}>
                  <img src={item.image_name} alt="" />
                </Link>
              </li>
            )
          })}
      </ul>
    </div>
  )
}

export default compose(
  WithFullSize,
  connect(
    ({ anniversary2020Question, user }) => ({
      cache: anniversary2020Question,
      user,
    }),
    (dispatch) => ({
      addData: (data) => dispatch(addData(data)),
    })
  )
)(Question)
