import React, { Component } from 'react'
import './index.scss'
import { Tabs, Toast } from "antd-mobile"
import { getParam, http, SendMessageToApp } 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 {

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


  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
          }, {})

          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 = data.data['data_hot'].map(item => ({title: item.date}))
            today = data.data['data_hot'].findIndex(item => item['is_today'])
          }


          this.setState({
            tabs,
            lives,
            today,
            preheatLives: data.data['data_hot']
          })

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

      })
  }

  toLiveRoom = id => {
    if (this.state.isApp) {
      SendMessageToApp('toLiveRoom', id)
    } else {
      window.location.href = `${window.location.protocol}//www.julyedu.com/live/m_room/${id}`
    }
  }

  makeSubscribe = id => {
    const {user, history} = this.props
    if (user.hasError) {
      history.push('/passport/login')
    }
    http.get(`${API.home}/sys/createLiveQrcode/${id}`)
      .then(res => {
        const {data} = res
        if (data.code == 200) {
          QRCode.toDataURL(data.data.url, (err, url) => {
            this.setState({
              qrcode: url,
              visible: true
            })
          })
        } else {
          Toast.info(data.msg, 2, null, false)
        }
      })
  }

  render() {
    const {tabs, lives, visible, qrcode, preheatLives, today} = this.state
    return (
      <div id={'live'}>
        <Popup title={'扫码关注“七月在线”服务号即可预约'}
               visible={visible}
        >
          <img id={'live-qr-code'} src={qrcode} alt=""/>
        </Popup>
        <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}
            >
              {
                this.props.isFormal
                  ? tabs.map((item, index) => {
                    const todayLives = lives[item.title]
                    return (
                      <div key={index}>
                        {
                          todayLives.map((item, index) => {
                            return (
                              <LiveContent item={item} key={index} makeSubscribe={this.makeSubscribe}/>
                            )
                          })
                        }
                      </div>
                    )
                  })
                  : preheatLives.map((item, index) => {
                    return (
                      <div key={index}>
                        {
                          preheatLives.map((item, index) => {
                            return <LiveContent key={index} item={item} makeSubscribe={this.makeSubscribe}/>
                          })
                        }
                      </div>
                    )
                  })
              }
            </Tabs>

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

function LiveContent({item, makeSubscribe}) {
  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={this.toLiveRoom.bind(this, item['live_id'])}>正在直播</button>
          :
          item['is_subscribe']
            ? <button className={'subscribed'}>已预约</button>
            : <button className={'subscribe'}
                      onClick={makeSubscribe.bind(this, item['live_id'])}>立即预约</button>
      }
    </div>
  )
}

export default withRouter(Live)
