import 'package:equatable/equatable.dart';
import 'package:laki_icu_app/models/bo/device_control_bo.dart';

/// 默认的 DeviceControlBO 数据（所有字段为初始值）
const DeviceControlBO _defaultDeviceControlBO = DeviceControlBO(
  sn: null,
  totalRunTime: '0h',
  environmentTemp: '25.0℃',
  totalOxygenTime: '0h',
  cabinTemp: TemperatureControlBO(
    currentValue: '--',
    setValue: '24',
    unit: '℃',
    isOn: false,
  ),
  cabinHumidity: HumidityControlBO(
    currentValue: '--',
    setValue: '50',
    unit: '%',
    isOn: false,
  ),
  oxygenConcentration: OxygenConcentrationBO(
    currentValue: '--',
    setValue: '90',
    unit: '%',
    isOn: true,
  ),
  co2Concentration: CO2ConcentrationBO(
    currentValue: '--',
    alarmThreshold: '4000',
    unit: 'PPM',
  ),
  careLevel: CareLevelControlBO(
    currentLevel: CareLevel.special,
  ),
  freshAir: FreshAirControlBO(
    mode: FreshAirMode.auto,
    description: 'CO₂超设定值时自动启动外循环净化，当降至2000ppm后，本功能自动关闭',
  ),
  windSpeed: WindSpeedControlBO(
    currentMode: WindSpeedMode.sleep,
  ),
  nebulizationTime: NebulizationTimeBO(
    setMinutes: '00',
  ),
  disinfectionTime: DisinfectionTimeBO(
    setMinutes: '14',
  ),
  openOxygen: OpenOxygenControlBO(
    isOn: false,
    description: '开启后风扇打开，制冷、加热和循环等设备暂停。\n*保持设备周围空气相对禁止，严禁烟火',
  ),
  oxygenTimer: OxygenTimerBO(
    hours: '00',
    minutes: '00',
    seconds: '00',
  ),
  circulationMode: CirculationModeBO(
    currentMode: CirculationMode.external,
  ),
  lightControl: LightControlBO(
    checkLightOn: false,
    illuminationOn: false,
    blueLightOn: false,
    redLightOn: false,
  ),
);

/// 用途：设备控制状态
/// 涉及页面：设备控制页面
class DeviceControlState extends Equatable {
  /// 设备控制数据
  final DeviceControlBO data;

  /// 用户设置（仅包含用户可配置的字段，用于 hydrated_bloc 持久化）
  final DeviceControlUserSettings userSettings;

  /// 加载状态
  final bool isLoading;

  /// 错误信息
  final String? error;

  const DeviceControlState({
    this.data = _defaultDeviceControlBO,
    this.userSettings = const DeviceControlUserSettings(),
    this.isLoading = false,
    this.error,
  });

  DeviceControlState copyWith({
    DeviceControlBO? data,
    DeviceControlUserSettings? userSettings,
    bool? isLoading,
    String? error,
    bool clearError = false,
  }) {
    return DeviceControlState(
      data: data ?? this.data,
      userSettings: userSettings ?? this.userSettings,
      isLoading: isLoading ?? this.isLoading,
      error: clearError ? null : error ?? this.error,
    );
  }

  /// 从持久化存储中恢复状态（仅恢复用户设置，MCU值使用默认值）
  factory DeviceControlState.fromJson(Map<String, dynamic> json) {
    final userSettings = DeviceControlUserSettings.fromJson(json);
    final restoredData = userSettings.applyTo(_defaultDeviceControlBO);
    final data = restoredData.copyWith(
      cabinTemp: restoredData.cabinTemp.copyWith(currentValue: '--'),
      cabinHumidity: restoredData.cabinHumidity.copyWith(currentValue: '--'),
      oxygenConcentration:
          restoredData.oxygenConcentration.copyWith(currentValue: '--'),
      co2Concentration:
          restoredData.co2Concentration.copyWith(currentValue: '--'),
    );
    return DeviceControlState(
      data: data,
      userSettings: userSettings,
    );
  }

  /// 序列化为持久化存储（仅持久化用户设置，不包含MCU获取的值）
  Map<String, dynamic> toJson() {
    return userSettings.toJson();
  }

  @override
  List<Object?> get props => [data, userSettings, isLoading, error];
}
