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

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

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

  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()));
    }
  }

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

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

    return state.copyWith(
      isLoading: false,
      reportHeader: {
        'title': '经营概览看板',
        'subtitle': '管理层视角 · 关键指标一览',
      },
      reportMetrics: {
        'powerUsage': {
          'value': todayVal.toInt(),
          'unit': 'kWh',
          'change': isDown ? -changeAbs : changeAbs,
          'changeText': isDown ? '↓ $changeAbs%' : '↑ $changeAbs%',
          'progress': (todayVal / 2000).clamp(0.0, 1.0),
        },
        'pendingAlerts': {
          'value': overview.alertPending.count,
          'unit': '条',
          'change': null,
          'changeText': overview.alertPending.count > 0 ? '需关注' : '无告警',
          'progress': (overview.alertPending.count / 10).clamp(0.0, 1.0),
        },
      },
      weeklyPowerUsage: {
        'title': '本周用电趋势',
        'unit': 'kWh',
        'dateRange': overview.electricityTrend.dateRange,
        'data': _mapWeekDays(overview.electricityTrend.points),
      },
      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<Map<String, dynamic>> _mapWeekDays(List<DashboardTrendPointBO> points) {
    const dayLabels = ['一', '二', '三', '四', '五', '六', '日'];
    return points.asMap().entries.map((entry) {
      final index = entry.key;
      final point = entry.value;
      return {
        'day': index < dayLabels.length ? dayLabels[index] : '${index + 1}',
        'value': point.value.toInt(),
      };
    }).toList();
  }

  /// 映射客房状态并分配颜色
  List<Map<String, dynamic>> _mapRoomStatuses(List<RoomStatusItemBO> items) {
    const statusColors = [
      Color.fromRGBO(59, 130, 246, 1),
      Color.fromRGBO(148, 163, 184, 1),
      Color.fromRGBO(96, 165, 250, 1),
      Color.fromRGBO(249, 115, 22, 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();
  }
}
