import 'dart:async';

import 'package:hydrated_bloc/hydrated_bloc.dart';

import 'device_control_event.dart';
import 'device_control_state.dart';
import 'package:laki_icu_app/models/bo/device_control_bo.dart';
import 'package:laki_icu_app/models/bo/bluetooth_read_model.dart';
import 'package:laki_icu_app/utils/bluetooth/index.dart';
import 'package:laki_icu_app/utils/event_bus.dart';
import 'package:laki_icu_app/utils/logger.dart';
import 'package:laki_icu_app/utils/storage/storage_service.dart';

/// 用途：设备控制Bloc
/// 涉及页面：设备控制页面
/// 说明：提供各个子模块的获取和设置方法，方便MCU单元调用
/// 使用 HydratedBloc 持久化用户设置，MCU获取的值不做持久化
class DeviceControlBloc
    extends HydratedBloc<DeviceControlEvent, DeviceControlState> {
  DeviceControlBloc({
    BleBluetoothManager? bluetoothManager,
    StorageService? storageService,
  })  : _bluetoothManager = bluetoothManager ?? appBluetoothManager,
        _storageService = storageService ?? StorageService(),
        _mcuReportDecoder = McuReportFrameDecoder(),
        super(const DeviceControlState()) {
    // ==================== 基础事件 ====================
    on<DeviceControlLoadRequested>(_onLoadRequested);
    on<DeviceControlDataUpdated>(_onDataUpdated);
    on<DeviceControlMcuReportFetched>(_onMcuReportFetched);

    // ==================== 设备SN事件 ====================
    on<DeviceControlSnFetched>(_onSnFetched);
    on<DeviceControlSnChanged>(_onSnChanged);

    // ==================== 舱内温度控制事件 ====================
    on<DeviceControlCabinTempCurrentValueFetched>(
        _onCabinTempCurrentValueFetched);
    on<DeviceControlCabinTempSetValueChanged>(_onCabinTempSetValueChanged);
    on<DeviceControlCabinTempSetValueAdjusted>(_onCabinTempSetValueAdjusted);
    on<DeviceControlCabinTempSwitchChanged>(_onCabinTempSwitchChanged);

    // ==================== 舱内湿度控制事件 ====================
    on<DeviceControlCabinHumidityCurrentValueFetched>(
        _onCabinHumidityCurrentValueFetched);
    on<DeviceControlCabinHumiditySetValueChanged>(
        _onCabinHumiditySetValueChanged);
    on<DeviceControlCabinHumiditySetValueAdjusted>(
        _onCabinHumiditySetValueAdjusted);
    on<DeviceControlCabinHumiditySwitchChanged>(_onCabinHumiditySwitchChanged);

    // ==================== 氧气浓度控制事件 ====================
    on<DeviceControlOxygenConcentrationCurrentValueFetched>(
        _onOxygenConcentrationCurrentValueFetched);
    on<DeviceControlOxygenConcentrationSetValueChanged>(
        _onOxygenConcentrationSetValueChanged);
    on<DeviceControlOxygenConcentrationSetValueAdjusted>(
        _onOxygenConcentrationSetValueAdjusted);
    on<DeviceControlOxygenConcentrationSwitchChanged>(
        _onOxygenConcentrationSwitchChanged);

    // ==================== 二氧化碳浓度控制事件 ====================
    on<DeviceControlCO2ConcentrationCurrentValueFetched>(
        _onCO2ConcentrationCurrentValueFetched);
    on<DeviceControlCO2ConcentrationAlarmThresholdChanged>(
        _onCO2ConcentrationAlarmThresholdChanged);
    on<DeviceControlCO2ConcentrationAlarmThresholdAdjusted>(
        _onCO2ConcentrationAlarmThresholdAdjusted);

    // ==================== 护理等级控制事件 ====================
    on<DeviceControlCareLevelChanged>(_onCareLevelChanged);

    // ==================== 新风进化控制事件 ====================
    on<DeviceControlFreshAirModeChanged>(_onFreshAirModeChanged);

    // ==================== 风速调节控制事件 ====================
    on<DeviceControlWindSpeedModeChanged>(_onWindSpeedModeChanged);

    // ==================== 雾化时间设置事件 ====================
    on<DeviceControlNebulizationTimeChanged>(_onNebulizationTimeChanged);

    // ==================== 消毒时间设置事件 ====================
    on<DeviceControlDisinfectionTimeChanged>(_onDisinfectionTimeChanged);

    // ==================== 开放供氧控制事件 ====================
    on<DeviceControlOpenOxygenSwitchChanged>(_onOpenOxygenSwitchChanged);

    // ==================== 供氧计时事件 ====================
    on<DeviceControlOxygenTimerUpdated>(_onOxygenTimerUpdated);
    on<DeviceControlOxygenTimerCleared>(_onOxygenTimerCleared);

    // ==================== 循环模式控制事件 ====================
    on<DeviceControlCirculationModeChanged>(_onCirculationModeChanged);

    // ==================== 灯光控制事件 ====================
    on<DeviceControlCheckLightSwitchChanged>(_onCheckLightSwitchChanged);
    on<DeviceControlIlluminationLightSwitchChanged>(
        _onIlluminationLightSwitchChanged);
    on<DeviceControlBlueLightSwitchChanged>(_onBlueLightSwitchChanged);
    on<DeviceControlRedLightSwitchChanged>(_onRedLightSwitchChanged);

    // ==================== 全局统计数据事件 ====================
    on<DeviceControlTotalRunTimeUpdated>(_onTotalRunTimeUpdated);
    on<DeviceControlEnvironmentTempUpdated>(_onEnvironmentTempUpdated);
    on<DeviceControlTotalOxygenTimeUpdated>(_onTotalOxygenTimeUpdated);
    on<DeviceControlResetSettings>(_onResetSettings);

    // 加载初始化数据
    _mcuReportSub = eventBus.on<McuReportChangedEvent>().listen(
          (event) => add(DeviceControlMcuReportFetched(event.report)),
        );
    _bluetoothDataSub = _bluetoothManager.dataStream.listen(
      _onBluetoothDataPacket,
    );
    add(const DeviceControlLoadRequested());
  }

  final BleBluetoothManager _bluetoothManager;
  final StorageService _storageService;
  final McuReportFrameDecoder _mcuReportDecoder;
  late final StreamSubscription<McuReportChangedEvent> _mcuReportSub;
  late final StreamSubscription<BluetoothDataPacket> _bluetoothDataSub;

  // ==================== HydratedBloc 持久化 ====================

  @override
  DeviceControlState? fromJson(Map<String, dynamic> json) {
    return DeviceControlState.fromJson(json);
  }

  @override
  Map<String, dynamic>? toJson(DeviceControlState state) {
    return state.toJson();
  }

  // ==================== 基础事件处理 ====================

  Future<void> _onLoadRequested(
    DeviceControlLoadRequested event,
    Emitter<DeviceControlState> emit,
  ) async {
    emit(state.copyWith(isLoading: true, clearError: true));
    try {
      emit(state.copyWith(
        data: _clearMcuReadValues(state.data),
        isLoading: false,
        clearError: true,
      ));
    } catch (e) {
      emit(state.copyWith(isLoading: false, error: e.toString()));
    }
  }

  void _onDataUpdated(
    DeviceControlDataUpdated event,
    Emitter<DeviceControlState> emit,
  ) {
    emit(state.copyWith(data: event.data, clearError: true));
  }

  DeviceControlBO _clearMcuReadValues(DeviceControlBO data) {
    return data.copyWith(
      cabinTemp: data.cabinTemp.copyWith(currentValue: '--'),
      cabinHumidity: data.cabinHumidity.copyWith(currentValue: '--'),
      oxygenConcentration:
          data.oxygenConcentration.copyWith(currentValue: '--'),
      co2Concentration: data.co2Concentration.copyWith(currentValue: '--'),
    );
  }

  void _onBluetoothDataPacket(BluetoothDataPacket packet) {
    try {
      Log.warn(
        '🔥🔥🔥 BLE_READ_DEBUG device_control_packet len=${packet.bytes.length} '
        'hex=${packet.rawHex}',
      );
      final reports = _mcuReportDecoder.addBytes(packet.bytes);
      Log.warn(
        '🔥🔥🔥 BLE_READ_DEBUG device_control_parse reports=${reports.length} '
        'buffered=${_mcuReportDecoder.bufferedBytes} '
        'bufferHex=${_mcuReportDecoder.bufferedHexPreview}',
      );
      if (reports.isEmpty || isClosed) return;
      final latestReport = reports.last;
      eventBus.emit(
        BluetoothReadInfoChangedEvent(
          BluetoothReadModel.fromMcuReport(latestReport),
        ),
      );
      eventBus.emit(McuReportChangedEvent(latestReport));
    } catch (e) {
      Log.warn('🔥🔥🔥 BLE_READ_DEBUG device_control_parse_error error=$e');
      // 蓝牙原始数据可能分包或夹杂非MCU帧，这里只忽略控制页同步失败。
    }
  }

  void _onMcuReportFetched(
    DeviceControlMcuReportFetched event,
    Emitter<DeviceControlState> emit,
  ) {
    final report = event.report;
    Log.warn(
      '🔥🔥🔥 BLE_READ_DEBUG device_control_sync '
      'frameLength=${report.length} '
      'temp=${report.mainTemperature} '
      'tempSet=${report.temperatureSetting} '
      'humidity=${report.humidity} '
      'humiditySet=${report.humiditySetting} '
      'o2=${report.oxygenConcentration} '
      'o2Set=${report.oxygenSetting} '
      'co2=${report.co2Measurement} '
      'co2Set=${report.co2Setting} '
      'sn=${report.sn.isEmpty ? '<EMPTY>' : report.sn}',
    );
    final newData = state.data.copyWith(
      sn: report.sn.isEmpty ? state.data.sn : report.sn,
      cabinTemp: state.data.cabinTemp.copyWith(
        currentValue: _formatTemperature(report.mainTemperature),
        setValue: _formatTemperatureOrKeep(
          report.temperatureSetting,
          state.data.cabinTemp.setValue,
        ),
      ),
      cabinHumidity: state.data.cabinHumidity.copyWith(
        currentValue: _formatInt(report.humidity),
        setValue: _formatIntOrKeep(
          report.humiditySetting,
          state.data.cabinHumidity.setValue,
        ),
      ),
      oxygenConcentration: state.data.oxygenConcentration.copyWith(
        currentValue: _formatInt(report.oxygenConcentration),
        setValue: _formatIntOrKeep(
          report.oxygenSetting,
          state.data.oxygenConcentration.setValue,
        ),
      ),
      co2Concentration: state.data.co2Concentration.copyWith(
        currentValue: _formatInt(report.co2Measurement),
        alarmThreshold: _formatIntOrKeep(
          report.co2Setting,
          state.data.co2Concentration.alarmThreshold,
        ),
      ),
    );
    emit(state.copyWith(data: newData, clearError: true));
  }

  // ==================== 设备SN事件处理 ====================

  /// [MCU调用] 更新设备SN（从MCU获取的真实数据）
  void _onSnFetched(
    DeviceControlSnFetched event,
    Emitter<DeviceControlState> emit,
  ) {
    final newData = state.data.copyWith(
      sn: event.sn,
    );
    emit(state.copyWith(data: newData, clearError: true));
  }

  /// [用户操作] 设置设备SN（发送给MCU）—— 持久化
  void _onSnChanged(
    DeviceControlSnChanged event,
    Emitter<DeviceControlState> emit,
  ) {
    final newData = state.data.copyWith(
      sn: event.sn,
    );
    emit(state.copyWith(
      data: newData,
      userSettings: state.userSettings.copyWith(sn: event.sn),
      clearError: true,
    ));
    // TODO: 发送设置到MCU
  }

  // ==================== 舱内温度控制事件处理 ====================

  /// [MCU调用] 更新舱内温度当前值（从MCU获取的真实数据）
  void _onCabinTempCurrentValueFetched(
    DeviceControlCabinTempCurrentValueFetched event,
    Emitter<DeviceControlState> emit,
  ) {
    final newData = state.data.copyWith(
      cabinTemp: state.data.cabinTemp.copyWith(
        currentValue: event.currentValue,
      ),
    );
    emit(state.copyWith(data: newData, clearError: true));
  }

  /// [用户操作] 设置舱内温度设定值（发送给MCU）—— 持久化
  Future<void> _onCabinTempSetValueChanged(
    DeviceControlCabinTempSetValueChanged event,
    Emitter<DeviceControlState> emit,
  ) async {
    await _setCabinTempSetValue(event.setValue, emit);
  }

  /// [用户操作] 点击舱内温度设定值 -/+（发送给MCU）—— 持久化
  Future<void> _onCabinTempSetValueAdjusted(
    DeviceControlCabinTempSetValueAdjusted event,
    Emitter<DeviceControlState> emit,
  ) async {
    final currentValue = int.tryParse(state.data.cabinTemp.setValue) ?? 0;
    final nextValue = (currentValue + event.step).clamp(0, 99);
    Log.warn(
      '🔥🔥🔥 BLE_WRITE_DEBUG cabin_temp_adjust '
      'current=$currentValue step=${event.step} next=$nextValue',
    );
    await _setCabinTempSetValue('$nextValue', emit);
  }

  Future<void> _setCabinTempSetValue(
    String setValue,
    Emitter<DeviceControlState> emit,
  ) async {
    final newData = state.data.copyWith(
      cabinTemp: state.data.cabinTemp.copyWith(
        setValue: setValue,
      ),
    );
    emit(state.copyWith(
      data: newData,
      userSettings: state.userSettings.copyWith(cabinTempSetValue: setValue),
      clearError: true,
    ));
    Log.warn(
      '🔥🔥🔥 BLE_WRITE_DEBUG cabin_temp_set_value value=$setValue',
    );
    await _writeControlValueToBluetooth(
      identifier: 0x02,
      setValue: setValue,
      errorPrefix: '舱内温度设定',
      emit: emit,
      scale: 10,
    );
  }

  /// [用户操作] 设置舱内温度开关（发送给MCU）—— 持久化
  void _onCabinTempSwitchChanged(
    DeviceControlCabinTempSwitchChanged event,
    Emitter<DeviceControlState> emit,
  ) {
    final newData = state.data.copyWith(
      cabinTemp: state.data.cabinTemp.copyWith(
        isOn: event.isOn,
      ),
    );
    emit(state.copyWith(
      data: newData,
      userSettings: state.userSettings.copyWith(cabinTempIsOn: event.isOn),
      clearError: true,
    ));
    // TODO: 发送设置到MCU
  }

  // ==================== 舱内湿度控制事件处理 ====================

  /// [MCU调用] 更新舱内湿度当前值（从MCU获取的真实数据）
  void _onCabinHumidityCurrentValueFetched(
    DeviceControlCabinHumidityCurrentValueFetched event,
    Emitter<DeviceControlState> emit,
  ) {
    final newData = state.data.copyWith(
      cabinHumidity: state.data.cabinHumidity.copyWith(
        currentValue: event.currentValue,
      ),
    );
    emit(state.copyWith(data: newData, clearError: true));
  }

  /// [用户操作] 设置舱内湿度设定值（发送给MCU）—— 持久化
  Future<void> _onCabinHumiditySetValueChanged(
    DeviceControlCabinHumiditySetValueChanged event,
    Emitter<DeviceControlState> emit,
  ) async {
    await _setCabinHumiditySetValue(event.setValue, emit);
  }

  /// [用户操作] 点击舱内湿度设定值 -/+（发送给MCU）—— 持久化
  Future<void> _onCabinHumiditySetValueAdjusted(
    DeviceControlCabinHumiditySetValueAdjusted event,
    Emitter<DeviceControlState> emit,
  ) async {
    final currentValue = int.tryParse(state.data.cabinHumidity.setValue) ?? 0;
    final nextValue = (currentValue + event.step).clamp(0, 100);
    Log.warn(
      '🔥🔥🔥 BLE_WRITE_DEBUG cabin_humidity_adjust '
      'current=$currentValue step=${event.step} next=$nextValue',
    );
    await _setCabinHumiditySetValue('$nextValue', emit);
  }

  Future<void> _setCabinHumiditySetValue(
    String setValue,
    Emitter<DeviceControlState> emit,
  ) async {
    final newData = state.data.copyWith(
      cabinHumidity: state.data.cabinHumidity.copyWith(
        setValue: setValue,
      ),
    );
    emit(state.copyWith(
      data: newData,
      userSettings:
          state.userSettings.copyWith(cabinHumiditySetValue: setValue),
      clearError: true,
    ));
    Log.warn(
      '🔥🔥🔥 BLE_WRITE_DEBUG cabin_humidity_set_value value=$setValue',
    );
    await _writeControlValueToBluetooth(
      identifier: 0x04,
      setValue: setValue,
      errorPrefix: '舱内湿度设定',
      emit: emit,
    );
  }

  /// [用户操作] 设置舱内湿度开关（发送给MCU）—— 持久化
  void _onCabinHumiditySwitchChanged(
    DeviceControlCabinHumiditySwitchChanged event,
    Emitter<DeviceControlState> emit,
  ) {
    final newData = state.data.copyWith(
      cabinHumidity: state.data.cabinHumidity.copyWith(
        isOn: event.isOn,
      ),
    );
    emit(state.copyWith(
      data: newData,
      userSettings: state.userSettings.copyWith(cabinHumidityIsOn: event.isOn),
      clearError: true,
    ));
    // TODO: 发送设置到MCU
  }

  // ==================== 氧气浓度控制事件处理 ====================

  /// [MCU调用] 更新氧气浓度当前值（从MCU获取的真实数据）
  void _onOxygenConcentrationCurrentValueFetched(
    DeviceControlOxygenConcentrationCurrentValueFetched event,
    Emitter<DeviceControlState> emit,
  ) {
    final newData = state.data.copyWith(
      oxygenConcentration: state.data.oxygenConcentration.copyWith(
        currentValue: event.currentValue,
      ),
    );
    emit(state.copyWith(data: newData, clearError: true));
  }

  /// [用户操作] 设置氧气浓度设定值（发送给MCU）—— 持久化
  Future<void> _onOxygenConcentrationSetValueChanged(
    DeviceControlOxygenConcentrationSetValueChanged event,
    Emitter<DeviceControlState> emit,
  ) async {
    await _setOxygenConcentrationSetValue(event.setValue, emit);
  }

  /// [用户操作] 点击氧气浓度设定值 -/+（发送给MCU）—— 持久化
  Future<void> _onOxygenConcentrationSetValueAdjusted(
    DeviceControlOxygenConcentrationSetValueAdjusted event,
    Emitter<DeviceControlState> emit,
  ) async {
    final currentValue =
        int.tryParse(state.data.oxygenConcentration.setValue) ?? 0;
    final nextValue = (currentValue + event.step).clamp(0, 100);
    Log.warn(
      '🔥🔥🔥 BLE_WRITE_DEBUG oxygen_concentration_adjust '
      'current=$currentValue step=${event.step} next=$nextValue',
    );
    await _setOxygenConcentrationSetValue('$nextValue', emit);
  }

  Future<void> _setOxygenConcentrationSetValue(
    String setValue,
    Emitter<DeviceControlState> emit,
  ) async {
    final newData = state.data.copyWith(
      oxygenConcentration: state.data.oxygenConcentration.copyWith(
        setValue: setValue,
      ),
    );
    emit(state.copyWith(
      data: newData,
      userSettings:
          state.userSettings.copyWith(oxygenConcentrationSetValue: setValue),
      clearError: true,
    ));
    Log.warn(
      '🔥🔥🔥 BLE_WRITE_DEBUG oxygen_concentration_set_value value=$setValue',
    );
    await _writeControlValueToBluetooth(
      identifier: 0x05,
      setValue: setValue,
      errorPrefix: '氧气浓度设定',
      emit: emit,
    );
  }

  /// [用户操作] 设置氧气浓度开关（发送给MCU）—— 持久化
  void _onOxygenConcentrationSwitchChanged(
    DeviceControlOxygenConcentrationSwitchChanged event,
    Emitter<DeviceControlState> emit,
  ) {
    final newData = state.data.copyWith(
      oxygenConcentration: state.data.oxygenConcentration.copyWith(
        isOn: event.isOn,
      ),
    );
    emit(state.copyWith(
      data: newData,
      userSettings:
          state.userSettings.copyWith(oxygenConcentrationIsOn: event.isOn),
      clearError: true,
    ));
    // TODO: 发送设置到MCU
  }

  // ==================== 二氧化碳浓度控制事件处理 ====================

  /// [MCU调用] 更新二氧化碳浓度当前值（从MCU获取的真实数据）
  void _onCO2ConcentrationCurrentValueFetched(
    DeviceControlCO2ConcentrationCurrentValueFetched event,
    Emitter<DeviceControlState> emit,
  ) {
    final newData = state.data.copyWith(
      co2Concentration: state.data.co2Concentration.copyWith(
        currentValue: event.currentValue,
      ),
    );
    emit(state.copyWith(data: newData, clearError: true));
  }

  /// [用户操作] 设置二氧化碳浓度告警阈值（发送给MCU）—— 持久化
  Future<void> _onCO2ConcentrationAlarmThresholdChanged(
    DeviceControlCO2ConcentrationAlarmThresholdChanged event,
    Emitter<DeviceControlState> emit,
  ) async {
    await _setCO2ConcentrationAlarmThreshold(event.alarmThreshold, emit);
  }

  /// [用户操作] 点击二氧化碳浓度设定值 -/+（发送给MCU）—— 持久化
  Future<void> _onCO2ConcentrationAlarmThresholdAdjusted(
    DeviceControlCO2ConcentrationAlarmThresholdAdjusted event,
    Emitter<DeviceControlState> emit,
  ) async {
    final currentValue =
        int.tryParse(state.data.co2Concentration.alarmThreshold) ?? 0;
    final nextValue = (currentValue + event.step).clamp(0, 9999);
    Log.warn(
      '🔥🔥🔥 BLE_WRITE_DEBUG co2_alarm_threshold_adjust '
      'current=$currentValue step=${event.step} next=$nextValue',
    );
    await _setCO2ConcentrationAlarmThreshold('$nextValue', emit);
  }

  Future<void> _setCO2ConcentrationAlarmThreshold(
    String alarmThreshold,
    Emitter<DeviceControlState> emit,
  ) async {
    final newData = state.data.copyWith(
      co2Concentration: state.data.co2Concentration.copyWith(
        alarmThreshold: alarmThreshold,
      ),
    );
    emit(state.copyWith(
      data: newData,
      userSettings:
          state.userSettings.copyWith(co2AlarmThreshold: alarmThreshold),
      clearError: true,
    ));
    Log.warn(
      '🔥🔥🔥 BLE_WRITE_DEBUG co2_alarm_threshold_set_value '
      'value=$alarmThreshold',
    );
    await _writeControlValueToBluetooth(
      identifier: 0x31,
      setValue: alarmThreshold,
      errorPrefix: '二氧化碳浓度设定',
      emit: emit,
    );
  }

  // ==================== 护理等级控制事件处理 ====================

  /// [用户操作] 设置护理等级（发送给MCU）—— 持久化
  void _onCareLevelChanged(
    DeviceControlCareLevelChanged event,
    Emitter<DeviceControlState> emit,
  ) {
    final newData = state.data.copyWith(
      careLevel: state.data.careLevel.copyWith(
        currentLevel: event.level,
      ),
    );
    emit(state.copyWith(
      data: newData,
      userSettings: state.userSettings.copyWith(careLevelValue: event.level),
      clearError: true,
    ));
    // TODO: 发送设置到MCU
  }

  // ==================== 新风进化控制事件处理 ====================

  /// [用户操作] 设置新风模式（发送给MCU）—— 持久化
  void _onFreshAirModeChanged(
    DeviceControlFreshAirModeChanged event,
    Emitter<DeviceControlState> emit,
  ) {
    final newData = state.data.copyWith(
      freshAir: state.data.freshAir.copyWith(
        mode: event.mode,
      ),
    );
    emit(state.copyWith(
      data: newData,
      userSettings: state.userSettings.copyWith(freshAirModeValue: event.mode),
      clearError: true,
    ));
    // TODO: 发送设置到MCU
  }

  // ==================== 风速调节控制事件处理 ====================

  /// [用户操作] 设置风速模式（发送给MCU）—— 持久化
  Future<void> _onWindSpeedModeChanged(
    DeviceControlWindSpeedModeChanged event,
    Emitter<DeviceControlState> emit,
  ) async {
    final newData = state.data.copyWith(
      windSpeed: state.data.windSpeed.copyWith(
        currentMode: event.mode,
      ),
    );
    emit(state.copyWith(
      data: newData,
      userSettings: state.userSettings.copyWith(windSpeedModeValue: event.mode),
      clearError: true,
    ));
    await _writeControlValueToBluetooth(
      identifier: 0xB3,
      setValue: '${_windSpeedProtocolValue(event.mode)}',
      errorPrefix: '风速调节',
      emit: emit,
    );
  }

  // ==================== 雾化时间设置事件处理 ====================

  /// [用户操作] 设置雾化时间（发送给MCU）—— 持久化
  void _onNebulizationTimeChanged(
    DeviceControlNebulizationTimeChanged event,
    Emitter<DeviceControlState> emit,
  ) {
    final newData = state.data.copyWith(
      nebulizationTime: state.data.nebulizationTime.copyWith(
        setMinutes: event.minutes,
      ),
    );
    emit(state.copyWith(
      data: newData,
      userSettings:
          state.userSettings.copyWith(nebulizationTimeMinutes: event.minutes),
      clearError: true,
    ));
    // TODO: 发送设置到MCU
  }

  // ==================== 消毒时间设置事件处理 ====================

  /// [用户操作] 设置消毒时间（发送给MCU）—— 持久化
  void _onDisinfectionTimeChanged(
    DeviceControlDisinfectionTimeChanged event,
    Emitter<DeviceControlState> emit,
  ) {
    final newData = state.data.copyWith(
      disinfectionTime: state.data.disinfectionTime.copyWith(
        setMinutes: event.minutes,
      ),
    );
    emit(state.copyWith(
      data: newData,
      userSettings:
          state.userSettings.copyWith(disinfectionTimeMinutes: event.minutes),
      clearError: true,
    ));
    // TODO: 发送设置到MCU
  }

  // ==================== 开放供氧控制事件处理 ====================

  /// [用户操作] 设置开放供氧开关（发送给MCU）—— 持久化
  Future<void> _onOpenOxygenSwitchChanged(
    DeviceControlOpenOxygenSwitchChanged event,
    Emitter<DeviceControlState> emit,
  ) async {
    final newData = state.data.copyWith(
      openOxygen: state.data.openOxygen.copyWith(
        isOn: event.isOn,
      ),
    );
    emit(state.copyWith(
      data: newData,
      userSettings: state.userSettings.copyWith(openOxygenIsOn: event.isOn),
      clearError: true,
    ));
    await _writeSwitchValueToBluetooth(
      identifier: 0x26,
      isOn: event.isOn,
      errorPrefix: '开放供氧',
      emit: emit,
    );
  }

  // ==================== 供氧计时事件处理 ====================

  /// [MCU调用] 更新供氧计时（从MCU获取）
  void _onOxygenTimerUpdated(
    DeviceControlOxygenTimerUpdated event,
    Emitter<DeviceControlState> emit,
  ) {
    final newData = state.data.copyWith(
      oxygenTimer: state.data.oxygenTimer.copyWith(
        hours: event.hours,
        minutes: event.minutes,
        seconds: event.seconds,
      ),
    );
    emit(state.copyWith(data: newData, clearError: true));
  }

  /// [用户操作] 清零供氧计时
  void _onOxygenTimerCleared(
    DeviceControlOxygenTimerCleared event,
    Emitter<DeviceControlState> emit,
  ) {
    final newData = state.data.copyWith(
      oxygenTimer: const OxygenTimerBO(
        hours: '00',
        minutes: '00',
        seconds: '00',
      ),
    );
    emit(state.copyWith(data: newData, clearError: true));
    // TODO: 发送清零指令到MCU
  }

  // ==================== 循环模式控制事件处理 ====================

  /// [用户操作] 设置循环模式（发送给MCU）—— 持久化
  Future<void> _onCirculationModeChanged(
    DeviceControlCirculationModeChanged event,
    Emitter<DeviceControlState> emit,
  ) async {
    final newData = state.data.copyWith(
      circulationMode: state.data.circulationMode.copyWith(
        currentMode: event.mode,
      ),
    );
    emit(state.copyWith(
      data: newData,
      userSettings:
          state.userSettings.copyWith(circulationModeValue: event.mode),
      clearError: true,
    ));
    await _writeSwitchValueToBluetooth(
      identifier: 0x06,
      isOn: event.mode == CirculationMode.external,
      errorPrefix: event.mode == CirculationMode.external ? '外循环' : '内循环',
      emit: emit,
    );
  }

  // ==================== 灯光控制事件处理 ====================

  /// [用户操作] 设置检查灯开关（发送给MCU）—— 持久化
  Future<void> _onCheckLightSwitchChanged(
    DeviceControlCheckLightSwitchChanged event,
    Emitter<DeviceControlState> emit,
  ) async {
    final newData = state.data.copyWith(
      lightControl: state.data.lightControl.copyWith(
        checkLightOn: event.isOn,
      ),
    );
    emit(state.copyWith(
      data: newData,
      userSettings: state.userSettings.copyWith(checkLightOn: event.isOn),
      clearError: true,
    ));
    await _writeSwitchValueToBluetooth(
      identifier: 0x0A,
      isOn: event.isOn,
      errorPrefix: '检查灯',
      emit: emit,
    );
  }

  /// [用户操作] 设置照明灯开关（发送给MCU）—— 持久化
  Future<void> _onIlluminationLightSwitchChanged(
    DeviceControlIlluminationLightSwitchChanged event,
    Emitter<DeviceControlState> emit,
  ) async {
    final newData = state.data.copyWith(
      lightControl: state.data.lightControl.copyWith(
        illuminationOn: event.isOn,
      ),
    );
    emit(state.copyWith(
      data: newData,
      userSettings: state.userSettings.copyWith(illuminationOn: event.isOn),
      clearError: true,
    ));
    await _writeSwitchValueToBluetooth(
      identifier: 0x09,
      isOn: event.isOn,
      errorPrefix: '照明灯',
      emit: emit,
    );
  }

  /// [用户操作] 设置蓝光灯开关（发送给MCU）—— 持久化
  Future<void> _onBlueLightSwitchChanged(
    DeviceControlBlueLightSwitchChanged event,
    Emitter<DeviceControlState> emit,
  ) async {
    final newData = state.data.copyWith(
      lightControl: state.data.lightControl.copyWith(
        blueLightOn: event.isOn,
      ),
    );
    emit(state.copyWith(
      data: newData,
      userSettings: state.userSettings.copyWith(blueLightOn: event.isOn),
      clearError: true,
    ));
    await _writeSwitchValueToBluetooth(
      identifier: 0x1E,
      isOn: event.isOn,
      errorPrefix: '蓝光',
      emit: emit,
    );
  }

  /// [用户操作] 设置红光灯开关（发送给MCU）—— 持久化
  Future<void> _onRedLightSwitchChanged(
    DeviceControlRedLightSwitchChanged event,
    Emitter<DeviceControlState> emit,
  ) async {
    final newData = state.data.copyWith(
      lightControl: state.data.lightControl.copyWith(
        redLightOn: event.isOn,
      ),
    );
    emit(state.copyWith(
      data: newData,
      userSettings: state.userSettings.copyWith(redLightOn: event.isOn),
      clearError: true,
    ));
    await _writeSwitchValueToBluetooth(
      identifier: 0x1F,
      isOn: event.isOn,
      errorPrefix: '红光',
      emit: emit,
    );
  }

  // ==================== 全局统计数据事件处理 ====================

  /// [MCU调用] 更新总运行时长
  void _onTotalRunTimeUpdated(
    DeviceControlTotalRunTimeUpdated event,
    Emitter<DeviceControlState> emit,
  ) {
    final newData = state.data.copyWith(
      totalRunTime: event.totalRunTime,
    );
    emit(state.copyWith(data: newData, clearError: true));
  }

  /// [MCU调用] 更新环境温度
  void _onEnvironmentTempUpdated(
    DeviceControlEnvironmentTempUpdated event,
    Emitter<DeviceControlState> emit,
  ) {
    final newData = state.data.copyWith(
      environmentTemp: event.environmentTemp,
    );
    emit(state.copyWith(data: newData, clearError: true));
  }

  /// [MCU调用] 更新总制氧时长
  void _onTotalOxygenTimeUpdated(
    DeviceControlTotalOxygenTimeUpdated event,
    Emitter<DeviceControlState> emit,
  ) {
    final newData = state.data.copyWith(
      totalOxygenTime: event.totalOxygenTime,
    );
    emit(state.copyWith(data: newData, clearError: true));
  }

  /// [用户操作] 重置设备设置为默认值 —— 清除持久化
  void _onResetSettings(
    DeviceControlResetSettings event,
    Emitter<DeviceControlState> emit,
  ) {
    emit(const DeviceControlState());
    // TODO: 发送重置指令到MCU
  }

  Future<void> _writeControlValueToBluetooth({
    required int identifier,
    required String setValue,
    required String errorPrefix,
    required Emitter<DeviceControlState> emit,
    int scale = 1,
  }) async {
    final command = _buildControlValueCommand(
      identifier: identifier,
      setValue: setValue,
      scale: scale,
    );
    if (command == null) {
      emit(state.copyWith(error: '$errorPrefix值无效: $setValue'));
      return;
    }

    try {
      if (!_bluetoothManager.isConnected) {
        final boundDevice = await _storageService.getBoundBluetoothDevice();
        final deviceId = boundDevice['deviceId'];
        if (deviceId == null || deviceId.isEmpty) {
          emit(state.copyWith(error: '未绑定蓝牙设备，无法发送$errorPrefix'));
          return;
        }
        await _bluetoothManager.connectToDeviceId(deviceId);
      }

      Log.warn(
        '🔥🔥🔥 BLE_WRITE_DEBUG send_control '
        'identifier=0x${identifier.toRadixString(16).padLeft(2, '0').toUpperCase()} '
        'value=$setValue scale=$scale '
        'hex=${BleBluetoothManager.bytesToHex(command)} '
        'isConnected=${_bluetoothManager.isConnected}',
      );
      await _bluetoothManager.writeData(command);
    } catch (e) {
      emit(state.copyWith(error: '$errorPrefix发送失败: $e'));
    }
  }

  Future<void> _writeSwitchValueToBluetooth({
    required int identifier,
    required bool isOn,
    required String errorPrefix,
    required Emitter<DeviceControlState> emit,
  }) async {
    Log.warn(
      '🔥🔥🔥 BLE_WRITE_DEBUG switch_set_value '
      'name=$errorPrefix isOn=$isOn',
    );
    await _writeControlValueToBluetooth(
      identifier: identifier,
      setValue: isOn ? '1' : '0',
      errorPrefix: errorPrefix,
      emit: emit,
    );
  }

  int _windSpeedProtocolValue(WindSpeedMode mode) {
    switch (mode) {
      case WindSpeedMode.comfort:
        return 0;
      case WindSpeedMode.strong:
        return 1;
      case WindSpeedMode.sleep:
        return 2;
    }
  }

  List<int>? _buildControlValueCommand({
    required int identifier,
    required String setValue,
    int scale = 1,
  }) {
    final value = double.tryParse(setValue);
    if (value == null) return null;

    final payloadValue = (value * scale).round();
    return [
      0x68,
      0x02,
      0x02,
      0x01,
      identifier,
      payloadValue & 0xFF,
      (payloadValue >> 8) & 0xFF,
      0x16,
    ];
  }

  String _formatTemperature(double value) {
    if (value.isNaN) return '--';
    final fixed = value.toStringAsFixed(1);
    return fixed.endsWith('.0') ? fixed.substring(0, fixed.length - 2) : fixed;
  }

  String _formatTemperatureOrKeep(double value, String fallback) {
    return value.isNaN ? fallback : _formatTemperature(value);
  }

  String _formatInt(int value) {
    return value < 0 ? '--' : '$value';
  }

  String _formatIntOrKeep(int value, String fallback) {
    return value < 0 ? fallback : '$value';
  }

  @override
  Future<void> close() async {
    await _mcuReportSub.cancel();
    await _bluetoothDataSub.cancel();
    return super.close();
  }

  // ==================== 便捷方法 - 供外部调用 ====================

  /// [MCU调用] 更新设备SN
  void updateSn(String? sn) => add(DeviceControlSnFetched(sn));

  /// [用户调用] 设置设备SN
  void setSn(String? sn) => add(DeviceControlSnChanged(sn));

  /// [MCU调用] 更新舱内温度当前值
  void updateCabinTempCurrentValue(String value) =>
      add(DeviceControlCabinTempCurrentValueFetched(value));

  /// [用户调用] 设置舱内温度设定值
  void setCabinTempSetValue(String value) =>
      add(DeviceControlCabinTempSetValueChanged(value));

  /// [用户调用] 调整舱内温度设定值
  void adjustCabinTempSetValue(int step) =>
      add(DeviceControlCabinTempSetValueAdjusted(step));

  /// [用户调用] 设置舱内温度开关
  void setCabinTempSwitch(bool isOn) =>
      add(DeviceControlCabinTempSwitchChanged(isOn));

  /// [MCU调用] 更新舱内湿度当前值
  void updateCabinHumidityCurrentValue(String value) =>
      add(DeviceControlCabinHumidityCurrentValueFetched(value));

  /// [用户调用] 设置舱内湿度设定值
  void setCabinHumiditySetValue(String value) =>
      add(DeviceControlCabinHumiditySetValueChanged(value));

  /// [用户调用] 调整舱内湿度设定值
  void adjustCabinHumiditySetValue(int step) =>
      add(DeviceControlCabinHumiditySetValueAdjusted(step));

  /// [用户调用] 设置舱内湿度开关
  void setCabinHumiditySwitch(bool isOn) =>
      add(DeviceControlCabinHumiditySwitchChanged(isOn));

  /// [MCU调用] 更新氧气浓度当前值
  void updateOxygenConcentrationCurrentValue(String value) =>
      add(DeviceControlOxygenConcentrationCurrentValueFetched(value));

  /// [用户调用] 设置氧气浓度设定值
  void setOxygenConcentrationSetValue(String value) =>
      add(DeviceControlOxygenConcentrationSetValueChanged(value));

  /// [用户调用] 调整氧气浓度设定值
  void adjustOxygenConcentrationSetValue(int step) =>
      add(DeviceControlOxygenConcentrationSetValueAdjusted(step));

  /// [用户调用] 设置氧气浓度开关
  void setOxygenConcentrationSwitch(bool isOn) =>
      add(DeviceControlOxygenConcentrationSwitchChanged(isOn));

  /// [MCU调用] 更新二氧化碳浓度当前值
  void updateCO2ConcentrationCurrentValue(String value) =>
      add(DeviceControlCO2ConcentrationCurrentValueFetched(value));

  /// [用户调用] 设置二氧化碳浓度告警阈值
  void setCO2ConcentrationAlarmThreshold(String value) =>
      add(DeviceControlCO2ConcentrationAlarmThresholdChanged(value));

  /// [用户调用] 调整二氧化碳浓度告警阈值
  void adjustCO2ConcentrationAlarmThreshold(int step) =>
      add(DeviceControlCO2ConcentrationAlarmThresholdAdjusted(step));

  /// [用户调用] 设置护理等级
  void setCareLevel(CareLevel level) =>
      add(DeviceControlCareLevelChanged(level));

  /// [用户调用] 设置新风模式
  void setFreshAirMode(FreshAirMode mode) =>
      add(DeviceControlFreshAirModeChanged(mode));

  /// [用户调用] 设置风速模式
  void setWindSpeedMode(WindSpeedMode mode) =>
      add(DeviceControlWindSpeedModeChanged(mode));

  /// [用户调用] 设置雾化时间
  void setNebulizationTime(String minutes) =>
      add(DeviceControlNebulizationTimeChanged(minutes));

  /// [用户调用] 设置消毒时间
  void setDisinfectionTime(String minutes) =>
      add(DeviceControlDisinfectionTimeChanged(minutes));

  /// [用户调用] 设置开放供氧开关
  void setOpenOxygenSwitch(bool isOn) =>
      add(DeviceControlOpenOxygenSwitchChanged(isOn));

  /// [MCU调用] 更新供氧计时
  void updateOxygenTimer(String hours, String minutes, String seconds) =>
      add(DeviceControlOxygenTimerUpdated(hours, minutes, seconds));

  /// [用户调用] 清零供氧计时
  void clearOxygenTimer() => add(const DeviceControlOxygenTimerCleared());

  /// [用户调用] 设置循环模式
  void setCirculationMode(CirculationMode mode) =>
      add(DeviceControlCirculationModeChanged(mode));

  /// [用户调用] 设置检查灯开关
  void setCheckLightSwitch(bool isOn) =>
      add(DeviceControlCheckLightSwitchChanged(isOn));

  /// [用户调用] 设置照明灯开关
  void setIlluminationLightSwitch(bool isOn) =>
      add(DeviceControlIlluminationLightSwitchChanged(isOn));

  /// [用户调用] 设置蓝光灯开关
  void setBlueLightSwitch(bool isOn) =>
      add(DeviceControlBlueLightSwitchChanged(isOn));

  /// [用户调用] 设置红光灯开关
  void setRedLightSwitch(bool isOn) =>
      add(DeviceControlRedLightSwitchChanged(isOn));

  /// [MCU调用] 更新总运行时长
  void updateTotalRunTime(String time) =>
      add(DeviceControlTotalRunTimeUpdated(time));

  /// [MCU调用] 更新环境温度
  void updateEnvironmentTemp(String temp) =>
      add(DeviceControlEnvironmentTempUpdated(temp));

  /// [MCU调用] 更新总制氧时长
  void updateTotalOxygenTime(String time) =>
      add(DeviceControlTotalOxygenTimeUpdated(time));

  /// [用户调用] 重置设备设置
  void resetSettings() => add(const DeviceControlResetSettings());
}
