import React, { Component } from 'react'
import BoxContainer from '../box-container/container'
import { Toast } from "antd-mobile"
import { Popup } from "@common/index"
import cls from 'classnames'

import './landing.scss'
import { browser, getParam, http } from "@/utils"

class Landing extends Component {

  prizeBox
  prizeList
  bg
  innerBox
  closeIcon = 'https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/newyear20/H5/close-btn.png'

  state = {
    prizes: [
      {
        grant_max: 3,
        id: 3,
        img_name: "http://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/home/56b3777563.jpg",
        is_captain: 1,
        mode: 1,
        name: "测试1",
        stage_no: 0,
        surplus: 62,
      },
      {
        grant_max: 3,
        id: 3,
        img_name: "http://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/home/56b3777563.jpg",
        is_captain: 1,
        mode: 1,
        name: "测试1",
        stage_no: 0,
        surplus: 62,
      },
      {
        grant_max: 3,
        id: 3,
        img_name: "http://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/home/56b3777563.jpg",
        is_captain: 1,
        mode: 1,
        name: "测试1",
        stage_no: 0,
        surplus: 62,
      },
      {
        grant_max: 3,
        id: 3,
        img_name: "http://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/home/56b3777563.jpg",
        is_captain: 1,
        mode: 1,
        name: "测试1",
        stage_no: 0,
        surplus: 62,
      },
      {
        grant_max: 3,
        id: 3,
        img_name: "http://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/home/56b3777563.jpg",
        is_captain: 1,
        mode: 1,
        name: "测试1",
        stage_no: 0,
        surplus: 62,
      },
      {
        grant_max: 3,
        id: 3,
        img_name: "http://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/home/56b3777563.jpg",
        is_captain: 1,
        mode: 1,
        name: "测试1",
        stage_no: 0,
        surplus: 62,
      },
      {
        grant_max: 3,
        id: 3,
        img_name: "http://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/home/56b3777563.jpg",
        is_captain: 1,
        mode: 1,
        name: "测试1",
        stage_no: 0,
        surplus: 62,
      },
      {
        grant_max: 3,
        id: 3,
        img_name: "http://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/home/56b3777563.jpg",
        is_captain: 1,
        mode: 1,
        name: "测试1",
        stage_no: 0,
        surplus: 62,
      },
      {
        grant_max: 3,
        id: 3,
        img_name: "http://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/home/56b3777563.jpg",
        is_captain: 1,
        mode: 1,
        name: "测试1",
        stage_no: 0,
        surplus: 62,
      },
    ],
    unfoldList: false,
    teamData: {
      member: [
        {
          head_img: 'https://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/default/robot.png',
          is_captain: 1
        },
        {
          head_img: 'http://img2.imgtn.bdimg.com/it/u=2138045196,3587715336&fm=26&gp=0.jpg',
          is_captain: 0
        },

      ]
    },
    origin: getParam('origin'),
    treasure_code: getParam('treasure_code'),
    activityEnd: false
  }

  componentDidMount() {
    const {origin, treasure_code} = this.state
    http.get(`${API.home}/sys/prize_data`)
      .then(res => {
        const {data, code, msg} = res.data
        if (code == 200) {

        } else {
          Toast.info(msg, 2, null, false)
        }
      })
    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
          })

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

        } else if (code === 12005) {

          this.setState({
            activityEnd: true
          })

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


  }

  joinTeam = () => {
    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) {

          switch (data.status) {
            case 1:
            case 2:
              this.joinSuccess(data)
              break
            default:
              alert('aaa')
          }

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

  showRules = () => {
    Popup({
      title: '组队开宝箱活动规则',
      className: 'landing-treasure-rules',
      content: <ul>
        <li>1. 活动期间（12月18日-12月31日）可随时参与开宝箱；</li>
        <li>2. 当前队伍满员后可继续创建新队伍；</li>
        <li>3. 每人有一次机会加入好友的队伍；</li>
        <li>4. 队伍满员后所有成员均可随机获得宝箱内奖品，队长奖励更丰厚哦~</li>
        <li>5. 代金券、课程等虚拟奖品将直接发放至账户，实物奖品活动结束后统一邮寄；</li>
        <li>6. 现金可提现：我的 → 赚奖学金 → 提现。</li>
      </ul>,
      closeIcon: this.closeIcon
    })
  }

  showMore = () => {
    this.setState(prev => {
      if (this.state.unfoldList) {
        this.bg.style = this.innerBox.style = this.prizeBox.style = ''
      } else {
        let headHeight = parseFloat(getComputedStyle(this.prizeBox, ':before').getPropertyValue('height')),
          footerHeight = parseFloat(getComputedStyle(this.prizeBox, ':after').getPropertyValue('height')),
          innerOffsetTop = 0.12458,
          footerOffsetTop = 0.595,
          h = this.prizeList.scrollHeight,
          scrollListHeight = headHeight + h - (innerOffsetTop * headHeight) - (footerOffsetTop * footerHeight) + footerHeight

        this.prizeBox.style.height = `${scrollListHeight}px`
        this.innerBox.style.height = `${h}px`
        this.bg.style.height = `${h - footerHeight + innerOffsetTop * headHeight}px`
      }
      return {unfoldList: !prev.unfoldList}
    })

  }

  joinSuccess = ({status, team_num, lack_member, is_team}) => {
    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/H5/treasure-box-icon.png" alt=""/>
            : <button type="button">{is_team ? '继续组队' : '创建我的队伍'}</button>
        }
      </div>,
      closeIcon: this.closeIcon
    })
  }

  createTeamSuccess = ({head_img, team_num, lack_member, treasure_code}) => {
    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) => {
              return <li key={index}>
                {index === 0 && <sup>队长</sup>}
                <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/newyear20/H5/not-joined-placeholder.png"
                     alt=""/>
              </li>
            })
          }
        </ul>
        <button type={'button'}>邀请好友加入队伍</button>
      </div>,
      closeIcon: this.closeIcon
    })
  }

  remind = (type = 'create') => {
    Popup({
      title: '提醒服务',
      className: 'landing-remind',
      closeIcon: this.closeIcon,
      content: <div>
        <div className="des">{type === 'create' ? '有好友加入队伍后第一时间通知我~' : '获得宝箱时第一时间通知我~'}</div>
        <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/tinypng-common/right_weixin.png" alt=""/>
        <div className="des">长按识别/扫码 关注【七月在线】服务号即可预约</div>
      </div>
    })
  }

  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,
    })
  }

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

  createMyTeam = () => {
    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)
        }
      })
  }


  render() {
    const {
      teamData: {
        head_img,
        member,
        status,
        lack_member,
        team_num,
        prize_info,
        is_team
      }
    } = this.state
    return (
      <div id={'landing'}>
        <div id="to-square">
          前往活动会场，享更多福利！ >>
        </div>
        <BoxContainer>
          <i className="snow-deco"/>
          <img className='main-avatar'
               src={head_img} alt=""/>
          {
            status === 1 && <div className="des">邀请好友加入队伍，开宝箱领取丰厚奖品~</div>
          }
          {
            status === 2 || status === 3 && <div className="des">加入我的<span>{team_num}</span>号队伍，一起开宝箱领取丰厚奖品~</div>
          }
          <div className={'prizes-box'} ref={el => this.prizeBox = el}>
            <a href="javascript:;" className='rule-btn' onClick={this.showRules}>活动规则 > </a>
            <div className={`bg`} ref={el => this.bg = el}/>
            <div className={`inner-box`} ref={el => this.innerBox = el}>
              <ul className='prize-list' ref={el => this.prizeList = el}>
                {
                  this.state.prizes.map((item, index) => {
                    return (
                      <li key={index}>
                        <img src={item.img_name} alt=""/>
                      </li>
                    )
                  })
                }
              </ul>
            </div>
            <div className="show-more" onClick={this.showMore}>
              {
                this.state.unfoldList
                  ? <div>
                    收起
                    <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/newyear20/H5/fold-icon.png" alt=""/>
                  </div>
                  : <div>
                    查看全部奖品
                    <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/newyear20/H5/unfold-icon.png" alt=""/>
                  </div>
              }
            </div>
          </div>
          <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 && <div className="group-des">
                还差 {lack_member} 名队员即可获得当前宝箱哦~
              </div>
            }
            {
              status === 3 && <div className="group-des">
                <p>已加入当前队伍</p>
                {
                  is_team
                    ? <p>您的{team_num}号队伍还差{lack_member}人即可获得宝箱~</p>
                    : <p>自己当队长，宝箱内有专属奖品哦~</p>
                }

              </div>
            }
            {
              status === 1 &&
              <button type='button' className={'invite-btn'} onClick={this.showShareTip}>
                邀请好友加入队伍
              </button>
            }
            {
              status === 2 && < button type='button' className={'invite-btn'} onClick={this.joinTeam}>
                同意加入队伍
              </button>
            }
            {
              status === 3 && < button type='button' className={'invite-btn'} onClick={this.createMyTeam}>
                创建我的队伍
              </button>
            }
            {
              status === 2 && prize_info && <div className="certainly-prompt">
                第{prize_info.stage_no}次必中 {prize_info.name}
              </div>
            }
          </div>
        </BoxContainer>
      </div>
    )
  }
}

export default Landing
