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_03';

  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');
    // console.log('safeVideoUrl', url)
    return `${url}?t=${Math.random()}`;
    // const d = this.sanitization.bypassSecurityTrustResourceUrl(url);
    return `${url}`; // ?t=${Math.random()  //this.sanitization.bypassSecurityTrustHtml(url);
  }
  ngOnChanges() {
    console.log(1, 'ngOnChanges');
    // if (typeof this.item.contentObj.video_url !== 'string') {
    //   // this.item.contentObj.video_url = '';
    //   setTimeout(() => {
    //   this.item.contentObj.video_url = '';
    //   });
    // }
  }
  ngOnInit() {
    console.log(2, 'ngOnInit');
    // if (typeof this.item.contentObj.video_url !== 'string') {
    //   // this.item.contentObj.video_url = '';
    //   setTimeout(() => {
    //     this.item.contentObj.video_url = '';
    //   });
    // }

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

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

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

      console.log('data:', data);
      // this.init();

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

      // this.refresh();

    }, 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;
    // setTimeout(() => {
    //   this.setVideoCover();
    // }, 1500);
    // this.videoSeeked(evt, item);
  }
  videoError(evt) {
    this.nzMessageService.error('video error');
  }
  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() {
    // console.log(111)
    // (seeked)="videoSeeked($event, item)"
    // if (!item.video_preview_thumb) {
    if (!this.videoNode) {
      return;
    }
      const video  = this.videoNode.nativeElement;
      if (!video.src) { return; }
    // console.log(222, video.currentTime)
      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);

      // item.video_preview_thumb = canvas.toDataURL();
      const video_preview_thumb = canvas.toDataURL();

      // console.log(video_preview_thumb.substr(0, 100));
      // console.log('%c       ', `font-size: 100px; background: url(${video_preview_thumb}) no-repeat;`);
      canvas.remove();
      // video.currentTime = 0;
    // }

    const img: any = this.convertImageToBlob(video_preview_thumb);
    img.name = `video_${this.item.sid}_${Date.now()}_cover.png`;
    this.coverImg = img;

    // this.coverComponent.customUpload(img);
    /*
    const formData = new FormData();
    formData.append('file', img);
    this.coursewareService.uploadResource(formData).then(res => {
      // console.log(res);
      // console.log(1, this.item.contentObj.video_url);
      this.item.contentObj.pic_id = res.res_id;
      // const ndata = JSON.parse(JSON.stringify(this.item)); // Object.assign({}, this.item);
      // if (typeof ndata.contentObj.video_url !== 'string') {
      //   delete  ndata.contentObj.video_url;
      // }
      //
      // console.log(2, ndata.contentObj.video_url);
      // console.log(3, this.item.contentObj.video_url);
      this.update.emit(this.item);
    });
    */

  }
  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) {
    this.item.contentObj.video_url = e.url;
    this.save();
  }

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

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

