import React, { Component } from 'react';
import './index.scss';
import { Toast } from 'antd-mobile';
import {Link, withRouter} from "react-router-dom"
import { getParam, http, SendMessageToApp, browser } from "@/utils"
import CommonContainer from './../../common/commonContainer/index'
import CommonPopup from './../../common/commonPopup/index';
import { connect } from 'react-redux';
import { Popup } from "@common/index"
import QRCode from 'qrcode'
@connect(state => ({
  user: state.user
}))
class LiveRoom extends Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      showMark: false,
      subUrl: '',
      QRCodeUrl: '',
    }
  }

  componentDidMount() {
    this.getLiveInfo();
  }
  shouldComponentUpdate(nextProps, nextState, nextContext) {
    if (this.props.isAppUpdate !== nextProps.isAppUpdate) {
        this.getLiveInfo();
        return false
    }
    return true
  }
  getLiveInfo = () => {
    http.get(`${API.home}/activity/get_live_info`).then(res => {
      const { code, data, msg } = res.data;
      if (code === 200) {
        this.setState({
          list: data
        })
      } else {
        Toast.info(msg);
      }
    });
  }
  // 预约直播
  subscribe = (id) => {
    // 检查是否已登录
    const {hasError, data = {}} = this.props.user;
    if(hasError) {
      this.toLogin();
    }else{
      http.get(`${API['base-api']}/sys/createLiveQrcode/${id}`).then(res => {
        let { errno, data, msg } = res.data;
        if (errno === 200) {
          QRCode.toDataURL(data.url, (err, url) => {
            this.setState({
              showMark: true,
              subUrl: url,
              QRCodeUrl: data.url,
            })
          })
        } else {
          Toast.info(msg);
        }
      });
    }

  }
  // 已预约 给提示
  tip = () => {
    Toast.info('你已预约该直播');
  }
  // 去直播间
  toLivingRoom = (id) => {
    const {hasError, data = {}} = this.props.user;
    if(hasError) {
      this.toLogin();
    }else{
      window.location.href = `${window.location.protocol}//www.julyedu.com/live/m_room/${id}`
    }
  }
  // 查看回放
  checkVideo = (url) => {
    const {hasError, data = {}} = this.props.user;
    if(hasError) {
      this.toLogin();
    }else{
      const vCourseId = url.split('/')[0];
      window.location.href = `/play/video?id=${vCourseId}`
    }
  }
  // 关闭弹框
  closePopup = () => {
    this.setState({
      showMark: false,
    })
    // 关闭弹框的时候再次查询接口 查询预约状态
    this.getLiveInfo();
  }

  // APP内需要保存图片 是否还是这样做 需要确认
  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)
    }
  }

  // 去登录
  toLogin = () => {
    if (!getParam('version')) {
        this.props.history.push('/passport/login')
    } else {
        SendMessageToApp("toLogin")
    }
  }

  render() {
    const { list,showMark,subUrl } = this.state;
    return (
      <div className='live__container'>
        {
          showMark && (
            <CommonPopup top={50} closePopup={this.closePopup} mark={true}>
              <div className='sub__code_container'>
                <p className='sub__title'>扫码关注“七月在线”服务号即可预约</p>
                <img className='sub__qr_code' id={'live-qr-code'} src={subUrl} alt=""/>
              {
                browser.isAndroidApp ? (
                  <button className={'save-image'} onClick={this.saveImage}>保存二维码</button>
                ) : null
              }
              </div>
            </CommonPopup>
          )
        }

        <CommonContainer title='大咖直播' id="year-live">
          <ul className='live__list'>
            {
              list.length && (
                list.map((item, index) => {
                  return <li key={index} className='live_room_item'>
                    <img className='user__avatar' src={item.avatar} alt="" />
                    <div className='live__info'>
                      <div className="theme">
                        <span>主题：</span>
                        <p>{item.title}</p>
                      </div>
                      <div className="info__item">
                        <span>时间：</span>
                        <p>{item.date}</p>
                      </div>
                      <div className="info__item">
                        <span>讲师：</span>
                        <p>{item.teacher}</p>
                      </div>
                      {
                        item.on_live == 0 && item.is_end == 0 && item.is_subscribe == 0 && (
                          <span onClick={ ()=>this.subscribe(item.live_id)} className="order__btn">立即预约</span>
                        )
                      }

                      {
                        item.is_end == 1 && item.transcribe_url=='' && (
                          <span className="order__btn live__end">已结束</span>
                        )
                      }

                      {
                        item.on_live == 0 && item.is_end == 0 && item.is_subscribe == 1 && (
                          <span onClick={this.tip} className="order__btn subscribed">已预约</span>
                        )
                      }
                      {
                        item.on_live == 1 && item.is_end == 0 && (
                          <span onClick={()=>this.toLivingRoom(item.room_url)} className="order__btn living">正在直播</span>
                        )
                      }
                      {
                        item.is_end == 1 && item.transcribe_url != '' && (
                          <span onClick={() => this.checkVideo(item.transcribe_url)} className="order__btn check__video">查看回放</span>
                        )
                      }

                    </div>
                  </li>
                })
              )
            }
          </ul>
        </CommonContainer>
      </div>
    )
  }
}
export default withRouter(LiveRoom)
