import React, { Component } from 'react'
import BoxContainer from '../box-container/container'
import { Toast, WhiteSpace } from "antd-mobile"
import { Popup } from "@common/index"
import { connect } from "react-redux"
import Prizes from "@components/activity/newyear-2019/common/prizes"
import BulletScreen from "@components/activity/newyear-2019/common/user-bullet-screen"
import './landing.scss'
import { browser, getParam, http, wxShare } from "@/utils"
import { Link } from "react-router-dom"
import QRCode from "qrcode"
import YearCourse from '../preheat/YearCourse'


class Landing extends Component {


  closeIcon = 'https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/newyear20/H5/close-btn.png'
  createTeamSuccessPopup = null
  joinSuccessPopup = null
  swiper = null

  state = {
    teamData: {
      member: []
    },
    origin: getParam('origin'),
    treasure_code: getParam('treasure_code'),
    activityEnd: false,
    notices: [],
    rule: '',
    isCaptain: getParam('origin') == 1
  }

  componentDidMount() {
    this.fetchPageData()
  }

  componentDidUpdate(prevProps) {
    if (prevProps.user.hasError !== this.props.user.hasError && !this.props.user.hasError) {
      this.fetchPageData()
    }
  }


  fetchPageData = ({origin = this.state.origin, treasure_code = this.state.treasure_code} = {}) => {
    http.post(`${API.home}/sys/treasure/team`, {
      treasure_code,
      origin
    })
      .then(res => {
        const {data, code, msg} = res.data
        if (code == 200) {

          this.setState({
            teamData: data,
            isCaptain: sessionStorage.getItem('isCaptain') ? sessionStorage.getItem('isCaptain') : getParam('origin') == 1
          })

          let searchParams = new URLSearchParams(window.location.search)
          if (searchParams.get('origin') === '1' && !browser.isWeixin) {
            searchParams.set('origin', '2')
            sessionStorage.setItem('isCaptain', '1')
            window.history.replaceState(null, '', `landing?${searchParams.toString()}`)
          }

          this.showSharePromptWithParam()


        } else if (code === 12005) {

          this.setState({
            activityEnd: true
          })

        } else {
          Toast.info(msg, 2, null, false)
        }
      })
  }

  showSharePromptWithParam = () => {
    if (sessionStorage.getItem('showShareTip')) {
      this.showShareTip()
    }
  }

  joinTeam = () => {
    if (this.requiredLogin()) {
      return
    }
    const {treasure_code} = this.state
    http.post(`${API.home}/sys/treasure/joinTeam`, {
      treasure_code
    })
      .then(res => {
        const {data, code, msg} = res.data
        if (code === 200) {

          /*
          *  status
          *  1-成功加入
          *  2-成功加入组队成功
          *  3-已加入当前队伍
          *  4-已加入其他队伍
          * */

          switch (data.status) {
            case 1:
            case 2:
              this.joinSuccess(data)
              break
            default:
              Toast.info(msg, 2, null, false)
          }

        } else {
          Toast.info(msg, 2, null, false)
        }
      })
  }

  joinSuccess = ({id, status, my_team: {team_num, lack_member, is_team, treasure_code}}) => {
    const {history} = this.props
    this.joinSuccessPopup = Popup({
      title: <div className={'join-success'}>
        <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/newyear20/H5/check-icon.png" alt=""/>
        <div>成功加入队伍</div>
      </div>,
      className: 'landing-join-success-wrapper',
      content: <div>
        <div className={'tip'}>
          {
            status === 2
              ? '组队成功，恭喜你获得一个宝箱！'
              : is_team
              ? <>您的{<span>{team_num}</span>}号队伍还差{<span>{lack_member}</span>}人即可获得宝箱</>
              : '自己当队长，宝箱内有专属奖品哦~'
          }
        </div>
        {
          status === 2
            ? <img style={{width: '150px', marginTop: '23px'}}
                   src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/newyear20/PC/treasure-box.png"
                   alt=""
                   onClick={() => {
                     history.push(`/year/yearTreasure?id=${id}`)
                   }}
            />
            : is_team
            ? <button type='button'
                      onClick={this.inviteMembers.bind(this, treasure_code)}>继续组队</button>
            : <button type="button" onClick={this.createMyTeam}>创建我的队伍</button>
        }
      </div>,
      closeIcon: this.closeIcon,
      close: () => {
        this.fetchPageData()
        this.getFollowStatus()
          .then(isFollow => {
            !isFollow && this.remind('join', getParam('treasure_code'))
          })
      }
    })
  }

  inviteMembers = treasure_code => {
    const {history, match, user, location} = this.props
    if (browser.isWeixin) {
      wxShare({
        title: `@${user.data.username} 邀您一起组队拿豪礼！`,
        desc: `加我我的队伍，机械键盘，纸质书籍等超多奖品等你拿！`,
        link: `${window.location.origin}/${location.pathname}?treasure_code=${treasure_code}&origin=2`,
        imgUrl: 'https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/newIndex/community/tou5_bj.png'
      })
    }
    sessionStorage.setItem('showShareTip', '1')
    history.replace(`${match.path}?treasure_code=${treasure_code}&origin=${1}`)
    this.createTeamSuccessPopup && this.createTeamSuccessPopup.remove() && (this.createTeamSuccessPopup = null)
    this.joinSuccessPopup && this.joinSuccessPopup.remove() && (this.joinSuccessPopup = null)
    this.fetchPageData({treasure_code, origin: 1})
    this.setState({
      isCaptain: true
    })
  }

  getFollowStatus = () => http.get(`${API.home}/sys/user/isFollowWeChat`)
    .then(res => {
      const {code, data} = res.data
      return code === 200 && data['is_follow']
    })

  createTeamSuccess = (member, team_num, lack_member, treasure_code) => {
    this.joinSuccessPopup && this.joinSuccessPopup.remove() && (this.joinSuccessPopup = null)
    this.getFollowStatus()
      .then(isFollow => {
        this.createTeamSuccessPopup = Popup({
          title: '创建成功',
          className: 'landing-create-success',
          content: <div>
            <div className="tip">{<span>{team_num}</span>}号队伍 还差{<span>{lack_member}</span>}名队员即可获得宝箱哦~</div>
            <img className={'treasure-box'}
                 src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/newyear20/H5/treasure-box-icon.png" alt=""/>
            <ul className='members'>
              {
                new Array(5).fill('a').map((item, index) => {
                  const _member = member[index]
                  return <li key={index}>
                    {_member && _member['is_captain'] && <sup>队长</sup>}
                    <img
                      className={'avatar'}
                      src={
                        _member
                          ? _member['head_img']
                          : "https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/newyear20/H5/not-joined-placeholder.png"
                      }
                      alt=""/>
                  </li>
                })
              }
            </ul>
            <button type={'button'} onClick={this.inviteMembers.bind(this, treasure_code)}>邀请好友加入队伍</button>
          </div>,
          closeIcon: this.closeIcon,
          afterClose: () => {
            if (!isFollow) {
              this.remind('create', treasure_code)
            }
          }
        })

      })
  }

  remind = (type = 'create', treasure_code) => {
    const {match, history, user} = this.props
    http.get(`${API["base-api"]}/wx/user_temporary_qrcode/${user.data.uid}`)
      .then(res => {
        const {data} = res.data
        return data.url
      })
    QRCode.toDataURL('http://m.julyedu.com')
      .then(url => {
        Popup({
          title: '提醒服务',
          className: 'landing-remind',
          closeIcon: this.closeIcon,
          content: <div>
            <div className="des">{type === 'create' ? '有好友加入队伍后第一时间通知我~' : '获得宝箱时第一时间通知我~'}</div>
            <img src={url} alt=""/>
            <div className="des">长按识别/扫码 关注【七月在线】服务号即可预约</div>
          </div>,
          close: () => {
            // history.replace(`${match.path}?treasure_code=${treasure_code}&origin=1`)
            this.fetchPageData({
              treasure_code,
              origin: '1'
            })
          }
        })
      })
  }

  unpackTreasureBox = () => {
    Popup({
      title: '恭喜你获得',
      className: 'landing-unpack-treasure-box',
      closeIcon: this.closeIcon,
      content: <div className='unpack-box-wrapper'>
        <div className="prize-wrapper">
          <img className='prize'
               src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1575544072904&di=474bca496055f1141a40ae2df45d1bbb&imgtype=0&src=http%3A%2F%2Fphotocdn.sohu.com%2F20110926%2FImg320518331.jpg"
               alt=""/>
        </div>
        <div className="prize-name">AI100题纸质书</div>
        <a className="delivery-info" href='javascript:;'>查看/修改收货信息</a>
        <ul className="members">
          {
            new Array(4).fill('a').map((item, index) => {
              return <li key={index}>
                <div className="avatar-wrapper">
                  {
                    index === 0 && <sup>队长</sup>
                  }
                  <img src="https://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/default/robot.png"
                       alt=""/>
                </div>
                <span className='prize-name'>AI100题纸质书</span>
              </li>
            })
          }
        </ul>
        <button>继续组队开宝箱</button>
      </div>
    })
  }

  showShareTip = () => {
    Popup({
      title: <div>还差<span>{this.state.teamData.lack_member}</span>名队友即可获得宝箱 快分享给好友吧~</div>,
      className: `landing-share-tip ${browser.isWeixin ? 'wechat' : ''}`,
      closable: false,
      close: () => {
        sessionStorage.removeItem('showShareTip')
        this.getFollowStatus()
          .then(isFollow => {
            !isFollow && this.remind('create', getParam('treasure_code'))
          })
      }
    })
  }

  showOpenInBrowserTip = () => {
    Popup({
      title: <div>点击右上角，选择“在浏览器打开”</div>,
      className: 'landing-open-in-browser-tip',
      closable: false,
    })
  }

  createMyTeam = () => {
    if (this.requiredLogin()) {
      return
    }
    http.get(`${API.home}/sys/treasure/createMyTeam`)
      .then(res => {
        const {data, code, msg} = res.data
        if (code == 200) {

          this.createTeamSuccess(data)

        } else {
          Toast.info(msg, 2, null, false)
        }
      })
  }

  requiredLogin = () => {
    const {history, user} = this.props

    if (user.hasError) {
      history.push('/passport')
      return true
    }
  }


  render() {
    const {
      teamData: {
        head_img,
        member,
        status,
        lack_member,
        team_num,
        prize_info,
        my_team
      },
      activityEnd,
      isCaptain
    } = this.state
    /*
    * status
    * 1-自己的队伍
    * 2-未加入队伍
    * 3-已加入当前队伍
    * 4-已加入别的队伍
    * */

    return (
      <div id={'landing'}>
        <div id="to-square">
          <Link to='/year/yearindex'>前往活动会场，享更多福利！ >></Link>
        </div>
        <BoxContainer>
          <i className="snow-deco"/>
          <img className='main-avatar'
               src={head_img} alt=""/>
          {
            status === 1
              ? <div className="des">邀请好友加入队伍，开宝箱领取丰厚奖品~</div>
              : <div className="des">加入我的<span>{team_num}</span>号队伍，一起开宝箱领取丰厚奖品~</div>
          }
          <Prizes showSystemNotices={false}/>
          <BulletScreen/>
          <div className="group">
            <ul className={'member'}>
              {
                member && member.length &&
                new Array(5).fill('a').map((item, index) => {
                  const _member = member[index]
                  return (
                    _member
                      ? <li key={index}>
                        <div className='avatar-wrapper'>
                          {
                            _member.is_captain ? <sup>队长</sup> : null
                          }
                          <img
                            src={_member.head_img}
                            alt=""
                            className="avatar"/>
                        </div>
                      </li>
                      :
                      <li key={index}>
                        <div className="avatar-wrapper">
                          <img
                            src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/newyear20/H5/default-member-avatar.png"
                            alt=""
                            className="avatar"/>
                        </div>
                      </li>
                  )
                })
              }
            </ul>
            <ul className={'bars'}>
              {
                member && member.length &&
                new Array(5).fill('a').map((item, index) => {
                  return (
                    <li key={index} className={`${index < member.length ? 'active' : ''}`}/>
                  )
                })
              }
            </ul>
            {
              status === 1 && !activityEnd &&
              <>
                <div className="group-des">
                  还差 {lack_member} 名队员即可获得当前宝箱哦~
                </div>
                <button type='button' className={'invite-btn'} onClick={this.showShareTip}>
                  邀请好友加入队伍
                </button>
              </>
            }
            {
              status === 3 && !activityEnd &&
              <>
                <div className="group-des">
                  <p>已加入当前队伍</p>
                  {
                    my_team['is_team']
                      ? <p>您的{my_team['team_num']}号队伍还差{my_team['lack_member']}人即可获得宝箱~</p>
                      : <p>自己当队长，宝箱内有专属奖品哦~</p>
                  }
                </div>
                {
                  my_team['is_team'] ?
                    <button type='button' className={'invite-btn'}
                            onClick={this.inviteMembers.bind(this, my_team['treasure_code'])}>
                      继续组队
                    </button>
                    : <button type='button' className={'invite-btn'} onClick={this.createMyTeam}>
                      创建我的队伍
                    </button>
                }
              </>
            }
            {
              status === 4 && !activityEnd &&
              <>
                <div className="group-des">
                  <p>已加入其他队伍</p>
                  {
                    my_team['is_team']
                      ? <p>您的{my_team['team_num']}号队伍还差{my_team['lack_member']}人即可获得宝箱~</p>
                      : <p>自己当队长，宝箱内有专属奖品哦~</p>
                  }
                </div>
                {
                  my_team['is_team'] ?
                    <button type='button' className={'invite-btn'}
                            onClick={this.inviteMembers.bind(this, my_team['treasure_code'])}>
                      继续组队
                    </button>
                    : <button type='button' className={'invite-btn'} onClick={this.createMyTeam}>
                      创建我的队伍
                    </button>
                }
              </>
            }
            {
              status === 2 && !activityEnd && < button type='button' className={'invite-btn'} onClick={this.joinTeam}>
                同意加入队伍
              </button>
            }
            {
              prize_info && prize_info.length !== 0 && !activityEnd && !isCaptain && <div className="certainly-prompt">
                第{prize_info[0].stage_no}次必中 {prize_info[0].name}
              </div>
            }
            {
              activityEnd &&
              <div className='activity-end'>
                <div>活动已结束</div>
                <div>关注【七月在线】服务号了解更多活动信息</div>
                <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/tinypng-common/right_weixin.png" alt=""/>
                <div>长按识别 / 微信扫码</div>
              </div>
            }
          </div>
        </BoxContainer>
        {
          !isCaptain &&
          <>
            <WhiteSpace size={'xl'}/>
            <YearCourse getSum={() => {
            }}/>
          </>
        }
      </div>
    )
  }
}

export default connect(
  state => ({user: state.user}),
  null
)(Landing)
