import 'package:domain/entity/rewards_index_entity.dart';
import 'package:flutter/material.dart';
import 'package:plugin_platform/http/http_result.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:router/componentRouter/component_service_manager.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/picker/option_pick_util.dart';
import 'package:widgets/widget_export.dart';
import './rewards_state.dart';
import './rewards_repository.dart';
part 'rewards_vm.g.dart';

@riverpod
class RewardsVm extends _$RewardsVm {
  late RewardsRepository rewardsRepository;
  bool _needShowPlaceholder = false; //是否展示LoadingView

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

  RewardsState initState() {
    return RewardsState(
      list: RewardsIndexEntity()
    );
  }

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

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

  // 上拉加载
  // Future onLoadData() async {
  //   Log.d("----property_news_vm-----initListData");
  //   getListData();
  // }

// 去新闻详情页
  void goNewsDetail(String item) {
    Log.d(item);
    // PropertyPage.startInstance(context: context, item: item);
  }
//去社区页面
  void gotoCommunityPage() {
    ComponentServiceManager().communityService.startCommunityPage();
  }
// 重试请求
  Future retryRequest() async {
    _needShowPlaceholder = true;
    getListData();
  }

  // 获取list 列表数据
  void getListData<T>() async {
    Log.d("加载listData数据---------------start-----");
    try {
      //请求网络
      Map<String, dynamic> params = {};
      Log.d("请求参数------$params");
      final result = await rewardsRepository.fetchPropertyNewsList(params);
      Log.d("请求完成结果------${result.data}");
      //校验成功失败
      if (result.isSuccess) {
        state = state.copyWith(list: result.data, loadingState: LoadState.State_Success);
      } else {
        String errorMessage = result.errorMsg!;
        state = state.copyWith(list: null, loadingState: LoadState.State_Error,errorMessage: errorMessage);
        ToastEngine.show(result.errorMsg ?? "Network Load Error");
      }
    } catch (e) {
      ToastEngine.show("Error: $e");
    }
  }
  // // 下拉刷新
  // Future refreshListData() async {
  //   Log.d("----property_news_vm-----refreshListData ");

  //   // await Future.delayed(const Duration(seconds: 2));

  //   state = state.copyWith(curPage: 1, pageSize: 10);
  //   // ref.invalidateSelf();
  //   // ref.invalidate(propertyNewsVmProvider);
  //   getListData();
  // }
}
