import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:smart_hotel_app/repositories/device_list_repository.dart';
import 'package:smart_hotel_app/services/device_list_service.dart';
import 'package:smart_hotel_app/views/report/device/cubit/device_list_state.dart';

class DeviceListCubit extends Cubit<DeviceListState> {
  static const int pageSize = 20;

  final DeviceListService _service;
  PagingController<int, DeviceInfo>? _pagingController;

  DeviceListCubit({DeviceListService? service})
      : _service = service ?? DeviceListService(repository: DeviceListRepository()),
        super(const DeviceListState());

  /// 绑定 PagingController，在 View 的 initState 中调用
  void bindPagingController(PagingController<int, DeviceInfo> controller) {
    _pagingController = controller;
  }

  /// 解绑 PagingController，在 View 的 dispose 中调用
  void unbindPagingController() {
    _pagingController = null;
  }

  /// 供 PagingController.fetchPage 回调使用
  Future<List<DeviceInfo>> fetchPage(int pageKey) async {
    final typeId = deviceTypeIdFromEnum(state.selectedType);
    final result = await _service.getList(
      pageSize: pageSize,
      pageNum: pageKey,
      deviceTypeId: typeId,
    );

    // 首页时更新 tab 计数和总数
    if (pageKey == 1) {
      emit(state.copyWith(
        tabAll: result.tabCount.all,
        tabAirSwitch: result.tabCount.airSwitch,
        tabGuestControl: result.tabCount.guestControl,
        tabNetwork: result.tabCount.gateway,
        totalCount: result.total,
      ));
    }

    return result.rows.map((row) {
      return DeviceInfo(
        deviceId: row.deviceId,
        name: row.deviceName,
        room: row.roomNumber.isNotEmpty ? row.roomNumber : row.deviceLocation,
        type: DeviceTypeEnum.all,
        online: row.onlineStatus == '1',
        status: row.statusTag.text.isNotEmpty
            ? row.statusTag.text
            : (row.onlineStatus == '1' ? '正常' : '离线'),
        color: row.statusTag.color,
        lastUpdate: row.subtitle.text,
        deviceTypeIcon: row.deviceTypeIcon,
        subTitle: row.subtitle.toSubTitle(),
      );
    }).toList();
  }

  /// 切换筛选类型
  void selectType(DeviceTypeEnum type) {
    if (state.selectedType == type) return;
    emit(state.copyWith(selectedType: type));
    _pagingController?.refresh();
  }
}
