import 'package:cpt_rewards/modules/rewards_list/dialog/reward_listfilter_all_dialog.dart';
import 'package:domain/entity/rewards_category_entity.dart';
import 'package:domain/entity/rewards_history_earned_entity.dart';
import 'package:domain/entity/rewards_list_entity.dart';
import 'package:flutter/material.dart';
import 'package:cpt_rewards/modules/rewards_list/dialog/reward_listfilter_dialog.dart';
import 'package:plugin_platform/engine/dialog/dialog_engine.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_list_state.dart';
import './rewards_list_repository.dart';
part 'rewards_list_vm.g.dart';

@riverpod
class RewardsListVm extends _$RewardsListVm {
  late RewardsListRepository rewardsListRepository;
  var page = 1;
  var limit = 10;

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

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

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

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

  // 初始化页面数据&0
  initPageData() async {
    Log.d("----property_news_vm-----initPageData");
    await getCategoryData();
    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();
  }

  // 获取Category数据
  Future getCategoryData<T>() async {
    // if (_needShowPlaceholder) {
    //   changeLoadingState(LoadState.State_Loading, null);
    // }

    Log.d("加载listData数据---------------start--${page}---");
    try {
      //请求网络
      Map<String, dynamic> params = {};
      Log.d("请求参数------$params");
      final result = await rewardsListRepository.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}");
    }
  }

  // 获取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,
        "category_id": state.category_id == 0 ? '' : state.category_id,
        "point_min": state.point_min,
        "point_max": state.point_max == 0 ? 100000 : state.point_max,
        "sort_by": state.sort_by,
        "sort": state.sort,
      };
      Log.d("请求参数------$params");
      final result = await rewardsListRepository.fetchList(params);
      //校验成功失败
      if (result.isSuccess) {
        handlerResultList((result.data as RewardsListEntity).list);
      } 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<RewardsListList>? 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);
      }
    }
  }

  void applyClick() {
    onRefresh();
  }

  void categoryClick(item) {
    state =
        state.copyWith(category_id: item['id'], category_name: item['name']);
    _needShowPlaceholder = true;
    onRefresh();
    Log.d("category_id------${state.category_id}");
    Log.d("category_name------${state.category_name}");
  }

  void sortByClick(star) {
    state = state.copyWith(sort_by: star);
    Log.d("sort_by------${state.sort_by}");
  }

  void sortClick(star) {
    state = state.copyWith(sort: star);
    Log.d("sort------${state.sort}");
  }

  void rangeSliderChanged(value) {
    Log.d("category_id------$value");
    state = state.copyWith(
        point_min: value.start.toInt(), point_max: value.end.toInt());
    Log.d("category_id------${state.point_min}");
    Log.d("category_name------${state.point_max}");
  }

  void doDeleteAccount(context) {
    SmartDialog.dismiss();
    DialogEngine.show(
      maskColor: Colors.transparent,
      animType: DialogAnimation.centerScale_otherSlide,
      position: DialogPosition.top,
      widget: RewardsListfilterDialo(
        confirmAction: () {
          ToastEngine.show("点击了确定");
        },
      ),
    );
  }

  void doDeleteAccountAll(context) {
    SmartDialog.dismiss();
    DialogEngine.show(
      maskColor: Colors.transparent,
      animType: DialogAnimation.centerScale_otherSlide,
      position: DialogPosition.top,
      widget: RewardsListfilterAllDialo(
        confirmAction: () {
          ToastEngine.show("点击了确定");
        },
      ),
    );
  }
}
