import {
  ApplicationRef, ChangeDetectorRef,
  Component,
  ElementRef,
  EventEmitter,
  Input,
  OnChanges,
  OnInit,
  Output,
  ViewChild
} from '@angular/core';
import {NzMessageDataFilled, NzMessageService} from 'ng-zorro-antd';


@Component({
  // providers:[UploadImageWithPreviewComponent ],
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit, OnChanges {
  // @Input()
  item;
  @ViewChild('videoContainer')
  videoContainer: ElementRef;
  @ViewChild('videoNode')
  videoNode: ElementRef;
  @Output()
  update = new EventEmitter();
  newVideoCover = true;
  coverImg: any = null;


  KEY = 'dfzx_zx_video';

  videoUrl;

  showGuideAudio;

  private tooBigError: NzMessageDataFilled = null;


  constructor(private nzMessageService: NzMessageService,
              private appRef: ApplicationRef,
              public changeDetectorRef: ChangeDetectorRef) {


  }
  safeVideoUrl(url) {
    if (url && url.constructor.name === 'SafeUrlImpl') {
      this.videoNode && this.videoNode.nativeElement.removeAttribute('crossorigin');
      return url;
    }
    this.videoNode && this.videoNode.nativeElement.setAttribute('crossorigin', 'anonymous');
    return `${url}?t=${Math.random()}`;
  }
  ngOnChanges() {
    console.log(1, 'ngOnChanges');
  }
  ngOnInit() {

    this.item = {};
    this.item.contentObj = {};

    const getData = (<any> window).courseware.getData;
    getData((data) => {

      if (data) {
        this.item = data;
        this.videoUrl = this.item.contentObj.video_url;
      } else {
        this.item = {};
        this.item.contentObj = {};
      }

      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();

    }, this.KEY);

  }

  videoLoaded(evt, item) {
    // console.log(111, 'video loaded', item);
    const video  = evt.target;

    if (video.src.startsWith('blob:') && video.videoWidth > 1280 && video.videoHeight > 720) {
      this.tooBigError = this.nzMessageService.error('视频分辨率过大，请调整分辨率后上传，建议 1280x720', {nzDuration: 10 * 1000});
      // video.src = null;
      return ;
    } else {

      if (this.tooBigError && this.tooBigError.messageId) {
        this.nzMessageService.remove(this.tooBigError.messageId);
        this.tooBigError = null;
      }
    }

    if (video.src && video.src.startsWith('blob:')) {
      return;
    }
    if ( item.contentObj.origin_video_url && item.contentObj.origin_video_url.startsWith('http') ) {
      item.video_preview_thumb = null;
      return;
    }
    // item.video_preview_thumb = null;
    this.newVideoCover = true;
    video.currentTime = .1;
  }
  videoError(evt) {
    // this.nzMessageService.error('video error');
    this.videoUrl = this.videoUrl.replace("_l", "");
  }
  videoSeeked(evt) {
    const video  = evt.target;
    if (video.src && video.src.startsWith('blob:')) {
      return;
    }
    if (!this.item.contentObj.video_cover_url) {
      this.setVideoCover();
      this.newVideoCover = false;
    }

  }
  setVideoCover() {
    if (!this.videoNode) {
      return;
    }
    const video  = this.videoNode.nativeElement;
    if (!video.src) { return; }
    const canvas = document.createElement('canvas');
    canvas.setAttribute('crossorigin', "anonymous");
    canvas.width = video.videoWidth ;
    canvas.height = video.videoHeight ;
    canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);

    const video_preview_thumb = canvas.toDataURL();
    canvas.remove(); 

    const img: any = this.convertImageToBlob(video_preview_thumb);
    img.name = `video_${this.item.sid}_${Date.now()}_cover.png`;
    this.coverImg = img;
 
  }
  onCoverUploadSuccess(e) {
    this.coverImg = null;
    this.item.contentObj.video_cover_id = e.res_id;
    this.item.contentObj.video_cover_url = e.url;
    this.update.emit(this.item);
  }
  convertImageToBlob(data) {
    const imgType = data.substring(data.indexOf(':') + 1, data.indexOf(';'));
    const binary = atob(data.split(',')[1]);
    const array = [];
    let i = 0;
    while (i < binary.length) {
      array.push (binary.charCodeAt(i));
      i++;
    }
    return new Blob([ new Uint8Array(array) ], {type: imgType});
  }
  onVideoUploadSuccess(e) {
    const videoUrl = e.url.replace(/.mp4$/g, "_l.mp4");
    this.videoUrl = videoUrl;
    this.item.contentObj.video_url = videoUrl;
    this.save();
  }

  saveItem() {
    this.save();
  }

  save() {
    (<any> window).courseware.setData(this.item, null, this.KEY);
    this.refresh();
  }

  refresh() {
    setTimeout(() => {
      this.appRef.tick();
    }, 1);
  }


  guideBtnClick(value) {
    this.showGuideAudio = value;
  }
}

