import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:laki_icu_app/models/bo/monitoring_bo.dart';
import 'package:laki_icu_app/services/monitoring_service.dart';

import 'device_control_index_state.dart';

class DeviceControlIndexCubit extends Cubit<DeviceControlIndexState> {
  final MonitoringService _monitoringService;

  DeviceControlIndexCubit({ 
    MonitoringService? monitoringService,
  })  : _monitoringService = monitoringService ?? MonitoringService(),
        super(DeviceControlIndexState()) {
    loadMetrics();
  }

  void selectMetric(String label) {
    emit(state.copyWith(selectedMetricLabel: label));
  }

  Future<void> loadMetrics() async {
    emit(state.copyWith(
      status: DeviceControlIndexStatus.loading,
      isLoading: true,
      error: null,
    ));

    try {
      final allMetrics = await _monitoringService.getMetrics();
      final envMetrics = _environmentMetrics(allMetrics);
      emit(state.copyWith(
        status: DeviceControlIndexStatus.success,
        isLoading: false,
        metrics: envMetrics,
        error: null,
      ));
    } catch (e) {
      emit(state.copyWith(
        status: DeviceControlIndexStatus.failure,
        isLoading: false,
        error: e.toString(),
      ));
    }
  }

  /// 过滤出环境指标（温度/湿度/氧气/二氧化碳），最多取4个
  List<MonitoringMetricBO> _environmentMetrics(
      List<MonitoringMetricBO> metrics) {
    final matched = metrics
        .where((item) =>
            item.label.contains('温度') ||
            item.label.contains('湿度') ||
            item.label.contains('氧气') ||
            item.label.contains('二氧化碳') ||
            item.label.toUpperCase().contains('CO'))
        .take(4)
        .toList();

    if (matched.length == 4) return matched;

    return const [
      MonitoringMetricBO(value: '--', unit: '℃', label: '舱内温度'),
      MonitoringMetricBO(value: '--', unit: 'RH', label: '舱内湿度'),
      MonitoringMetricBO(value: '--', unit: '%', label: '氧气浓度'),
      MonitoringMetricBO(value: '--', unit: '%', label: '二氧化碳'),
    ];
  }
}
