import {Component, ElementRef, ViewChild, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef} from '@angular/core';
import {NzMessageService, NzMessageDataFilled} from 'ng-zorro-antd';
import {HttpClient, HttpEvent, HttpEventType, HttpRequest} from '@angular/common/http';


@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit, OnChanges, OnDestroy {
  // 储存数据用
  saveKey = 'ww_video';
  // 储存对象
  item;

  @ViewChild('videoContainer')
  videoContainer: ElementRef;
  @ViewChild('videoNode')
  videoNode: ElementRef;

  newVideoCover = true;

  private tooBigError: NzMessageDataFilled = null;


  uploadUrl;
  uploadData;

  constructor(private appRef: ApplicationRef,
              private http: HttpClient,
              private changeDetectorRef: ChangeDetectorRef,
              private nzMessageService: NzMessageService) {
    this.uploadUrl = (<any> window).courseware.uploadUrl();
    // this.uploadData = (<any> window).courseware.uploadData();
    // window['air'] && (window['air'].getUploadCallback = (url, data) => {
    // window['air'] && (window['air'].getUploadCallback = (url, data) => {
    //   console.log(url, data);
    //   this.uploadUrl = url;
    //   this.uploadData = data;
    // });
  }


  ngOnInit() {

    this.item = {
      contentObj: {
        pic_id: null,
        video_url: null
      }
    };

    // 获取存储的数据
    (window as any).courseware.getData((data) => {
      if (data) {
        this.item = data;
      }
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
      this.refresh();

    }, this.saveKey);

  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }

  videoLoaded(evt, 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');
  }
  videoSeeked(evt) {
    return
    const video  = evt.target;
    if (video.src && video.src.startsWith('blob:')) {
      return;
    }
    if (!this.item.contentObj.pic_id) {
      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.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 = this.convertImageToBlob(video_preview_thumb);
    const formData = new FormData();
    const ext = img.type.replace('image/', '');
    formData.append('file', img, `cover.${ext}`);

    this.http.post(this.uploadUrl, formData).subscribe(
      (res: any) => {
        this.item.contentObj.pic_id = res.url;
        this.save();
      },
      (err) => {
        console.log(err);
        this.nzMessageService.error('封面截取失败');
      }
    );
  }

  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.saveKey);
    this.refresh();
  }

  /**
   * 刷新 渲染页面
   */
  refresh() {
    setTimeout(() => {
      this.appRef.tick();
    }, 1);
  }

}

