import { Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef } from '@angular/core';
import { NzMessageService } from "ng-zorro-antd";
import WaveSurfer from 'wavesurfer.js';

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit, OnChanges, OnDestroy {

  // 储存数据用
  saveKey = "gs_cartoon";
  // 储存对象
  item;
  wavesurfer;
  isPlaying: boolean = false; // 用于跟踪播放状态
  currentTime: number = 0;

  hotZones: any[] = []; // 存储热区数据
  isCollapsed: boolean[] = []; // 存储每个热区的折叠状态


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

  }


  ngOnInit() {

    this.item = {};

    // 获取存储的数据
    (<any>window).courseware.getData((data) => {

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

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

    }, this.saveKey);

  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }



  init() {
    this.hotZones = this.item.hotZones || [];
    this.isCollapsed = this.hotZones.map((item, index) => {
      return index !== 0;
    });

    // 使用 wavesurfer.js 绘制波形图
    this.wavesurfer = WaveSurfer.create({
      container: '#waveform', // 你需要在 HTML 中有一个对应的容器
      waveColor: 'violet',
      progressColor: 'purple'
    });
    // 监听播放完成事件
    this.wavesurfer.on('finish', () => {
      this.isPlaying = false; // 重置播放状态
    });
    this.wavesurfer.on('audioprocess', () => {
      console.log('audioprocess');
      this.updateCurrentTime();
    });
    this.wavesurfer.on('seek', () => {
      this.updateCurrentTime();
    });

    if (this.item.bg_audio_url) {
      this.wavesurfer.load(this.item.bg_audio_url);
    }

  }
  updateCurrentTime() {
    this.currentTime = Math.floor(this.wavesurfer.getCurrentTime() * 1000); // 转换为毫秒
  }

  addHotZone() {
    this.hotZones.push({
      bgItem: {},
      hotZoneItemArr: []
    }); // 添加一个新的热区
    this.isCollapsed.push(false); // 初始化为展开状态
  }

  toggleCollapse(index: number) {
    // 切换折叠状态
    this.isCollapsed[index] = !this.isCollapsed[index];

    // 确保只有一个热区是展开的
    if (!this.isCollapsed[index]) {
      this.isCollapsed = this.isCollapsed.map((collapsed, i) => i === index ? false : true);
    }
  }

  deleteHotZone(index: number) {
    this.hotZones.splice(index, 1);
    this.isCollapsed.splice(index, 1);
  }
  
  /**
     * 储存图片数据
     * @param e
     */
  onImageUploadSuccess(e, key, it) {

    it[key] = e.url;
    this.save();
  }

  /**
   * 储存音频数据
   * @param e
   */
  onAudioUploadSuccess(e, key, it) {
    console.log('e: ', e);
    it[key] = e.url;
    if (key === 'bg_audio_url') {
      this.wavesurfer.load(e.url);
    }
    this.save();
  }

  saveHotZone(e, i) {
    console.log('e: ', e);
    const { bgItem, hotZoneItemArr } = e;
    this.hotZones[i].bgItem = bgItem;
    this.hotZones[i].hotZoneItemArr = hotZoneItemArr;

    this.item.hotZones = this.hotZones;

    this.save();

    this.message.create(
      'success',
      '保存成功'
    );
  }

  togglePlayPause() {
    if (this.isPlaying) {
      this.wavesurfer.pause();
    } else {
      this.wavesurfer.play();
    }
    this.isPlaying = !this.isPlaying; // 切换播放状态
  }

  /**
   * 储存数据
   */
  save() {
    console.log('this.item JSON: ', JSON.stringify(this.item));
    (<any>window).courseware.setData(this.item, null, this.saveKey);
    this.refresh();
  }

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

}
