import 'package:record/record.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:async';
import 'dart:io';

// 负责录音相关功能
class AudioRecorderService {
  final AudioRecorder _recorder = AudioRecorder();
  bool _isRecording = false;
  String? _tempFilePath;

  bool get isRecording => _isRecording;

  Future<bool> hasPermission() => _recorder.hasPermission();

  Future<void> checkPermission() async {
    final hasPermission = await _recorder.hasPermission();
    print('麦克风权限状态: $hasPermission');
  }

  Future<void> startRecording() async {
    print('开始录音...');

    try {
      // 使用文件录音可能更稳定
      final tempDir = await getTemporaryDirectory();
      _tempFilePath =
          '${tempDir.path}/temp_audio_${DateTime.now().millisecondsSinceEpoch}.opus';

      print('录音文件路径: $_tempFilePath');

      if (await _recorder.hasPermission()) {
        await _recorder.start(
          const RecordConfig(encoder: AudioEncoder.opus),
          path: _tempFilePath!,
        );

        _isRecording = true;
        print('录音已开始，使用OPUS格式，文件: $_tempFilePath');
      } else {
        print('没有麦克风权限，无法开始录音');
      }
    } catch (e) {
      print('录音开始出错: $e');
      _isRecording = false;
    }
  }

  Future<List<int>?> stopRecording() async {
    if (!_isRecording) return null;

    _isRecording = false;

    print('停止录音...');
    try {
      final path = await _recorder.stop();
      print('录音已停止，文件路径: $path');

      if (path != null) {
        final file = File(path);
        if (await file.exists()) {
          final bytes = await file.readAsBytes();
          print('读取到录音数据: ${bytes.length} 字节');

          if (bytes.isNotEmpty) {
            return bytes;
          } else {
            print('录音数据为空');
          }
        } else {
          print('录音文件不存在: $path');
        }
      } else {
        print('录音路径为空');
      }
    } catch (e) {
      print('停止录音或发送过程出错: $e');
    }
    return null;
  }

  void dispose() => _recorder.dispose();
}
