import React, { Component } from 'react';
import './index.scss'
import { WithFullSize } from "@/HOCs"
import { connect } from "react-redux";
import { compose } from "redux";
import { HeaderBar } from "@common/index"
import { getParam, http, browser, wxShare } from "@/utils"
import { Toast } from "antd-mobile";
import { CopyToClipboard } from "react-copy-to-clipboard";
import { Link } from 'react-router-dom'


class Invitation extends Component {

  state = {
    prizes: [],
    invitationInfo: {},
    inviteUid: getParam('invite_uid'),
    isShowGuide: false,
    teamInfo: {},
    isTeamHead: true,
    isMaster: !getParam('team_code'),
    isActivityEnd: false,
  }

  componentDidMount() {
    this.getPrizesInfo()
    if (getParam('team_code')) {
      this.getTeamInfo()
    } 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'),
          });
        } else {
          Toast.info(msg)
        }
      }).catch(err => {
      Toast.fail('请求过于频繁，请稍后再试')
    })
  }

  joinTeam = () => {
    const {user, history} = this.props
    if (user.hasError) {
      if (browser.isWeixin) {
        window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx23dac6775ac82877&redirect_uri=" + encodeURIComponent(url + "&aa=bb").toLowerCase() + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
      } else {
        history.push('/passport')
      }
      return
    }
    http.post(`${API.home}/activity/anniversary/joinTeam`, {
      team_code: getParam('team_code'),
    })
      .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}},
            }
          });

        } else if (code === 25015) {
          this.setState({
            isActivityEnd: true,
          });
        } else {
          Toast.info(msg)
        }
      })
  }

  setupWechatShare = () => {
    wxShare({
      title: '答题抽华为P40 Pro+',
      desc: '这道题你会吗？答题抽奖，100%有奖的，能不能拿华为P40 Pro+，看你自己了--七月在线',
      link: `${API.m}${location.pathname}?team_code=${this.state.invitationInfo.team_code || getParam('team_code')}`,
      imgUrl: '',
    })
    this.setState({
      isShowGuide: true,
    });
  }

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

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

    return (
      <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 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>
        {
          isShowGuide && <div className="guide" onClick={() => {
            this.setState({
              isShowGuide: false,
            });
          }}>
            <i className={'indicator'}></i>
            <div className="tip">点击右上角，分享给好友</div>
          </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(
  WithFullSize,
  connect(
    ({user}) => ({user}),
    null,
  ),
)(Invitation);