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: [],
    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
          }, {})
          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')
      }
    }
  }

  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) {
          QRCode.toDataURL(data.data.url, (err, url) => {
            Popup({
              title: '扫码关注“七月在线”服务号即可预约',
              content: <img id={'live-qr-code'} src={url} alt=""/>
            })
          })
        } 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.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.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)