import 'package:domain/entity/rewards_history_earned_entity.dart';
import 'package:domain/entity/rewards_my_entity.dart';
import 'package:plugin_platform/http/http_result.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';
import './rewards_my_active_state.dart';
import './rewards_my_active_repository.dart';
part 'rewards_my_active_vm.g.dart';

@riverpod
class RewardsMyActiveVm extends _$RewardsMyActiveVm {
  late RewardsMyActiveRepository rewardsMyActiveRepository;
  var page = 1;
  var limit = 10;

  bool _needShowPlaceholder = false; //是否展示LoadingView

  // Refresh 控制器
  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishRefresh: true, //允许刷新
    controlFinishLoad: true, //允许加载
  );
  RewardsMyActiveState initState() {
    return RewardsMyActiveState(
      list: [],
    );
  }

  @override
  RewardsMyActiveState build() {
    // 引入数据仓库
    rewardsMyActiveRepository = ref.read(rewardsMyActiveRepositoryProvider);
    // 初始化状态
    RewardsMyActiveState state = initState();
    // 初始化列表数据
    return state;
  }

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

  // 初始化页面数据&0
  initPageData() {
    Log.d("----property_news_vm-----initPageData");
    onRefresh();
  }

  // 上拉加载 更多
  Future loadMore() async {
    Log.d("----property_news_vm-----loadMore");
    // await Future.delayed(const Duration(seconds: 2));
    // if(state.list.length >= state.count){
    //   return;
    // }else {
    //   int page = page + 1;
    //   state = state.copyWith(page: page,);
    //   getListData();
    // }
    // 检查 page 是否为 null，并初始化为 1
    page++;

    getListData();
  }

  // 下拉刷新
  Future onRefresh() async {
    Log.d("----property_news_vm-----onRefresh ");

    // await Future.delayed(const Duration(seconds: 2));
    page = 1;
    getListData();
  }

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

  // 获取list 列表数据
  Future getListData<T>() async {
    // if (_needShowPlaceholder) {
    //   changeLoadingState(LoadState.State_Loading, null);
    // }

    Log.d("加载listData数据---------------start--${page}---");
    try {
      //请求网络
      Map<String, dynamic> params = {
        "page": page,
        "limit": limit,
        "list_type": 'active'
      };
      Log.d("请求参数------$params");
      final result = await rewardsMyActiveRepository.fetchList(params);
      //校验成功失败
      if (result.isSuccess) {
        handlerResultList(
            (result.data as RewardsMyEntity).list.cast<RewardsMyList>());
      } else {
        String errorMessage = result.errorMsg!;
        changeLoadingState(LoadState.State_Error, errorMessage);
        ToastEngine.show(result.errorMsg ?? "Network Load Error");
      }
    } catch (e) {
      ToastEngine.show("Error: $e");
    }
  }

  void handlerResultList(List<RewardsMyList>? list) {
    if (list != null && list.isNotEmpty) {
      //有数据，判断是刷新还是加载更多的数据
      if (page == 1) {
        //刷新的方式
        state.list!.clear();
        state.list!.addAll(list.map((item) => item.toJson()).toList());
        refreshController.finishRefresh();

        //更新展示的状态
        changeLoadingState(LoadState.State_Success, null);
      } else {
        //加载更多
        final allList = state.list;
        state = state.copyWith(list: allList);
        refreshController.finishLoad();
        // update();
      }
    } else {
      if (page == 1) {
        //展示无数据的布局
        state.list!.clear();
        changeLoadingState(LoadState.State_Empty, null);
        refreshController.finishRefresh();
      } else {
        //展示加载完成，没有更多数据了
        if (state.list!.length == 0) {
          changeLoadingState(LoadState.State_Empty, null);
        } else {
          changeLoadingState(LoadState.State_Success, null);
        }
        refreshController.finishLoad(IndicatorResult.noMore);
      }
    }
  }
}
