import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smart_hotel_app/models/bo/room_bo.dart';
import 'package:smart_hotel_app/repositories/room_repository.dart';
import 'package:smart_hotel_app/services/room_service.dart';
import 'package:smart_hotel_app/views/report/room/cubit/room_report_state.dart';

class RoomReportCubit extends Cubit<RoomReportState> {
  final RoomService _service;

  /// 全量数据缓存，切换楼层时直接从内存过滤，不重新请求接口
  List<RoomGridBO> _allRoomGrid = [];
  List<RoomDetailListBO> _allDetailRooms = [];

  RoomReportCubit({RoomService? service})
      : _service = service ?? RoomService(repository: RoomRepository()),
        super(const RoomReportState()) {
    loadData();
  }

  Future<void> loadData() async {
    emit(state.copyWith(isLoading: true, error: null, clearError: true));
    try {
      // 不传 floorId，获取全量数据
      final overview = await _service.getOverview(null);
      final activeIndex = overview.floorList.indexWhere((f) => f.isActive);
      final selectedFloorIndex = activeIndex >= 0 ? activeIndex : 0;

      // 过滤掉每个房间 deviceList 中名称含"分控"的设备，并缓存全量
      _allRoomGrid = overview.roomGrid;
      _allDetailRooms = overview.roomDetailList.map((room) {
        return RoomDetailListBO(
          roomBasicInfo: room.roomBasicInfo,
          statusTags: room.statusTags,
          deviceList: room.deviceList
              .where((d) => !d.deviceName.contains('分控'))
              .toList(),
        );
      }).toList();

      // 按选中楼层的 floorNumber 过滤
      final floorNumber = overview.floorList[selectedFloorIndex].floorNumber;

      emit(state.copyWith(
        isLoading: false,
        summary: overview.summary,
        floors: overview.floorList,
        selectedFloorIndex: selectedFloorIndex,
        roomGrid: _filterRoomGrid(floorNumber),
        detailRooms: _filterDetailRooms(floorNumber),
        selectedRoomId: null,
      ));
    } catch (e) {
      emit(state.copyWith(isLoading: false, error: e.toString()));
    }
  }

  /// 切换楼层
  void selectFloor(int index) {
    if (state.selectedFloorIndex == index) return;
    if (index < 0 || index >= state.floors.length) return;

    final floorNumber = state.floors[index].floorNumber;

    emit(state.copyWith(
      selectedFloorIndex: index,
      roomGrid: _filterRoomGrid(floorNumber),
      detailRooms: _filterDetailRooms(floorNumber),
      selectedRoomId: null,
    ));
  }

  void selectRoom(int roomId) {
    final newId = state.selectedRoomId == roomId ? null : roomId;
    emit(state.copyWith(selectedRoomId: newId));
  }

  List<RoomGridBO> _filterRoomGrid(int floorNumber) {
    return _allRoomGrid.where((r) => r.floorNumber == floorNumber).toList();
  }

  List<RoomDetailListBO> _filterDetailRooms(int floorNumber) {
    return _allDetailRooms
        .where((r) => r.roomBasicInfo.floorNumber == floorNumber)
        .toList();
  }
}
