import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'inspection_history_state.dart';
import '../../../../services/inspection_history_service.dart';

class InspectionHistoryCubit extends Cubit<InspectionHistoryState> {
  static const int pageSize = 10;

  final InspectionHistoryService _service;
  final int _deviceIdInt;

  InspectionHistoryCubit({
    required String deviceId,
    required InspectionHistoryService service,
  })  : _service = service,
        _deviceIdInt = int.tryParse(deviceId) ?? 0,
        super(InspectionHistoryState(deviceId: deviceId));

  /// 供 PagingController.fetchPage 回调使用，每次加载新的一页
  Future<List<InspectionRecord>> fetchPage(int pageKey) async {
    final result = await _service.getList(
      pageSize: pageSize,
      pageNum: pageKey,
      deviceId: _deviceIdInt,
    );

    // 首页时更新统计数
    if (pageKey == 1) {
      emit(state.copyWith(
        totalCount: result.tabCount.total,
        passCount: result.tabCount.passCount,
        warningCount: result.tabCount.warnCount,
        failCount: result.tabCount.failCount,
      ));
    }

    return result.rows.map((row) {
      return InspectionRecord(
        deviceName: result.deviceInfo.deviceName,
        inspectorName: row.inspectorName,
        inspectionTime: row.inspectTime,
        result: row.inspectStatus,
        remark: row.remark,
        items: row.itemsDetail
            .map((item) => InspectionItemRecord(
                  name: item.name,
                  result: item.status,
                ))
            .toList(),
        icon: Icons.devices,
      );
    }).toList();
  }
}