import React, { Component } from 'react'
import './index.scss'
import { Tabs, Toast } from "antd-mobile"
import { getParam, http, SendMessageToApp, browser } from "@/utils"
import { Popup } from "@common/index"
import QRCode from 'qrcode'
import { uniqBy } from 'lodash'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'


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

  popupInstance = null

  state = {
    tabs: [],
    lives: {},
    preheatLives: [],
    today: '',
    isApp: getParam('version'),
    QRCodeUrl: '',
  }


  componentDidMount() {
    http.get(`${API.home}/sys/get_live_info`)
      .then(res => {
        const {data} = res
        if (data.code == 200) {

          const lives = data.data['data_active'].reduce((accu, current) => {
            if (!(current.date in accu)) {
              accu[current.date] = [current]
            } else {
              accu[current.date].push(current)
            }
            return accu
          }, {})
          const preheatLives = data.data['data_hot'].reduce((accu, current) => {
            if (!(current.date in accu)) {
              accu[current.date] = [current]
            } else {
              accu[current.date].push(current)
            }
            return accu
          }, {})

          let tabs, today
          if (this.props.isFormal) {
            tabs = Object.keys(lives).map(item => ({title: item}))
            today = uniqBy(data.data['data_active'], value => value.date).findIndex(item => item['is_today'])
          } else {
            tabs = Object.keys(preheatLives).map(item => ({title: item}))
            today = uniqBy(data.data['data_hot'], value => value.date).findIndex(item => item['is_today'])
          }


          this.setState({
            tabs,
            lives,
            today,
            preheatLives
          })

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

      })
  }

  toLiveRoom = id => {
    const {history, isLogin} = this.props
    if (this.state.isApp) {
      if (isLogin) {
        SendMessageToApp('toLiveRoom', id)
      } else {
        SendMessageToApp("toLogin")
      }
    } else {
      if (isLogin) {
        window.location.href = `${window.location.protocol}//www.julyedu.com/live/m_room/${id}`
      } else {
        history.push('/passport')
      }
    }
  }

  saveImage = () => {
    let version = getParam('version')
    version = typeof version === 'string' ? version.replace('.', '').replace('.', '').slice(0, 3) : ''
    const {QRCodeUrl} = this.state
    if (version && parseInt(version) < 451) {
      Toast.info('当前不支持此功能，升级到最新版本app可以点击保存二维码！', 2, null, false)
    } else {
      SendMessageToApp('generateQRCode', QRCodeUrl)
    }
  }

  makeSubscribe = id => {
    const {user, history} = this.props
    if (user.hasError) {
      history.push('/passport/login')
    }
    http.get(`${API['base-api']}/sys/createLiveQrcode/${id}`)
      .then(res => {
        const {data} = res
        if (data.errno == 200) {
          this.setState(() => ({
            QRCodeUrl: data.data.url,
          }))
          QRCode.toDataURL(data.data.url, (err, url) => {
            if (!this.popupInstance) {
              this.popupInstance = Popup({
                title: '扫码关注“七月在线”服务号即可预约',
                content: (
                  <>
                    <img id={'live-qr-code'} src={url} alt=""/>
                    {
                      browser.isAndroidApp ? (
                        <button className={'save-image'} onClick={this.saveImage}>保存二维码</button>
                      ) : null
                    }
                  </>
                ),
                close: () => new Promise(resolve => {
                  this.popupInstance = null
                  resolve()
                })
              })
            }
          })
        } else {
          Toast.info(data.msg, 2, null, false)
        }
      })
  }

  render() {
    const {tabs, lives, preheatLives, today} = this.state
    return (
      <div id={'live'}>
        <div className="title">
          <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/active19_1111/title-decorate-left.png" alt=""/>
          <span>大咖直播</span>
          <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/active19_1111/title-decorate-right.png" alt=""/>
        </div>
        <div className="live-container">
          {
            today !== '' &&
            <Tabs
              tabs={tabs}
              tabBarBackgroundColor={'transparent'}
              tabBarActiveTextColor={'#5600DF'}
              tabBarInactiveTextColor={'#FFF604'}
              tabBarUnderlineStyle={{display: 'none'}}
              initialPage={today}
              swipeable={false}
            >
              {
                this.props.isFormal
                  ? tabs.map((item, index) => {
                    const todayLives = lives[item.title]
                    return (
                      <div key={index}>
                        {
                          todayLives && todayLives.map((item, index) => {
                            return (
                              <LiveContent item={item} key={index} makeSubscribe={this.makeSubscribe}
                                           toLiveRoom={this.toLiveRoom}/>
                            )
                          })
                        }
                      </div>
                    )
                  })
                  : tabs.map((item, index) => {
                    const todayLives = preheatLives[item.title]
                    return (
                      <div key={index}>
                        {
                          todayLives && todayLives.map((item, index) => {
                            return (
                              <LiveContent item={item} key={index} makeSubscribe={this.makeSubscribe}
                                           toLiveRoom={this.toLiveRoom}/>
                            )
                          })
                        }
                      </div>
                    )
                  })
              }
            </Tabs>

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

function LiveContent({item, makeSubscribe, toLiveRoom}) {
  return (
    <div className="content">
      {
        item['is_teacher']
          ? <div className="tag teacher">讲师分享</div>
          : <div className="tag student">学员分享</div>
      }
      <div className="person-info">
        <div className="left">
          <img
            src={item.avatar}
            alt="头像"
            className="avatar"/>
        </div>
        <div className="right">
          <div className="name">讲师：{item['teacher']}</div>
          <div className="profession">{item['teacher_desc']}</div>
        </div>
      </div>
      <div className="title">{item.title}</div>
      <div className="time">直播时间：{item.time}</div>
      <div className="outline">
        <div className="outline-title">内容大纲：</div>
        <ul>
          {
            item['content'].map((content, index) => {
              return <li key={index}>{content}</li>
            })
          }
        </ul>
      </div>
      {
        item['on_live']
          ? <button className={'on-living'} onClick={() => {
            toLiveRoom(item['room_url'])
          }}>正在直播</button>
          :
          item['is_end']
            ? <button className={'subscribed'}>已结束</button>
            : item['is_subscribe']
            ? <button className={'subscribed'}>已预约</button>
            : <button className={'subscribe'}
                      onClick={makeSubscribe.bind(this, item['live_id'])}>立即预约</button>
      }
    </div>
  )
}

export default withRouter(Live)
