import 'dart:async';

import 'package:audio_session/audio_session.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:camera/camera.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:flutter/foundation.dart' show kDebugMode, kIsWeb;
import 'package:flutter/widgets.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:flutter_sound_platform_interface/flutter_sound_recorder_platform_interface.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/services/entity/hardware_setting.dart';
import 'package:flyinsono/architecture/services/modules/hardware_setting_configuration.dart';
import 'package:flyinsono/managers/interfaces/device.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'package:tencent_trtc_cloud/trtc_cloud.dart';
import 'package:tencent_trtc_cloud/tx_device_manager.dart';
import 'package:fis_common/env/env.dart';
import 'package:fis_jsonrpc/services/platform.dart';
import 'index.dart';

class HardwareDetectionController extends GetxController {
  /// 本地硬件设置持久化缓存服务
  HardwareSettingService hardwareSettingService =
      Get.find<HardwareSettingService>();
  HardwareSetting hardwareSetting = HardwareSetting.ins;
  final state = HardwareDetectionState();

  /// 相机控制器需要的参数
  late List<CameraDescription> _cameras;

  late CameraController cameraController;

  /// 扬声器控制器需要的参数
  final FlutterSoundPlayer flutterSound = FlutterSoundPlayer();

  /// 相机是否正在初始化【此变量用于防止相机在初始化时，再次尝试初始化】
  bool _cameraInitializing = false;

  /// 麦克风控制器需要的参数
  Codec _codec = Codec.aacMP4;

  final FlutterSoundRecorder flutterRecorder = FlutterSoundRecorder();
  HardwareDetectionController();

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
    cameraController.dispose();
    flutterSound.closePlayer();
    flutterRecorder.closeRecorder();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() async {
    // WidgetsBinding.instance.addPostFrameCallback((_) async {
    if (CartSystemPlatform.isCartSystemVersion) {
      state.isOldVBox = await rpc.platform.getCurrentIsOldBox();
      if (!state.isOldVBox) {
        state.navTitles = [
          i18nBook.setting.start.t,
          i18nBook.setting.cameraDetection.t,
          i18nBook.setting.speakerDetection.t,
          i18nBook.setting.microphoneDetection.t,
          i18nBook.setting.sonopostDetetion.t,
        ];
      }
    }
    // });

    _sp60StopCameraPreview();
    hardwareSettingService.init();
    await _intialize();
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  // 刷新设备列表
  Future<void> refreshAllDevices() async {
    await refreshCameraList();
    await refreshMicrophoneList();
    await refreshSpeakerList();
  }

  /// 刷新摄像头列表
  Future<void> refreshCameraList({bool isRetry = false}) async {
    state.searchingCamera = true;

    if (CartSystemPlatform.isCartSystemVersion) {
      IDeviceManager _deviceManager = Get.find<IDeviceManager>();
      if (state.deviceCode != null && state.deviceCode != "") {
        await _deviceManager.exitLiveRoom(state.deviceCode);
      }
      await rpc.platform.stopPreview();
      await Future.delayed(Duration(milliseconds: 2000));
    }
    try {
      _cameras = await availableCameras();
      state.cameraList = [];
      state.cameraAvailable = null;
      await Future.delayed(Duration(milliseconds: 100));
      state.cameraList = await _trtcGetCameras();
      state.searchingCamera = false;
    } on Exception catch (e) {
      state.cameraList = [];
      state.cameraAvailable = null;
      state.searchingCamera = false;
      logger.e('Search camera failed: $e');
    }
    // 如果当前没有选择摄像头，则选择第一个
    if (state.currentCamera == null && state.cameraList.isNotEmpty) {
      selectCameraById(state.cameraList.first.id);
    }

    if (state.detectingCamera) stopDetectingCamera();
  }

  /// 刷新麦克风列表
  Future<void> refreshMicrophoneList() async {
    state.searchingMicrophone = true;
    if (state.detectingMicrophone) stopDetectingMicrophone();
    state.microphoneList = [];
    state.microphoneAvailable = null;
    await Future.delayed(Duration(milliseconds: 100));
    try {
      state.microphoneList = await _trtcGetMicrophones();
      state.searchingMicrophone = false;
    } on Exception catch (e) {
      state.microphoneList = [];
      state.searchingMicrophone = false;
      logger.e('Search microphone failed: $e');
    }
    // 如果当前选中的麦克风不在列表中，则设置为 null
    if (state.currentMicrophone != null &&
        !state.microphoneList
            .map((e) => e.name)
            .contains(state.currentMicrophone?.name)) {
      state.currentMicrophone = null;
    }
    // 如果当前没有选择麦克风，则选择第一个
    if (state.currentMicrophone == null && state.microphoneList.isNotEmpty) {
      selectMicrophoneById(state.microphoneList.first.id);
    }
  }

  /// 刷新扬声器列表
  Future<void> refreshSpeakerList() async {
    state.searchingSpeaker = true;
    _updateSystemSpeakerVolumeSetting();
    if (state.detectingSpeaker) stopDetectingSpeaker();
    state.speakerList = [];
    state.speakerAvailable = null;
    await Future.delayed(Duration(milliseconds: 100));
    try {
      state.speakerList = await _getSpeakers();
      state.searchingSpeaker = false;
    } on Exception catch (e) {
      state.speakerList = [];
      state.searchingSpeaker = false;
      logger.e('Search speaker failed: $e');
    }
    // 如果当前没有选择扬声器，则选择第一个
    if (state.currentSpeaker == null && state.speakerList.isNotEmpty) {
      selectSpeakerById(state.speakerList.first.id);
    }
  }

  /// 选择摄像头
  void selectCameraById(String deviceId) {
    if (state.currentCamera != null && deviceId == state.currentCamera!.id)
      return;

    state.cameraList.forEach((element) {
      if (element.id == deviceId) {
        state.currentCamera = element;
        state.cameraAvailable = null;
        hardwareSetting.setIdealWebVideoInputDeviceName(element.name);
        hardwareSettingService.save();
      }
    });
    if (state.currentCamera == null) return;
    if (state.detectingCamera) {
      _stopCamera();
      _openSelectedCamera();
    }
  }

  /// 选择麦克风
  Future<void> selectMicrophoneById(String deviceId) async {
    state.microphoneList.forEach((element) {
      if (element.id == deviceId) {
        state.currentMicrophone = element;
        state.microphoneAvailable = null;
        hardwareSetting.setIdealWebAudioInputDeviceName(element.name);
        hardwareSettingService.save();
      }
    });
    if (state.currentMicrophone == null) return;
    if (state.detectingMicrophone) {
      await _stopRecordMicrophone();
      _startRecordMicrophone();
    }
  }

  /// 选择扬声器
  void selectSpeakerById(String deviceId) {
    state.speakerList.forEach((element) {
      if (element.id == deviceId) {
        state.currentSpeaker = element;
        state.speakerAvailable = null;
      }
    });
    if (state.currentSpeaker == null) return;
    _windowsSetSpeaker(state.currentSpeaker!.id);
  }

  /// 设置当前选中的摄像头可用性
  void setCameraAvailable(bool available) {
    state.cameraAvailable = available;
    stopDetectingCamera();
  }

  /// 设置当前选中的麦克风可用性
  void setMicrophoneAvailable(bool available) {
    state.microphoneAvailable = available;
    stopDetectingMicrophone();
  }

  /// 设置当前选中的扬声器可用性
  void setSpeakerAvailable(bool available) {
    state.speakerAvailable = available;
    stopDetectingSpeaker();
  }

  /// 开始检测所有设备
  Future<void> startDetectingAll() async {
    await refreshAllDevices();
    if (state.cameraList.isNotEmpty) startDetectingCamera();
    if (state.microphoneList.isNotEmpty) startDetectingMicrophone();
    if (state.speakerList.isNotEmpty) startDetectingSpeaker();
  }

  /// 开始检测摄像头
  void startDetectingCamera() {
    state.cameraAvailable = null;
    state.detectingCamera = true;
    IDeviceManager _deviceManager = Get.find<IDeviceManager>();
    if (state.deviceCode != null && state.deviceCode != "") {
      _deviceManager.exitLiveRoom(state.deviceCode);
    }
    _openSelectedCamera();
  }

  /// 开始检测麦克风
  void startDetectingMicrophone() {
    state.microphoneAvailable = null;
    state.detectingMicrophone = true;
    _startRecordMicrophone();
  }

  /// 开始检测扬声器
  void startDetectingSpeaker() {
    state.speakerAvailable = null;
    state.detectingSpeaker = true;
    _startPlaySound();
  }

  /// 结束检测摄像头
  void stopDetectingCamera() {
    state.detectingCamera = false;
    _stopCamera();
  }

  /// 结束检测麦克风
  void stopDetectingMicrophone() {
    state.detectingMicrophone = false;
    _stopRecordMicrophone();
  }

  /// 结束检测扬声器
  void stopDetectingSpeaker() {
    state.detectingSpeaker = false;
    _stopPlaySound();
  }

  /// 初始化摄像头列表
  Future<void> _initCameras({bool isRetry = false}) async {
    state.searchingCamera = true;
    if (CartSystemPlatform.isCartSystemVersion) {
      IDeviceManager _deviceManager = Get.find<IDeviceManager>();
      if (state.deviceCode != null && state.deviceCode != "") {
        await _deviceManager.exitLiveRoom(state.deviceCode);
      }
      await rpc.platform.stopPreview();
      await Future.delayed(Duration(milliseconds: 2000));
    }
    List<HardwareDevice> _cameraList = await _trtcGetCameras();
    try {
      _cameras = await availableCameras();
    } on Exception catch (e) {
      logger.e('Search camera failed: $e');
      _cameras = [];
    }
    for (var i = 0; i < _cameras.length; i++) {
      for (var j = 0; j < _cameraList.length; j++) {
        if (_cameras[i].name == _cameraList[j].name) {
          state.cameraList.add(_cameraList[j]);
          break;
        }
      }
    }
    if (state.cameraList.isNotEmpty) state.currentCamera = state.cameraList[0];
    final idealCameraName = hardwareSetting.idealWebVideoInputDeviceName;
    bool isFind = false;
    if (idealCameraName != '') {
      for (var i = 0; i < state.cameraList.length; i++) {
        if (state.cameraList[i].name == idealCameraName) {
          state.currentCamera = state.cameraList[i];
          isFind = true;
          break;
        }
      }
    }
    if (isFind == false && state.cameraList.isNotEmpty) {
      hardwareSetting.setIdealWebVideoInputDeviceName(state.cameraList[0].name);
      hardwareSettingService.save();
    }
    state.searchingCamera = false;
    if (state.cameraList.isEmpty && !isRetry) {
      _initCameras(isRetry: true);
    }
  }

  /// 初始化麦克风列表
  Future<void> _initMicrophones() async {
    state.searchingMicrophone = true;
    List<HardwareDevice> _microphoneList = await _trtcGetMicrophones();
    state.microphoneList.addAll(_microphoneList);
    await _initTheRecorder();
    if (state.microphoneList.isNotEmpty)
      state.currentMicrophone = state.microphoneList[0];
    final idealMicrophoneName = hardwareSetting.idealWebAudioInputDeviceName;
    bool isFind = false;
    if (idealMicrophoneName != '') {
      for (var i = 0; i < state.microphoneList.length; i++) {
        if (state.microphoneList[i].name == idealMicrophoneName) {
          state.currentMicrophone = state.microphoneList[i];
          isFind = true;
          break;
        }
      }
    }
    if (isFind == false && state.microphoneList.isNotEmpty) {
      hardwareSetting
          .setIdealWebAudioInputDeviceName(state.microphoneList[0].name);
      hardwareSettingService.save();
    }
    state.searchingMicrophone = false;
  }

  /// 初始化扬声器列表
  Future<void> _initSpeakers() async {
    state.searchingSpeaker = true;
    List<HardwareDevice> _speakerList = await _getSpeakers();
    state.speakerList.addAll(_speakerList);
    await _updateSystemSpeakerVolumeSetting();
    await _initThePlayer();
    if (state.speakerList.isNotEmpty)
      state.currentSpeaker = state.speakerList[0];
    state.searchingSpeaker = false;
  }

  /// 更新系统扬声器音量设置
  Future<void> _updateSystemSpeakerVolumeSetting() async {
    int initVolume = await _windowsGetSpeakerVolume();
    state.speakerVolume = initVolume.toDouble();
  }

  /// 初始化播放器
  Future<void> _initThePlayer() async {
    await flutterSound.openPlayer();
    await flutterSound
        .setSubscriptionDuration(const Duration(milliseconds: 100));
    state.isDisplaySpeakerWave = true;
  }

  /// 初始化麦克风录音器
  Future<void> _initTheRecorder() async {
    await flutterRecorder.openRecorder();
    if (!await flutterRecorder.isEncoderSupported(_codec) && kIsWeb) {
      _codec = Codec.opusWebM;
      if (!await flutterRecorder.isEncoderSupported(_codec) && kIsWeb) {
        state.isDisplayMicrophoneWave = true;
        return;
      }
    }
    // 设置采样率
    await flutterRecorder
        .setSubscriptionDuration(const Duration(milliseconds: 50));
    final session = await AudioSession.instance;
    await session.configure(AudioSessionConfiguration(
      avAudioSessionCategory: AVAudioSessionCategory.playAndRecord,
      avAudioSessionCategoryOptions:
          AVAudioSessionCategoryOptions.allowBluetooth |
              AVAudioSessionCategoryOptions.defaultToSpeaker,
      avAudioSessionMode: AVAudioSessionMode.spokenAudio,
      avAudioSessionRouteSharingPolicy:
          AVAudioSessionRouteSharingPolicy.defaultPolicy,
      avAudioSessionSetActiveOptions: AVAudioSessionSetActiveOptions.none,
      androidAudioAttributes: const AndroidAudioAttributes(
        contentType: AndroidAudioContentType.speech,
        flags: AndroidAudioFlags.none,
        usage: AndroidAudioUsage.voiceCommunication,
      ),
      androidAudioFocusGainType: AndroidAudioFocusGainType.gain,
      androidWillPauseWhenDucked: true,
    ));
    state.isDisplayMicrophoneWave = true;
  }

  /// 初始化设备列表
  Future<void> _intialize() async {
    await _initCameras();
    await _initMicrophones();
    await _initSpeakers();
  }

  /// 打开当前选中的摄像头
  _openSelectedCamera() {
    if (_cameraInitializing) {
      return;
    }
    bool found = false;
    int cameraIndex = 0;
    for (var i = 0; i < _cameras.length; i++) {
      if (_cameras[i].name == state.currentCamera?.name) {
        cameraIndex = i;
        found = true;
        break;
      }
    }
    if (!found) {
      return;
    }
    cameraController =
        CameraController(_cameras[cameraIndex], ResolutionPreset.max);
    _cameraInitializing = true;
    cameraController.initialize().then((_) {
      if (state.cameraAvailable == null) {
        state.isDisplayCameraWindow = true;
      } else {
        _stopCamera(isForceStop: true);
      }
      _cameraInitializing = false;
    }).catchError((Object e) {
      _cameraInitializing = false;
      _stopCamera(isForceStop: true);
      if (e is CameraException) {
        switch (e.code) {
          case 'CameraAccessDenied':
            // Handle access errors here.
            break;
          default:
            // Handle other errors here.
            break;
        }
      }
    });
  }

  /// 使用当前的扬声器播放测试音频
  Future<void> _startPlaySound() async {
    await flutterSound.startPlayer(
        fromURI: kDebugMode
            ? "assets/audio/testspeak.mp3"
            : "assets/assets/audio/testspeak.mp3",
        codec: Codec.aacADTS,
        whenFinished: () {});
  }

  /// 设置扬声器音量
  Future<void> setSpeakerVolume(double volume) async {
    state.speakerVolume = volume;
    int volumeInt = (volume).toInt();
    _windowsSetSpeakerVolume(volumeInt);
  }

  // 开始采集麦克风音频
  void _startRecordMicrophone() async {
    /// 获取到当前选中的麦克风的id
    if (state.currentMicrophone == null) {
      return;
    }
    final String fileNameWithMicrophoneId =
        "temp@${state.currentMicrophone!.id}.webm";

    ///  将麦克风的id作为文件名，web端的record会做处理，会将文件名作为选中的麦克风id进行设置
    await flutterRecorder.startRecorder(
        toFile: fileNameWithMicrophoneId,
        codec: _codec,
        audioSource: AudioSource.microphone);
  }

  /// 关闭摄像头并释放
  _stopCamera({bool isForceStop = false}) {
    state.isDisplayCameraWindow = false;
    if (cameraController.value.isStreamingImages) {
      cameraController.stopImageStream();
    }
    if (cameraController.value.isInitialized) {
      cameraController.dispose();
    }
    if (isForceStop) {
      cameraController.dispose();
    }
  }

  /// 停止播放音频
  _stopPlaySound() {
    flutterSound.stopPlayer();
  }

  /// 停止采集麦克风音频
  Future<void> _stopRecordMicrophone() async {
    await flutterRecorder.stopRecorder();
  }

  /// 调用 TRTC 获取摄像头列表以及ids
  Future<List<HardwareDevice>> _trtcGetCameras() async {
    List<HardwareDevice> deviceList = [];
    TRTCCloud trtcCloud = (await TRTCCloud.sharedInstance())!;
    TXDeviceManager deviceManager = trtcCloud.getDeviceManager();
    final Map<dynamic, dynamic>? cameras =
        await deviceManager.getDevicesList(2);
    if (cameras != null && cameras.isNotEmpty) {
      cameras.forEach((key, value) {
        if (key == 'deviceList') {
          // print("🔍 _trtcGetCameras $key $value");
          if (value is List) {
            value.forEach(
              (element) {
                if (element is Map) {
                  String cameraLable = element["label"];
                  if (!cameraLable.contains("Card") &&
                      !cameraLable.contains("HDPro 1")) {
                    deviceList.add(HardwareDevice(
                        id: element["deviceId"],
                        name: cameraLable,
                        type: HardwareDeviceType.camera));
                  }
                }
              },
            );
          }
        }
        if (key == "count") {
          if (value is num) {
            print("🔍 _trtcGetCameras count $value");
          }
        }
      });
    }
    return deviceList;
  }

  /// 调用 TRTC 获取麦克风列表
  Future<List<HardwareDevice>> _trtcGetMicrophones() async {
    List<HardwareDevice> deviceList = [];
    TRTCCloud trtcCloud = (await TRTCCloud.sharedInstance())!;
    TXDeviceManager deviceManager = trtcCloud.getDeviceManager();
    final Map<dynamic, dynamic>? microphones =
        await deviceManager.getDevicesList(0);
    if (microphones != null && microphones.isNotEmpty) {
      microphones.forEach((key, vlaue) {
        if (key == 'deviceList') {
          // print("🔍 _trtcGetMicrophones $key $vlaue");
          if (vlaue is List) {
            vlaue.forEach(
              (element) {
                if (element is Map) {
                  String deviceId = element["deviceId"];
                  String cameraLable = element["label"];
                  if (deviceId != "default" &&
                      deviceId != "communications" &&
                      !cameraLable.contains("Card") &&
                      !cameraLable.contains("HDPro 1")) {
                    deviceList.add(HardwareDevice(
                        id: deviceId,
                        name: cameraLable,
                        type: HardwareDeviceType.microphone));
                  }
                }
              },
            );
          }
        }
        if (key == "count") {
          if (vlaue is num) {
            print("🔍 _trtcGetMicrophones count $vlaue");
          }
        }
      });
    }
    return deviceList;
  }

  /// 获取扬声器列表
  Future<List<HardwareDevice>> _getSpeakers() async {
    List<HardwareDevice> deviceList = [];
    if (FPlatform.isWindows) {
      deviceList = await _windowsGetSpeakers();
    } else {
      deviceList = await _trtcGetSpeakers();
    }
    return deviceList;
  }

  /// 调用 windows API 获取扬声器列表
  Future<List<HardwareDevice>> _windowsGetSpeakers() async {
    List<HardwareDevice> deviceList = [];
    if (!FPlatform.isWindows) return deviceList;
    List<dynamic> speakerDeviceListStr =
        await rpc.platform.getAudioDevice(AudioTypeEnum.Speaker);
    speakerDeviceListStr.forEach((element) {
      if (element is String) {
        deviceList.add(HardwareDevice(
            id: element, name: element, type: HardwareDeviceType.speaker));
      }
    });
    print("🔍 _windowsGetSpeakers $speakerDeviceListStr");
    return deviceList;
  }

  /// 调用 windows API 设置扬声器 [id 即 name]
  void _windowsSetSpeaker(String speakerId) async {
    if (!FPlatform.isWindows) return;
    bool success = await rpc.platform.setSystemAudioDevice(speakerId);
    print("🔍 _windowsSetSpeaker $success");
  }

  /// 调用 windows API 扬声获取扬声器音量
  Future<int> _windowsGetSpeakerVolume() async {
    if (!FPlatform.isWindows) return 0;
    double speakerVolume =
        await rpc.platform.getAudioDeviceVolume(AudioTypeEnum.Speaker);
    int volume = (speakerVolume * 100).toInt();
    return volume;
  }

  /// 调用 windows API 设置扬声器音量
  void _windowsSetSpeakerVolume(int volume) async {
    if (!FPlatform.isWindows) return;
    double volumeDouble = (volume / 100).toDouble();
    try {
      await rpc.platform
          .setActiveDeviceVolume(AudioTypeEnum.Speaker, volumeDouble);
    } catch (e) {
      print(e);
    }
  }

  /// 调用 TRTC 获取扬声器列表
  Future<List<HardwareDevice>> _trtcGetSpeakers() async {
    List<HardwareDevice> deviceList = [];
    TRTCCloud trtcCloud = (await TRTCCloud.sharedInstance())!;
    TXDeviceManager deviceManager = trtcCloud.getDeviceManager();
    final Map<dynamic, dynamic>? speakers =
        await deviceManager.getDevicesList(1);
    if (speakers != null && speakers.isNotEmpty) {
      speakers.forEach((key, value) {
        if (key == 'deviceList') {
          // print("🔍 _trtcGetSpeakers $key $value");
          if (value is List) {
            value.forEach(
              (element) {
                if (element is Map) {
                  deviceList.add(HardwareDevice(
                      id: element["deviceId"],
                      name: element["label"],
                      type: HardwareDeviceType.speaker));
                }
              },
            );
          }
        }
        if (key == "count") {
          if (value is num) {
            print("🔍 _trtcGetSpeakers count $value");
          }
        }
      });
    }
    return deviceList;
  }

  /// 调用 SP60 API 关闭摄像头预览
  Future<void> _sp60StopCameraPreview() async {
    if (!FPlatform.isWindows) return;
    await rpc.platform.stopPreview();
  }

  /// 调用 SP60 API 获取 SP60 正在使用的摄像头的名称（会发生抢占，需要建议不使用）
  Future<String> _sp60GetUsedCameraName() async {
    if (!FPlatform.isWindows) return "";
    // String cameraInfo = await rpc.platform.getCameraInfo();
    // print("🔍 _sp60GetCamera01Info $cameraInfo");
    return 'USB 2.0 HD Camera ';
  }

  /// 调用 SP60 API 获取采集卡列表（会被误认为是摄像头，需要屏蔽）
  Future<List<String>> _sp60GetSonoCaptureCardList() async {
    if (!FPlatform.isWindows) return [];
    List<String> deviceList = [];
    // List<dynamic> deviceListStr =
    //     await rpc.platform.getIgnoreMicList(AudioTypeEnum.Microphone);
    // deviceListStr.forEach((element) {
    //   if (element is String) {
    //     deviceList.add(element);
    //   }
    // });
    deviceList.add('HD Video 1 (LT8501-DVI Card)');
    print("🔍 _sp60GetSonoCaptureCardList $deviceList");
    return deviceList;
  }

  // 调用 SP60 API 获取需要屏蔽的扬声器
  Future<List<String>> _sp60GetIgnoreSpeakerList() async {
    if (!FPlatform.isWindows) return [];
    List<String> ignoreSpeakerList = [];
    // List<dynamic> ignoreSpeakerListStr =
    //     await rpc.platform.getIgnoreMicList(AudioTypeEnum.Microphone);
    // ignoreSpeakerListStr.forEach((element) {
    //   if (element is String) {
    //     ignoreSpeakerList.add(element);
    //   }
    // });
    ignoreSpeakerList.add("mock 扬声器 (Realtek(R) Audio)");
    print("🔍 _sp60GetIgnoreSpeakerList $ignoreSpeakerList");
    return ignoreSpeakerList;
  }

  /// 调用 SP60 API 获取需要屏蔽的麦克风 GetIgnoreMicList
  Future<List<String>> _sp60GetIgnoreMicList() async {
    if (!FPlatform.isWindows) return [];
    List<String> ignoreMicList = [];
    // List<dynamic> ignoreMicListStr =
    //     await rpc.platform.getIgnoreMicList(AudioTypeEnum.Microphone);
    // ignoreMicListStr.forEach((element) {
    //   if (element is String) {
    //     ignoreMicList.add(element);
    //   }
    // });
    ignoreMicList.add("mock 麦克风 (Realtek(R) Audio)");
    print("🔍 _sp60GetIgnoreMicList $ignoreMicList");
    return ignoreMicList;
  }
}
