/* eslint-disable eqeqeq */
import React, { Component } from "react"
import "./index.scss"

class CourseItem extends Component {
  constructor(props) {
    super(props)
    this.state = {
      countdown: "",
    }
  }

  componentDidMount() {
    const { time } = this.props
    this.startCountDown(time)
  }

  componentWillReceiveProps(nextProps) {
    const { time: newTime } = nextProps
    const { time: oldTime } = this.props
    if (oldTime != newTime) {
      this.startCountDown(newTime)
    }
  }

  startCountDown = (time) => {
    if (time) {
      let date = time * 1000,
        hours = 0,
        minutes = 0,
        seconds = 0
      setInterval(() => {
        date -= 1000
        hours = `${parseInt(date / (60 * 60 * 1000))}`.padStart(2, 0)
        minutes = `${parseInt((date - hours * 3600000) / 60000)}`.padStart(2, 0)
        seconds = `${parseInt(
          (date - hours * 3600000 - minutes * 60000) / 1000
        )}`.padStart(2, 0)
        this.setState({
          countdown: `${hours}时${minutes}分${seconds}秒后结束`,
        })
      }, 1000)
    }
  }

  render() {
    const { image, toCourse, id } = this.props
    const { countdown } = this.state
    return (
      <div className="course-container">
        <div className="course__cover">
          {countdown && <p className="course__time">{countdown}</p>}
          <img src={image} alt="cover" onClick={() => toCourse(id)} />
        </div>
        {this.props.children}
      </div>
    )
  }
}

export default CourseItem
