import 'package:flutter/material.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/picker/option_pick_util.dart';
import './rewards_code_state.dart';
import './rewards_code_repository.dart';
part 'rewards_code_vm.g.dart';

@riverpod
class RewardsCodeVm extends _$RewardsCodeVm {
  late RewardsCodeRepository rewardsCodeRepository;
  RewardsCodeState initState() {
    return RewardsCodeState(
      curPage: 1,
      pageSize: 10,
      list: [
        {
          "id": 1,
          "title":
              "The community will hold the activity of making Zongzi on the Loong Boat ……",
          "price": "Monday 14 0ct 2024, 15:00 PM~18:00PM",
        },
        {
          "id": 2,
          "title": "Community basketball competition activities",
          "price": "Monday 14 Oct 2024, 10:19 AM",
        },
      ],
      filterCount: 2,
    );
  }

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

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

  // 上拉加载
  Future onLoadData() async {
    Log.d("----property_news_vm-----initListData");
    // await Future.delayed(const Duration(seconds: 2));
    // if(state.list.length >= state.filterCount){
    //   return;
    // }else {
    //   int curPage = state.curPage + 1;
    //   state = state.copyWith(curPage: curPage,);
    //   getListData();
    // }
    getListData();
  }

// 去新闻详情页
  void goNewsDetail(String item) {
    Log.d(item);
    // PropertyPage.startInstance(context: context, item: item);
  }

  // 获取list 列表数据
  void getListData<T>() async {
    Log.d("加载listData数据---------------start-----");
    try {
      //请求网络
      Map<String, dynamic> params = {
        "curPage": state.curPage,
        "pageSize": state.pageSize,
      };
      Log.d("请求参数------$params");
      final result = await rewardsCodeRepository.fetchPropertyNewsList(params);
      Log.d("请求完成结果------${result.data}");
      //校验成功失败
      if (result.isSuccess) {
        // state = state.copyWith(serverTime: result.data);
        state = state;
        ToastEngine.show("获取数据成功");
      } else {
        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();
  }


}
