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);
  const loopMode = ref<'off' | 'list' | 'single'>('off'); // 循环模式：关闭/列表循环/单曲循环
  const shuffleMode = ref(false); // 随机播放模式
  const autoPlayNext = ref(true); // 自动播放下一首

  // 音频上下文
  let audioContext: UniApp.InnerAudioContext | null = null;

  // 计算属性
  const hasPlaylist = computed(() => playlist.value.length > 0);
  const hasNext = computed(() => {
    if (loopMode.value === 'list') return true;
    return currentIndex.value < playlist.value.length - 1;
  });
  const hasPrev = computed(() => {
    if (loopMode.value === 'list') return true;
    return currentIndex.value > 0;
  });

  // 初始化音频上下文
  function initAudioContext() {
    if (audioContext) return;

    audioContext = uni.createInnerAudioContext();

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

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

    audioContext.onEnded(() => {
      // 自动播放下一首或循环
      if (autoPlayNext.value || loopMode.value === 'list' || loopMode.value === 'single') {
        handleAutoPlay();
      } else {
        isPlaying.value = false;
      }
    });

    audioContext.onTimeUpdate(() => {
      currentTime.value = audioContext?.currentTime || 0;
      duration.value = audioContext?.duration || 0;
    });

    audioContext.onError((err) => {
      console.error('音频播放错误:', 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
  ) {
    console.log('📤 TTS 请求参数:', { text: text.substring(0, 50) + '...', textLength: text.length, voiceId, voiceParams });
    uni.showLoading({ title: '正在创建任务...' });
    try {
      // 1. 发起异步生成请求，立即返回 audioId
      const { audioId } = await post<{
        audioId: string;
        status: string;
      }>('/tts/generate', { text, voiceId, voiceParams });

      // 2. 轮询状态直到完成
      let attempts = 0;
      const maxAttempts = 60; // 最多等待60次（60秒）
      let pollInterval = 1; // 初始轮询间隔（秒）

      console.log('🔄 开始轮询状态, audioId:', audioId);
      while (attempts < maxAttempts) {
        await new Promise(resolve => setTimeout(resolve, pollInterval * 1000));

        const statusResult = await get<{
          status: string;
          audio?: {
            audioUrl: string;
            audioDuration: number;
            audioSize: number;
          };
        }>(`/tts/status/${audioId}`);

        console.log(`📊 轮询 ${attempts + 1}: status = ${statusResult.status}`);
        
        if (statusResult.status === 'completed' && statusResult.audio) {
          uni.hideLoading();
          console.log('✅ 生成成功');
          uni.showToast({ title: '生成成功', icon: 'success' });
          return {
            audioId: audioId,
            audioUrl: statusResult.audio.audioUrl,
            duration: statusResult.audio.audioDuration,
            size: statusResult.audio.audioSize,
          };
        }

        if (statusResult.status === 'failed') {
          console.log('❌ 状态为 failed');
          console.log('❌ 完整状态:', statusResult);
          uni.hideLoading();
          throw new Error('音频生成失败，请重试');
        }

        // 渐进式增加轮询间隔（避免频繁请求）
        pollInterval = Math.min(pollInterval + 0.5, 5);
        attempts++;
      }

      uni.hideLoading();
      throw new Error('生成超时，请稍后重试');
    } catch (error) {
      uni.hideLoading();
      throw error;
    }
  }

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

    currentAudio.value = audio;
    
    // 获取完整的音频 URL
    const fullUrl = getFullUrl(audio.audioUrl);
    
    // 如果音频源相同，只切换播放状态
    if (audioContext && audioContext.src === fullUrl) {
      audioContext.play();
    } else if (audioContext) {
      audioContext.src = fullUrl;
      audioContext.play();
    }
  }

  // 暂停
  function pause() {
    if (audioContext) {
      audioContext.pause();
    }
  }

  // 继续播放
  function resume() {
    if (audioContext) {
      audioContext.play();
    }
  }

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

  // 播放上一首
  function playPrev() {
    if (shuffleMode.value && playlist.value.length > 1) {
      // 随机播放时：随机选择不是当前的一首
      let newIndex;
      do {
        newIndex = Math.floor(Math.random() * playlist.value.length);
      } while (newIndex === currentIndex.value);
      currentIndex.value = newIndex;
    } else if (hasPrev.value) {
      currentIndex.value--;
    } else if (loopMode.value === 'list' && playlist.value.length > 0) {
      // 列表循环：回到最后一首
      currentIndex.value = playlist.value.length - 1;
    } else {
      return;
    }
    play(playlist.value[currentIndex.value]);
  }

  // 切换循环模式
  function toggleLoopMode() {
    if (loopMode.value === 'off') {
      loopMode.value = 'list';
    } else if (loopMode.value === 'list') {
      loopMode.value = 'single';
    } else {
      loopMode.value = 'off';
    }
  }

  // 切换随机播放模式
  function toggleShuffleMode() {
    shuffleMode.value = !shuffleMode.value;
  }

  // 设置自动播放下一首
  function setAutoPlayNext(value: boolean) {
    autoPlayNext.value = value;
  }

  // 播放下一首
  function playNext() {
    if (shuffleMode.value && playlist.value.length > 1) {
      // 随机播放：随机选择不是当前的一首
      let newIndex;
      do {
        newIndex = Math.floor(Math.random() * playlist.value.length);
      } while (newIndex === currentIndex.value);
      currentIndex.value = newIndex;
    } else if (hasNext.value) {
      currentIndex.value++;
    } else if (loopMode.value === 'list' && playlist.value.length > 0) {
      // 列表循环：回到第一首
      currentIndex.value = 0;
    } else {
      return;
    }
    play(playlist.value[currentIndex.value]);
  }

  // 自动播放处理（播放结束时）
  function handleAutoPlay() {
    if (loopMode.value === 'single') {
      // 单曲循环：重新播放当前音频
      if (audioContext) {
        audioContext.seek(0);
        audioContext.play();
      }
    } else if (shuffleMode.value && playlist.value.length > 1) {
      // 随机播放
      playNext();
    } else if (hasNext.value) {
      // 下一首
      currentIndex.value++;
      play(playlist.value[currentIndex.value]);
    } else if (loopMode.value === 'list' && playlist.value.length > 0) {
      // 列表循环
      currentIndex.value = 0;
      play(playlist.value[currentIndex.value]);
    } else {
      isPlaying.value = false;
    }
  }

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

  // 设置播放速度
  function setPlayRate(rate: number) {
    playRate.value = rate;
    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 (audioContext) {
      audioContext.destroy();
      audioContext = null;
    }
  }

  return {
    // 状态
    voices,
    currentAudio,
    playlist,
    currentIndex,
    isPlaying,
    currentTime,
    duration,
    playRate,
    loopMode,
    shuffleMode,
    autoPlayNext,
    // 计算属性
    hasPlaylist,
    hasNext,
    hasPrev,
    // 方法
    fetchVoices,
    generateAudio,
    play,
    pause,
    resume,
    togglePlay,
    playPrev,
    playNext,
    seek,
    setPlayRate,
    setPlaylist,
    setAutoPlayNext,
    toggleLoopMode,
    toggleShuffleMode,
    destroy,
  };
});