import 'package:cpt_community/modules/community/community_vm.dart';
import 'package:cpt_community/respository/common_garage.dart';
import 'package:cs_resources/generated/assets.dart';
import 'package:domain/entity/garage_sale_rent_entity.dart';
import 'package:domain/entity/newsfeed_detail_entity.dart';
import 'package:flutter/cupertino.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';

import '../../../router/page/community_page_router.dart';
import '../../community/community_page.dart';
import '../../community/community_pageview_idx_data.dart';
import '../garagesale_detail/garagesale_detail_page.dart';
import 'for_sale_state.dart';

part 'for_sale_vm.g.dart';

@riverpod
class ForsaleVm extends _$ForsaleVm {
  late CommonGarageRespository commonGarageRespositoryInstance;
  bool _needShowPlaceholder = false; //是否展示LoadingView
  int _page = 1;  // 当前页
  int _limit = 10; // 每页数量
  int _count = 0; // 总条数

  Map<String, dynamic> _queryParams = {
    'category_id': '',
    'keyword': '',
    'liked': '',
  };

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

  ForsaleState initState() {
    return ForsaleState(
      list: []
    );
  }

  @override
  ForsaleState build(){
    // 引入数据仓库
    commonGarageRespositoryInstance = ref.read(commonGarageRespositoryProvider);
    final state = initState();
    Log.d("--------------------------build---------------------");

    return state;
  }


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

  // 初始化页面数据
  initPageData() {
    Log.d("----for_sale_vm-----initPageData   ${state.loadingState}");
    onRefresh();
  }

  // 上拉加载 更多
  Future loadMore() async {
      Log.d("----for_sale_vm-----loadMore");
      _page++;
      getListData();
  }


  // 下拉刷新
  Future onRefresh() async {
      // 当前pageView 页面正处于显示状态
      Log.d("----forsale_vm-----onRefresh ");
      // await Future.delayed(const Duration(seconds: 2));
      _page = 1;
      getListData();
  }


  // 手动进行刷新
  Future triggerRefresh() async {
    Log.d("trggerRefresh");
    refreshController.callRefresh();
  }

  // 手动进行刷新
  Future directRefresh() async {
    state = state.copyWith(list:[]);
    // 注意：由于 nestedscrollview 嵌套easyfresh 组件  refreshController.callRefresh() 自动刷新只能滚动顶部但是不会触发下拉刷新，这里调用是 用到了将其滚动到顶部的作用，进而刷新操作主动掉接口
    // https://github.com/xuelongqy/flutter_easy_refresh/issues/692
    refreshController.callRefresh();
    refreshController.resetFooter();
    _page = 1;
    _needShowPlaceholder = true;
    getListData();
  }


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


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

    try {
      //请求网络
      Map<String, dynamic>  params = {
        "type": 1,  // 类型(1=Sale,2=Rent)
        "category_id": _queryParams['category_id'],
        "keyword": _queryParams['keyword'],
        "liked": _queryParams['liked']?? "",
        "page": _page,
        "limit": _limit,
      };
      Log.d("请求参数------$params");
      final result = await commonGarageRespositoryInstance.fetchGarageDataList(params);
      //校验成功失败
      if (result.isSuccess) {
        handlerResultList((result.data as GarageSaleRentEntity).list as List<GarageSaleRentList>, isLoadMore ?? false);
      } else {
        String errorMessage = result.errorMsg!;
        changeLoadingState(LoadState.State_Error, errorMessage);
        ToastEngine.show(result.errorMsg ?? "Network Load Error");
      }
    } catch (e) {
      ToastEngine.show("Error: $e");
    }

    // 最后赋值
    _needShowPlaceholder = false;

  }


  void handlerResultList(List<GarageSaleRentList>? list, bool isLoadMore) {
    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;
        allList!.addAll(list.map((item) => item.toJson()).toList());
        state = state.copyWith(list: allList);
        refreshController.finishLoad();
      }
    } else {
      if (_page == 1) {
        //展示无数据的布局
        state.list!.clear();
        changeLoadingState(LoadState.State_Empty, null);
        refreshController.finishRefresh();
      } 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);
            refreshController.finishLoad();
          }else {
            if(_needShowPlaceholder){
              changeLoadingState(LoadState.State_Success, null);
            }
          }
          //更新展示的状态
          refreshController.finishLoad(IndicatorResult.noMore);
        }
      }
    }
  }


  // 点击 收藏/取消收藏
  Future<bool?> handlerClickCollection(int id, bool? isCollection) async{
    try {
      //请求网络
      Map<String, dynamic>  params = {
        "id": id,
      };
      Log.d("请求参数------$params");
      final result = await commonGarageRespositoryInstance.fetchGarageColleciton(params);
      //校验成功失败
      if (result.isSuccess) {
        // 修改 该id 的 liked 和 likes_count 字段
        state.list!.forEach((Map<String, dynamic> element) {
          GarageSaleRentList elementEntity = GarageSaleRentList.fromJson(element);

          if(elementEntity.id == id){
            elementEntity.liked = !elementEntity.liked!;
            elementEntity.likesCount = elementEntity.liked! ? (elementEntity.likesCount! + 1) : (elementEntity.likesCount! - 1);
          }

          element = elementEntity.toJson();

        });
        return true;
      } else {
        String errorMessage = result.errorMsg!;
        changeLoadingState(LoadState.State_Error, errorMessage);
        ToastEngine.show(result.errorMsg ?? "Network Load Error");
      }
    } catch (e) {
      Log.e("Error: $e");
      ToastEngine.show("Error: $e");
    }
  }

  // 设置当前的 _queryParams
  setCurrentQueryParams(Map<String, dynamic> params){
    _queryParams.addAll(params);
  }

  // 获取当前的 _queryParams
  Map<String, dynamic> getCurrentQueryParams(String? key){
    if(key!=null && key!.isNotEmpty){
      return _queryParams[key];
    }
    return _queryParams;
  }

  // 去详情页面
  void handlerGotoDetail({BuildContext? context, required int id, String type='forSale'}){
    Log.d("去详情页面");
    appRouter.push(GaragesaleDetailPageRoute(id: id, type: 'forSale'));
  }
}