import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { get, post, getFullUrl } from '../utils/request';
import type { AudioItem, Voice, VoiceParams } from '../types';

export const useAudioStore = defineStore('audio', () => {
  // 状态
  const voices = ref<Voice[]>([]);
  const currentAudio = ref<AudioItem | null>(null);
  const playlist = ref<AudioItem[]>([]);
  const currentIndex = ref(-1);
  const isPlaying = ref(false);
  const currentTime = ref(0);
  const duration = ref(0);
  const playRate = ref(1);
  
  // 播放模式: 'sequence' | 'loop' | 'single' | 'random'
  const playMode = ref<'sequence' | 'loop' | 'single' | 'random'>('sequence');

  // 音频上下文 - 双模式：BackgroundAudioManager（App后台播放）+ InnerAudioContext（H5降级）
  let audioContext: UniApp.InnerAudioContext | null = null;
  let bgAudioManager: any = null;
  // H5 环境不支持 BackgroundAudioManager，使用 InnerAudioContext
  const useBackgroundAudio: boolean = (function() {
    // #ifdef H5
    return false;
    // #endif
    // #ifndef H5
    return true;
    // #endif
  })();

  // 计算属性
  const hasPlaylist = computed(() => playlist.value.length > 0);
  const hasNext = computed(() => currentIndex.value < playlist.value.length - 1);
  const hasPrev = computed(() => currentIndex.value > 0);

  // 获取当前活跃的音频上下文（背景模式优先）
  function getActiveContext() {
    if (useBackgroundAudio && bgAudioManager) return bgAudioManager;
    return audioContext;
  }

  // 初始化音频上下文
  function initAudioContext() {
    if (useBackgroundAudio) {
      if (!bgAudioManager) {
        try {
          bgAudioManager = uni.getBackgroundAudioManager();
          setupBackgroundAudioEvents();
          console.log('[Audio] 使用 BackgroundAudioManager 支持后台播放');
        } catch (e) {
          console.warn('[Audio] BackgroundAudioManager 不可用，降级到 InnerAudioContext');
          initInnerAudioContext();
        }
      }
      return;
    }
    initInnerAudioContext();
  }

  function initInnerAudioContext() {
    if (audioContext) return;

    audioContext = uni.createInnerAudioContext();

    audioContext.onPlay(() => {
      isPlaying.value = true;
    });

    audioContext.onPause(() => {
      isPlaying.value = false;
    });

    audioContext.onEnded(() => {
      isPlaying.value = false;
      if (hasNext.value) {
        playNext();
      } else {
        handlePlayMode();
      }
    });

    audioContext.onTimeUpdate(() => {
      currentTime.value = audioContext?.currentTime || 0;
      const d = audioContext?.duration || 0;
      if (d > 0 && d < 3600) {
        if (duration.value === 0 || duration.value > 3600 || Math.abs(duration.value - d) < 1) {
          duration.value = d;
        }
      }
    });

    audioContext.onError((err: any) => {
      console.error('音频播放错误:', err);
      isPlaying.value = false;
      if (audioContext) {
        console.error('audioContext.src:', audioContext.src);
      }
    });

    audioContext.onCanplay(() => {
      console.log('音频已准备好播放');
    });
  }

  // 设置 BackgroundAudioManager 事件
  function setupBackgroundAudioEvents() {
    if (!bgAudioManager) return;

    bgAudioManager.onPlay(() => {
      isPlaying.value = true;
    });

    bgAudioManager.onPause(() => {
      isPlaying.value = false;
    });

    bgAudioManager.onStop(() => {
      isPlaying.value = false;
    });

    bgAudioManager.onEnded(() => {
      isPlaying.value = false;
      if (hasNext.value) {
        playNext();
      } else {
        handlePlayMode();
      }
    });

    bgAudioManager.onTimeUpdate(() => {
      currentTime.value = bgAudioManager?.currentTime || 0;
      const d = bgAudioManager?.duration || 0;
      if (d > 0 && d < 3600) {
        if (duration.value === 0 || duration.value > 3600 || Math.abs(duration.value - d) < 1) {
          duration.value = d;
        }
      }
    });

    bgAudioManager.onError((err: any) => {
      console.error('[BackgroundAudio] 播放错误:', err);
      isPlaying.value = false;
    });
  }

  // 获取音色列表
  async function fetchVoices() {
    const result = await get<{ voices: Voice[] }>('/tts/voices');
    voices.value = result.voices;
    return result.voices;
  }

  // 生成音频（异步模式 - 复用有声书逻辑）
  async function generateAudio(
    text: string,
    voiceId: string,
    voiceParams: VoiceParams,
    options?: { bookId?: string }
  ) {
    uni.showLoading({ title: '提交中...', mask: true });
    try {
      const res = await post<{
        chapterId: number;
        bookId: number;
      }>('/tts/generate', {
        text,
        voiceId,
        voiceParams,
        bookId: options?.bookId,
      });

      uni.hideLoading();
      return res;
    } catch (error) {
      uni.hideLoading();
      throw error;
    }
  }

  // 轮询章节音频生成状态
  async function fetchChapterStatus(chapterId: number) {
    const res = await get<{
      chapterId: number;
      genStage: string;
      audioUrl: string | null;
      audioDuration: number;
      title: string;
      isReady: boolean;
      isFailed: boolean;
    }>(`/tts/chapter-status/${chapterId}`);
    return res;
  }

  // 播放音频
  function play(audio: AudioItem) {
    initAudioContext();

    // 重置时长
    currentTime.value = 0;
    duration.value = 0;

    currentAudio.value = audio;

    // 获取完整的音频 URL
    const fullUrl = getFullUrl(audio.audioUrl);
    console.log('播放音频:', audio.title, 'URL:', fullUrl, '时长:', audio.audioDuration);

    const ctx = getActiveContext();
    if (!ctx) {
      console.error('audioContext 未初始化!');
      return;
    }

    // BackgroundAudioManager 模式下设置锁屏信息
    if (useBackgroundAudio && bgAudioManager) {
      bgAudioManager.title = audio.title || '有声书';
      bgAudioManager.epname = audio.title || '';
      bgAudioManager.singer = 'AI有声书';
    }

    // 如果音频源相同，只切换播放状态
    if (ctx.src === fullUrl) {
      console.log('音频源相同，切换播放状态');
      ctx.play();
    } else {
      console.log('设置新音频源并播放:', fullUrl);
      ctx.src = fullUrl;
      ctx.play();
    }

    // 使用 API 返回的 audioDuration 作为初始时长
    if (audio.audioDuration && audio.audioDuration > 0 && audio.audioDuration < 3600) {
      duration.value = audio.audioDuration;
    }
  }

  // 暂停
  function pause() {
    const ctx = getActiveContext();
    if (ctx) {
      ctx.pause();
    }
  }

  // 继续播放
  function resume() {
    const ctx = getActiveContext();
    if (ctx) {
      ctx.play();
    }
  }

  // 切换播放/暂停
  function togglePlay() {
    if (isPlaying.value) {
      pause();
    } else {
      resume();
    }
  }

  // 播放上一首
  function playPrev() {
    if (hasPrev.value) {
      currentIndex.value--;
      play(playlist.value[currentIndex.value]);
    }
  }

  // 播放下一首
  function playNext() {
    if (hasNext.value) {
      currentIndex.value++;
      play(playlist.value[currentIndex.value]);
    }
  }

  // 处理播放模式
  function handlePlayMode() {
    if (playlist.value.length === 0) return;

    switch (playMode.value) {
      case 'single':
        // 单曲循环
        play(playlist.value[currentIndex.value]);
        break;
      case 'loop':
        // 列表循环
        if (currentIndex.value < playlist.value.length - 1) {
          playNext();
        } else {
          // 回到第一首
          currentIndex.value = 0;
          play(playlist.value[0]);
        }
        break;
      case 'random':
        // 随机播放
        const randomIndex = Math.floor(Math.random() * playlist.value.length);
        currentIndex.value = randomIndex;
        play(playlist.value[randomIndex]);
        break;
      case 'sequence':
      default:
        // 顺序播放（不自动播放）
        break;
    }
  }

  // 切换播放模式
  function togglePlayMode() {
    const modes: Array<'sequence' | 'loop' | 'single' | 'random'> = ['sequence', 'loop', 'single', 'random'];
    const currentIndex = modes.indexOf(playMode.value);
    playMode.value = modes[(currentIndex + 1) % modes.length];
    
    const modeNames = {
      sequence: '顺序播放',
      loop: '列表循环',
      single: '单曲循环',
      random: '随机播放',
    };
    
    uni.showToast({
      title: modeNames[playMode.value],
      icon: 'none',
    });
  }

  // 跳转到指定位置
  function seek(time: number) {
    const ctx = getActiveContext();
    if (ctx) {
      ctx.seek(time);
      currentTime.value = time;
    }
  }

  // 设置播放速度
  function setPlayRate(rate: number) {
    playRate.value = rate;
    if (useBackgroundAudio && bgAudioManager) {
      // BackgroundAudioManager 不支持 playbackRate
      return;
    }
    if (audioContext) {
      audioContext.playbackRate = rate;
    }
  }

  // 设置播放列表
  function setPlaylist(list: AudioItem[], index: number = 0, autoPlay: boolean = true) {
    playlist.value = list;
    currentIndex.value = index;
    if (list.length > 0 && autoPlay) {
      play(list[index]);
    }
  }

  // 销毁音频上下文
  function destroy() {
    if (useBackgroundAudio && bgAudioManager) {
      bgAudioManager.stop();
      bgAudioManager = null;
    }
    if (audioContext) {
      audioContext.destroy();
      audioContext = null;
    }
    isPlaying.value = false;
  }

  return {
    // 状态
    voices,
    currentAudio,
    playlist,
    currentIndex,
    isPlaying,
    currentTime,
    duration,
    playRate,
    playMode,
    // 计算属性
    hasPlaylist,
    hasNext,
    hasPrev,
    // 方法
    fetchVoices,
    generateAudio,
    fetchChapterStatus,
    play,
    pause,
    resume,
    togglePlay,
    playPrev,
    playNext,
    handlePlayMode,
    togglePlayMode,
    seek,
    setPlayRate,
    setPlaylist,
    destroy,
  };
});