import 'dart:math';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:smart_hotel_app/views/service/index/cubit/service_index_state.dart';

class ServiceIndexCubit extends Cubit<ServiceIndexState> {
  Map<String, List<Map<String, dynamic>>>? _roomCache;

  ServiceIndexCubit() : super(const ServiceIndexState()) {
    initData();
  }

  void initData() {
    emit(state.copyWith(
      pendingCount: 2,
      occupiedRooms: 45,
      vacantRooms: 7,
      floors: ['1楼', '2楼', '3楼', '4楼', '5楼', '6楼'],
    ));
  }

  void selectFloor(String? floor) {
    emit(state.copyWith(selectedFloor: floor));
  }

  void selectType(String? type) {
    emit(state.copyWith(selectedType: type));
  }

  void selectRoom(String? room) {
    emit(state.copyWith(selectedRoom: room));
  }

  void setSearchText(String text) {
    emit(state.copyWith(searchText: text));
  }

  Map<String, List<Map<String, dynamic>>> _buildRoomCache() {
    return {
      '1楼': _generateRooms(1, 20),
      '2楼': _generateRooms(2, Random().nextInt(21) + 10),
      '3楼': _generateRooms(3, Random().nextInt(21) + 10),
      '4楼': _generateRooms(4, Random().nextInt(21) + 10),
      '5楼': _generateRooms(5, Random().nextInt(5) + 10),
      '6楼': _generateRooms(6, Random().nextInt(21) + 10),
    };
  }

  bool get _cacheValid {
    if (_roomCache == null) return false;
    final firstFloor = _roomCache!['1楼'];
    if (firstFloor == null || firstFloor.isEmpty) return false;
    return firstFloor.first.containsKey('type');
  }

  List<Map<String, dynamic>> getRoomsByFloor(String floor) {
    if (!_cacheValid) {
      _roomCache = _buildRoomCache();
    }
    return _roomCache![floor] ?? [];
  }

  List<Map<String, dynamic>> _generateRooms(int floor, int count) {
    final statuses = ['空闲', '入住', '待清洁'];
    final types = ['客房', '大堂', '过道', '会议', '餐厅'];
    final List<Map<String, dynamic>> rooms = [];

    for (int i = 1; i <= count; i++) {
      final roomNum = floor * 100 + i;
      final statusIndex = (roomNum % 3);
      final typeIndex = (roomNum % types.length);
      rooms.add({
        'number': roomNum.toString(),
        'status': statuses[statusIndex],
        'type': types[typeIndex],
      });
    }
    return rooms;
  }

  void powerOnRoom(String roomNumber) {
    // ignore: avoid_print
    print('给 $roomNumber 号房送电');
  }

  void powerOffRoom(String roomNumber) {
    // ignore: avoid_print
    print('给 $roomNumber 号房断电');
  }
}