import 'package:cs_resources/generated/assets.dart';
import 'package:domain/entity/rewards_category_entity.dart';
import 'package:domain/entity/rewards_home_entity.dart';
import 'package:domain/entity/rewards_home_tx_entity.dart';
import 'package:domain/entity/text_kon_entity.dart';
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/load_state_layout.dart';
import 'package:widgets/picker/option_pick_util.dart';
import 'package:widgets/widget_export.dart';
import './rewards_home_state.dart';
import './rewards_home_repository.dart';
part 'rewards_home_vm.g.dart';

@riverpod
class RewardsHomeVm extends _$RewardsHomeVm {
  late RewardsHomeRepository rewardsHomeRepository;
  bool _needShowPlaceholder = false; //是否展示LoadingView

  // Refresh 控制器
  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishRefresh: true, //允许刷新
    controlFinishLoad: true, //允许加载
  );
  RewardsHomeState initState() {
    return RewardsHomeState(
      list: [],
      categoryList: [],
      lists: [
        {'title': 'YY', 'icon': Assets.rewardsRewardsIndex1},
        {'title': 'F&B', 'icon': Assets.rewardsRewardsIndex2},
        {'title': 'F&B', 'icon': Assets.rewardsRewardsIndex3},
        {'title': 'Beauty', 'icon': Assets.rewardsRewardsIndex4},
        {'title': 'Activites', 'icon': Assets.rewardsRewardsIndex5},
        {'title': 'Travel', 'icon': Assets.rewardsRewardsIndex6},
        {'title': 'Electronics', 'icon': Assets.rewardsRewardsIndex7},
        {'title': 'Gifts', 'icon': Assets.rewardsRewardsIndex8},
        {'title': 'Services', 'icon': Assets.rewardsRewardsIndex9},
      ],
    );
  }

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

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

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

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

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

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

  void changeList(List<Map<String, dynamic>> lis) {
    state = state.copyWith(list: lis);
  }

  // 获取list 列表数据
  void getListData<T>() async {
    Log.d("加载listData数据---------------start-----");
    try {
      //请求网络
      Map<String, dynamic> params = {};
      Log.d("请求参数------$params");
      final result = await rewardsHomeRepository.fetchPropertyNewsList(params);
      Log.d("请求完成结果------${result.list}");
      //校验成功失败
      if (result.isSuccess) {
        handlerResultList((result.list as List<RewardsHomeTxEntity>));
      } 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<RewardsHomeTxEntity>? list) {
    if (list != null) {
      //有数据，判断是刷新还是加载更多的数据
      //刷新的方式
      state.list.clear();
      state.list.addAll(list.map((item) => item.toJson()).toList());
      Log.d("请state.list------${state.list}");
      changeLoadingState(LoadState.State_Success, null);
    }
  }

  // 获取Category数据
  Future getCategoryData<T>() async {
    try {
      //请求网络
      Map<String, dynamic> params = {};
      Log.d("请求参数------$params");
      final result = await rewardsHomeRepository.fetchCategory(params);
      //校验成功失败
      if (result.isSuccess) {
        handlerCategory((result.list as List<RewardsCategoryEntity>));
      } else {
        ToastEngine.show(result.errorMsg ?? "Network Load Error");
      }
    } catch (e) {
      ToastEngine.show("Error: $e");
    }
  }

  void handlerCategory(List<RewardsCategoryEntity>? list) {
    if (list != null) {
      //有数据，判断是刷新还是加载更多的数据
      //刷新的方式
      state.categoryList?.clear();
      state.categoryList?.addAll(list.map((item) => item.toJson()).toList());
      Log.d("请categoryList------${state.categoryList}");
    }
  }
}
