import 'package:cs_resources/generated/assets.dart';
import 'package:domain/entity/myposts_newsfeed_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/ext_dart.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';
import 'package:auto_route/auto_route.dart';

import '../../../respository/common_newsfeed.dart';
import '../../../router/page/community_page_router.dart';

import '../../community/newsfeed_detail/newsfeed_detail_page.dart';
import '../my_posts_vm.dart';
import 'my_posts_newsfeed_state.dart';
import '../my_posts_repository.dart';
import 'newsfeed_itemgroup_state.dart';
part 'my_posts_newsfeed_vm.g.dart';

@riverpod
class MyPostsNewsfeedVm extends _$MyPostsNewsfeedVm {
  late CommonNewsFeedRespository commonNewsFeedRespositoryInstance;

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

  int _page = 1;
  int _limit = 10;
  int _count = 0;

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

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

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

    return state;
  }

  // 设置当前的 tabsRouter 和 pageController
  handlerChangeTab(BuildContext context, int activeTabIdx) {
    final tabsRouter = AutoTabsRouter.of(context);
    tabsRouter.setActiveIndex(activeTabIdx);
  }


  //刷新页面状态
  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("----forsale_vm-----onRefresh ");

    // await Future.delayed(const Duration(seconds: 2));
    _page = 1;
    getListData();
  }

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

  // 获取list 列表数据
  Future getListData<T>({bool? isLoadMore = false}) async {
    Log.d("加载listData数据---------------start-----");

    if (_needShowPlaceholder) {
      changeLoadingState(LoadState.State_Loading, null);
    }

    Log.d("for_sale加载listData数据---------------start--${_page}---");
    //   try {
    //     //请求网络
    //     Map<String, dynamic>  params = {
    //       "page": _page,
    //       "limit": _limit,
    //     };
    //     Log.d("请求参数------$params");
    //     final result = await propertyNewsRepository.fetchPropertyNewsList(params);
    //     Log.d("请求完成结果------${result.data}");
    //     //校验成功失败
    //     if (result.isSuccess) {
    //       // state = state.copyWith(serverTime: result.data);
    //       state = state;
    //   handleList(listResult.data?.rows);
    //       ToastEngine.show("获取数据成功");
    //     } else {
    //   errorMessage = listResult.errorMsg;
    //   changeLoadingState(LoadState.State_Error);
    //       ToastEngine.show(result.errorMsg ?? "Network Load Error");
    //     }
    //   } catch (e) {
    //     ToastEngine.show("Error: $e");
    //   }

    await Future.delayed(const Duration(milliseconds: 1500));

    // final List<NewsFeedItemGroupState> listData = [];
    //
    // listData.add(
    //     NewsFeedItemGroupState(
    //     groupId: "June 17,2024",
    //     itemgroupDatas: [
    //       {
    //         'id': 1,
    //         'avator': 'https://img1.baidu.com/it/u=3890726495,1572750319&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
    //         'title': 'William Jefferson',
    //         'isFollow': false,
    //         'content': 'She said YES and our lives changed.Thank you all for coming to my propose today.We hope everyone can ……[More]',
    //         'imageUrls': ['https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500','https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500','https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500'],
    //         'time': 'June 17,2016 at 7:23 p.m.',
    //         'isLike': true,
    //         'likeno': 12
    //       },
    //       {
    //         'id': 2,
    //         'avator': 'https://img1.baidu.com/it/u=3890726495,1572750319&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
    //         'title': 'William Jefferson',
    //         'isFollow': false,
    //         'content': 'She said YES and our lives changed.Thank you all for coming to my propose today.We hope everyone can ……[More]',
    //         'imageUrls': ['https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500','https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500','https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500'],
    //         'time': 'June 17,2016 at 7:23 p.m.',
    //         'isLike': true,
    //         'likeno': 12
    //       },
    //     ]
    // ));




    // 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();
    // }

    // // 最后赋值
    // _needShowPlaceholder = false;

    try {
      //请求网络
      Map<String, dynamic>  params = {
        "page": _page,
        "limit": _limit,
      };
      Log.d("请求参数------$params");
      final result = await commonNewsFeedRespositoryInstance.fetchMyPostNewsfeedList(params);
      //校验成功失败
      if (result.isSuccess) {
        handlerResultList((result.data  as MypostsNewsfeedEntity).list as List<MypostsNewsfeedList>, 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");
    }

    updateMyPostsTabsNum('newsFeed', state.list!.length, 0);
  }


  void handlerResultList(List<MypostsNewsfeedList>? list, bool isLoadMore) {
    if (list != null && list.isNotEmpty) {
      //有数据，判断是刷新还是加载更多的数据
      if (_page == 1) {
        //刷新的方式
        state.list!.clear();

        state.list!.addAll(groupList(list));
        refreshController.finishRefresh();
        //更新展示的状态
        changeLoadingState(LoadState.State_Success, null);
      } else {
        //加载更多
        final allList = state.list;
        allList!.addAll(groupList(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);
      }
    }
  }

  // 根据created_at 将 list 进行分组
  List<NewsFeedItemGroupState> groupList(List<MypostsNewsfeedList> list) {
    if (list == null || list.isEmpty) {
      return [];
    }

    Map<String, List<MypostsNewsfeedList>> groupedMap = {};

    for (var item in list) {
      groupedMap.putIfAbsent(item.createdAt!, () => []).add(item);
    }

    return groupedMap.entries.map((entry) {
      return NewsFeedItemGroupState(
        groupId: entry.key,
        itemgroupDatas: entry.value,
      );
    }).toList();
  }



  // 更新 my_posts_tabs 里面的数字
  updateMyPostsTabsNum(String key, int num, int activeTabIdx){
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 需要更新 my_posts_tabs 里面的数字
      ref.read(myPostsVmProvider.notifier)
          .updateMyPostsTabsNum(key, num, activeTabIdx );
    });
  }

  // 点赞/取消点赞
  Future handlerLikeClick(int id, bool isLike, int? groupIndex, int? childIndex) async {
    Log.d("99999   id:$id   isLike:$isLike groupIndex:$groupIndex  childIndex:$childIndex");
    try {
      final result = await commonNewsFeedRespositoryInstance.fetchLikeClick({
        "id": id,
      });
      List<NewsFeedItemGroupState> listCopyDta =  List.from(state.list!);
      if (result.isSuccess) {
        if(groupIndex != null){
          MypostsNewsfeedList currentGroupItem = listCopyDta[groupIndex!].itemgroupDatas[childIndex!];
          Map<String, dynamic> currentGroupItemJson = currentGroupItem.toJson();
          Log.d("77777  $currentGroupItemJson");
          // 修改 listCopyDta[itemIdx] 中的 like 状态 和 likes_count
          currentGroupItemJson['liked'] = !isLike;

          if(isLike){
            // 取消点赞
            if(currentGroupItemJson['likes_count']>0){
              currentGroupItemJson['likes_count'] = currentGroupItemJson['likes_count'] - 1;
            }
          }else {
            currentGroupItemJson['likes_count'] = currentGroupItemJson['likes_count'] + 1;
          }


          listCopyDta[groupIndex!].itemgroupDatas[childIndex] = MypostsNewsfeedList.fromJson(currentGroupItemJson);
        }else {
          Log.d("88888");
          // 详情中的点赞 需要找到对应的 item 进行 修改 like 和 likes_count
          listCopyDta!.forEach((groupitem) {
            List<MypostsNewsfeedList> groupItemGroupDatas = groupitem.itemgroupDatas;
            if(groupItemGroupDatas!=null && groupItemGroupDatas.isNotEmpty){
              for (var value in groupItemGroupDatas) {

                if(value.id == id){
                  value.liked = !isLike;
                  if(isLike){
                    // 取消点赞
                    if(value.likesCount!>0){
                      value.likesCount =value.likesCount! - 1;
                    }
                  }else {
                    value.likesCount = value.likesCount! + 1;
                  }
                }
              }
            }

          });
        }

        state = state.copyWith(list: listCopyDta);

        final String toastMsg = isLike ? "Cancel successfully": "Liked successfully";
        ToastEngine.show(toastMsg);

        return true;
      }else {
        return false;
      }
    }catch(error) {
      Log.d("my_posts_newsfeed_vm handlerLikeClick 发生错误: $error");
      return false;
    }
  }


  // 点击 like comments  share
  Future<bool?> handlerClickActionBtn(String? actionStr, Map<String, dynamic> item, int? groupIndex, int? childIndex) async{
    final id = item['id'];
    final liked = item.getValue('liked', false);
    switch (actionStr) {
      case 'like':
        return await handlerLikeClick(id, liked, groupIndex, childIndex!);
      case 'comments':
        Log.d("点击了 评论");
        handlerGotoDetail(null, id);
        break;
      case 'share':
        Log.d("点击了 分享");
        handlerGotoDetail(null, id);
        break;
      default:
        Log.d("点击了卡片");
        handlerGotoDetail(null, id);
        break;
    }
  }


  // 关注/取消关注
  Future<bool> handlerFollow(BuildContext? context, int to_user_id, int cardId, bool isFollow) async{
    Log.d("点击了 关注");
    try {
      final result = await commonNewsFeedRespositoryInstance.handlerFollowOrCancel({
        "to_user_id": to_user_id,
      });
      if(result.isSuccess){
        return true;
      }else {
        return false;
      }
    }catch(error){
      Log.d("error: $error");
      return false;
    }
  }

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