import React, { Component } from 'react';
import { debounce, groupBy, isEmpty } from "lodash";
import { browser, http } from "@/utils"
import { Toast, Carousel } from "antd-mobile";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import './index.scss'
import { Popup } from "@common/index"
import classnames from 'classnames'
import tweenFunctions from 'tween-functions'
import storage from 'store2'


class Anniversary2020 extends Component {

  nav = null
  store = storage.namespace('anniversary2020')
  stages = {
    1: '基础',
    2: '进阶',
    3: '高阶',
    4: '拓展',
  }
  stageParams = ['one', 'two', 'three', 'four']
  records = null
  answerRule = `
  1.邀请好友加入队伍，好友答对题你和好友均可增加抽奖机会
  2.每增加3个队员答对题，你可以增加N次抽奖机会，N=1 ,2, 3 (有3个队员答对题，你可+1次抽奖机会；6个队员答对题，你再+2次抽奖机会，超过6个队员答对题时，每+3人答对题都可+3次抽奖机会)
  3.被邀请好友答对题TA可+1次抽奖机会
  4.每人只能当1次队员哦
  `
  drawTimer = null
  hasMore = true

  state = {
    //静态数据
    navs: [
      {
        text: '一分拼团',
        id: '#group',
      },
      {
        text: '抽华为P40Pro+',
        id: '#lottery',
      },
      {
        text: '组队答题',
        id: '#group-answer',
      },
      {
        text: '免费试听',
        id: '#audition',
      },
      {
        text: '冰点秒杀',
        id: '#stage-course',
      },
    ],
    titleImages: [
      require('../images/title_1.png'),
      require('../images/title_2.png'),
      require('../images/title_3.png'),
      require('../images/title_4.png'),
      require('../images/title_5.png'),
    ],
    rankIcons: [
      require('../images/rank1.png'),
      require('../images/rank2.png'),
      require('../images/rank3.png'),
    ],
    navActive: 0,
    sectionsPosition: [],
    //课程
    auditions: [],
    auditionShowAll: false,
    group: [],
    groupShowAll: false,
    stageCourses: [],
    activityData: {},
    team: {},
    rankList: [],
    isShowAllRankList: false,
    qrcode: undefined,
    //弹框
    userAddress: {
      name: '',
      phone: '',
      address: '',
    },
    isShowUserAddress: false,
    isShowPrizesRecords: false,
    isWinPrize: false, //抽中奖品弹框
    isShowTeamMember: false,
    isShowFollow: false,
    //抽奖
    prizeData: {},
    drawOrder: [0, 1, 2, 5, 8, 7, 6, 3],
    drawItemIds: [],
    drawingItemId: undefined,
    isDrawing: false,
    drawResult: {},
    prizeRecords: [],
    prizeRecordsPagination: 0,
    bulletScreenList: [],
  }

  componentDidMount() {
    this.getActivityStage()
    this.getTeam()
    this.getUserAddress()
    this.getPrizeData()
    this.getAuditionCourses()
    this.getGroupCourses()
    this.getBulletScreenData()
    this.getRankList()
    this.getStageCourses('zero')
    if (this.store.session.get('toInvitation') && !this.props.user.hasError) {
      this.getFollowStaus()
      this.store.session.remove('toInvitation')
    }
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.navActive !== this.state.navActive) {
      this.showActiveNav()
    }
  }

  componentWillUnmount() {
    document.removeEventListener('scroll', this.setNavActive)
    document.body.style.overflow = 'auto'
    clearInterval(this.drawTimer)
  }

  getActivityStage = () => {
    http.get(`${API.home}/activity/anniversary/activityStage`)
      .then(res => {
        const {code, msg, data} = res.data

        if (code === 200) {
          this.setState({
            activityData: data,
          }, this.bindNavAction);
        } else {
          Toast.info(msg)
        }
      })
  }

  getAuditionCourses = () => {
    http.get(`${API.home}/activity/anniversary/big_course`)
      .then(res => {
        const {code, msg, data} = res.data
        if (code === 200) {
          this.setState({
            auditions: data,
          }, this.bindNavAction);
        } else {
          Toast.info(msg)
        }
        return 1
      })
  }

  getGroupCourses = () => {
    http.get(`${API.home}/activity/anniversary/point_course`)
      .then(res => {
        const {code, msg, data} = res.data
        if (code === 200) {
          this.setState({
            group: data,
          });
        } else {
          Toast.info(msg)
        }
      })
  }

  getStageCourses = (key) => {
    http.get(`${API.home}/activity/anniversary/four_stage/${key}`)
      .then(res => {
        const {code, msg, data} = res.data

        if (code === 200) {
          this.setState(state => {
            if (key === 'zero') {
              return {
                stageCourses: groupBy(data, item => {
                  return item.stage
                }),
              }
            } else {
              const index = this.stageParams.findIndex(item => item === key) + 1
              state.stageCourses[index] = data
              return {
                stageCourses: state.stageCourses,
              }
            }
          }, this.bindNavAction)
        } else {
          Toast.info(msg)
        }
      })
  }

  getPrizeData = () => {
    http.get(`${API.home}/activity/anniversary/prize_data`)
      .then(res => {
        const {code, msg, data} = res.data
        data.prizes.splice(4, 0, {})
        if (code === 200) {
          this.setState({
            prizeData: data,
            drawItemIds: this.state.drawOrder.map(order => ({itemId: data.prizes[order].id})),
          })
        } else {
          Toast.info(msg)
        }
      })
  }

  getRankList = () => {
    http.get(`${API.home}/activity/anniversary/team_ranks`)
      .then(res => {
        const {code, msg, data} = res.data
        if (code === 200) {
          this.setState({
            rankList: data,
          });
        } else {
          Toast.info(msg)
        }
      })
  }

  getTeam = () => {
    http.get(`${API.home}/activity/anniversary/teamInfo`)
      .then(res => {
        const {code, msg, data} = res.data
        if (code === 200) {
          this.setState({
            team: data,
          }, this.bindNavAction);
        } else {
          Toast.info(msg)
        }
      })
  }

  getPrizeRecords = (() => {
    let  isFetching = false
    return () => {
      if (isFetching || !this.hasMore) {
        return
      }
      isFetching = true
      http.get(`${API.home}/activity/anniversary/user_prizes/${this.state.prizeRecordsPagination}`)
        .then(res => {
          const {code, msg, data} = res.data
          if (code === 200) {
            if (isEmpty(data)) {
              this.hasMore = false
            }
            const _records = Array.isArray(data) ? data : []
            this.setState(state => {
              return {
                prizeRecords: [...state.prizeRecords, ..._records],
                prizeRecordsPagination: state.prizeRecordsPagination + 1,
              }
            }, () => {
              setTimeout(() => {
                isFetching = false
              }, 100)
            });
          } else {
            Toast.info(msg)
          }
        })
    }
  })()

  handleRecordsScroll = debounce((e) => {
    let scrollTop = e.target.scrollTop, scrollHeight = e.target.scrollHeight, height = e.target.clientHeight
    if (scrollTop > scrollHeight - height - 120) {
      this.getPrizeRecords()
    }
  }, 16)

  handleChange = e => {
    let name = e.target.name, value = e.target.value
    this.setState(state => {
      return {
        userAddress: {...state.userAddress, ...{[name]: value}},
      }
    });
  }

  submitUserAddress = () => {
    http.post(`${API.home}/sys/update_address`, this.state.userAddress)
      .then(res => {
        const {code, msg} = res.data
        if (code === 200) {
          Toast.info('提交成功')
          this.setState({
            isShowUserAddress: false,
          });
        } else {
          Toast.info(msg)
        }
      })
  }

  getUserAddress = () => {
    http.get(`${API.home}/sys/user_address_info`)
      .then(res => {
        const {code, msg, data} = res.data
        if (code === 200) {
          this.setState({
            userAddress: data,
          });
        }
      })
  }

  bindNavAction = () => {
    document.removeEventListener('scroll', this.setNavActive)
    this.setNavActive()
    this.setState({
      sectionsPosition: this.state.navs.map(item => {
        const el = document.querySelector(item.id)
        return {
          top: el.offsetTop - 50,
          height: el.offsetHeight,
        }
      }),
    }, () => {
      const {hash} = this.props.location
      if (hash) {
        const index = this.state.navs.findIndex(item => item.id === hash)
        window.scrollTo(0, this.state.sectionsPosition[index].top)
      }
      document.removeEventListener('scroll', this.setNavActive)
      document.addEventListener('scroll', this.setNavActive)
    })
  }

  getFollowStaus = () => {
    http.get(`${API.home}/sys/user/isFollowWeChat`)
      .then(res => {
        const {code, data} = res.data
        if (code === 200) {
          if (!data.is_follow) {
            this.getQRCode()
          }
          this.setState({
            isShowFollow: !data.is_follow,
          });
        }
      })
  }

  getQRCode = () => {
    http.get(`${API["base-api"]}/wx/user_temporary_qrcode/${this.props.user.data.uid}`)
      .then(res => {
        const {code, msg, data} = res.data
        if (code === 200) {
          this.setState({
            qrcode: data.qr_image,
          });
        } else {
          Toast.info(msg)
        }
      })
  }

  setNavActive = debounce(() => {
    const {navActive, sectionsPosition} = this.state
    const pageY = window.pageYOffset
    for (let i = navActive; i < sectionsPosition.length; i++) {
      const section = sectionsPosition[i]
      const nextSection = sectionsPosition[i + 1]
      const prevSection = i > 0 && sectionsPosition[i - 1]

      if (pageY > section.top + section.height && nextSection) {
        if (pageY < nextSection.top || pageY < nextSection.top + nextSection.height) {
          this.setState({
            navActive: i + 1,
          });
          break
        }
      } else {
        if (pageY < section.top + section.height && prevSection && pageY < prevSection.top + prevSection.height) {
          this.setState({
            navActive: i - 1 ? i - 1 : 0,
          })
          break
        }
      }
    }
  }, 1000 / 60)

  showRule = (content) => {
    this.popupInstance = Popup({
      className: 'rule-popup',
      title: '活动规则',
      content,
    })
  }

  showActiveNav = () => {
    const listItems = this.nav.querySelectorAll('li')
    const activeItem = listItems[this.state.navActive]
    const box = activeItem.getBoundingClientRect()
    let offsetWidth = this.nav.offsetWidth, scrollLeft = this.nav.scrollLeft
    if (box.left < 0) {
      this.nav.scrollLeft = box.left
    } else if (box.right > offsetWidth + scrollLeft) {
      this.nav.scrollLeft = box.right
    }
  }

  draw = debounce((i) => {
    const {activityData, prizeData, isDrawing} = this.state
    if (i !== 4 || isDrawing || prizeData.odd_times === 0 || activityData.stage === 4) {
      return
    }
    this.startDraw()
    this.requestDraw()
  }, 100)

  requestDraw = () => {
    http.get(`${API.home}/activity/anniversary/draw_lottery`)
      .then(res => {
        const {code, msg, data} = res.data
        if (code === 200) {
          this.setState((state, props) => {
            let oddTimes = state.prizeData.odd_times
            return {
              prizeData: {...state.prizeData, ...{odd_times: oddTimes - 1 < 0 ? 0 : oddTimes - 1}},
            }
          });
          setTimeout(() => {
            this.setState({
              drawResult: data,
            });
          }, 3000)
        } else {
          Toast.info(msg)
        }
      }).catch(e => {
      Toast.fail('操作频繁，请稍后再试')
    })
  }

  startDraw = () => {
    let index = 0
    this.setState({
      isDrawing: true,
    });
    this.drawTimer = setInterval(() => {
      const {drawItemIds, drawResult} = this.state
      if (drawResult.id && drawItemIds[index % drawItemIds.length].itemId === drawResult.id) {
        clearInterval(this.drawTimer)
        this.setState({
          isWinPrize: true,
          isDrawing: false,
        });
      }
      this.setState({
        drawingItemId: drawItemIds[(index++) % drawItemIds.length].itemId,
      });
    }, 100)
  }

  sign = () => {
    if (this.isGotoLogin()) {
      return
    }
    http.get(`${API.home}/activity/anniversary/sign`)
      .then(res => {
        const {code, msg} = res.data
        if (code === 200) {
          Toast.info('签到成功 抽奖次数+1')
          this.setState((state, props) => {
            return {
              prizeData: {...state.prizeData, ...{odd_times: state.prizeData.odd_times + 1}},
              activityData: {...state.activity_stage, ...{is_sign: true}},
            }
          });
        } else {
          Toast.info(msg)
        }
      })
  }

  isGotoLogin = () => {
    const {user, history} = this.props
    if (user.hasError) {
      history.push('/passport')
      return true
    }
    return false
  }

  getBulletScreenData = () => {
    http.get(`${API.home}/activity/anniversary/barrages`)
      .then(res => {
        const {code, msg, data} = res.data
        if (code === 200) {
          this.setState((state, props) => {
            return {
              bulletScreenList: state.bulletScreenList.concat(data),
            }
          });

        } else {
          Toast.info(msg)
        }
      })
  }

  handleBulletScreenChange = (from, to) => {
    if (to >= this.state.bulletScreenList.length - 5) {
      this.getBulletScreenData()
    }
  }

  render() {
    const {
      navs,
      navActive,
      titleImages,
      rankIcons,
      auditions,
      auditionShowAll,
      group,
      groupShowAll,
      stageCourses,
      activityData,
      team,
      userAddress,
      isShowUserAddress,
      prizeData,
      isShowPrizesRecords,
      prizeRecords,
      isWinPrize,
      drawingItemId,
      drawResult,
      isShowTeamMember,
      bulletScreenList,
      rankList,
      isShowAllRankList,
      isShowFollow,
      qrcode,
    } = this.state
    const {history, user} = this.props

    const _auditions = auditionShowAll && auditions.length ? auditions : auditions.slice(0, 4)
    const _group = groupShowAll && group.length ? group : group.slice(0, 4)
    const _rankList = isShowAllRankList ? rankList : rankList.slice(0, 10)

    return (
      <div className={'anniversary-2020'}>
        <div className="banner">
          <img src="" alt=""/>
        </div>
        {
          !activityData.is_sign && <div className="sign" onClick={this.sign}></div>
        }
        <nav ref={el => this.nav = el}>
          <ul>
            {
              navs.map((item, index) => {
                return <li key={index} className={index === navActive ? 'active' : ''}>
                  <a href='javascript:void(0);' onClick={() => {
                    this.setState({
                      navActive: index,
                    });
                    window.scrollTo(0, this.state.sectionsPosition[index].top)
                  }}>{item.text}</a>
                </li>
              })
            }
          </ul>
        </nav>
        <section id={'group'} className="group block">
          <h2 className="block-title"
              style={{background: `url(${titleImages[0]}) no-repeat`, backgroundSize: 'contain'}}></h2>
          <ul className={'course-container'}>
            {
              !!_group.length && _group.map((item, index) => {
                let Button
                if (activityData.stage === 1) {
                  Button = <button className={'unavailable'}>7月15日开始</button>
                } else if (activityData.stage === 2) {
                  switch (item.is_assemble) {
                    case 0:
                      Button = <button className="main"><Link to={`/detail?id=${item.course_id}`}>立即拼团</Link></button>
                      break
                    case 1:
                      Button = <button className="main"><Link to={`/detail?id=${item.course_id}`}>继续拼团</Link></button>
                      break
                    default:
                      Button =
                        <button className={'study'}><Link to={`/play?id=${item.v_course_id}`}>开始学习</Link></button>
                  }
                } else {
                  Button = <button className={'unavailable'}>活动已结束</button>
                }
                return <li className={'course'} key={index} onClick={(e) => {
                  let nodeName = e.target.nodeName.toLowerCase()
                  if (nodeName !== 'a' || nodeName !== 'button') {
                    history.push(`/detail?id=${item.course_id}`)
                  }
                }}>
                  <div className="cover">
                    <img src={item.image_name}
                         alt=""/>
                  </div>
                  <div className="info">
                    <div className="title">{item.course_title}</div>
                    <div className="des">{item.simpledescription}</div>
                    {
                      item.is_buy
                        ? <div className="purchased">已购买</div>
                        : <div className="prices">
                          <span>¥{item.price1}</span>
                          <span>¥{item.price0}</span>
                        </div>
                    }
                    <div className="btn">
                      {Button}
                    </div>
                  </div>
                </li>
              })
            }
            {
              group.length > 4 &&
              <li>
                <button className={'show-more'} onClick={() => {
                  this.setState({
                    groupShowAll: true,
                  })
                }}>查看更多
                </button>
              </li>
            }
          </ul>
        </section>
        <section id={'lottery'} className={'lottery block'}>
          <div className="block-title"
               style={{background: `url(${titleImages[1]}) no-repeat`, backgroundSize: 'contain'}}></div>
          <div className="rule">
            <a href="javascript:void(0);" onClick={this.showRule.bind(this, prizeData.rule)}>规则</a>
          </div>
          <div className="prize-container">
            {
              !!bulletScreenList.length && activityData.stage === 2 &&
              <Carousel
                dragging={false}
                swiping={false}
                dots={false}
                speed={200}
                autoplayInterval={3000}
                easing={tweenFunctions.easeOutCubic}
                vertical
                autoplay
                infinite
                beforeChange={this.handleBulletScreenChange}
              >
                {
                  bulletScreenList.map((item, index) => {
                    return <div key={index} className={'bullet'}>{item}</div>
                  })
                }
              </Carousel>
            }
            <div className="prize-wrapper">
              <div className={'h-bar'}></div>
              <div className={'h-bar'}></div>
              <div className={'v-bar'}></div>
              <div className={'v-bar'}></div>
              <ul className="prizes">
                {
                  prizeData.prizes && !!prizeData.prizes.length && prizeData.prizes.map((item, index) => {
                    return <li key={index}
                               className={classnames([
                                 index === 4 ? (prizeData.odd_times ? 'available' : 'unavailable') : '',
                                 {
                                   active: drawingItemId === item.id,
                                 },
                               ])} onClick={this.draw.bind(this, index)}>
                      {
                        index !== 4
                          ? <div className={'prize'}>
                            <img src={item.img_name} alt=""/>
                          </div>
                          : activityData.stage === 1 ?
                          <div className={'draw'} style={{lineHeight: '350%'}}>7月15日开始</div> : <div className={'draw'}>
                            <div>抽奖</div>
                            <div>剩余{prizeData.odd_times || 0}次机会</div>
                          </div>
                      }
                    </li>
                  })
                }
              </ul>
            </div>
          </div>
          <div className="content">
            <div className={'operations'}>
              <a href="javascript:void(0);" onClick={() => {
                if(user.hasError){
                  return history.push('/passport')
                }
                this.setState({
                  isShowUserAddress: true,
                })
              }}>收货信息</a>
              <a href="javascript:void(0);" onClick={() => {
                if (this.isGotoLogin()) {
                  return
                }
                document.body.style.overflow = 'hidden'
                this.getPrizeRecords()
                this.setState({
                  isShowPrizesRecords: true,
                }, () => {
                  this.records && this.records.addEventListener('scroll', this.handleRecordsScroll)
                });
              }}>中奖纪录</a>
            </div>
            <div className="lottery-info">
              <div className={'title'}><i></i>如何获取更多抽奖机会？</div>
              <ul className={'rules'}>
                {
                  prizeData.more_rule && prizeData.more_rule.split('\n').map((item, index) => {
                    return <li key={index}>
                      <span className={'index'}>{index + 1}</span>
                      {item}
                    </li>
                  })
                }
              </ul>
            </div>
          </div>
        </section>
        <section id={'group-answer'} className={'group-answer block'}>
          <div className="block-title" style={{background: `url(${titleImages[2]})`, backgroundSize: 'contain'}}></div>
          <div style={{textAlign: 'center', marginBottom: '10px'}}>
            <a className="rule-btn" href="javascript:void(0);"
               onClick={this.showRule.bind(this, this.answerRule)}>规则</a>
          </div>
          <div className="content">
            <div className="team">
              <div className="func">
                <i className={'my-team-icon'}></i>
                <div className="summary">
                  <span>共<span className={'count'}>{team.people_num}</span>人</span>
                  <span>排名<span className={'count'}>{team.ranking}</span></span>
                </div>
                <ul>
                  {
                    !!team.team_info && team.team_info.length && team.team_info.slice(0, 5).map((item, index) => {
                      return <li key={index}>
                        <img
                          src="https://julyedu-img-public.oss-cn-beijing.aliyuncs.com/Public/Image/home/avatar_20191104.png"
                          alt=""/>
                      </li>
                    })
                  }
                  {
                    activityData.stage !== 1
                    && !!team.team_info && team.team_info.length > 1
                    && <li className={'more'} onClick={() => {
                      this.setState({
                        isShowTeamMember: true,
                      });
                    }}>更多</li>
                  }
                </ul>
                <div className="invite">
                  {
                    activityData.stage === 1 ? <button className={'invite'}>7月15日开始</button> :
                      <Link to={'/anniversary_2020/invitation'} onClick={(e) => {
                        if (user.hasError) {
                          e.preventDefault()
                          history.push('/passport')
                        } else {
                          this.store.session.set('toInvitation', '1')
                        }
                      }}>
                        <button className={'invite'}>邀请好友加入队伍</button>
                      </Link>
                  }
                </div>
              </div>
              <div className="des">
                <div className="title">组队答题抽奖</div>
                <ol>
                  <li>
                    1. 邀请好友加入队伍，好友答对题可获得一次抽奖机会；
                  </li>
                  <li>
                    2. 每3个队员答对题，你可以获得N次抽奖机会，N=1，2，3（上限）。
                  </li>
                </ol>
              </div>
            </div>
            <div className="exercise">
              <div className="func">
                {
                  activityData.stage === 1
                    ? <div className="btn">
                      <button>7月15日开始</button>
                    </div>
                    : <>
                      {
                        activityData.practice_num
                          ? <Link to={'/anniversary_2020/question/1'} onClick={(e) => {
                            if (user.hasError) {
                              e.preventDefault()
                              history.push('/passport')
                            }
                          }}>
                            <div className="btn">
                              <button><i></i>开始练习</button>
                            </div>
                          </Link>
                          : <div className="btn no-chance">
                            <button><i></i>开始练习</button>
                          </div>
                      }
                      {
                        !user.hasError && <div className="chance">今日剩余<span>{activityData.practice_num}</span>次</div>
                      }
                    </>
                }
              </div>
              <div className="des">
                <div className="title">练一练</div>
                <ol>
                  <li>1. 每日可练习 2 次 。每次 1 道题，从题库中随机抽取；</li>
                  <li> 2. 答对可增加1次抽奖机会。</li>
                </ol>
              </div>
            </div>
            <div className="rank-list">
              <div className="title">测试排行榜</div>
              <div className="description">仅展示前50名，队员越多、用时越短排名越靠前</div>
              <div className="prize-display">
                <ul>
                  <li className={'top-three'}>
                    <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/active20_717/m/top1.png" alt=""/>
                  </li>
                  <li className={'top-three'}>
                    <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/active20_717/m/top2.png" alt=""/>
                  </li>
                  <li className={'top-three'}>
                    <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/active20_717/m/top3.png" alt=""/>
                  </li>
                  <li>
                    <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/active20_717/m/top4%EF%BD%9E7.png"
                         alt=""/>
                  </li>
                  <li>
                    <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/active20_717/m/top8%EF%BD%9E15.png"
                         alt=""/>
                  </li>
                  <li>
                    <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/active20_717/m/top16%EF%BD%9E30.png"
                         alt=""/>
                  </li>
                  <li>
                    <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/active20_717/m/top31%EF%BD%9E50.png"
                         alt=""/>
                  </li>
                </ul>
              </div>
              {
                prizeData.stage !== 1 && <table>
                  <thead>
                  <tr>
                    <th>名次</th>
                    <th>队长</th>
                    <th>队员</th>
                    <th>奖品</th>
                  </tr>
                  </thead>
                  <tbody>
                  {
                    !!_rankList.length && _rankList.map((item, index) => {
                      return <tr key={index}>
                        <td>
                          {
                            index < 3 ? <img src={rankIcons[index]} alt=""/> : index + 1
                          }
                        </td>
                        <td>
                          <img
                            src={item.avatar}
                            alt="" className={'avatar'}/>
                          _{item.username}
                        </td>
                        <td>{item.member_num}</td>
                        {
                          item.prize_url ? <td><a href={item.prize_url}>{item.prize}</a></td>
                            : <td>{item.prize}</td>
                        }
                      </tr>
                    })
                  }
                  </tbody>
                </table>
              }
              {
                !isShowAllRankList && <div className="btn">
                  <button onClick={() => {
                    this.setState({
                      isShowAllRankList: true,
                    });
                  }}>查看更多
                  </button>
                </div>
              }
            </div>
          </div>
        </section>
        <section id={'audition'} className={'audition'}>
          <div className="block-title"
               style={{background: `url(${titleImages[3]}) no-repeat`, backgroundSize: 'contain'}}></div>
          <ul className="course-container">
            {
              !!_auditions.length && _auditions.map((item, index) => {
                return <li className={'course'} key={index} onClick={(e) => {
                  if (e.target.nodeName.toLowerCase() !== 'a') {
                    history.push(`/detail?id=${item.course_id}`)
                  }
                }}>
                  <div className="cover">
                    <img src={item.image_name}
                         alt=""/>
                  </div>
                  <div className="info">
                    <div className="title">{item.course_title}</div>
                    <div className="des">{item.simpledescription}</div>
                    {
                      item.is_buy
                        ? <div className="purchased">已购买</div>
                        : <div className="prices">
                          <span>¥{item.price1}</span>
                          <span>¥{item.price0}</span>
                        </div>
                    }
                    <div className="btn">
                      {
                        item.is_buy
                          ?
                          <button className={'study-btn'}><Link to={`/play?id=${item.v_course_id}`}>开始学习</Link></button>
                          : <button className="audition-btn"><a
                            href="https://q.url.cn/AB8aue?_type=wpa&qidian=true">免费试听</a></button>
                      }
                      {
                        !!item.is_dist &&
                        <button><Link to={`/detail?id=${item.course_id}`}>赚{item.dist_amount}元</Link></button>
                      }
                    </div>
                  </div>
                </li>
              })
            }
            {
              auditions.length > 4 &&
              <li>
                <button className={'show-more'} onClick={() => {
                  this.setState({
                    auditionShowAll: true,
                  });
                }}>查看更多
                </button>
              </li>
            }
          </ul>
        </section>
        <section id={'stage-course'} className={'stage-course'}>
          <div className="block-title"
               style={{background: `url(${titleImages[4]}) no-repeat`, backgroundSize: 'contain'}}></div>
          <div className="course-container">
            {
              !isEmpty(stageCourses) && Object.keys(stageCourses).map(key => {
                return <ul key={key}>
                  <li><span className={'stage'}>{this.stages[key]}</span></li>
                  {
                    !!stageCourses[key].length && stageCourses[key].map((item, index) => {
                      let Button = null
                      if (activityData.stage === 1) {
                        Button = <button className={'unavailable'}>7月15日开始</button>
                      } else if (activityData.stage === 2) {
                        switch (item.type) {
                          case 0:
                            Button = <button><Link to={`/detail?id=${item.course_id}`}>立即报名</Link></button>
                            break
                          case 1:
                            Button =
                              <button className={'study-btn'}><Link to={`/play?id=${item.v_course_id}`}>开始学习</Link>
                              </button>
                            break
                          case 2:
                            Button = <button><Link to={`/detail?id=${item.course_id}`}>立即拼团</Link></button>
                            break
                          case 3:
                            Button = <button><Link to={`/detail?id=${item.course_id}`}>继续参团</Link></button>
                            break
                          case 4:
                            Button = <button><Link to={`/detail?id=${item.course_id}`}>继续砍价</Link></button>
                            break
                          case 5:
                            Button = <button><Link to={`/detail?id=${item.course_id}`}>我要砍价</Link></button>
                            break
                        }
                      } else {
                        Button = <button className={'unavailable'}>活动已结束</button>
                      }
                      return <li className={'course'} key={index}>
                        <div className="cover">
                          {
                            item.save && <span>立省{item.save}元</span>
                          }
                          <img src={item.image_name}
                               alt=""/>
                        </div>
                        <div className="info">
                          <div className="title">{item.course_title}</div>
                          <div className="des">{item.simpledescription}</div>
                          {
                            item.type === 1
                              ? <div className="purchased">已购买</div>
                              : <div className="prices">
                                <span>¥{item.price0}</span>
                                <span>¥{item.price1}</span>
                              </div>
                          }
                          <div className="btn">
                            {Button}
                            {
                              !!item.is_dist && <button>赚{item.dist_amount}元</button>
                            }
                          </div>
                        </div>
                      </li>
                    })
                  }
                  {
                    stageCourses[key].length === 4 && <li className={'show-more-box'}>
                      <button className={'show-more'}
                              onClick={() => this.getStageCourses(this.stageParams[key - 1])}>查看更多
                      </button>
                    </li>
                  }
                </ul>
              })
            }
          </div>
        </section>
        {
          isShowUserAddress &&
          <div className="modal-cover">
            <div className="modal recipient">
              <h4 className="title">收货信息</h4>
              <div className="tip">获奖用户（以最终榜单为准）请及时填写收货信息</div>
              <input type="text" name={'name'} value={userAddress.name} placeholder={'收件人'}
                     onChange={this.handleChange}/>
              <input type="text" name={'phone'} value={userAddress.phone} placeholder={'联系方式'}
                     onChange={this.handleChange}/>
              <input type="text" name={'address'} value={userAddress.address} placeholder={'收货地址'}
                     onChange={this.handleChange}/>
              <button disabled={!userAddress.name || !userAddress.phone || !userAddress.address}
                      onClick={this.submitUserAddress}>提交
              </button>
              <i className={'iconfont iconiconfront-2 close'} onClick={() => {
                this.setState({
                  isShowUserAddress: false,
                })
              }}></i>
            </div>
          </div>
        }
        {
          isShowPrizesRecords && <div className={'modal-cover prize-records'}>
            <div className="modal">
              <h4 className="title">中奖纪录</h4>
              <div className="content" ref={el => this.records = el}>
                <div className="rule">
                  1. 现金红包自动发放到账户中，可前往 我的- 赚奖学金 中提现；<br/>
                  2. 代金券碎片自动发放到账户中，可前往优惠券 - 碎片合成 中兑换代金券；<br/>
                  3. 实物奖品请尽快填写收货信息，活动结束后统一邮寄。
                </div>
                <ul className={'records'}>
                  {
                    !!prizeRecords.length && prizeRecords.map((item, index) => {
                      return <li key={index}>
                        <div className="record">
                          <div className="name">
                            {item.prize_name} {(item.prize_type === 1 || item.prize_type === 2) && `${item.amount}元`}
                          </div>
                          <div className="time">{item.create_time}</div>
                        </div>
                        {
                          item.prize_type === 4 && <div className="contact">{item.prize_info}</div>
                        }
                      </li>
                    })
                  }
                </ul>
                <i className={'iconfont iconiconfront-2 close'} onClick={() => {
                  this.records.removeEventListener('scroll', this.handleRecordsScroll)
                  document.body.style.overflow = 'auto'
                  this.hasMore = true
                  this.setState({
                    isShowPrizesRecords: false,
                    prizeRecordsPagination: 0
                  });
                }}></i>
              </div>
            </div>
          </div>
        }
        {
          isWinPrize && <WinPrize name={drawResult.prize_name} info={drawResult.prize_info} close={() => {
            this.setState({
              isWinPrize: false,
              drawResult: {},
            });
          }}></WinPrize>
        }
        {
          isShowTeamMember && <TeamMember members={team.team_info} close={() => {
            this.setState({
              isShowTeamMember: false,
            });
          }}></TeamMember>
        }
        {
          isShowFollow && <div className={'modal-cover follow'}>
            <div className="modal">
              <div className="title">邀请好友/进度提醒</div>
              <div className="tip">邀请好友加入队伍，获得更多抽奖机会</div>
              <div className="qrcode">
                <img src={qrcode} alt=""/>
                <div>长按识别/扫码，分享给好友</div>
              </div>
              <i className={'iconfont iconiconfront-2 close'} onClick={() => {
                this.setState({
                  isShowFollow: false,
                });
              }}></i>

            </div>
          </div>
        }
      </div>
    );
  }
}

function WinPrize({name, close, info}) {
  return <div className={'modal-cover'}>
    <div className="modal win-prize">
      <div className="title">恭喜您</div>
      <div className="des">抽中了XXX<span className={'name'}>{name}</span></div>
      <div className="contact">{/*{info}*/}请添加客服微信号：********请添加客服微信号：</div>
      <button onClick={close}>我知道了</button>
    </div>
  </div>
}

function TeamMember({members, close}) {
  const _members = Array.isArray(members) && members.slice(0, members.length - 2)
  const statusText = ['回答错误', '回答正确', '未作答']
  const statusClass = ['wrong', 'correct', 'unanswered']

  return <div className={'modal-cover members'}>
    <div className="modal">
      <div className="title">我的队伍</div>
      <ul>
        {
          _members && !!_members.length && _members.map((item, index) => {
            return <li key={item.uid}>
              <div>
                <img className={'avatar'} src={item.head_img} alt=""/>
                <span className={'username'}>{item.user_name}</span>
              </div>
              <span className={`status ${statusClass[item.is_correct]}`}>
                {statusText[item.is_correct]}
              </span>
            </li>
          })
        }
      </ul>
      <i className={'iconfont iconiconfront-2 close'} onClick={close}></i>
    </div>
  </div>
}

export default connect(
  ({user}) => ({user}),
  null,
)(Anniversary2020);