import React, { Component } from 'react';
import { http } from '@/utils';
import { HeaderBar } from "@/common";
import CollegeBanner from './banner';
import './courseList.scss';
import { Toast } from 'antd-mobile';

class CollegeCourse extends Component {

  constructor(props) {
    super(props);
    this.state = {
      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({
          courseList: data
        });
      }
    });
  }

  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 = [] } = this.state;
    return (
      <>
        <HeaderBar title={'助学计划'} arrow={true}/>
        <CollegeBanner />
        <div className="college-course__header">
          <i className="header__decorate"></i>
          <p className="header__desc">点击需要学习的课程封面，在课程详情页进入购买流程凭免单券免费兑换课程。</p>
        </div>
        <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;