import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } 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 {
  @ViewChild('video') video: ElementRef;
  pdfPath: any;
  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;
  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 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.pdfPath = this.activatedRoute.snapshot.queryParams['path'];
    this.lifeCustomerInfo = JSON.parse(localStorage.getItem('lifeCustomerInfo'));
    if(!this.pdfPath){
      this.queryVideoPlayback(1);
    }
    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(this.status,null)
    }else{
      this.filePathQuery(this.status,this.fileId)
    }
  }

  filePathQuery(status,fileId){
    this.myService.filePath('3','0','23','yd_trainning_file_type',null,this.customerId,status,fileId).subscribe(res=>{
      if(res['success']){
        if(fileId){
          this.fileUploadItem = res['data']['fileUploadItemList'] ? res['data']['fileUploadItemList'][0] : '';
          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'];
        }
        
      }
    })
  }

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

  
  ngAfterViewInit(): void {
    if(!this.pdfPath){
     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)
     });
    }
   }
   ngOnDestroy(): void {
     if(!this.pdfPath){
       clearInterval(this.timer);
       clearInterval(this.timer2);
       this.saveVideoPlayback();
     }
   }
   menuPrevent() {
     return false;
   }
   saveVideoPlayback() {
     // playbackStatus		视频播放状态(1:未播放完;2:已播放完)	【必填】
     const param = {
       id: '',
       customerId: this.lifeCustomerInfo.customerId,
       practitionerId: this.lifeCustomerInfo.practitionerId,
       fileId: this.fileId,
       totalTime: this.video.nativeElement.duration,
       viewTime: this.video.nativeElement.currentTime,
       playbackStatus: this.video.nativeElement.currentTime >= this.video.nativeElement.duration ? 2 : 1,
     }
     this.myService.saveVideoPlayback(param).subscribe(res => {

     })
   }
 
   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){
    if(val.learningStatus == '3'){
      this.state.modal1 = true;
    }else{
      this.filePathQuery(val.learningStatus,val.fileId)
    }
   }
 

}
