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'

class FormalDraw extends Component {

  swiper = null
  popupInstance = null
  subscribePopupInstance = null

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

  componentDidMount() {
    http.get(`${API.home}/sys/activity/prize_data`)
      .then(res => {
        const {data, code, msg} = res.data
        const oneDay = data.list.filter(item => item.date === data.value.today)
        const activeIndex = oneDay[0]['son'].findIndex(item => item.status == 3)
        if (code == 200) {
          const {is_login, today} = data.value
          this.setState({
            tabs: data.list.map(item => ({title: item.date})),
            today,
            initialPageIndex: data.list.findIndex(item => item.date == today) || 0,
            isLogin: is_login,
            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 => {
    var _czc = _czc || []
    _czc.push(["_trackEvent", '点击抽奖', 'm端双十一正式活动-点击抽奖'])
    let {surplus, is_prize} = this.state.userValue
    if (is_prize || this.popupInstance || surplus <= 0) {
      return
    }
    http.post(`${API.home}/sys/activity/prize`, {
      id
    }).then(res => {
      const {code, msg, data} = res.data
      if (code == 200) {
        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: --surplus}}
          })
        })

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

  lotteryFunc = (status, id) => {
    if (!this.state.isLogin) {
      this.props.history.push('/passport')
      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, isLogin, list, activeTimeRangeIndex, userValue} = this.state
    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" key={index}>
                      <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 &&
                                                <div className="tip">
                                                  满{prize.people_limit}人释放
                                                </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)
