import React, { Component } from "react"
import VList from '@/common/v-list-base'
import './my-courses.scss'
import { isToday, format } from "date-fns"
import { connect } from "react-redux"
import { fetchCoursesListIfNeeded, switchTab } from "./actions"
import InfiniteScroll from 'react-infinite-scroller'
import { debounce } from 'lodash'
import { Link } from 'react-router-dom'
import { Loading } from "@/common";


function getStudyTime(seconds) {
  return {
    hour: Math.floor(seconds / (60 * 60)),
    min: Math.floor(seconds / 60) % 60,
    sec: seconds % 60
  }
}

const AddCourse = React.memo(({addCourseClick}) => (
  <div className='add-course'>
    <button className='add' onClick={addCourseClick}>添加课程+</button>
  </div>
))

function Record({record: {seconds, lesson_name}}) {
  let re = /第[\s\S]+?课/,
    result = ''

  if (lesson_name) {
    let matchResult = re.exec(lesson_name)
    result += (matchResult && matchResult[0]) ? matchResult[0] : ''
  }

  if (seconds) {
    let studyTime = getStudyTime(seconds)
    let hour = studyTime.hour ? String(studyTime.hour).padStart(2, '0') + ':' : '',
      min = studyTime.min ? String(studyTime.min).padStart(2, '0') + ':' : '',
      sec = studyTime.sec ? String(studyTime.sec).padStart(2, '0') : ''

    result += hour + min + sec
  }

  return (
    <span className={'record'}>
            {
              result.length ? `学习到${result}` : null
            }
        </span>
  )
}


const Bottom = React.memo(({item}) => {
  if (item.ago || item.seconds) {
    let date = new Date(item.ago * 1000)
    let time = isToday(date) ? format(date, 'HH时mm分') : format(date, 'MM月DD日')
    return (
      <div className="des">
        <span className='time'>{time}</span>
        <Record record={item}/>
      </div>
    )
  }
  return (
    <button className='start-learn'>开始学习</button>
  )
})

class MyCourses extends Component {

  list

  state = {
    isLoading: true
  }

  handleClick = (id, item) => {
    const {history} = this.props
    const {mode, course_id} = item
    if (mode && mode == 6) {
      history.push(`/python?id=${course_id}`)
      return
    }
    history.push(`/play/video?id=${id}`)
  }
  addCourseClick = () => {
    this.props.history.push('/classify')
  }

  componentDidMount() {
    this.props.switchTab(false)
    this.props.fetchCoursesListIfNeeded()
  }

  componentWillUnmount() {
    this.props.switchTab(true);
  }

  loadFunc = debounce(() => {
    if (this.props.courseList.length % 10 === 0) {
      this.props.fetchCoursesListIfNeeded()
    }
  }, 200)

  render() {
    let {courseList, user} = this.props

    return <Loading isLoading={this.props.isLoading}>
      {
        courseList && courseList.length !== 0
          ?
          <>
            <div className="my-course-uid">
              {`加群请备注您的学号:${!user.hasError && this.props.user.data.uid}`}
            </div>
            <InfiniteScroll
              pageStart={0}
              hasMore={true}
              loadMore={this.loadFunc}
              useWindow={false}
            >
              <ul ref={el => this.list = el}>
                {
                  courseList.map((item, index) => {

                    const Info = (
                      <div className="info">
                        <div className='title'>{item.course_title}</div>
                        {
                          !item.is_restricted && item.is_aist &&
                          <div className='contact'>助教微信:{item.assist_weixin}</div>
                        }
                        {
                          !item.is_restricted && !item.is_aist && item.contact_type == 1 && item.course_qq &&
                          <div className='contact'>QQ群:{item.course_qq}</div>
                        }
                        {
                          !item.is_restricted && !item.is_aist && item.contact_type == 2 && item.course_qq &&
                          <div className='contact'>班主任微信:{item.course_qq}</div>
                        }

                        {
                          item.is_aist && item.aist_schedule &&
                          <div className="process-status">
                            <div className="process-wrapper">
                              <div className="process-bar"
                                   style={{width: `${parseFloat(item.aist_schedule)}%`}}/>
                            </div>
                            <div className="process-text">{item.aist_schedule}</div>
                          </div>
                        }
                        <Bottom item={item}/>
                      </div>
                    )

                    const status = (
                      item.is_aist
                        ? <span className='status'>返现</span>
                        : item.course_expire
                        ? <span className='course-expire'>{item.course_expire}</span>
                        : null
                    )
                    return (
                      <VList img={item.image_name}
                             handleClick={this.handleClick}
                             {...item}
                             key={index}
                             info={Info}
                             status={status}
                             item={item}
                             id={item['v_course_id']}
                      />
                    )
                  })
                }
              </ul>
            </InfiniteScroll>
            {
              courseList.length % 10 !== 0 ?
                <AddCourse addCourseClick={this.addCourseClick}/>
                : null
            }
          </>
          :
          <div className="empty">
            <p><i className='iconfont iconfish'/></p>
            <p className='empty-prompt'>您还没有课程哦,赶快去选课吧~</p>
            <p>
              <Link className='select-course' to='/classify'>去选课</Link>
            </p>
          </div>
      }
    </Loading>

  }
}

export default connect(
  state => ({
    courseList: state.myCourses.courseList,
    user: state.user,
    isLoading: state.myCourses.isLoading
  }),
  {
    fetchCoursesListIfNeeded,
    switchTab
  })(MyCourses)