import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smart_hotel_app/models/bo/inspection_room_bo.dart';
import 'package:smart_hotel_app/repositories/inspection_device_repository.dart';
import 'package:smart_hotel_app/repositories/inspection_room_repository.dart';
import 'package:smart_hotel_app/services/inspection_device_service.dart';
import 'package:smart_hotel_app/services/inspection_room_service.dart';
import 'package:smart_hotel_app/views/home/inspection/cubit/inspection_state.dart';

class InspectionCubit extends Cubit<InspectionState> {
  final InspectionRoomService _roomService;
  final InspectionDeviceService _deviceService;

  static const int pageSize = 20;

  InspectionCubit({
    InspectionRoomService? roomService,
    InspectionDeviceService? deviceService,
  })  : _roomService = roomService ??
            InspectionRoomService(repository: InspectionRoomRepository()),
        _deviceService = deviceService ??
            InspectionDeviceService(
                repository: InspectionDeviceRepository()),
        super(const InspectionState(isLoading: true)) {
    initData();
  }

  Future<void> initData() async {
    try {
      final rooms = await _roomService.getRooms();
      final tabCounts = _computeTabCounts(rooms.runStatus);
      final roomGroups = rooms.roomGroups;

      // 默认选中第一个区域、第一个房间
      const defaultAreaIndex = 0;
      final defaultRoomId = roomGroups.isNotEmpty &&
              roomGroups[defaultAreaIndex].rooms.isNotEmpty
          ? roomGroups[defaultAreaIndex].rooms.first.roomId
          : null;

      emit(state.copyWith(
        isLoading: false,
        error: null,
        roomGroups: roomGroups,
        selectedAreaIndex: defaultAreaIndex,
        selectedRoomId: defaultRoomId,
        tabCounts: tabCounts,
      ));
    } catch (e) {
      emit(state.copyWith(
        isLoading: false,
        error: e.toString(),
      ));
    }
  }

  /// 从顶层 runStatus 汇总计算各 tab 数量
  Map<DeviceStatusTab, int> _computeTabCounts(InspectionRoomRunStatusBO runStatus) {
    final total =
        runStatus.normal + runStatus.warning + runStatus.offline + runStatus.fault;
    return {
      DeviceStatusTab.total: total,
      DeviceStatusTab.on: runStatus.normal,
      // DeviceStatusTab.off: 0,
      DeviceStatusTab.offline: runStatus.offline,
      DeviceStatusTab.alarm: runStatus.warning,
      DeviceStatusTab.fault: runStatus.fault,
    };
  }

  /// 供 PagingController.fetchPage 回调使用
  Future<List<InspectionDevice>> fetchPage(int pageKey) async {
    final result = await _deviceService.getList(
      pageSize: pageSize,
      pageNum: pageKey,
      roomId: state.selectedRoomId,
      runStatus: state.selectedTab.runStatus,
    );

    if (pageKey == 1) {
      emit(state.copyWith(totalCount: result.total));
    }

    return result.data
        .map((e) => InspectionDevice.fromInspectionDeviceBO(e))
        .where((device) => !device.name.contains('分控'))
        .toList();
  }

  void selectTab(DeviceStatusTab tab) {
    emit(state.copyWith(selectedTab: tab));
  }

  void selectArea(int index) {
    if (index < 0 || index >= state.roomGroups.length) return;
    final rooms = state.roomGroups[index].rooms;
    emit(state.copyWith(
      selectedAreaIndex: index,
      selectedRoomId: rooms.isNotEmpty ? rooms.first.roomId : null,
    ));
  }

  void selectRoom(int roomId) {
    emit(state.copyWith(selectedRoomId: roomId));
  }
}
