import 'package:domain/entity/user_me_entity.dart';
import 'package:domain/repository/profile_repository.dart';
import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';

import 'my_household_state.dart';

part 'my_household_view_model.g.dart';

@riverpod
class MyHouseholdViewModel extends _$MyHouseholdViewModel with DioCancelableMixin {
  late final ProfileRepository _profileRepository;

  @override
  MyHouseholdState build() {
    _profileRepository = ref.read(profileRepositoryProvider);
    final state = MyHouseholdState(datas: []);
    registerCancellation();
    return state;
  }

  var _needShowPlaceholder = true; //是否展示LoadingView

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

  //刷新页面状态
  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);
    }

    // 获取 Applied 列表
    var result = await _profileRepository.fetchUserInfo(
      cancelToken: cancelToken,
    );

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

    // 最后赋值
    _needShowPlaceholder = false;
  }

  // 处理数据与展示的逻辑
  void handleList(List<UserMeHouseholds>? 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();
  }
}
