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

@Component({
  selector: 'ydlife-video',
  templateUrl: './video.component.html',
  styleUrls: ['./video.component.scss']
})
export class VideoComponent implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild('video') video: ElementRef;
  videoSrc: string;
  pdfPath: any;
  permissions: any;
  lifeCustomerInfo: any;
  timer: any;
  timer2: any;
  videoPlaybacks: Array<any>;
  originTime: number = 0;
  fileId:string;
  deviceType:string;
  maxViewTime:number = 0;
  constructor(private activatedRoute: ActivatedRoute, private myService: MyService,private lifeCommonService:LifeCommonService) { }

  ngOnInit() {
    this.deviceType = this.lifeCommonService.checkDeviceType();
    this.videoSrc = sessionStorage.getItem('videoPath');
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.pdfPath = this.activatedRoute.snapshot.queryParams['path'];
    this.lifeCustomerInfo = JSON.parse(localStorage.getItem('lifeCustomerInfo'));
    this.fileId = this.activatedRoute.snapshot.params['fileId'];
    if(!this.pdfPath){
      this.queryVideoPlayback(1);
    }
  }

  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)
    });
    if (this.permissions.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.permissions.isControlPlayback == '2') {
      this.video.nativeElement.setAttribute('controlslist', this.video.nativeElement.getAttribute('controlslist') + ' noplaybackrate')
    } else {
      this.video.nativeElement.setAttribute('controlslist', this.video.nativeElement.getAttribute('controlslist'))
    }
   }
  }
  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 => {
      console.log(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]['maxViewTime'];
        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;
      }
      console.log(res);
    })
  }

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

}
