import 'package:cpt_community/modules/my_posts/my_posts_vm.dart';
import 'package:cs_resources/generated/assets.dart';
import 'package:domain/entity/myposts_sale_rent_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 '../../../respository/common_garage.dart';
import '../../../router/page/community_page_router.dart';
import 'my_posts_forrent_respository.dart';
import 'my_posts_forrent_state.dart';

part 'my_posts_forrent_vm.g.dart';

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

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

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

  setCurrentPageContext(BuildContext context){
    _currentPageContext = context;
  }

  @override
  MyPostsForRentState 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 {
    Log.d("----forrent_vm-----onRefresh ");
    _page = 1;
    getListData();
  }

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


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

    // await Future.delayed(const Duration(milliseconds: 1500));
    // final List<Map<String, dynamic>> listData = [
    //   {
    //     'id':1,
    //     'goods_img':  'https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500',
    //     'title': 'Electronic keyboard',
    //     'price': '\$66',
    //     'isCollection': true,
    //     'collection_num': 12,
    //     'publisher': 'William Jefferson',
    //     'publish_time': 'June 17,2016 at 7:23 p.m.',
    //     'publisher_avator': 'https://img1.baidu.com/it/u=3890726495,1572750319&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500'
    //   },
    //   {
    //     'id':2,
    //     'goods_img':  'https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500',
    //     'title': 'Electronic keyboard',
    //     'price': '\$88',
    //     'isCollection': false,
    //     'collection_num': 12,
    //     'publisher': 'William Jefferson',
    //     'publish_time': 'June 17,2016 at 7:23 p.m.',
    //     'publisher_avator': 'https://img1.baidu.com/it/u=3890726495,1572750319&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500'
    //   },
    //   {
    //     'id':3,
    //     'goods_img':  'https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500',
    //     'title': 'Electronic keyboard',
    //     'price': '\$66',
    //     'isCollection': true,
    //     'collection_num': 12,
    //     'publisher': 'William Jefferson',
    //     'publish_time': 'June 17,2016 at 7:23 p.m.',
    //     'publisher_avator': 'https://img1.baidu.com/it/u=3890726495,1572750319&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500'
    //   },
    // ];
    //
    // if (_page == 1) {
    //   //刷新的方式
    //   state = state.copyWith(list: listData);
    //   refreshController.finishRefresh();
    //   // //更新展示的状态
    //   changeLoadingState(LoadState.State_Success, null);
    // } else {
    //   //加载更多
    //   final allList = state.list;
    //   allList.addAll(listData);
    //   state = state.copyWith(list: allList,);
    //   refreshController.finishLoad();
    // }

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

    // 需要更新 my_posts_tabs 里面的数字
    updateMyFollowingTabsNum('forRent', state.list.length, 2);

  }

  void handlerResultList(List<MypostsSaleRentList>? 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();
      }
    } 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);
      }
    }
  }


  // 更新 my_posts_tabs 里面的数字
  updateMyFollowingTabsNum(String key, int num, int activeTabIdx){
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 需要更新 my_posts_tabs 里面的数字
      ref.read(myPostsVmProvider.notifier)
          .updateMyPostsTabsNum(key, num, activeTabIdx );
    });
  }
  // 去详情页面
  void handlerGotoDetail(id){
    Log.d("去详情页面");
    appRouter.push(GaragesaleDetailPageRoute(id: id, type: 'mineForSale'));
  }
}