import 'package:domain/entity/facility_index_entity.dart';
import 'package:domain/entity/id_name_entity.dart';
import 'package:domain/repository/facility_repository.dart';
import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';

import 'facility_book_state.dart';

part 'facility_book_view_model.g.dart';

@riverpod
class FacilityBookViewModel extends _$FacilityBookViewModel with DioCancelableMixin{
  late final FacilityRepository _facilityRepository;
  var _needShowPlaceholder = true; //是否展示LoadingView

  // Refresh 控制器
  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishRefresh: true,  //允许刷新
    controlFinishLoad: false,   //允许加载
  );

  @override
  FacilityBookState build() {
    _facilityRepository = ref.read(facilityRepositoryProvider);
   final state = FacilityBookState(datas: []);
   registerCancellation();
    return state;
  }

  //刷新页面状态
  void changeLoadingState(LoadState loadState, String? errorMsg) {
    state = state.copyWith(loadingState: loadState, errorMessage: errorMsg);
  }

  // Refresh 刷新事件
  Future onRefresh() async {
    fetchList();
  }

  // 重试请求
  Future retryRequest() async {
    _needShowPlaceholder = true;
    fetchList();
  }

  /// 获取服务器数据
  Future fetchList() async {
    if (_needShowPlaceholder) {
      changeLoadingState(LoadState.State_Loading, null);
    }

    // 获取列表
    var result = await _facilityRepository.fetchFacilityList(
      cancelToken: cancelToken,
    );

    // 处理数据
    if (result.isSuccess) {
      handleList(result.list);
    } else {
      changeLoadingState(LoadState.State_Error, result.errorMsg);
    }

    // 最后赋值
    _needShowPlaceholder = false;
  }

  // 处理数据与展示的逻辑
  void handleList(List<FacilityIndexEntity>? list) {
    if (list != null && list.isNotEmpty) {
      //有数据
      state = state.copyWith(datas: list, loadingState: LoadState.State_Success);
    } else {
      //展示无数据的布局
      state = state.copyWith(datas: [], loadingState: LoadState.State_Empty, errorMessage: null);
    }

    refreshController.finishRefresh();
  }
}
