import Taro from "@tarojs/taro";
// 音频播放状态类型
type AudioPlayStatus = 'idle' | 'playing' | 'paused' | 'stopped' | 'error';

// 封装后的音频实例类型
interface AudioInstance {
  play: () => void;
  pause: () => void;
  stop: () => void;
  destroy: () => void;
  onStatusChange: (callback: (status: AudioPlayStatus) => void) => void;
  getStatus: () => AudioPlayStatus;
}

export function playWavAudio(url: string): AudioInstance {
  const audio = Taro.createInnerAudioContext();
  let currentStatus: AudioPlayStatus = 'idle';
  let statusChangeCallback: ((status: AudioPlayStatus) => void) | null = null;

  // 更新状态并触发回调
  const updateStatus = (newStatus: AudioPlayStatus) => {
    currentStatus = newStatus;
    if (statusChangeCallback) {
      statusChangeCallback(newStatus);
    }
  };

  audio.src = url;

  // 事件监听
  audio.onPlay(() => updateStatus('playing'));
  audio.onPause(() => updateStatus('paused'));
  audio.onStop(() => updateStatus('stopped'));
  audio.onEnded(() => updateStatus('stopped'));
  audio.onError(() => {
    updateStatus('error');
    audio.destroy();
  });

  return {
    play: () => {
      if (currentStatus !== 'playing') {
        audio.play();
      }
    },
    pause: () => {
      if (currentStatus === 'playing') {
        audio.pause();
      }
    },
    stop: () => {
      if (currentStatus === 'playing' || currentStatus === 'paused') {
        audio.stop();
      }
    },
    destroy: () => {
      audio.destroy();
      updateStatus('idle');
    },
    onStatusChange: (callback) => {
      statusChangeCallback = callback;
    },
    getStatus: () => currentStatus,
  };
}