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(this.status, null,this.fileUploadItem.mdDropOptionCode)
    } else {
      this.filePathQuery(this.status, this.fileId)
    }
  }

  filePathQuery(status, fileId,code=null) {
    if(status==='undefined'){
      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'];
        }

      }
    })
  }

  // 查询讲师信息
  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() {
    // 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);
      this.router.navigate(['/courseDetail','undefined',val.fileId],{replaceUrl:true});
      document.body.scroll({top:0,
      left: 0,
      behavior: 'smooth'})
    }
  }


}
