/* eslint-disable eqeqeq, default-case */
import React, { Component } from "react"
import { http } from "src/utils"
import "./index.scss"
import { HeaderBar } from "src/common/index"
import { WhiteSpace, Toast } from "antd-mobile"
import VList from "src/common/v-list-base"
import { Popup } from "src/common/index"
import WithFullSize from "src/HOCs/WithFullSize"
import { connect } from "react-redux"
import { Link } from "react-router-dom"

function showToast(msg) {
  Toast.info(msg, 2, null, false)
}

class LimitFree extends Component {
  nav
  state = {
    tab: {},
    courses: [],
    navItemStyle: {},
    tabActiveIndex: 0,
  }

  componentDidMount() {
    document.title = "助力春招，好课限免--七月在线"
    this.getData()
  }

  getData = () => {
    Promise.all([
      http.get(`${API.home}/sys/category`),
      http.get(`${API.home}/sys/course`),
    ]).then((res) => {
      const [tab, courses] = res
      const { data: tabData, code: tabCode, msg: tabMsg } = tab.data
      const {
        data: coursesData,
        code: coursesCode,
        msg: coursesMsg,
      } = courses.data
      if (tabCode === 200) {
        this.setState({
          tab: tabData,
        })
      } else {
        showToast(tabMsg)
      }
      if (coursesCode === 200) {
        this.setState({
          courses: coursesData,
        })
      } else {
        showToast(coursesMsg)
      }
    })
  }

  handleClick = (id) => {
    this.props.history.push(`/detail?id=${id}`)
  }

  changeTab = (e, index) => {
    const { tabActiveIndex } = this.state
    if (tabActiveIndex !== index) {
      this.setState({
        tabActiveIndex: index,
      })
    }
  }

  getCourse = (courseId, vCourseId) => {
    const { user, history } = this.props
    if (user.hasError) {
      history.push("/passport")
      return
    }
    http
      .post(`${API.home}/sys/limitFree/receive`, {
        course_id: courseId,
      })
      .then((res) => {
        const { code, msg } = res.data
        if (code === 200) {
          const instance = Popup({
            className: "get-course-popup",
            closable: false,
            clickMaskClose: false,
            title: (
              <div>
                <img
                  src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/time_limited_free/M/check.png"
                  alt=""
                />
                <div>课程有效期7天，快去学习吧~</div>
              </div>
            ),
            content: (
              <div className={"btns"}>
                <button
                  onClick={() => {
                    instance.close()
                    this.getData()
                  }}
                >
                  知道了
                </button>
                <button
                  onClick={() => {
                    this.toPlay(vCourseId)
                    instance.close()
                  }}
                >
                  立即学习
                </button>
              </div>
            ),
          })
        } else {
          showToast(msg)
        }
      })
  }

  toPlay = (id) => {
    this.props.history.push(`/play/video?id=${id}`)
  }

  formatTime = (seconds) => ({
    d: Math.floor(seconds / 60 / 60 / 24)
      .toString()
      .padStart(2, "0"),
    h: Math.floor((seconds / 60 / 60) % 24)
      .toString()
      .padStart(2, "0"),
    m: Math.floor((seconds / 60) % 60)
      .toString()
      .padStart(2, "0"),
  })

  render() {
    const { tab, courses, navItemStyle, tabActiveIndex } = this.state
    return (
      <div className="limit-free">
        <HeaderBar arrow={true} title={"限时免费"}></HeaderBar>
        <div className="banner">
          <img
            src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/time_limited_free/M/banner.png"
            alt=""
          />
        </div>
        <nav>
          {/*<div className="prev-cover"></div>*/}
          <ul ref={(el) => (this.nav = el)}>
            {tab &&
              !!tab.length &&
              tab.map((item, index) => {
                return (
                  <li
                    key={index}
                    className={index === tabActiveIndex ? "active" : ""}
                    style={navItemStyle}
                    onClick={(e) => this.changeTab(e, index)}
                  >
                    <a href={`#category${item.id}`} target={"_self"}>
                      {item.category_name}
                    </a>
                  </li>
                )
              })}
          </ul>
          <div className="next-cover"></div>
        </nav>
        <WhiteSpace />
        <div className="course-list">
          <ul>
            {tab &&
              !!tab.length &&
              tab.map((category) => {
                return (
                  <li key={category.id} className={"category"}>
                    <h2 id={`category${category.id}`}>
                      <img
                        src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/time_limited_free/M/category-icon.png"
                        alt=""
                      />
                      <span>{category.category_name}</span>
                    </h2>
                    <ul className={"courses"}>
                      {courses &&
                        courses.length &&
                        courses.map((item, index) => {
                          if (item.category_id != category.id) {
                            return null
                          }
                          /*
                           * course_status:
                           * 0未领取 1已领取未过期 2 已领取已过期 3 正常已购买
                           * */
                          let des, bottom
                          switch (item.course_status) {
                            case 0:
                              des = (
                                <div className={"learner"}>
                                  <i className="iconfont iconRectangleCopy4" />
                                  <span>{item.play_times}人学习</span>
                                </div>
                              )
                              bottom = (
                                <div className={"bottom"}>
                                  <span className={"red"}>限时免费</span>
                                  <span className={"origin-price"}>
                                    ¥{item.price0}
                                  </span>
                                  <button
                                    onClick={(e) => {
                                      e.stopPropagation()
                                      this.getCourse(
                                        item.course_id,
                                        item.v_course_id
                                      )
                                    }}
                                  >
                                    免费领取
                                  </button>
                                </div>
                              )
                              break
                            case 1:
                              const { d, h, m } = this.formatTime(
                                item.course_expire
                              )
                              des = (
                                <div className={"remain-time"}>
                                  <i className={"iconfont iconiconfront-21"} />
                                  <span>
                                    {d}天{h}时{m}分后过期
                                  </span>
                                </div>
                              )
                              bottom = (
                                <div className={"bottom"}>
                                  <span className={"purchased"}>已领取</span>
                                  <StudyButton id={item.course_id} />
                                </div>
                              )
                              break
                            case 2:
                              des = (
                                <div className={"remain-time"}>
                                  <i className={"iconfont iconiconfront-21"} />
                                  <span>{item.play_times}人学习</span>
                                </div>
                              )
                              bottom = (
                                <div className={"bottom"}>
                                  <span className={"red"}>¥{item.price1}</span>
                                  <span className={"origin-price"}>
                                    ¥{item.price0}
                                  </span>
                                  <Link to={`/detail?id=${item.course_id}`}>
                                    立即购买
                                  </Link>
                                </div>
                              )
                              break
                            case 3:
                              des = (
                                <div className={"learner"}>
                                  <i className="iconfont iconRectangleCopy4" />
                                  <span>{item.play_times}人学习</span>
                                </div>
                              )
                              bottom = (
                                <div className="bottom">
                                  <span className={"purchased"}>已购买</span>
                                  <StudyButton id={item.course_id} />
                                </div>
                              )
                          }

                          const info = (
                            <div className="info">
                              <div className="title">{item.course_title}</div>
                              {des}
                              {bottom}
                            </div>
                          )
                          return (
                            <VList
                              img={item.image_name}
                              handleClick={this.handleClick}
                              id={item.course_id}
                              info={info}
                              key={index}
                            />
                          )
                        })}
                    </ul>
                  </li>
                )
              })}
          </ul>
        </div>
        <div className="no-more">-没有更多了-</div>
      </div>
    )
  }
}

function StudyButton({ id }) {
  return <Link to={`/play/video?id=${id}`}>立即学习</Link>
}

export default connect(
  (state) => ({ user: state.user }),
  null
)(WithFullSize(LimitFree))
