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[] = []; // 存储每个热区的折叠状态

  isLoading: boolean = false; // 添加加载状态标志


  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() {
  }

  // 添加缩放限制常量
  private readonly MIN_PX_PER_SEC = 50;  // 最小缩放级别
  private readonly MAX_PX_PER_SEC = 8000; // 最大缩放级别
  private minPxPerSec = 50; // 初始值，将在加载音频后动态计算

  // 添加缩放控制方法
  zoomWaveform(isZoomIn: boolean) {
    const currentPxPerSec = this.wavesurfer.params.minPxPerSec;
    let newPxPerSec = isZoomIn
      ? currentPxPerSec * 1.2
      : currentPxPerSec / 1.2;

    // 使用动态计算的 minPxPerSec
    newPxPerSec = Math.max(this.minPxPerSec, Math.min(this.MAX_PX_PER_SEC, newPxPerSec));
    this.wavesurfer.zoom(newPxPerSec);
  }

  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: '#4F4A85',
      progressColor: '#383351',
      height: 100,
      // 添加以下缩放相关配置
      minPxPerSec: this.minPxPerSec,
      maxPxPerSec: this.MAX_PX_PER_SEC,
      scrollParent: true // 允许水平滚动
    });
    // 添加鼠标滚轮缩放事件
    document.querySelector('#waveform').addEventListener('wheel', (e) => {
      if (e['ctrlKey'] || e['metaKey']) {
        e.preventDefault();
        this.zoomWaveform(e['deltaY'] < 0);
      }
    });

    // 添加加载开始事件监听
    this.wavesurfer.on('loading', (progress) => {
      this.isLoading = true;
      this.changeDetectorRef.detectChanges();
    });
    // 监听音频加载完成事件
    this.wavesurfer.on('ready', () => {
      this.isLoading = false;
      const duration = this.wavesurfer.getDuration();
      const containerWidth = document.querySelector('#waveform').clientWidth;
      // 计算显示完整音频所需的最小缩放级别
      this.minPxPerSec = Math.max(1, (containerWidth / duration) * 0.9); // 0.9是为了留一些边距

      // 初始显示完整波形
      this.wavesurfer.zoom(this.minPxPerSec);
      this.changeDetectorRef.detectChanges();
    });
    // 监听播放完成事件
    this.wavesurfer.on('finish', () => {
      this.isPlaying = false; // 重置播放状态
    });
    this.wavesurfer.on('audioprocess', () => {
      this.updateCurrentTime();
    });
    this.wavesurfer.on('seek', () => {
      this.updateCurrentTime();
    });

    if (this.item.bg_audio_url) {
      this.isLoading = true; // 开始加载时设置状态
      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);
  }

}
