import 'package:flutter_tts/flutter_tts.dart';

/// TTS语音播报服务
class TTSService {
  static final TTSService _instance = TTSService._internal();
  factory TTSService() => _instance;
  TTSService._internal();

  final FlutterTts _flutterTts = FlutterTts();
  bool _isInitialized = false;

  /// 初始化TTS
  Future<void> initialize() async {
    if (_isInitialized) return;

    try {
      // 设置语言为美式英语
      await _flutterTts.setLanguage("en-US");
      
      // 设置语速 (0.0 - 1.0)
      await _flutterTts.setSpeechRate(0.5);
      
      // 设置音量 (0.0 - 1.0)
      await _flutterTts.setVolume(1.0);
      
      // 设置音调 (0.5 - 2.0)
      await _flutterTts.setPitch(1.0);

      _isInitialized = true;
      print('TTS服务初始化成功');
    } catch (e) {
      print('TTS服务初始化失败: $e');
    }
  }

  /// 播放单词发音
  /// [word] 要播放的单词
  /// [language] 语言代码，默认为美式英语 "en-US"，英式英语为 "en-GB"
  Future<void> speak(String word, {String language = "en-US"}) async {
    if (!_isInitialized) {
      await initialize();
    }

    try {
      // 如果正在播放，先停止
      await _flutterTts.stop();
      
      // 设置语言
      await _flutterTts.setLanguage(language);
      
      // 播放单词
      await _flutterTts.speak(word);
      
      print('播放单词发音: $word ($language)');
    } catch (e) {
      print('播放单词发音失败: $e');
    }
  }

  /// 停止播放
  Future<void> stop() async {
    try {
      await _flutterTts.stop();
    } catch (e) {
      print('停止播放失败: $e');
    }
  }

  /// 暂停播放
  Future<void> pause() async {
    try {
      await _flutterTts.pause();
    } catch (e) {
      print('暂停播放失败: $e');
    }
  }

  /// 设置语速
  /// [rate] 语速 (0.0 - 1.0)
  Future<void> setSpeechRate(double rate) async {
    try {
      await _flutterTts.setSpeechRate(rate);
    } catch (e) {
      print('设置语速失败: $e');
    }
  }

  /// 设置音调
  /// [pitch] 音调 (0.5 - 2.0)
  Future<void> setPitch(double pitch) async {
    try {
      await _flutterTts.setPitch(pitch);
    } catch (e) {
      print('设置音调失败: $e');
    }
  }

  /// 设置音量
  /// [volume] 音量 (0.0 - 1.0)
  Future<void> setVolume(double volume) async {
    try {
      await _flutterTts.setVolume(volume);
    } catch (e) {
      print('设置音量失败: $e');
    }
  }

  /// 获取可用语言列表
  Future<List<dynamic>> getLanguages() async {
    try {
      return await _flutterTts.getLanguages;
    } catch (e) {
      print('获取语言列表失败: $e');
      return [];
    }
  }

  /// 获取可用语音列表
  Future<List<dynamic>> getVoices() async {
    try {
      return await _flutterTts.getVoices;
    } catch (e) {
      print('获取语音列表失败: $e');
      return [];
    }
  }

  /// 设置完成回调
  void setCompletionHandler(Function callback) {
    _flutterTts.setCompletionHandler(() {
      callback();
    });
  }

  /// 设置错误回调
  void setErrorHandler(Function(dynamic) callback) {
    _flutterTts.setErrorHandler((msg) {
      callback(msg);
    });
  }

  /// 释放资源
  Future<void> dispose() async {
    try {
      await _flutterTts.stop();
      _isInitialized = false;
    } catch (e) {
      print('释放TTS资源失败: $e');
    }
  }
}
