import React, { Component } from "react"
import { http } from "src/utils"
import { HeaderBar } from "src/common"
import CollegeBanner from "./banner"
import CollegeHeader from "./header"
import "./courseList.scss"
import { Toast } from "antd-mobile"

class CollegeCourse extends Component {
  constructor(props) {
    super(props)
    this.state = {
      header: "",
      courseList: [],
    }
  }

  componentDidMount() {
    this.fetchCourseList()
  }

  fetchCourseList = () => {
    const { match } = this.props
    const id = match.params.id || 0
    http.get(`${API["home"]}/sys/school/${id}`).then((res) => {
      const { code, data } = res.data
      if (code === 200) {
        this.setState({
          header: data.name,
          courseList: data.data,
        })
        document.title = `助力高校在线教学计划之${data.name}专区 - 七月在线`
      }
    })
  }

  toCourseDetail = (id) => {
    const { history, match } = this.props
    const school_id = match.params.id || 0
    http
      .post(`${API["home"]}/sys/school/verify`, {
        school_id,
        course_id: id,
      })
      .then((res) => {
        const { code, msg } = res.data
        if (code === 200) {
          history.push(`/detail?id=${id}`)
        } else if (code === 4030 || code === 4013) {
          history.push("/passport/login")
        } else {
          Toast.info(`${msg}~`)
        }
      })
  }

  render() {
    const { courseList = [], header } = this.state
    return (
      <>
        <HeaderBar title={"助学计划"} arrow={true} />
        <CollegeBanner />
        <CollegeHeader
          headerStyle={{
            marginTop: "20px",
          }}
          title={header}
        />
        <p className="college-course__desc">
          点击需要学习的课程封面，在课程详情页进入购买流程凭免单券免费兑换课程。
        </p>
        <div className="college-course__body">
          {courseList.map((item) => (
            <div
              className="college-course__item"
              onClick={() => this.toCourseDetail(item.course_id)}
              key={item.course_id}
            >
              <i
                className="college-course__cover"
                style={{ backgroundImage: `url(${item.image_name})` }}
              ></i>
              <p className="college-course__title">{item.course_title}</p>
            </div>
          ))}
        </div>
      </>
    )
  }
}

export default CollegeCourse
