/* eslint-disable eqeqeq */
import React, { Component } from "react"
import "./index.scss"
import { Tabs, Toast } from "antd-mobile"
import { getParam, http, SendMessageToApp, browser } from "src/utils"
import { Popup } from "src/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: [],
    todayIndex: "",
    isApp: getParam("version"),
    QRCodeUrl: "",
  }

  componentDidMount() {
    http.get(`${API.home}/sys/get_live_info`).then((res) => {
      const { data, code, msg } = res.data
      if (code == 200) {
        let tabs = uniqBy(data, (item) => item.date)
        let todayIndex = tabs.findIndex((item) => item["is_today"])
        tabs = tabs.map((item) => ({ title: item.date }))

        this.setState({
          tabs,
          lives: data,
          todayIndex: todayIndex < 0 ? 0 : todayIndex,
        })
      } else {
        Toast.info(msg, 2, null, false)
      }
    })
  }

  toLogin = () => {
    const { history } = this.props
    if (!getParam("version")) {
      history.push("/passport")
    } else {
      SendMessageToApp("toLogin")
    }
  }

  toLiveRoom = (id) => {
    const { history, isLogin } = this.props
    var _czc = window._czc || []
    var name = "直播间id=" + id
    _czc.push(["_trackEvent", name, "m端双十一大咖直播-正在直播"])
    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)
    }
  }

  checkVideo = (url) => {
    let version = getParam("version")
    const { history, user } = this.props
    if (!version) {
      if (user.hasError) {
        this.toLogin()
      } else {
        const vCourseId = url.split("/")[0]
        history.push(`/play/video?id=${vCourseId}`)
      }
    } else {
      Toast.info(
        "当前版本不支持此功能，请前往h5/pc查看回放该直播",
        2,
        null,
        false
      )
    }
  }

  makeSubscribe = (id) => {
    const { user } = this.props
    if (user.hasError) {
      this.toLogin()
    }

    var name = "直播间id=" + id
    _czc.push(["_trackEvent", name, "m端双十一大咖直播-立即预约"])

    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 if (data.errno == 4030 || data.errno == 4040) {
      } else {
        Toast.info(data.msg, 2, null, false)
      }
    })
  }

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

function LiveContent({ item, makeSubscribe, toLiveRoom, checkVideo }) {
  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"] ? (
        item.transcribe_url === "" ? (
          <button className={"subscribed"}>已结束</button>
        ) : (
          <button
            className={"on-living"}
            onClick={() => checkVideo(item.transcribe_url)}
          >
            查看回放
          </button>
        )
      ) : item["is_subscribe"] ? (
        <button className={"subscribed"}>已预约</button>
      ) : (
        <button
          className={"subscribe"}
          onClick={makeSubscribe.bind(this, item["live_id"])}
        >
          立即预约
        </button>
      )}
    </div>
  )
}

export default withRouter(Live)
