import React, { Component } from 'react';
import { http, SendMessageToApp } from "@/utils";
import { Link } from 'react-router-dom';
import './index.scss';
import { getParam } from '../../../utils';

class CoursePopup extends Component {
  constructor(props) {
    super(props);
    this.state = {
      courseList: []
    };
  }

  componentDidMount() {
    this.fetchCourseData();
  }
  
  fetchCourseData = () => {
    Promise.all([
      http.get(`${API.home}/sys/browse/blessing/courses`),
      http.get(`${API.home}/sys/user/blessing`)
    ]).then(res => {
      const { code, data } = res[0].data;
      const doneCourse = res[1].data.data.today_browsed_courses || [];
      if(code === 200) {
        this.setState({
          courseList: data.map(item => {
            if(doneCourse.some(id => id == item.course_id)) {
              return Object.assign({}, item, {
                blessing: 2
              });
            }
            return item;
          })
        });
      }
    });
  }

  toCourseDetail = (item) => {
    console.log(this.props);
    const {isLogin, history, toLogin} = this.props;
    // to={`/detail?id=${item.course_id}&ac=11`} 
    if(isLogin) {
      if(!getParam('version')) {
        history.push(`/detail?id=${item.course_id}&ac=11`);
      }else{
        let type = 0;
        if(item.blessing) {
          type = 2;
        }else{
          type = 1;
        }
        let data = {
          courseId: item.course_id,
          type: type // 正常跳课程详情页type:0,积福气浏览课程详情页-没有浏览过type:1 已浏览过type:2
        }
        SendMessageToApp("toCourse", data);
      }
    }else{
      toLogin();
    }
  }

  render() {
    const { courseList } = this.state;
    const { handleToHide } = this.props;
    return (
      <div className="course-popup__container">
        <div className="course-popup">
          <h2 className="course-popup__title">指定课程</h2>
          <div className="course-popup__list">
            {
              courseList.map(item => (
                <span
                  className="course-popup__item" 
                  key={item.course_id}
                  onClick={()=>{this.toCourseDetail(item)}}
                >
                  <span className="course-popup__name">{item.course_title}</span>
                  {
                    item.blessing && 
                    <span>+2点</span>
                  }
                </span>
              ))
            }
          </div>
        </div>
        <i className="iconfont iconiconfront-2" onClick={handleToHide}></i>
      </div>
    );
  }
}

export default CoursePopup;