import 'package:domain/entity/form_list_entity.dart';
import 'package:domain/repository/form_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 'form_apply_state.dart';

part 'form_apply_view_model.g.dart';

@riverpod
class FormApplyViewModel extends _$FormApplyViewModel with DioCancelableMixin {
  late final FormRepository _formRepository;
  var _needShowPlaceholder = true; //是否展示LoadingView

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

  @override
  FormApplyState build() {
    _formRepository = ref.read(formRepositoryProvider);
    final state = FormApplyState(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);
    }

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

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

    // 最后赋值
    _needShowPlaceholder = false;
  }

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