index.js 29.7 KB
Newer Older
1
import React, { Component } from 'react'
2 3
import HeaderBar from '@/common/HeaderBar'
import './video.scss'
zhanghaozhe committed
4
import { NavLink, Route, Redirect, Switch } from 'react-router-dom'
zhanghaozhe committed
5
import { http, getParam, browser } from '@/utils'
6 7 8
import Recommendation from './recommendation'
import VideoCatalog from './video-catalog'
import DatumCatalog from './datum-catalog'
9
import { Toast } from 'antd-mobile'
10 11
import videojs from 'video.js'
import 'video.js/dist/video-js.min.css'
zhanghaozhe committed
12 13
import { Modal } from "antd-mobile"
import { Loading } from '@/common'
14
import { connect } from "react-redux"
15
import jsCookie from 'js-cookie'
xuzhenghua committed
16
import Single from "@/components/detail/single";
wangshuo committed
17
import SingleSuccess from "../detail/single/singleSuccess";
18
import './CustomPlayButton'
zhanghaozhe committed
19

xuzhenghua committed
20

zhanghaozhe committed
21
let alert = Modal.alert
22

23
function ProgressShareModal(props) {
zhanghaozhe committed
24 25 26 27 28 29 30 31 32 33 34 35 36
  return (
    props.isShow &&
    <div className='progress-share-modal-wrapper'>
      <div className="progress-share-modal">
        <div className="title">每日打卡</div>
        <ul className="progress-container">
          <li>
            <div className="title">累计学习</div>
            <div className="number"><span className='num'>{props.data.learn_day_count}</span>天</div>
          </li>
          <li>
            <div className="title">行动力超过</div>
            <div className="number"><span className='num'>{parseFloat(props.data.action_power)}</span>%
37
            </div>
zhanghaozhe committed
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
          </li>
        </ul>
        <div className="share-container">
          <div className="title">分享到</div>
          <ul>
            <li className='share-icon'>
              <a style={{display: 'block'}} href={props.data.url}>
                <div className="icon"><i className='iconfont iconweixinzhifu'/></div>
                <div className='text'>微信好友</div>
              </a>
            </li>
            <li className='share-icon'>
              <a style={{display: 'block'}} href={props.data.url}>
                <div className="icon"><i className='iconfont iconpengyouquaniconx'/></div>
                <div className='text'>朋友圈</div>
              </a>
            </li>
          </ul>
56
        </div>
zhanghaozhe committed
57 58 59 60
        <i className="iconfont iconiconfront-2 close" onClick={props.closeShareModal}/>
      </div>
    </div>
  )
61 62
}

63 64
class Video extends Component {

zhanghaozhe committed
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
  video   //video element
  player  //video player instance

  courseID

  ws  //websocket instance
  timer
  token
  count
  watchSec
  previousPlaybackRate = 1
  currentPlaybackRate = 1
  reconnect = true
  // timeEnough = false

  recordSocket
  recordTimer

  isCurrentVideoFirstPlay = true

  RECENTLEARN = "recent_learn"

  state = {
    title: '',
    courseId: null,
    videoList: [],
    datum: [],
    currentVideoSrc: '',
    activeIndex: 0,
    isAuth: true,
    course: {}, // course.course_id 为 0 或 '' 时 为免费课程
    salePrice: null,
    vCourseId: null,
    isLoading: true,
    isShowShareModal: false,
    shareData: {},
    singleBox: false,
    singMess: '',
    singleType: 1,// 单集购买需要
    nowPrice: 0,// 单集购买需要
    laterPrice: 0,// 单集购买需要
zhanghaozhe committed
106
    limitFreeNoPromptChecked: false,//是否勾选"不再显示此弹框"选项
zhanghaozhe committed
107
    showLimitFreePopup: false,
zhanghaozhe committed
108
    limitFreePopup: {},
zhanghaozhe committed
109 110
    isShowNeverShowPopupOption: false, //限时免费课程 播放结束后是否显示"不再显示此弹框"选项
    limitFreePopupVideos: JSON.parse(localStorage.getItem('limit-free-popup-videos'))
zhanghaozhe committed
111 112 113 114 115 116 117
  }


  componentDidMount() {
    if (window.location.protocol === 'https:') {
      window.location.replace('http' + window.location.href.slice(5))
      return
118 119
    }

zhanghaozhe committed
120 121 122 123
    this.courseID = getParam('id')
    if (!this.courseID) {
      this.props.history.replace('/')
      return
zhanghaozhe committed
124
    }
zhanghaozhe committed
125 126 127 128 129 130
    this.setState({
      courseId: this.courseID
    })
    const {location, location: {state = {}}} = this.props;
    if (state.oid) {
      this.check(state.oid);
xuzhenghua committed
131
    }
zhanghaozhe committed
132 133
    if (getParam('is_class') === 1 || getParam('weixinpay')) {
      this.payCallback()
xuzhenghua committed
134
    }
zhanghaozhe committed
135 136
    if (browser.isWeixin) {
      this.isweixinPay()
xuzhenghua committed
137
    }
zhanghaozhe committed
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
    this.token = jsCookie.get('token')
    this.getVideoList()
    this.getDatumCatalog()
  }

  // 直接购买
  tobuy = () => {
    // 详情页单集购买到该页面,url中的id不是课程id
    const {course = {}} = this.state;
    http.get(`${API['base-api']}/m/cart/addtopreorder/[${course.course_id}]`).then((res) => {
      if (res.data.errno === 0) {
        this.props.history.push(`/order?id=${course.course_id}`, {simple: 1})
      } else {
        Toast.info(res.data.msg, 2);
      }
    })
  }
  // 购买单集
  toSingleset = (item) => {
    this.setState({
      singleBox: true,
      singleType: 1,
      singMess: item
    })
    window.localStorage.setItem('singMess', JSON.stringify(item))
  }

  // 自组件传给父组件的boxHide
  boxHide = (val) => {
    this.setState({singleBox: val, singleType: 1})
  }

  // 单集购买 H5支付成功后回调
  payCallback = () => {
    const _this = this;
    if (!getParam('oid')) {
      return;
    } else {
      this.setState({
        singMess: JSON.parse(window.localStorage.getItem('singMess'))
      })
      _this.intervalPayStatus = setInterval(function () {
        http.get(`${API['base-api']}/m/orderState/oid/${getParam('oid')}`).then(res => {
          if (res.data.errno === 401) {
            clearInterval(_this.intervalPayStatus);
            _this.intervalPayStatus = null;
            // 获取课程类型
            http.get(`${API['base-api']}/class_order_status/${getParam('oid')}`).then((res) => {
              if (Number(res.data.data.errno) === 200) {
wangshuo committed
187
                // 正常购买单集成功
zhanghaozhe committed
188 189
                _this.setState({
                  singleType: 6,
wangshuo committed
190
                })
zhanghaozhe committed
191
              } else if (Number(res.data.data.errno) === 201) {
wangshuo committed
192
                // 0元参团
zhanghaozhe committed
193 194
                _this.setState({
                  singleType: 4,
wangshuo committed
195
                })
zhanghaozhe committed
196
              } else if (Number(res.data.data.errno) === 202) {
wangshuo committed
197
                // 0元购
zhanghaozhe committed
198 199
                _this.setState({
                  singleType: 3,
wangshuo committed
200
                })
zhanghaozhe committed
201
              } else if (Number(res.data.data.errno) === 203) {
wangshuo committed
202
                // 三天内特价
zhanghaozhe committed
203 204 205 206
                _this.setState({
                  nowPrice: res.data.data.data.now_price,
                  laterPrice: res.data.data.data.three_day_later_price,
                  singleType: 2,
wangshuo committed
207
                })
zhanghaozhe committed
208
              } else {
wangshuo committed
209
                Toast.info(res.data.data.msg, 2)
zhanghaozhe committed
210 211 212
              }
            })
          }
wangshuo committed
213
        })
zhanghaozhe committed
214
      }, 1000)
wangshuo committed
215
    }
zhanghaozhe committed
216 217 218 219 220 221 222 223 224 225 226
  };
  // 单集购买 微信内支付成功后回调
  isweixinPay = () => {
    let _this = this;
    let weixin_code = getParam('code');
    if (weixin_code) {
      if (!getParam('oid')) {
        return
      } else {
        this.setState({
          singMess: JSON.parse(window.localStorage.getItem('singMess'))
227
        })
zhanghaozhe committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
        // this.props.weixinPay(weixin_code)
        http.get(`${API['base-api']}/pay/wxpay/pub_charge/oid/${getParam('oid')}/code/${weixin_code}`).then((res) => {
          if (res.data.errno === 0) {
            const data = res.data.data;

            function onBridgeReady() {
              WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                  "appId": data.appId,                //公众号名称,由商户传入
                  "timeStamp": data.timeStamp,        //时间戳,自1970年以来的秒数
                  "nonceStr": data.nonceStr,          //随机串
                  "package": data.package,
                  "signType": data.signType,          //微信签名方式:
                  "paySign": data.paySign             //微信签名
                },
                function (res) {
                  if (res.err_msg == "get_brand_wcpay_request:ok") {
                    Toast.info('支付成功', 2);
                    _this.intervalPayStatus = setInterval(function () {
                      http.get(`${API['base-api']}/m/orderState/oid/${getParam('oid')}`).then(res => {
                        if (res.data.errno === 401) {
                          clearInterval(_this.intervalPayStatus);
                          _this.intervalPayStatus = null;
                          // 获取课程类型
                          http.get(`${API['base-api']}/class_order_status/${getParam('oid')}`).then((res) => {
                            if (Number(res.data.data.errno) === 200) {
                              // 正常购买单集成功
                              _this.setState({
                                singleType: 6,
                              })
                            } else if (Number(res.data.data.errno) === 201) {
                              // 0元参团
                              _this.setState({
                                singleType: 4,
                              })
                            } else if (Number(res.data.data.errno) === 202) {
                              // 0元购
                              _this.setState({
                                singleType: 3,
                              })
                            } else if (Number(res.data.data.errno) === 203) {
                              // 三天内特价
                              _this.setState({
                                nowPrice: res.data.data.data.now_price,
                                laterPrice: res.data.data.data.three_day_later_price,
                                singleType: 2,
                              })
                            } else {
                              Toast.info(res.data.data.msg, 2)
                            }
                          })
                        }
                      })
                    }, 1000)
                  } else {
                    alert('支付失败')
                  }
xuzhenghua committed
285
                }
zhanghaozhe committed
286
              )
xuzhenghua committed
287
            }
zhanghaozhe committed
288

zhanghaozhe committed
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
            if (typeof WeixinJSBridge == "undefined") {
              if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false)
              } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady)
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady)
              }
            } else {
              onBridgeReady()
            }
          } else {
            Toast.info(res.data.msg, 2)
          }
        })
      }
304
    }
zhanghaozhe committed
305 306 307 308 309 310 311 312 313 314 315
  };
  // 判断支付是否成功
  check = (oid) => {
    this.setState({
      singMess: JSON.parse(window.localStorage.getItem('singMess'))
    })
    http.get(`${API['base-api']}/class_order_status/${oid}`).then((res) => {
      if (Number(res.data.data.errno) === 200) {
        // 正常购买单集成功
        this.setState({
          singleType: 6,
zhanghaozhe committed
316

zhanghaozhe committed
317 318 319 320 321
        })
      } else if (Number(res.data.data.errno) === 201) {
        // 0元参团
        this.setState({
          singleType: 4,
322

xuzhenghua committed
323
        })
zhanghaozhe committed
324 325 326 327
      } else if (Number(res.data.data.errno) === 202) {
        // 0元购
        this.setState({
          singleType: 3,
328 329

        })
zhanghaozhe committed
330 331 332 333 334 335
      } else if (Number(res.data.data.errno) === 203) {
        // 三天内特价
        this.setState({
          nowPrice: res.data.data.data.now_price,
          laterPrice: res.data.data.data.three_day_later_price,
          singleType: 2,
zhanghaozhe committed
336

zhanghaozhe committed
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
        })
      } else {
        Toast.info(res.data.data.msg, 2)
      }
    })
  }

  // 9502 初始化 监听事件
  setupWS = () => {
    this.ws = new WebSocket(API["process-api"]);
    this.ws.addEventListener('error', () => {
      this.ws = null
    })
    this.ws.addEventListener('close', () => {
      if (this.reconnect) {
        this.ws = null
        setTimeout(() => {
          this.setupWS();
355
        }, 1000)
zhanghaozhe committed
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
      }
      clearInterval(this.timer)
      this.timer = null;
    })
    this.ws.addEventListener('message', e => {
      const data = JSON.parse(e.data);
      data.code == 4040 && (this.reconnect = false);
      if (data.code === 0) {
        if (data.data && data.data.position) {
          this.player.currentTime(data.data.position);
        }
      }
    })
  }

  sendMessage = message => {
    let readyState = this.ws.readyState, _this = this;
    if (readyState === 1) {
      this.ws && this.ws.send(JSON.stringify(message))
    } else if (readyState === 3) {
      this.ws.close();
      this.ws = null;
      let reconnect = setTimeout(function () {
        clearTimeout(reconnect);
        reconnect = null;
        _this.ws = new WebSocket(PROCESS_URL);
      }, 500);
zhanghaozhe committed
383
    }
zhanghaozhe committed
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
  }

  //视频结束请求接口
  getShareProgressInfo = () => {
    http.get(`${API['base-api']}/m/aist/share_data/${this.courseID}/${this.state.videoList[this.state.activeIndex]['id']}`)
      .then(res => {
        const {data} = res
        if (data.errno == 200) {
          this.setState({shareData: data.data, isShowShareModal: true})
        }
      })
  }

  //告诉服务端计算进度
  countSchedule = () => {
    const {videoList, activeIndex, vCourseId, course = {}} = this.state
    if (Number(course.course_id) === 0 || course.course_id === '') {
      return;
zhanghaozhe committed
402
    }
zhanghaozhe committed
403 404 405
    let ctype = 0;
    if (course.is_aist) {
      ctype = 2;
zhanghaozhe committed
406
    }
zhanghaozhe committed
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
    // 计算进度 根据ctype判断 课程类型 0-视频 1-直播 2-AI特训营
    this.sendMessage({
      mtype: 'count_schedule',
      uid: this.props.user.data.uid,
      token: this.token,
      platform: 5,
      video_id: videoList[activeIndex]['id'],
      course_id: this.state.courseId,
      v_course_id: vCourseId,
      ctype: ctype,
    })

  }
  // 发送时间消息
  sendWatchTime = (sec, rate) => {
    const {videoList, activeIndex, vCourseId, course = {}} = this.state
    // 免费课程不发送
    // if (Number(course.course_id) === 0 || course.course_id === '') {
    //     return;
    // }
    // 时间为0 不发送消息
    if (Number(sec) === 0) {
      return;
zhanghaozhe committed
430
    }
zhanghaozhe committed
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
    let ctype = 0;
    if (course.is_aist) {
      ctype = 2;
    }
    // 时间足够不发送
    // if(this.timeEnough) {
    //     return;
    // }
    this.sendMessage({
      mtype: 'watch_time',
      rate,
      time: sec,
      video_id: videoList[activeIndex]['id'],
      course_id: this.state.courseId,
      v_course_id: vCourseId,
      uid: this.props.user.data.uid,
      token: this.token,
      platform: 5,
      position: parseInt(this.player.currentTime()),
      ctype: ctype,
    })
  }

  setupTimer = () => {
    this.count = 0
    this.watchSec = 0
    clearInterval(this.timer)
    this.timer = null;
    this.timer = setInterval(() => {
      if (this.player && this.player.player()) {
        if (this.count === 5) {
          this.sendWatchTime(this.watchSec, this.currentPlaybackRate)
          this.count = this.watchSec = 0
        } else {
          !this.player.paused() && this.watchSec++
          !this.player.paused() && this.count++
xuzhenghua committed
467
        }
zhanghaozhe committed
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
      }
    }, 1000)

  }

  // 初始化视频播放器
  initializePlayer = () => {
    window.HELP_IMPROVE_VIDEOJS = false;
    this.player = videojs(this.video, {
      controls: true,
      preload: 'auto',
      bigPlayButton: false,
      textTrackDisplay: false,
      posterImage: false,
      errorDisplay: false,
      playbackRates: ['0.75', '1', '1.5', '2'],
      controlBar: {
        pictureInPictureToggle: false
      }
    })
    this.player.addChild('CustomPlayButtonCover')
    this.player.on('play', () => {
      const {videoList, activeIndex, vCourseId, course = {}} = this.state
      // 当视频播放时 看是否是第一次播放(初次进入页面 刷新页面 切换视频 都是第一次播放  需要获取上次的播放时间)
      if (this.isCurrentVideoFirstPlay) {
        // 当某些原因导致视频暂停时(用户暂停 网络不好等) 再播放时不需要发送
        this.isCurrentVideoFirstPlay = false;
        // 发送消息 recent_learn
        this.ws.send(JSON.stringify({
          mtype: this.RECENTLEARN,
          uid: this.props.user.data.uid,
          token: this.token,
          platform: 5,
          video_id: videoList[activeIndex]['id'],
          course_id: this.state.courseId,
          v_course_id: vCourseId,
          is_live: 0,
        }))
      }
      if (!this.timer) {
wangshuo committed
508
        this.setupTimer();
zhanghaozhe committed
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
      }
    })
    this.player.on('ratechange', () => {
      this.currentPlaybackRate = this.player.playbackRate()
      this.sendWatchTime(this.watchSec, this.previousPlaybackRate)
      this.count = this.watchSec = 0
      this.previousPlaybackRate = this.currentPlaybackRate
    })
    this.player.on('ended', () => {
      this.sendWatchTime(this.watchSec, this.currentPlaybackRate);
      this.count = this.watchSec = 0;
      this.countSchedule(); // 计算进度 -- 播放完毕
      // 返现课程才出现打卡记录
      if (this.state.course.is_aist) {
        this.getShareProgressInfo()
      }
      clearInterval(this.timer);
      this.timer = null;
zhanghaozhe committed
527 528 529 530 531
      if (this.state.limitFreePopup.is_free) {
        this.setState({
          showLimitFreePopup: true
        })
      }
zhanghaozhe committed
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
    })
  }

  sendLastRecord = () => {
    http.post(`${API.home}/m/course/record_last_video`, {
      v_course_id: this.state.course['v_course_id'],
      video_id: this.state.videoList[this.state.activeIndex].id
    })
  }

  componentWillUnmount() {
    this.player && this.player.dispose()

    clearInterval(this.timer)
    this.timer = null;
    this.ws && this.ws.close()
    this.ws = null

    clearInterval(this.recordTimer)
    this.recordSocket && this.recordSocket.close()
    this.recordSocket = null
  }

  // 选择新的视频
  selectVideo = index => {
    if (index === this.state.activeIndex) {
      return
559
    }
zhanghaozhe committed
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
    this.isCurrentVideoFirstPlay = true; // 切换视频则重置这个变量 因为新视频肯定是首次播放
    this.sendWatchTime(this.watchSec, this.currentPlaybackRate)
    this.countSchedule(); // 计算进度 -- 选择新视频(可能是M端特有的)
    this.setupTimer();

    this.setState(
      {
        activeIndex: index
      },
      () => {

        if (this.hasAuth(this.state.activeIndex)) {
          this.setPlayerSrc(this.state.videoList[index]['play_url'])
          this.sendLastRecord()
          this.playVideo()
xuzhenghua committed
575
        } else {
zhanghaozhe committed
576
          this.getCoursePrice();
xuzhenghua committed
577
        }
zhanghaozhe committed
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
      }
    );
  }

  getLastVideoIndex = lastIndex => {
    return this.state.videoList.findIndex(item => item.id == lastIndex)
  }

  getVideoList = () => {
    let url = '';
    if (getParam('video_id')) {
      url = `${API.home}/m/course/play/${this.courseID + '?video_id=' + getParam('video_id')}`
      http.post(`${API['base-api']}/sys/get_class_audition`, {
        video_id: getParam('video_id')
      })
    } else {
      url = `${API.home}/m/course/play/${this.courseID}`
595
    }
zhanghaozhe committed
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
    http.get(url).then(res => {
        const {data = {}, code} = res.data;
        if (code === 200) {
          this.setState(
            state => ({
              videoList: data['lessons'],
              currentVideoSrc: data['lessons'][state.activeIndex]['play_url'],
              course: data.course,
              courseId: data.course['course_id'],
              vCourseId: data.course['v_course_id'],
              title: data.course['course_title'],
              isLoading: false
            }),
            this.playSetup
          )
zhanghaozhe committed
611
          data.course.course_id && this.getLimitFreePopup(data.course.course_id)
zhanghaozhe committed
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
        } else {
          Toast.info(data.msg)
        }
      }
    )
  }

  playSetup = () => {
    // is_aist,是否AI特训营
    const {course = {}} = this.state;
    // if (Number(course.course_id) === 0 || course.course_id === '') {
    // }else{
    let _this = this;
    this.setupWS();
    this.setupTimer();
    let scheduleTime = setTimeout(function () {
      clearTimeout(scheduleTime);
      scheduleTime = null;
      _this.countSchedule(); // 刚进入页面的时候 就计算进度  先获取视频列表getVideoList 获取列表后 播放选择的视频 然后计算进度
    }, 1000);
    // }
    let index = this.getLastVideoIndex(course.last_video_id);
    index = index >= 0 ? index : 0;
    this.setState(
      {
        activeIndex: index
      },
      () => {
        if (this.lessonAvailable(index)) {
          if (this.hasAuth(index)) {
            Promise.resolve().then(() => {
              this.initializePlayer()
              this.playWithAuth()
            })
          } else {
            this.getCoursePrice();
          }
        } else {
          alert('暂无视频', '', [{
            text: 'OK',
            onPress: () => {
              this.props.history.push('/')
654
            }
zhanghaozhe committed
655
          }])
xuzhenghua committed
656
        }
zhanghaozhe committed
657 658
      }
    );
zhanghaozhe committed
659

zhanghaozhe committed
660
  }
xuzhenghua committed
661

zhanghaozhe committed
662 663 664
  setPlayerSrc = src => {
    if (!this.player) {
      this.initializePlayer()
zhanghaozhe committed
665
    }
zhanghaozhe committed
666 667 668 669 670
    this.player.src({
      src,
      type: 'application/x-mpegURL'
    })
  }
zhanghaozhe committed
671

zhanghaozhe committed
672 673 674 675
  playVideo = () => {
    this.player.ready(() => {
      this.player.play()
    })
676

zhanghaozhe committed
677
  }
678 679


zhanghaozhe committed
680 681 682 683 684
  getDatumCatalog() {
    http.get(`${API.home}/m/course/data/${this.courseID}`)
      .then(res => {
        const data = res.data
        if (data.code === 200) {
685

zhanghaozhe committed
686 687 688
          this.setState({
            datum: data.data
          })
zhanghaozhe committed
689

zhanghaozhe committed
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
        } else {
          Toast.info(data.msg)
        }
      })
  }

  lessonAvailable = index => {
    return this.state.videoList[index]['video_size'] !== 0
  }

  getCoursePrice = () => {
    const {course = {}} = this.state;
    http.get(`${API.home}/sys/course/price/${course.course_id}`)
      .then(res => {
        const {data} = res
        if (data.code === 200) {
          this.setState({
            salePrice: data.data['sale_price']
          })
        }
      })
  }
zhanghaozhe committed
712

zhanghaozhe committed
713 714
  playWithAuth = () => {
    const {videoList, activeIndex} = this.state
zhanghaozhe committed
715

zhanghaozhe committed
716 717
    if (this.hasAuth(activeIndex)) {
      this.setPlayerSrc(videoList[activeIndex]['play_url'])
zhanghaozhe committed
718
    }
zhanghaozhe committed
719
  }
zhanghaozhe committed
720

zhanghaozhe committed
721 722
  hasAuth = index => {
    const {videoList} = this.state
xuzhenghua committed
723

zhanghaozhe committed
724
    let lesson = videoList[index]
xuzhenghua committed
725

zhanghaozhe committed
726 727 728 729 730 731 732 733 734 735
    if (lesson['video_auth']) {
      this.setState({
        isAuth: true
      })
      return true
    } else {
      this.setState({
        isAuth: false
      })
      return false
zhanghaozhe committed
736 737

    }
zhanghaozhe committed
738 739
  }

zhanghaozhe committed
740 741 742 743 744 745 746 747
  getLimitFreePopup = id => {
    http.post(`${API.home}/sys/popup`, {
      course_id: id
    })
      .then(res => {
        const {code, msg, data} = res.data
        if (code === 200) {

zhanghaozhe committed
748
          const {courseId, limitFreePopupVideos} = this.state
zhanghaozhe committed
749
          this.setState({
zhanghaozhe committed
750 751
            limitFreePopup: data,
            isShowNeverShowPopupOption: limitFreePopupVideos ?  limitFreePopupVideos.includes(courseId) : false
zhanghaozhe committed
752 753 754 755 756 757 758 759
          })

        } else {
          Toast.info(msg, 2, null, false)
        }
      })
  }
  checkNeverShowLimitFreePopup = () => {
zhanghaozhe committed
760 761 762
    if (!this.state.limitFreeNoPromptChecked) {
      return
    }
zhanghaozhe committed
763 764 765 766 767 768 769 770 771 772
    http.post(`${API.home}/sys/checklist`, {
      course_id: this.state.course.course_id
    })
      .then(res => {
        const {code, msg} = res.data
        if (code === 200) {
          this.setState({
            limitFreePopup: {...this.state.limitFreePopup, is_free: 0}
          })

zhanghaozhe committed
773
        } else {
zhanghaozhe committed
774 775 776 777 778 779
          Toast.info(msg, 2, null, false)

        }
      })
  }

zhanghaozhe committed
780 781
  render() {
    let {match, location, history} = this.props
zhanghaozhe committed
782 783 784 785 786 787 788 789 790
    const {
      videoList,
      activeIndex,
      isAuth,
      salePrice,
      course,
      singleBox,
      singleType,
      showLimitFreePopup,
zhanghaozhe committed
791 792
      limitFreePopup,
      isShowNeverShowPopupOption
zhanghaozhe committed
793
    } = this.state;
zhanghaozhe committed
794 795 796
    let toHref = '';
    if (location.state && location.state.to && location.state.to === 'detail') {
      toHref = `/detail?id=${course.course_id}`
zhanghaozhe committed
797
    }
zhanghaozhe committed
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
    return (
      <div className='play'>
        <HeaderBar title={this.state.title} arrow={true} toHref={() => {
          toHref ? history.push(
            toHref,
            {
              to: 'classify'
            }
          ) : history.go(-1)
        }}/>
        <Loading isLoading={this.state.isLoading}>
          <div className="video">
            <video className={'video-js'} ref={el => this.video = el}
                   webkit-playsinline="true"
                   playsInline={true}
                   x-webkit-airplay="allow"
                   x5-video-player-type="h5">
              <source src={'/'} type='application/x-mpegURL'/>
            </video>
            {
              !isAuth && !!videoList[activeIndex]['is_class'] && (
                <div className="purchase-box">
                  <div className='hint'>您尚未购买该课时,请购买后学习。</div>
                  <div className='btns'>
                    <button
                      type='button'
                      onClick={this.tobuy}
                      className='purchase-class'
                    >
                      ¥{salePrice} 购买课程
                    </button>
                    <button
                      type='button'
                      onClick={this.toSingleset.bind(this, videoList[activeIndex])}
                      className='purchase-episode'
                    >
                      ¥{videoList.length && videoList[activeIndex]['class_price']} 购买单集
                    </button>
                  </div>
                </div>
              )
            }
            {
              !isAuth && !!course.is_aist && (
                <div className="is-aist-box">
                  <i className={'iconfont iconiconfront-21'}></i>
                  <p className={'time'}>{videoList[activeIndex]['aist_start_time']}</p>
                  <p className={'time'}>请耐心等待...</p>
                </div>
              )
            }
          </div>
          <div className='tab'>
            <div>
              <NavLink to={{pathname: `${match.url}/video`, search: `?id=${this.courseID}`}}
                       replace
                       activeClassName='active'
              >视频</NavLink>
            </div>
            <div>
              <NavLink to={{pathname: `${match.url}/datum`, search: `?id=${this.courseID}`}}
                       replace
                       activeClassName='active'
              >资料</NavLink>
            </div>
          </div>

          {/*单集购买*/}
          {
            singleBox &&
            <Single
              courseId={course.course_id}
              singleBox={this.state.singleBox}
              boxHide={this.boxHide}
              data={this.state.singMess}
              singleType={this.state.singleType}
              vcourseId={course.v_course_id}
              videoId={this.state.singMess.video_id}
              check={this.check}
              title={this.state.singMess.course_tile}/>
          }
          {/* 单集购买成功 */}
          {
            singleType !== 1 &&
            <SingleSuccess
              courseId={course.course_id}
              boxHide={this.boxHide}
              data={this.state.singMess}
              singleType={singleType}
              vcourseId={course.v_course_id}
              videoId={this.state.singMess.video_id}
              nowPrice={this.state.nowPrice}
              laterPrice={this.state.laterPrice}
            />
          }

        </Loading>
        <Switch>
          <Redirect exact from={'/play'} to={{
            pathname: '/play/video',
            search: location.search
          }}/>
          <Route
            path={`${match.path}/video`}
            render={props => {
              return (
                <VideoCatalog
                  activeIndex={this.state.activeIndex}
                  selectVideo={this.selectVideo}
                  videoCatalog={videoList}
zhanghaozhe committed
908
                  isAist={course.is_aist}
zhanghaozhe committed
909
                  {...props}
910
                />
zhanghaozhe committed
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
              );
            }}
          />
          <Route path={`${match.path}/datum`} render={props => {
            return <DatumCatalog {...props} datum={this.state.datum}/>
          }}/>
        </Switch>
        <Route render={props => {
          return this.state.vCourseId ? <Recommendation {...props} vCourseId={this.state.vCourseId}/>
            : null
        }}/>
        <ProgressShareModal isShow={this.state.isShowShareModal}
                            closeShareModal={() => this.setState({isShowShareModal: false})}
                            data={this.state.shareData}
        />
        {
          showLimitFreePopup &&
          <div className={'limit-free-cover'}>
            <div className="free-popup">
              <div className="title">
zhanghaozhe committed
931
                <span>{limitFreePopup.pop_descbition}</span>
zhanghaozhe committed
932 933 934
              </div>
              <div className={'des'}>
                <img className="qrcode"
zhanghaozhe committed
935
                     src={limitFreePopup.wechat_img} alt=''/>
zhanghaozhe committed
936
                <span>长按/扫码识别</span>
zhanghaozhe committed
937
                <span>添加时请备注<span>{course.course_id}</span>哦</span>
zhanghaozhe committed
938
                <div className="no-prompt">
zhanghaozhe committed
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
                  {
                    isShowNeverShowPopupOption &&
                    <label htmlFor="no-prompt">
                      <span
                        className={`checkbox-label ${this.state.limitFreeNoPromptChecked ? 'checked' : 'unchecked'}`}>
                        <i className={'iconfont iconiconfront-73'}/>
                      </span>
                      <input type="checkbox" id={'no-prompt'} onChange={(e) => {
                        this.setState({
                          limitFreeNoPromptChecked: e.target.checked
                        })
                      }}/>
                      <span>本课程不再提示</span>
                    </label>
                  }
zhanghaozhe committed
954 955 956 957
                </div>
              </div>
              <i className={'close-btn iconfont iconiconfront-2'} onClick={() => {
                this.setState({
zhanghaozhe committed
958 959
                  showLimitFreePopup: false,
                  isShowNeverShowPopupOption: true
zhanghaozhe committed
960
                })
zhanghaozhe committed
961 962 963 964
                const {courseId, limitFreePopupVideos} = this.state
                localStorage.setItem('limit-free-popup-videos', JSON.stringify(
                  limitFreePopupVideos ? [...limitFreePopupVideos, courseId] : [courseId]
                ))
zhanghaozhe committed
965
                this.checkNeverShowLimitFreePopup()
zhanghaozhe committed
966
              }}/>
967
            </div>
zhanghaozhe committed
968 969 970 971 972
          </div>
        }
      </div>
    );
  }
973 974 975
}


976
export default connect(
zhanghaozhe committed
977 978
  state => ({user: state.user}),
  null
xuzhenghua committed
979
)(Video);