import React, { Component } from 'react'
import { http } from "@/utils"
import { Toast, Tabs } from 'antd-mobile'
import './index.scss'
import 'swiper/dist/css/swiper.min.css'
import { Link, withRouter } from 'react-router-dom'
import classnames from 'classnames'
import Swiper from 'swiper'
import { Popup } from "@common/index"
import QRCode from 'qrcode'
import { connect } from 'react-redux'


@connect(state => ({user: state.user}))
class FormalDraw extends Component {

  swiper = null
  popupInstance = null
  subscribePopupInstance = null

  state = {
    prizes: [],
    currentDisplayPrizes: [],
    tabs: [],
    today: '',
    initialPageIndex: 0,
    list: [],
    activeTimeRangeIndex: 0,
    userValue: {},
  }

  componentDidMount() {
    http.get(`${API.home}/sys/activity/prize_data`)
      .then(res => {
        const {data, code, msg} = res.data
        if (code == 200) {
          const {today} = data.value
          const oneDay = data.list.filter(item => item.date === data.value.today)
          const activeIndex = oneDay[0]['son'].findIndex(item => item.status == 3)
          this.setState({
            tabs: data.list.map(item => ({title: item.date})),
            today,
            initialPageIndex: data.list.findIndex(item => item.date == today) || 0,
            list: data.list,
            userValue: data.value,
            activeTimeRangeIndex: activeIndex < 0 ? 0 : activeIndex
          }, () => {
            this.initializeSwiper()
          })
        } else {
          Toast.info(msg, 2, null, false)
        }
      })
  }

  initializeSwiper = () => {
    new Swiper(this.swiper, {
      slidesPerView: 'auto',
      scrollbar: {
        el: '.swiper-scrollbar',
        draggable: true
      }
    })
  }

  changeTab = (tab) => {
    const {list} = this.state
    const data = list.filter(item => item.date === tab.title)
    let index = data[0]['son'].findIndex(item => item.status == 3)
    this.setState({
      today: tab.title,
      activeTimeRangeIndex: index < 0 ? 0 : index
    }, () => {
      this.initializeSwiper()
    })
  }

  draw = id => {
    let {surplus, is_prize, hot_value} = this.state.userValue
    if (hot_value < 50) {
      Toast.info('你的福气值未达到参与抽奖所需福气值分数，快去积攒福气值吧', 2, null, false)
    } else if (is_prize == 1) {
      Toast.info('你已参与当前时段抽奖', 2, () => {
        this.requestDraw(id, true)
      }, false)
    } else if (surplus < 1) {
      Toast.info('你的抽奖次数已用光，快去积攒福气值可获得更多抽奖机会', 2, null, false)
    } else {
      this.requestDraw(id)
    }
  }

  requestDraw = (id, isDrawn) => {
    let {surplus} = this.state.userValue
    http.post(`${API.home}/sys/activity/prize`, {
      id
    }).then(res => {
      const {code, msg, data} = res.data
      if (code == 200) {
        var _czc = _czc || []
        _czc.push(["_trackEvent", '点击抽奖', 'm端双十一正式活动-点击抽奖'])
        QRCode.toDataURL(data.url, (err, url) => {
          this.popupInstance = Popup({
            title: '你已成功参与本时段抽奖',
            className: 'join-lottery',
            content: (
              <>
                <div className="text">
                  <div className="code">抽奖码为：{data.code}</div>
                  <div className="time">本时段的中奖结果将在{data.date}公布</div>
                  <div className="hint">你可关注‘七月在线’服务号第一时间获得中奖信息。</div>
                  <img src={url} className='qr-code' alt=""/>
                </div>
                <button onClick={() => {
                  this.popupInstance.close()
                }}>知道了
                </button>
              </>
            )
          })
          this.setState({
            userValue: {...this.state.userValue, ...{surplus: isDrawn ? surplus : --surplus}, ...{is_prize: 1}}
          })
        })
      } else {
        Toast.info(msg, 2, null, false)
      }
    })
  }

  lotteryFunc = (status, id) => {
    const {hasError} = this.props.user
    if (hasError) {
      this.props.toLogin()
      return
    }
    if (status == 3) {
      this.draw(id)
    } else if (status == 2) {
      this.subscribe()
    }
  }

  subscribe = () => {
    var _czc = _czc || []
    _czc.push(["_trackEvent", '预约抽奖', 'm端双十一正式页-立即预约'])
    if (this.subscribePopupInstance) {
      return
    }
    http.get(`${API["base-api"]}/sys/activity/create_pre_qrcode`)
      .then(res => {
        const {code, data, msg} = res.data
        if (code == 200) {
          this.subscribePopupInstance = QRCode.toDataURL(data.url, (err, url) => {
            Popup({
              title: '微信扫码“七月在线”服务号即可预约',
              className: 'subscribe',
              content: <img src={url} alt="" className="qr-code"/>,
              close: () => new Promise(resolve => {
                this.subscribePopupInstance = null
                resolve()
              })
            })
          })
        } else {
          Toast.info(msg, 2, null, false)
        }
      })
  }

  render() {
    const {tabs, today, initialPageIndex, list, activeTimeRangeIndex, userValue} = this.state
    const {hasError} = this.props.user
    const isLogin = !hasError
    const schedule = userValue.schedule <= 2 ? 2 : userValue.schedule
    return (
      list.length > 0 ?
        <div id={'formal-draw'}>
          {
            list.length &&
            <Tabs
              tabs={tabs}
              initialPage={initialPageIndex}
              tabBarBackgroundColor={'transparent'}
              tabBarActiveTextColor={'#5600DF'}
              tabBarInactiveTextColor={'#FFF604'}
              tabBarUnderlineStyle={{display: 'none'}}
              onTabClick={this.changeTab}
              swipeable={false}
            >
              {
                list.map((listItem, index) => {
                  return (
                    <div className={`content ${(isLogin && today === userValue.today) ? 'current' : ''}`} key={index}>
                      {
                        (isLogin && (today === userValue.today))
                          ?
                          <div className="prize_number_con">
                            当日剩余抽奖次数：
                            <span className={'prize__number'}>{userValue.surplus}次</span>
                          </div>
                          : ""
                      }
                      <div className="title">
                        <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/active19_1111/title-decorate-left.png"
                             alt=""/>
                        {
                          isLogin
                            ?
                            <div className="hot-value">中奖概率值：<span className={'grade'}>{userValue['hot_value']}分</span>
                            </div>
                            : <div className="hot-value">中奖概率值：<Link to={'/passport'}>登录</Link></div>
                        }
                        <img
                          src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/active19_1111/title-decorate-right.png"
                          alt=""/>
                      </div>

                      {
                        isLogin ?
                          <div className="progress-bar">
                            <img className={'locator'}
                                 src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/active19_1111/locator.png"
                                 alt=""
                                 style={{
                                   left: `${schedule - (11 / 330 - (6 / 330)) * 100}%`
                                 }}
                            />
                            <div className="progress" style={{
                              width: `${schedule}%`
                            }}></div>
                          </div>
                          : null
                      }
                      <ul className="time-ranges">
                        {
                          listItem.son && listItem.son.map((item, i) => {
                            let statusContent
                            switch (item.status) {
                              case 4:
                                statusContent = (
                                  <>
                                    <span>已结束</span>
                                    <Link to={`/prize-winner-list?tid=${item.id}`}>查看中奖名单</Link>
                                  </>
                                )
                                break
                              case 3:
                                statusContent = (
                                  <>
                                    <div>立即抽奖</div>
                                    <div>{item.num}人正在参与</div>
                                  </>
                                )
                                break
                              case 2:
                                statusContent = '立即预约'
                                break
                              default:
                                statusContent = '即将开启'
                            }
                            return (
                              <li key={i}
                                  className={classnames(`status-${item.status}`, {active: activeTimeRangeIndex === i})}>
                                <div className={'status-bar'} onClick={() => {
                                  this.setState({activeTimeRangeIndex: i}, () => {
                                    this.initializeSwiper()
                                  })
                                }}>
                                  <img className={'icon-clock'}
                                       src={
                                         item.status == 3
                                           ? 'https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/active19_1111/m/m-icon-clock-purple.png'
                                           : "https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/active19_1111/m/m-icon-clock.png"
                                       }
                                       alt=""/>
                                  <div className="time">
                                    <span>{item.time}</span>
                                  </div>
                                  <div className="status"
                                       onClick={this.lotteryFunc.bind(this, item.status, item.id)}>{statusContent}</div>
                                </div>
                                {
                                  activeTimeRangeIndex === i &&
                                  listItem.date === today &&
                                  <div className="swiper-container" ref={el => this.swiper = el}>
                                    <ul className={'prizes swiper-wrapper'}>
                                      {
                                        item.data.map((prize, index) => {
                                          return (
                                            <li key={index} className={'swiper-slide'}>
                                              {
                                                prize.level === 1 &&
                                                item.status === 3 &&
                                                <div className="tip">
                                                  满10000人释放
                                                </div>
                                              }
                                              <img src={prize.img} alt=""/>
                                              <div className='prize-name'>
                                                <div>{prize.name}</div>
                                                <div>*{prize.num}</div>
                                              </div>
                                            </li>
                                          )
                                        })
                                      }
                                      <li className='swiper-scrollbar'></li>
                                    </ul>
                                  </div>
                                }
                              </li>
                            )
                          })
                        }
                      </ul>
                    </div>
                  )
                })
              }
            </Tabs>
          }
        </div>
        : null
    )
  }
}

export default withRouter(FormalDraw)
