import { ApplicationRef, ChangeDetectorRef, ElementRef, ViewChild } from "@angular/core";
import { MetaFormCreator } from "./mataFormCreator";

export class ComponentBase {
  // 储存数据用
  saveKey = "";
  // 储存对象
  item: any = {};
  ngOnChanges() { }
  ngOnDestroy() { }

  constructor(public appRef: ApplicationRef, public changeDetectorRef: ChangeDetectorRef) { }
  ngOnInit() {
    // 获取存储的数据
    (<any>window).courseware.getData((data) => {
      if (data) {
        this.item = data;
        this.itemStr = JSON.stringify(this.item, null, 4).trim();
      }
      this.init();
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
      this.refresh();
    }, this.saveKey);
  }

  @ViewChild("itemTextarea", { static: true }) itemTextarea: ElementRef;
  copyData() {
    this.itemTextarea.nativeElement.select();
    document.execCommand("copy");
  }

  /**
   * 储存图片数据
   * @param e
   */
  // onAssetUploadSuccess(e: any, ...key: Array<string>) {
  //   let item = this.item;
  //   for (let i = 0; i < key.length; i++) {
  //     if (i + 1 == key.length) {
  //       if (key[i] == "audio") {
  //         let sp = e.url.split(".mp3");
  //         let u = sp[0] + "_l.mp3";
  //         item[key[i]] = u;
  //         item["audioName"] = e.name || "";
  //       } else {
  //         item[key[i]] = e.url;
  //       }
  //       this.save();
  //       return;
  //     }
  //     item = item[key[i]];
  //   }
  // }

  /**
   * 储存图片数据
   * @param e
   */
  onImageUploadSuccess(e, key, it = this.item) {
    it[key] = e.url;
    this.save();
  }

  /**
   * 储存音频数据
   * @param e
   */
  onAudioUploadSuccess(e, key, it = this.item) {
    let url = e.url;
    let sp = url.split(".mp3");
    let u = sp[0] + "_l.mp3";
    it[key] = u;
    it["audioName"] = e.name || "";
    this.save();
  }

  save() {
    (<any>window).courseware.setData(this.item, null, this.saveKey);
    this.itemStr = JSON.stringify(this.item, null, 4).trim();
    this.refresh();
    console.log('this.item = ' + JSON.stringify(this.item));
  }
  itemStr = "";
  load() {
    this.itemStr = this.itemTextarea.nativeElement.value;
    if (this.isJSON(this.itemStr)) {
      this.item = JSON.parse(this.itemStr);
      this.init();
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
      this.refresh();
    }
  }
  isJSON(str) {
    if (typeof str == 'string') {
      try {
        var obj = JSON.parse(str);
        if (typeof obj == 'object' && obj) {
          return true;
        }
        return false;
      } catch (e) {
        return false;
      }
    }
    return false;
  }

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