import React, { Component } from "react"
import "./index.scss"
import { connect } from "react-redux"
import { compose } from "redux"
import { HeaderBar } from "src/common/index"
import { getParam, http, browser, wxShare } from "src/utils"
import { Toast } from "antd-mobile"
import { CopyToClipboard } from "react-copy-to-clipboard"
import { Link } from "react-router-dom"
import storage from "store2"
import { CaptchaAli } from "src/common/index"
import { showCaptchaModal } from "src/store/no-trace-validation/reducer"

class Invitation extends Component {
  store = storage.namespace("anniversary2020")
  state = {
    prizes: [],
    invitationInfo: {},
    inviteUid: getParam("invite_uid"),
    isShowGuide: false,
    teamInfo: {},
    isTeamHead: true,
    isMaster: !getParam("team_code"),
    isActivityEnd: false,
    instance: null,
    isShowCaptcha: false,
  }

  componentDidMount() {
    this.getPrizesInfo()
    if (getParam("team_code")) {
      this.getTeamInfo()
      this.store.session.set("team_code", getParam("team_code"))
    } else {
      this.getInvitationInfo()
    }
  }

  getPrizesInfo = () => {
    http.get(`${API.home}/activity/anniversary/prizeInfo`).then((res) => {
      const { code, msg, data } = res.data
      data.splice(4, 0, {})
      if (code === 200) {
        this.setState({
          prizes: data,
        })
      } else {
        Toast.info(msg)
      }
    })
  }

  getInvitationInfo = () => {
    http
      .get(`${API.home}/activity/anniversary/invite`, {
        params: {
          invite_uid: this.state.inviteUid || 0,
        },
      })
      .then((res) => {
        const { code, msg, data } = res.data
        if (code === 200) {
          this.setState({
            invitationInfo: data,
          })
        } else {
          Toast.info(msg)
        }
      })
  }

  getTeamInfo = () => {
    http
      .get(`${API.home}/activity/anniversary/assist`, {
        params: {
          team_code: getParam("team_code"),
        },
      })
      .then((res) => {
        const { code, msg, data } = res.data
        if (code === 200) {
          this.setState({
            teamInfo: data,
            isMaster: data.is_captain || !getParam("team_code"),
          })
          if (data.is_captain) {
            this.getInvitationInfo()
          }
        } else {
          Toast.info(msg)
        }
      })
      .catch((err) => {
        Toast.fail("请求过于频繁，请稍后再试")
      })
  }

  joinTeam = (data) => {
    const { user, history, noTraceValidation, showCaptchaModal } = this.props
    if (noTraceValidation.isNeedValidation) {
      !noTraceValidation.isShowCaptcha && showCaptchaModal()
      return
    }

    if (user.isFetching) {
      return
    }

    if (user.hasError) {
      if (browser.isWeixin) {
        window.location.href =
          "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx23dac6775ac82877&redirect_uri=" +
          encodeURIComponent(window.location.href + "&aa=bb").toLowerCase() +
          "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
      } else {
        history.push("/passport")
      }
      return
    }

    if (this.state.teamInfo.is_check && !this.state.isShowCaptcha) {
      this.setState({
        isShowCaptcha: true,
      })
      return
    }

    let _data = { team_code: getParam("team_code") }
    if (data.token && data.sig) {
      _data = { ..._data, ...data }
    }
    http
      .post(`${API.home}/activity/anniversary/joinTeam`, _data)
      .then((res) => {
        const { code, msg } = res.data
        if (code === 200) {
          Toast.info("加入成功", 2, null, false)
          this.setState((state, props) => {
            return {
              teamInfo: {
                ...state.teamInfo,
                ...{ status: 2, is_check: false },
              },
              isShowCaptcha: false,
            }
          })
        } else if (code === 5002) {
          this.state.instance && this.state.instance.reset()
        } else if (code === 25015) {
          this.setState({
            isActivityEnd: true,
          })
        } else {
          Toast.info(msg)
        }
      })
  }

  setupWechatShare = () => {
    wxShare({
      title: "答题抽华为P40 Pro+",
      desc:
        "这道题你会吗？答题抽奖，100%有奖的，能不能拿华为P40 Pro+，看你自己了--七月在线",
      link: `${API.m}${window.location.pathname}?team_code=${
        this.state.invitationInfo.team_code || getParam("team_code")
      }`,
      imgUrl:
        "https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/active20_717/m/share-icon.png",
    })
    this.setState({
      isShowGuide: true,
    })
  }

  // 答题抽奖
  drawQuestions = () => {
    const { history } = this.props
    history.push(`/anniversary_2020/question/${0}`)
  }

  render() {
    const {
      prizes,
      invitationInfo,
      isShowGuide,
      teamInfo,
      isMaster,
      isActivityEnd,
      isShowCaptcha,
    } = this.state
    const { location } = this.props

    return isShowCaptcha ? (
      <div className={"captcha-container"}>
        <div className={"tip"}>亲，系统正忙，滑动一下马上回来</div>
        <CaptchaAli
          getInstance={(instance) => {
            this.setState({
              instance,
            })
          }}
          onVerify={(data) => this.joinTeam(data)}
        />
      </div>
    ) : (
      <div id={"invitation"}>
        <HeaderBar
          title={"答题抽奖"}
          arrow={true}
          goBack={() => {
            this.props.history.push("/anniversary_2020")
          }}
        />
        {isMaster ? (
          <div className="banner"></div>
        ) : (
          <div className="team-head">
            <img src={teamInfo.avatar_file} alt="" />
            <div className="username">{teamInfo.user_name}</div>
            <div>加入我的队伍，一起答题抽大奖</div>
          </div>
        )}

        <div className="prize-container">
          <div className={"h-bar"}></div>
          <div className={"h-bar"}></div>
          <div className={"v-bar"}></div>
          <div className={"v-bar"}></div>
          <ul className="prizes">
            {!!prizes.length &&
              prizes.map((item, index) => {
                return (
                  <li key={index} className={index === 4 ? "empty" : ""}>
                    {index === 4 ? (
                      <div>答题抽奖</div>
                    ) : (
                      <div className={"prize"}>
                        <img src={item.img_name} alt="" />
                      </div>
                    )}
                  </li>
                )
              })}
          </ul>
        </div>
        {isShowGuide && (
          <div
            className="guide"
            onClick={() => {
              this.setState({
                isShowGuide: false,
              })
            }}
          >
            <i className={"indicator"}></i>
            <div className="tip">点击右上角，分享给好友</div>
          </div>
        )}
        <div className="op">
          {isMaster ? (
            <>
              <div className="tip">
                再有{invitationInfo.invite_num}位队员答对即可获得
                {invitationInfo.draw_chance}次抽奖机会
              </div>
              {browser.isWeixin ? (
                <button className={"btn"} onClick={this.setupWechatShare}>
                  立即邀请
                </button>
              ) : (
                <CopyToClipboard
                  text={`${API.m}${location.pathname}?team_code=${
                    invitationInfo.team_code || getParam("team_code")
                  }`}
                  onCopy={() => {
                    Toast.info("链接已复制，快去粘贴发给好友吧")
                  }}
                >
                  <button className={"btn"}>立即邀请</button>
                </CopyToClipboard>
              )}
            </>
          ) : (
            <>
              {teamInfo.status !== 1 && (
                <div className={"tip"}>
                  {teamInfo.status === 2
                    ? "已加入当前队伍"
                    : teamInfo.status === 3
                    ? "已加入其他队伍"
                    : null}
                </div>
              )}
              <BottomButton
                isActivityEnd={isActivityEnd}
                joinTeam={this.joinTeam}
                status={teamInfo.status}
                drawQuestions={this.drawQuestions}
                isAnswered={teamInfo.is_answer}
              />
            </>
          )}
        </div>
      </div>
    )
  }
}

function BottomButton({
  status,
  isActivityEnd,
  isAnswered,
  joinTeam,
  drawQuestions,
}) {
  if (isActivityEnd) {
    return <button className={"activity-end"}>活动结束</button>
  }
  if (isAnswered) {
    return (
      <Link to={`/anniversary_2020#lottery`}>
        <button className={"btn"}>去抽奖</button>
      </Link>
    )
  }
  return status === 1 ? (
    <button className={"btn"} onClick={joinTeam}>
      加入队伍
    </button>
  ) : (
    <button className={"btn"} onClick={drawQuestions}>
      答题抽奖
    </button>
  )
}

export default compose(
  connect(({ user, noTraceValidation }) => ({ user, noTraceValidation }), {
    showCaptchaModal,
  })
)(Invitation)
