import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smart_hotel_app/models/bo/alert_dashboard_bo.dart';
import 'package:smart_hotel_app/repositories/alert_dashboard_repository.dart';
import 'package:smart_hotel_app/repositories/alert_detail_repository.dart';
import 'package:smart_hotel_app/services/alert_dashboard_service.dart';
import 'package:smart_hotel_app/services/alert_detail_service.dart';
import 'package:smart_hotel_app/utils/deal_utils.dart';
import 'package:smart_hotel_app/views/home/index/cubit/home_index_state.dart';

class HomeIndexCubit extends Cubit<HomeIndexState> {
  final AlertDashboardService _service;
  final AlertDetailService _alertDetailService;

  DateTime? _lastLoadTime;

  HomeIndexCubit({
    AlertDashboardService? service,
    AlertDetailService? alertDetailService,
  })  : _service = service ??
            AlertDashboardService(
              repository: AlertDashboardRepository(),
            ),
        _alertDetailService = alertDetailService ??
            AlertDetailService(
              repository: AlertDetailRepository(),
            ),
        super(const HomeIndexState()) {
    loadData();
  }

  Future<void> loadData() async {
    _lastLoadTime = DateTime.now();
    emit(state.copyWith(isLoading: true, error: null));
    try {
      final dashboard = await _service.getDashboard();
      _emitFromDashboard(dashboard);
    } catch (e) {
      emit(state.copyWith(isLoading: false, error: e.toString()));
    }
  }

  /// 切回页面时调用，距上次加载不足 30 秒则跳过
  void reloadDataIfStale() {
    if (_lastLoadTime != null &&
        DateTime.now().difference(_lastLoadTime!) < const Duration(seconds: 30)) {
      return;
    }
    loadData();
  }

  /// 处理告警
  Future<void> handleAlert(int alertId) async {
    if (state.isHandlingAlert) return;
    emit(state.copyWith(isHandlingAlert: true));
    try {
      await _alertDetailService.handleAlert(alertId: alertId);
      emit(state.copyWith(isHandlingAlert: false));
      await loadData();
    } catch (e) {
      emit(state.copyWith(isHandlingAlert: false, error: e.toString()));
      rethrow;
    }
  }

  void _emitFromDashboard(AlertDashboardBO dashboard) {
    emit(state.copyWith(
      isLoading: false,
      error: null,
      highAlarmCount: dashboard.statistics.highAlertCount,
      mediumAlarmCount: dashboard.statistics.mediumAlertCount,
      onlineDeviceCount: dashboard.statistics.onlineDeviceCount,
      alerts: dashboard.alerts.take(5).toList(),
      equipmentList: dashboard.devices
          .where((d) => !d.deviceName.contains('分控'))
          .map((d) => _mapDeviceToEquipment(d))
          .toList(),
    ));
  }

  EquipmentItem _mapDeviceToEquipment(DeviceItemBO d) {
    return EquipmentItem(
      icon: DealUtils.deviceIcon(d.deviceTypeIcon),
      title: d.deviceLocation + d.deviceName,
      subtitle: _buildDeviceSubtitle(d),
      // status: d.onlineStatus == '1' ? d.runStatusText : '离线',
      status: d.runStatusText,
      statusColor: _mapStatusColor(d.runStatus),
    );
  }

  String _buildDeviceSubtitle(DeviceItemBO d) {
    return [
      if (d.roomName.isNotEmpty) d.roomName,
      if (d.temperature.isNotEmpty) '${DealUtils.cleanNumber(d.temperature)}°C',
      if (d.voltage.isNotEmpty) '${DealUtils.cleanNumber(d.voltage)}V',
      if (d.power.isNotEmpty) '${DealUtils.cleanNumber(d.power)}kW',
      if (d.current.isNotEmpty) '${DealUtils.cleanNumber(d.current)}A',
    ].join('·');
  }

  Color _mapStatusColor(String runStatus) {
    switch (runStatus) {
      case 'normal':
        return const Color.fromRGBO(20, 184, 166, 1.0);
      case 'warning':
        return const Color.fromRGBO(250, 204, 21, 1.0);
      case 'fault':
        return const Color.fromRGBO(255, 77, 79, 1.0);
      case 'offline':
      default:
        return const Color.fromRGBO(102, 102, 102, 1.0);
    }
  }
}
