/**
 * 移动端兼容的文本转语音服务
 * 优先使用Web Speech API，备用Web Audio API
 */

class TTSService {
  constructor() {
    this.audioContext = null
    this.synthesis = window.speechSynthesis
    this.voices = []
    this.isInitialized = false
    this.init()
  }

  /**
   * 初始化音频服务
   */
  async init() {
    try {
      // 尝试初始化Web Speech API
      if (this.synthesis) {
        this.voices = this.synthesis.getVoices()
        
        if (this.voices.length === 0) {
          this.synthesis.onvoiceschanged = () => {
            this.voices = this.synthesis.getVoices()
            this.isInitialized = true
            console.log('Web Speech API 语音加载完成，可用语音数量:', this.voices.length)
          }
        } else {
          this.isInitialized = true
          console.log('Web Speech API 语音已加载，可用语音数量:', this.voices.length)
        }
      }

      // 备用：初始化Web Audio API
      if (window.AudioContext || window.webkitAudioContext) {
        this.audioContext = new (window.AudioContext || window.webkitAudioContext)()
        console.log('Web Audio API 初始化成功')
      }

    } catch (error) {
      console.error('音频服务初始化失败:', error)
      this.isInitialized = false
    }
  }

  /**
   * 检查浏览器支持
   */
  isSupported() {
    return !!(this.synthesis || (window.AudioContext || window.webkitAudioContext))
  }

  /**
   * 检查移动端
   */
  isMobile() {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
  }

  /**
   * 获取英文语音
   */
  getEnglishVoice() {
    if (!this.synthesis || this.voices.length === 0) return null
    
    // 优先选择美式英语语音
    const usVoice = this.voices.find(voice => 
      voice.lang.includes('en-US') && voice.name.includes('Google')
    )
    
    if (usVoice) return usVoice
    
    // 其次选择任何美式英语语音
    const enUSVoice = this.voices.find(voice => 
      voice.lang.includes('en-US')
    )
    
    if (enUSVoice) return enUSVoice
    
    // 最后选择任何英语语音
    const enVoice = this.voices.find(voice => 
      voice.lang.includes('en')
    )
    
    return enVoice || this.voices[0]
  }

  /**
   * 播放英文语音
   * @param {string} text 要播放的英文文本
   * @param {Event} event 用户交互事件
   */
  speak(text, event = null) {
    if (!this.isSupported()) {
      console.error('浏览器不支持语音合成')
      this.showFallbackMessage()
      return
    }

    // 移动端需要用户交互
    if (this.isMobile() && !event) {
      console.warn('移动端需要用户交互才能播放语音')
      return
    }

    // 优先使用Web Speech API
    if (this.synthesis && this.voices.length > 0) {
      this.speakWithWebSpeech(text)
    } else if (this.audioContext) {
      // 备用：使用Web Audio API
      this.speakWithWebAudio(text)
    } else {
      // 最后的备用方案：显示文本提示
      this.showTextHint(text)
    }
  }

  /**
   * 使用Web Speech API播放
   */
  speakWithWebSpeech(text) {
    try {
      // 停止当前播放
      this.synthesis.cancel()

      // 创建语音合成
      const utterance = new SpeechSynthesisUtterance(text)
      
      // 设置语音
      const voice = this.getEnglishVoice()
      if (voice) {
        utterance.voice = voice
        console.log('使用语音:', voice.name, voice.lang)
      }
      
      // 设置参数
      utterance.lang = 'en-US'
      utterance.rate = 0.9
      utterance.pitch = 1.0
      utterance.volume = 1.0

      // 添加事件监听
      utterance.onstart = () => {
        console.log('开始播放语音:', text)
      }
      
      utterance.onend = () => {
        console.log('语音播放结束')
      }
      
      utterance.onerror = (event) => {
        console.error('Web Speech API播放错误:', event.error)
        // 如果Web Speech API失败，尝试Web Audio API
        if (this.audioContext) {
          this.speakWithWebAudio(text)
        } else {
          this.showTextHint(text)
        }
      }

      // 播放
      this.synthesis.speak(utterance)
      
    } catch (error) {
      console.error('Web Speech API播放失败:', error)
      // 备用方案
      if (this.audioContext) {
        this.speakWithWebAudio(text)
      } else {
        this.showTextHint(text)
      }
    }
  }

  /**
   * 使用Web Audio API播放（生成简单的音频信号）
   */
  speakWithWebAudio(text) {
    try {
      // 确保音频上下文已恢复
      if (this.audioContext.state === 'suspended') {
        this.audioContext.resume()
      }

      // 创建音频节点
      const oscillator = this.audioContext.createOscillator()
      const gainNode = this.audioContext.createGain()
      
      // 连接节点
      oscillator.connect(gainNode)
      gainNode.connect(this.audioContext.destination)

      // 设置音频参数 - 生成更复杂的音频模式
      oscillator.type = 'sine'
      
      // 根据文本长度调整频率
      const baseFreq = 440 // A4音符
      const textLength = text.length
      const freq = baseFreq + (textLength * 10) // 根据文本长度调整频率
      
      oscillator.frequency.setValueAtTime(freq, this.audioContext.currentTime)
      
      // 音量控制
      gainNode.gain.setValueAtTime(0.05, this.audioContext.currentTime)
      gainNode.gain.exponentialRampToValueAtTime(0.01, this.audioContext.currentTime + 0.8)

      // 播放音频
      oscillator.start(this.audioContext.currentTime)
      oscillator.stop(this.audioContext.currentTime + 0.8)

      console.log('Web Audio API播放音频提示音:', text)
      
      // 显示文本提示
      this.showTextHint(text)

    } catch (error) {
      console.error('Web Audio API播放失败:', error)
      this.showTextHint(text)
    }
  }

  /**
   * 显示文本提示
   */
  showTextHint(text) {
    // 移除之前的提示
    const existingHint = document.querySelector('.tts-text-hint')
    if (existingHint) {
      existingHint.remove()
    }

    // 创建一个临时的文本提示
    const hint = document.createElement('div')
    hint.className = 'tts-text-hint'
    hint.style.cssText = `
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: rgba(0, 0, 0, 0.9);
      color: white;
      padding: 20px;
      border-radius: 15px;
      z-index: 10000;
      font-size: 18px;
      text-align: center;
      max-width: 80%;
      word-wrap: break-word;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
      animation: fadeInOut 3s ease-in-out;
    `
    hint.textContent = text
    
    // 添加动画样式
    const style = document.createElement('style')
    style.textContent = `
      @keyframes fadeInOut {
        0% { opacity: 0; transform: translate(-50%, -50%) scale(0.8); }
        20% { opacity: 1; transform: translate(-50%, -50%) scale(1); }
        80% { opacity: 1; transform: translate(-50%, -50%) scale(1); }
        100% { opacity: 0; transform: translate(-50%, -50%) scale(0.8); }
      }
    `
    document.head.appendChild(style)
    
    document.body.appendChild(hint)
    
    // 3秒后自动移除
    setTimeout(() => {
      if (hint.parentNode) {
        hint.parentNode.removeChild(hint)
      }
      if (style.parentNode) {
        style.parentNode.removeChild(style)
      }
    }, 3000)
  }

  /**
   * 显示备用消息
   */
  showFallbackMessage() {
    if (this.isMobile()) {
      alert('移动端音频播放受限，请查看屏幕中央的文本提示。\n\n建议：\n1. 使用Chrome或Safari浏览器\n2. 确保已授予音频权限\n3. 尝试刷新页面')
    }
  }

  /**
   * 停止播放
   */
  stop() {
    if (this.synthesis) {
      this.synthesis.cancel()
      console.log('停止Web Speech API播放')
    }
    
    // 移除文本提示
    const existingHint = document.querySelector('.tts-text-hint')
    if (existingHint) {
      existingHint.remove()
    }
  }

  /**
   * 检查是否正在播放
   */
  isSpeaking() {
    return this.synthesis ? this.synthesis.speaking : false
  }

  /**
   * 获取可用语音列表
   */
  getAvailableVoices() {
    return this.voices
  }
}

// 创建单例实例
const ttsService = new TTSService()

export default ttsService 
