import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smart_hotel_app/models/bo/dashboard_bo.dart';
import 'package:smart_hotel_app/repositories/dashboard_repository.dart';
import 'package:smart_hotel_app/services/dashboard_service.dart';
import 'package:smart_hotel_app/views/report/energy/cubit/energy_state.dart';

class EnergyCubit extends Cubit<EnergyState> {
  final DashboardService _service;

  EnergyCubit({DashboardService? service})
      : _service = service ?? DashboardService(repository: DashboardRepository()),
        super(const EnergyState()) {
    loadData();
  }

  Future<void> loadData() async {
    emit(state.copyWith(isLoading: true, clearError: true));
    try {
      final data = await _service.getEnergyAnalysis();
      emit(_mapAnalysisToState(data));
    } catch (e) {
      emit(state.copyWith(isLoading: false, error: e.toString()));
    }
  }

  Future<void> reloadData() async {
    loadData();
  }

  EnergyState _mapAnalysisToState(EnergyAnalysisBO data) {
    // 计算今日变化百分比
    double todayChange = 0;
    if (data.yesterdayElectricity > 0) {
      todayChange =
          ((data.todayElectricity - data.yesterdayElectricity) /
                  data.yesterdayElectricity) *
              100;
    }

    // 计算本月变化百分比
    double monthChange = 0;
    if (data.lastMonthElectricity > 0) {
      monthChange =
          ((data.monthElectricity - data.lastMonthElectricity) /
                  data.lastMonthElectricity) *
              100;
    }

    // 将逐小时数据点提取为 List<double>
    final hourlyData = data.hourlyUsageToday.hourlyPoints
        .map((p) => p.value)
        .toList();

    // 将分区数据映射为 ZoneData 列表
    final totalToday = data.zoneUsageRatio.totalToday;
    final zoneData = data.zoneUsageRatio.zones.map((z) {
      final percent = totalToday > 0 ? (z.todayKwh / totalToday * 100) : 0.0;
      return ZoneData(
        name: z.zoneLabel,
        percentage: percent,
        energy: z.todayKwh,
      );
    }).toList();

    return EnergyState(
      isLoading: false,
      todayEnergy: data.todayElectricity,
      todayEnergyChange: todayChange,
      monthEnergy: data.monthElectricity,
      monthEnergyChange: monthChange,
      monthBill: data.monthCostEstimate,
      hourlyData: hourlyData,
      zoneData: zoneData,
    );
  }
}
