class AudioManager {
  constructor() {
    this.audioContext = null;
    this.isPlaying = false;
  }

  init() {
    if (!this.audioContext) {
      // #ifdef APP-PLUS
      // 使用 plus.audio 而不是 createInnerAudioContext
      this.audioContext = plus.audio.createPlayer('/static/audio/ninyouxindepeibudan.mp3');
      
      // 监听播放完成
      this.audioContext.addEventListener('ended', () => {
        console.log('Audio playback completed');
        this.isPlaying = false;
      });
      
      // 监听错误
      this.audioContext.addEventListener('error', (e) => {
        console.error('Audio error:', e.message);
        this.isPlaying = false;
      });
      // #endif
    }
  }

  play() {
	  console.log('audioContext',this.audioContext)
	  console.log('isplay', this.isPlaying)
    if (!this.audioContext) {
      this.init();
    }
    
    // #ifdef APP-PLUS
    if (!this.isPlaying) {
      try {
        // 开始播放
        this.audioContext.play(() => {
			// 当音频文件播放完成时回调。
          this.isPlaying = false;
          console.log('开始播放音频');
        }, (e) => {
          console.error('播放音频失败:', e.message);
        });
      } catch (e) {
        console.error('播放异常:', e);
      }
    }
    // #endif
  }

  stop() {
    // #ifdef APP-PLUS
    if (this.audioContext && this.isPlaying) {
      try {
        this.audioContext.stop();
        this.isPlaying = false;
      } catch (e) {
        console.error('停止播放失败:', e);
      }
    }
    // #endif
  }

  destroy() {
    // #ifdef APP-PLUS
    if (this.audioContext) {
      try {
        this.stop();
        this.audioContext = null;
      } catch (e) {
        console.error('销毁音频播放器失败:', e);
      }
    }
    // #endif
  }
}

export const audioManager = new AudioManager();
