// 浏览器内置语音识别（如果支持的话）
export class SpeechRecognitionService {
  private recognition: any = null;
  private isListening = false;

  constructor(
    private onResult?: (text: string) => void,
    private onError?: (error: Error) => void,
    private onEnd?: () => void,
    private onInterim?: (text: string) => void
  ) {
    // 检查浏览器是否支持语音识别
    const SpeechRecognition = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;
    
    if (SpeechRecognition) {
      this.recognition = new SpeechRecognition();
      this.setupRecognition();
    }
  }

  private setupRecognition(): void {
    if (!this.recognition) return;

    // 配置语音识别
    this.recognition.continuous = true; // 持续监听，不会因为停顿而停止
    this.recognition.interimResults = true; // 显示临时结果
    this.recognition.lang = 'zh-CN'; // 设置中文
    this.recognition.maxAlternatives = 1;

    // 结果处理
    this.recognition.onresult = (event: any) => {
      let finalText = '';
      let interimText = '';

      for (let i = event.resultIndex; i < event.results.length; i++) {
        const transcript = event.results[i][0].transcript;
        if (event.results[i].isFinal) {
          finalText += transcript;
        } else {
          interimText += transcript;
        }
      }

      // 回调临时结果（实时显示）
      if (interimText && this.onInterim) {
        this.onInterim(interimText);
      }

      // 回调最终结果
      if (finalText && this.onResult) {
        this.onResult(finalText);
        // 清除临时文本
        if (this.onInterim) {
          this.onInterim('');
        }
      }
    };

    // 错误处理
    this.recognition.onerror = (event: any) => {
      console.error('语音识别错误:', event.error);
      
      // 根据错误类型给出不同提示
      let errorMessage = '语音识别错误';
      switch (event.error) {
        case 'no-speech':
          errorMessage = '未检测到语音，请重试';
          break;
        case 'audio-capture':
          errorMessage = '无法访问麦克风，请检查权限';
          break;
        case 'not-allowed':
          errorMessage = '麦克风权限被拒绝，请在浏览器设置中允许';
          break;
        case 'network':
          errorMessage = '网络错误，请检查网络连接';
          break;
        case 'aborted':
          // 用户主动停止，不显示错误
          return;
        default:
          errorMessage = `语音识别错误: ${event.error}`;
      }
      
      const error = new Error(errorMessage);
      if (this.onError) {
        this.onError(error);
      }
    };

    // 结束处理
    this.recognition.onend = () => {
      console.log('语音识别结束');
      this.isListening = false;
      if (this.onEnd) {
        this.onEnd();
      }
    };

    // 开始处理
    this.recognition.onstart = () => {
      console.log('语音识别已启动');
    };

    // 音频开始
    this.recognition.onaudiostart = () => {
      console.log('音频捕获开始');
    };
  }

  startListening(): void {
    if (this.recognition && !this.isListening) {
      try {
        this.recognition.start();
        this.isListening = true;
        console.log('开始语音识别...');
      } catch (error) {
        console.error('启动语音识别失败:', error);
        // 如果已经在运行，先停止再启动
        if ((error as Error).message?.includes('already started')) {
          this.recognition.stop();
          setTimeout(() => {
            this.recognition.start();
            this.isListening = true;
          }, 100);
        }
      }
    }
  }

  stopListening(): void {
    if (this.recognition && this.isListening) {
      this.recognition.stop();
      this.isListening = false;
      console.log('停止语音识别...');
    }
  }

  getListeningState(): boolean {
    return this.isListening;
  }

  // 检查浏览器是否支持语音识别
  static isSupported(): boolean {
    const SpeechRecognition = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;
    return !!SpeechRecognition;
  }
}
