import React, { Component } from 'react'
import { browser, getParam, http } from "src/utils"
import { Toast } from "antd-mobile"
import { withRouter } from 'react-router-dom'
import './assistance.scss'
import { Base64 } from "js-base64"
import { connect } from 'react-redux'
import Swiper from 'swiper'

function showToast(text) {
  Toast.info(text, 2, null, false)
}

@connect(({user}) => ({
  user
}))
class GiveCourseAssistance extends Component {

  scrollContainer = null
  cloned = false
  animationId = 0
  swiper = null

  state = {
    allCourse: [],
    activeName: '',
    activeUrl: '',
    isAwards: '',
    count: '',
    assistItems: [],
    name: '',
    courseImg: '',
    code: getParam('magic_word'),
    getBtnStatus: '1',
    disabled: false,
    successOneStatus: false,
    errorStatus: false,
    activeStatus: false,
    friendStatus: false,
    posY: 0,
    scrollStyle: {
      transform: `translateY(${0}px)`,
      transition: 'all linear 0ms',
      overflow: 'hidden'
    },
    headItems: []
  }

  componentDidMount() {
    this.giveDetail()
    this.assistantScroll()
    this.requestHeadItems()
    let baseCode = decodeURIComponent(Base64.decode(this.state.code)).split(',')
    this.setState({
      baseCode: baseCode[0],
      getBtnStatus: this.props.user.data.uid == baseCode[0] ? '2' : '1'
    })
  }

  componentWillUpdate(nextProps) {
    const {user} = this.props
    if (nextProps.user.hasError !== user.hasError) {
      this.setState({
        getBtnStatus: nextProps.user.data.uid == this.state.baseCode ? '2' : '1'
      })
    }
  }


  componentWillUnmount() {
    window.cancelAnimationFrame(this.animationId)
    this.swiper && this.swiper.destroy()
  }


  giveDetail = () => {
    http.get(`${API["base-api"]}/assistance/detail`)
      .then(res => {
        const {data, msg, errno} = res.data
        if (errno === 200) {
          this.setState({
            allCourse: data.course_info,
            activeName: data.active_info.activity_name,
            activeUrl: data.active_info.activity_url,
            isAwards: data.is_awards
          })
        } else {
          showToast(msg)
        }
      })
  }

  assistantScroll = () => {
    http.get(`${API["base-api"]}/assistance/active_detail?code=${getParam('magic_word')}`)
      .then(res => {
        const {data, msg, errno} = res.data
        if (errno === 0) {
          this.setState({
            count: data.assistant_count,
            assistItems: data.assistants,
            name: data.invitation_user_nickname,
            courseImg: data.course_image_name
          }, this.displayScrollArea)

        } else {
          showToast(msg)
        }
      })
  }

  getCourse = () => {
    _czc && _czc.push(["_trackEvent", '中间页免费领取课程', '中间页免费领取课程'])
    const {history, user} = this.props
    if (browser.isWeixin) {
      if (user.hasError) {
        history.push('/passport')
        return
      }
      this.setState({
        disabled: true
      })
      http.post(`${API["base-api"]}/assistance/assistant`, {
        code: this.state.code,
      })
        .then(res => {
          const {errno, msg} = res.data
          let success = errno == 200
          this.setState({
            successOneStatus: success,
            errorStatus: !success,
            disabled: false
          })
        })


    } else {
      history.push('/wxerr')
    }
  }

  toGetDetail = courseId => {
    _czc && _czc.push(["_trackEvent", `课程id=${courseId}`, '中间页查看课程详情'])
    window.location.href = this.state.activeUrl
  }

  displayScrollArea = () => {
    let {
      assistItems: list,
      posY
    } = this.state
    if (list.length < 3) return
    if (!this.cloned) {
      const cloneNode = this.scrollContainer.firstChild.firstChild.cloneNode(true)
      this.scrollContainer.firstChild.appendChild(cloneNode)
      this.cloned = true
    }
    const h = this.scrollContainer.firstChild.offsetHeight / 2
    if (Math.abs(posY) >= h) posY = 0
    posY -= 0.5
    this.setState({
      posY,
      scrollStyle: {
        transform: `translateY(${posY}px)`,
        transition: 'all linear 0ms',
        overflow: 'hidden'
      }
    })
    this.animationId = window.requestAnimationFrame(this.displayScrollArea)
  }

  requestHeadItems = () => {
    http.get(`${API["base-api"]}/assistance/roll_tip`)
      .then(res => {
        const {errno, data, msg} = res.data
        if (errno === 200) {
          this.setState({
            headItems: data
          }, this.setupHeadItemsSwiper)
        } else {
          showToast(msg)
        }
      })
  }

  setupHeadItemsSwiper = () => {
    this.swiper = new Swiper('.barrage-wrapper', {
      autoplay: {
        delay: 5000
      },
      direction: 'vertical',
      loop: true,
      allowTouchMove: false
    })
  }

  render() {
    const {
      isAwards,
      courseImg,
      activeName,
      name,
      getBtnStatus,
      disabled,
      count,
      allCourse,
      successOneStatus,
      errorStatus,
      activeStatus,
      friendStatus,
      assistItems,
      scrollStyle,
      headItems
    } = this.state
    const {history} = this.props
    return (
      <div id='assistance'>

        {<div className="barrage-wrapper">
          <ul className="barrage-list swiper-wrapper">
            {
              headItems.map((item, index) => {
                return (
                  <li key={index} className={'swiper-slide'}>
                    <div className="person-left">
                      <img className="avatar" src={item.head_img} alt=""/>
                      <span className="name">{item["nickname"]}</span>
                    </div>
                    <div className="title">{item["word"]}</div>
                  </li>
                )
              })
            }

          </ul>

        </div>}

        <div className="bg-image" style={{backgroundImage: `url(${courseImg})`}}>
          {
            isAwards == 1 && <button className="ranklist-btn" type="button" onClick={() => {
              _czc && _czc.push(["_trackEvent", '中间页大奖排行榜', '中间页面大奖排行榜'])
              history.push(`/active/givecourse?activename=${activeName}`)
            }}>大奖排行榜&gt;&gt;</button>
          }
        </div>


        <div className="christ-getwrap">
          {
            getBtnStatus === '1' &&
            <div className="title">
              <span className="active">@{name}</span> 赠送您一门课程
            </div>
          }

          <div className="btn-get-wrap">
            {
              getBtnStatus === '1'
                ?
                <button type="button" className="btn-get" disabled={disabled} onClick={this.getCourse}>
                  免费领取
                </button>
                :
                <button type="button" className="btn-get" onClick={() => {
                  _czc && _czc.push(["_trackEvent", '中间页继续邀请好友', '中间页继续邀请好友'])
                  this.setState({
                    friendStatus: true
                  })
                }}>
                  继续邀请好友
                </button>
            }
          </div>
          <p className="person-tolearn">领取的课程可前往七月在线APP或官网学习</p>
          <div className="person-getwarp">
            <div className="person-get">
              已有
              <span>{count}</span>
              人通过助力领取课程
            </div>

            {
              assistItems.length ?
                <div className='scroll-container person-list' ref={el => this.scrollContainer = el}>
                  <div className="wrapper" style={scrollStyle}>
                    <ul>
                      {
                        assistItems.map(item => {
                          return (
                            <li key={item["assistant_uid"]}>
                              <div className="person-left">
                                <img className="avatar" src={item["avatar_file"]} alt=""/>
                                <span className="name">{item.user_name}</span>
                              </div>
                              <div className="person-right">
                                <span className="time">{item["add_time"]}前领取成功</span>
                              </div>
                            </li>
                          )
                        })
                      }
                    </ul>
                  </div>
                </div>

                :
                <p className="person-null">目前暂无邀请</p>
            }


            <div className="btn-morewap">
              <button type="button" className="btn-more" onClick={() => {
                _czc && _czc.push(["_trackEvent", '中间页参与活动领更多课时', '中间页参与活动领更多课时'])
                this.setState({activeStatus: true})
              }}>参与活动领更多课时
              </button>
            </div>
            <p className="more-title">参与活动可免费领取以下课程</p>
            <ul className="course-wrap">
              {
                allCourse.map((item) => {
                  return (
                    <li key={item.course_id} onClick={this.toGetDetail.bind(this, item.course_id)}>
                      <img src={item.image_name} alt=""/>
                    </li>
                  )
                })
              }
            </ul>
          </div>
        </div>

        {
          successOneStatus &&
          <div className="module-dialog">
            <div className="box-mask">
              <div className="box-container">
                <div className="box-content">
                  <div className="box-title">
                    <i className="iconfont icon-chenggong icon-right"/>
                    领取成功
                  </div>
                  <div className="box-text">
                    <p className="text1">恭喜您获得第一课的免费学习权限</p>
                  </div>
                </div>
                <div className="box-bottom">
                  <button type="button" className="activeallcourse" onClick={() => {
                    this.setState({activeStatus: true, successOneStatus: false})
                  }}>进入服务号领取全部课时
                  </button>
                </div>
              </div>
            </div>
          </div>
        }
        {
          errorStatus &&
          <div className="module-dialog">
            <div className="box-mask">
              <div className="box-container">
                <div className="box-content">
                  <div className="box-title" style={{color: `#f00`}}>
                    领取失败
                  </div>
                  <div className="box-text">
                    <p className="text1">只能免费领取1次，想获得更多课时快去参与活动吧！</p>
                  </div>
                </div>
                <div className="box-bottom">
                  <button type="button" className="activeallcourse" onClick={() => {
                    this.setState({errorStatus: false, friendStatus: true})
                  }}>确定
                  </button>
                </div>
              </div>
            </div>
          </div>
        }

        {
          activeStatus &&
          <div className="module-dialog">
            <div className="box-mask">
              <div className="box-container">
                <div className="box-content">
                  <div className="box-title">
                    <p className="text1">进入服务号回复<i>77</i>免费领取课程</p>
                  </div>
                  <div className="box-bottom1">
                    <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/2018christyear/h5/qrcode.jpg" alt=""/>
                    <p>长按扫码进入服务号</p>
                  </div>
                </div>
                <div className="box-close" onClick={() => {
                  this.setState({activeStatus: false})
                }}>
                  <i className="iconfont iconiconfront-2"/>
                </div>
              </div>
            </div>
          </div>
        }

        {
          friendStatus &&
          <div className="module-dialog">
            <div className="box-mask">
              <div className="box-container">
                <div className="box-content">
                  <div className="box-title">
                    <p className="text1">进入服务号回复<i>77</i>免费领取课程</p>
                  </div>

                  <div className="box-bottom1">
                    <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/2018christyear/h5/qrcode.jpg" alt=""/>
                    <p>长按扫码进入服务号</p>
                  </div>
                </div>
                <div className="box-close" onClick={() => {
                  this.setState({friendStatus: false})
                }}>
                  <i className="iconfont iconiconfront-2"/>
                </div>
              </div>
            </div>
          </div>
        }
      </div>
    )
  }
}

export default withRouter(GiveCourseAssistance)
