import { AfterViewInit, Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { LifeCommonService } from 'src/app/common/life-common.service';
import { MyService } from '../my.service';

@Component({
  selector: 'ydlife-course-detail',
  templateUrl: './course-detail.component.html',
  styleUrls: ['./course-detail.component.scss']
})
export class CourseDetailComponent implements OnInit,OnDestroy {
  @ViewChild('video') video: ElementRef;
  lifeCustomerInfo: any;
  timer: any;
  timer2: any;
  videoPlaybacks: Array<any>;
  originTime: number = 0;
  fileId: string;
  deviceType: string;
  maxViewTime: number = 0;
  status: string;
  tabType: number = 1;
  LecturerInfo: any;
  canplay:boolean = true;
  public fileUploadItem: any;
  public fileUploadItemList: Array<any>;
  public customerId: string = localStorage.getItem('lifeCustomerInfo') ? JSON.parse(localStorage.getItem('lifeCustomerInfo')).customerId : null;
  state = {
    modal1: false,
  };
  onClose(key) {
    this.state[key] = false;
  }

  constructor(private router:Router,private activatedRoute: ActivatedRoute, private myService: MyService, private lifeCommonService: LifeCommonService) { }

  ngOnInit() {
    this.fileId = this.activatedRoute.snapshot.params.fileId;
    this.status = this.activatedRoute.snapshot.params.status;
    this.deviceType = this.lifeCommonService.checkDeviceType();
    this.lifeCustomerInfo = JSON.parse(localStorage.getItem('lifeCustomerInfo'));
    this.filePathQuery(this.status, this.fileId);
  }

  // tab切换
  switchTab(type) {
    this.tabType = type;
    if (type === 3) {
      this.lecturerQuery(this.fileUploadItem.fileLecturerId);
    } else if (type == 2) {
      this.filePathQuery(null, null,this.fileUploadItem.mdDropOptionCode)
    } else {
      this.filePathQuery(this.status, this.fileId)
    }
  }

  filePathQuery(status, fileId,code=null) {
    if(status=='undefined' || status == '0'){
      status = undefined;
    }
    this.myService.filePath('3', '0', '23', 'yd_trainning_file_type', code, this.customerId, status, fileId).subscribe(res => {
      if (res['success']) {
        if (fileId) {
          this.fileUploadItem = res['data']['fileUploadItemList'] ? res['data']['fileUploadItemList'][0] : null;
          if(this.fileUploadItem && this.fileUploadItem.filePath.indexOf('.pdf') < 0 && (this.fileUploadItem.learningStatus == 1 || this.fileUploadItem.learningStatus == 2)){
            this.canplay = true;
          }else{
            this.canplay = false;
          }
          if (this.canplay) {
            this.queryVideoPlayback(1);
            setTimeout(() => {
              this.video.nativeElement.addEventListener('pause', () => { //暂停开始执行的函数
                clearInterval(this.timer);
                clearInterval(this.timer2);
                console.log('暂停播放')
                this.saveVideoPlayback();
              });
              this.video.nativeElement.addEventListener('play', () => { //开始执行的函数
                this.timer = setInterval(() => {
                  console.log('开始播放')
                  this.saveVideoPlayback();
                }, 1000 * 20)
                this.queryVideoPlayback(2)
              });
              if (this.fileUploadItem.isDownload == '2') {
                this.video.nativeElement.setAttribute('controlslist', this.video.nativeElement.getAttribute('controlslist') + ' nodownload')
              } else {
                this.video.nativeElement.setAttribute('controlslist', this.video.nativeElement.getAttribute('controlslist'))
              }
              if (this.fileUploadItem.isControlPlayback == '2') {
                this.video.nativeElement.setAttribute('controlslist', this.video.nativeElement.getAttribute('controlslist') + ' noplaybackrate')
              } else {
                this.video.nativeElement.setAttribute('controlslist', this.video.nativeElement.getAttribute('controlslist'))
              }
            })
          }
        } else {
          this.fileUploadItemList = res['data']['fileUploadItemList'];
        }
      }else{
        clearInterval(this.timer);
        clearInterval(this.timer2);
      }
    })
  }

  // 查询讲师信息
  lecturerQuery(id) {
    const param = {
      id: id
    }
    this.myService.lecturerQuery(param).subscribe(res => {
      if (res['success']) {
        this.LecturerInfo = res['data']['lecturerInfos'][0]
      }
    })
  }

  ngOnDestroy(): void {
    if (this.canplay) {
      clearInterval(this.timer);
      clearInterval(this.timer2);
      this.saveVideoPlayback();
    }
  }
  menuPrevent() {
    return false;
  }
  saveVideoPlayback(type=1) {
    // playbackStatus		视频播放状态(1:未播放完;2:已播放完)	【必填】
    let param = {
      id: '',
      customerId: this.lifeCustomerInfo.customerId,
      practitionerId: this.lifeCustomerInfo.practitionerId,
      fileId: this.fileId,
    }
    if(type===2){
      param['playbackStatus'] = param['totalTime'] == param['viewTime'] ? 1 : 2;
      param['totalTime'] =  param['viewTime'] = 0;
    }else{
      param['totalTime']=this.video.nativeElement.duration;
      param['viewTime']= this.video.nativeElement.currentTime;
      param['playbackStatus']=this.video.nativeElement.currentTime >= this.video.nativeElement.duration ? 2 : 1;
      if(param['totalTime'] == param['viewTime']){
        clearInterval()
      }
    }

    this.myService.saveVideoPlayback(param).subscribe(res => {

    })
  }

  // 立即阅读
  viewPdfDetail(fileId){
    this.saveVideoPlayback(2);
    this.router.navigate(['/pdfView',fileId]);
  }

  queryVideoPlayback(type) {
    const param = {
      id: null,
      customerId: this.lifeCustomerInfo.customerId,
      practitionerId: this.lifeCustomerInfo.practitionerId,
      fileId: this.fileId,
    }
    this.myService.queryVideoPlayback(param).subscribe(res => {
      if (res['success']) {
        this.videoPlaybacks = res['data']['videoPlaybacks'];
        this.maxViewTime = this.videoPlaybacks[0] ? this.videoPlaybacks[0]['maxViewTime'] : 0;
        if (type === 1) {
          // 设置开始播放时间为上次离开时间
          this.originTime = this.video.nativeElement.currentTime = this.videoPlaybacks.length > 0 ? this.videoPlaybacks[0]['viewTime'] : 0;
        } else {
          // 监测有没有拖动进度条
          this.timer2 = setInterval(() => {
            if (this.video.nativeElement.currentTime - this.originTime > 1 && this.video.nativeElement.currentTime > this.maxViewTime) {
              this.video.nativeElement.currentTime = this.originTime;
            }
            this.originTime = this.video.nativeElement.currentTime;
          }, 500)
        }
      } else {
        this.video.nativeElement.currentTime = 0;
      }
    })
  }

  download(path) {
    window.open(path)
  }

  selectVideo(val) {
    clearInterval();
    if (val.learningStatus == '3') {
      this.state.modal1 = true;
    } else {
      this.fileId = val.fileId;
      this.filePathQuery(val.learningStatus, this.fileId);
      this.router.navigate(['/courseDetail','undefined',this.fileId],{replaceUrl:true});
      document.body.scroll({top:0,
      left: 0,
      behavior: 'smooth'})
    }
  }
  


}
