import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fl_chart/fl_chart.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/index/cubit/report_index_state.dart';

class ReportIndexCubit extends Cubit<ReportIndexState> {
  final DashboardService _service;

  DateTime? _lastLoadTime;

  ReportIndexCubit({DashboardService? service})
      : _service = service ?? DashboardService(repository: DashboardRepository()),
        super(const ReportIndexState());

  Future<void> loadData() async {
    emit(state.copyWith(isLoading: true, clearError: true));
    try {
      final overview = await _service.getOverview();
      emit(_mapOverviewToState(overview));
    } 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;
    }
    _lastLoadTime = DateTime.now();
    loadData();
  }

  ReportIndexState _mapOverviewToState(DashboardOverviewBO overview) {
    // 今日用电
    final yesterdayVal = overview.electricityToday.yesterdayValue;
    final todayVal = overview.electricityToday.value;
    double changePercent = 0;
    if (yesterdayVal > 0) {
      changePercent = ((todayVal - yesterdayVal) / yesterdayVal * 100);
    }
    final isDown = changePercent <= 0;
    final changeAbs = changePercent.abs().round();

    //待处理告警
    final count = overview.alertPending.count;
    final todayTotal = overview.alertPending.todayTotal;

    return state.copyWith(
      isLoading: false,
      reportHeader: {
        'title': '经营概览看板',
        'subtitle': '管理层视角 · 关键指标一览',
      },
      reportMetrics: {
        'powerUsage': {
          'value': todayVal.toString(),
          'unit': 'kWh',
          'change': isDown ? -changeAbs : changeAbs,
          'changeText': isDown ? '↓ $changeAbs%' : '↑ $changeAbs%',
          'progress': (todayVal / yesterdayVal).clamp(0.0, 1.0),
        },
        'pendingAlerts': {
          'value': count.toString(),
          'unit': '条',
          'change': null,
          'changeText': count > 0 ? '需关注' : '无告警',
          'progress': (count / todayTotal).clamp(0.0, 1.0),
        },
      },
      weeklyPowerUsage: {
        'title': '本周用电趋势',
        'unit': 'kWh',
        'dateRange': overview.electricityTrend.dateRange,
        'maxValue': overview.electricityTrend.maxValue,
        'spots': _buildSpots(overview.electricityTrend.points),
        'timeLabels': overview.electricityTrend.points.map((p) {
          // "06-10 19:21:47" → "06-10"
          return p.time.split(' ').first;
        }).toList(),
      },
      roomStatusDistribution: {
        'title': '客房状态分布',
        'totalRooms': overview.roomStatusDistribution.total,
        'statuses': _mapRoomStatuses(overview.roomStatusDistribution.items),
      },
      deviceOnlineRate: {
        'title': '设备在线率',
        'rate': 1.0,
        'rateText': '${overview.deviceTypeDistribution.totalDeviceCount}',
        'devices': _mapDeviceTypes(overview.deviceTypeDistribution.items),
      },
      quickActions: {
        'title': '快捷操作',
        'actions': [
          {'name': '告警记录', 'icon': Icons.warning_amber_outlined},
          {'name': '联动规则', 'icon': Icons.tune},
        ],
      },
    );
  }

  List<FlSpot> _buildSpots(List<DashboardTrendPointBO> points) {
    return points.asMap().entries.map((entry) {
      return FlSpot(entry.key.toDouble(), entry.value.value);
    }).toList();
  }

  /// 映射客房状态并分配颜色
  List<Map<String, dynamic>> _mapRoomStatuses(List<RoomStatusItemBO> items) {
    const statusColors = [
      Color.fromRGBO(73, 149, 234, 1),
      Color.fromRGBO(100, 116, 139, 1),
      Color.fromRGBO(139, 193, 255, 1),
      Color.fromRGBO(250, 204, 21, 1),
    ];
    return items.asMap().entries.map((entry) {
      final index = entry.key;
      final item = entry.value;
      return {
        'name': item.statusLabel,
        'count': item.count,
        'color': statusColors[index % statusColors.length],
      };
    }).toList();
  }

  /// 映射设备类型分布
  List<Map<String, dynamic>> _mapDeviceTypes(List<DeviceTypeItemBO> items) {
    return items.map((item) {
      return {
        'name': item.typeLabel,
        'count': item.count,
      };
    }).toList();
  }
}
