
import 'package:cpt_community/components/comments_dialog.dart';
import 'package:cpt_community/modules/community/following/following_vm.dart';
import 'package:cpt_community/modules/community/news/news_vm.dart';
import 'package:cpt_community/respository/common_garage.dart';
import 'package:cpt_community/respository/common_newsfeed.dart';
import 'package:cpt_community/router/page/community_page_router.dart';
import 'package:cs_resources/generated/assets.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:plugin_basic/constants/app_constant.dart';
import 'package:plugin_platform/engine/dialog/dialog_engine.dart';
import 'package:plugin_platform/engine/sp/sp_util.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:auto_route/auto_route.dart';
import 'package:widgets/dialog/app_custom_dialog.dart';
import 'package:widgets/my_checkbox_group.dart';
import 'package:widgets/utils/dark_theme_util.dart';

import '../garage/for_rent/for_rent_vm.dart';
import '../garage/for_sale/for_sale_vm.dart';
import '../garage/garagesale_post/garagesale_post_page.dart';
import 'community_page.dart';
import 'community_pageview_idx_data.dart';
import 'community_state.dart';
import 'foryou/foryou_vm.dart';
import 'newsfeed_post/newsfeed_post_page.dart';

part 'community_vm.g.dart';

@riverpod
class CommunityVm extends _$CommunityVm {
  get topSectionsData => state.topSectionsData;
  late CommonNewsFeedRespository commonNewsFeedRespositoryInstance;
  late CommonGarageRespository commonGarageRespositoryInstance;
  late Map<int, dynamic> providerMap = {};

  bool _isSingleSelect = true;
  List<Map<String, dynamic>> _currentSelectedGarageCategory = [];

  Map<int, Map<String, dynamic>> _queryParams = {};

  // 获取当前的查询参数
  getCurrentQueryParams(String key) {
    return _queryParams[state.currentPageViewIdx]?[key];
  }

  // 根据索引获取 Provider
  ProviderBase getProvider(int index) {
    return providerMap[index]!;
  }

  CommunityVmState initState() {
    List<String> newsFeedTabsList = [
      S.current.newsfeed_news,
      S.current.newsfeed_following,
      S.current.for_you,
    ];
    List<String> garageSaleTabsList = [
      S.current.for_sale,
      S.current.for_rent,
    ];

    List<String> COMMUNITY_TABS_LIST = [...newsFeedTabsList];
    COMMUNITY_TABS_LIST.addAll(garageSaleTabsList);


    // s.add(garageSaleTabsList);
    Log.d("COMMUNITY_TABS_LIST   $COMMUNITY_TABS_LIST");
    // Log.d("s   $newsFeedTabsList");
    COMMUNITY_TABS_LIST.asMap().forEach((index, value) {
      _queryParams[index] = {
        'keyword': "",
        'liked': "",
        'category_id': "",
        'category_name': "",
        'page_view_idx': index,
        'page_view_name': value,
      };
    });

    return CommunityVmState(
      currentCategoryIdx: 0,
      currentPageViewIdx: 0,
      lastGarageTabIdx: 0,
      lastNewsfeedTabIdx: 0,
      newsFeedTabsList: newsFeedTabsList,
      garageSaleTabsList: garageSaleTabsList,
    );
  }

  @override
  CommunityVmState build(){

    // 引入数据仓库
    commonNewsFeedRespositoryInstance = ref.read(commonNewsFeedRespositoryProvider);
    commonGarageRespositoryInstance = ref.read(commonGarageRespositoryProvider);
    final state = initState();

    setCurrentPageViewIconStatus();
    getPageViewVm();

    Log.d("-------------community vm-------------build---------------------");
    ref.onDispose((){
      providerMap = {};
      Log.d("-------------community vm-------------dispose---------------------");
    });
    return state;
  }

  // 搜集pageView 对应的vm
  void getPageViewVm(){
    // 每次切换后需要重新获取 一组 pageView的 vm
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      // 存入 一组 pageView的 vm
      CommunityPageViewIdxData.values.forEach((key, value) {
        switch(key){
          case 0:
            providerMap[key] = ref.read(newsVmProvider.notifier);
            break;
          case 1:
            providerMap[key] = ref.read(followingVmProvider.notifier);
            break;
          case 2:
            providerMap[key] = ref.read(foryouVmProvider.notifier);
            break;
          case 3:
            providerMap[key] = ref.read(forsaleVmProvider.notifier);
            break;
          case 4:
            providerMap[key] = ref.read(forrentVmProvider.notifier);
        }
      });
    });
  }

  // 设置当前导航栏的 图标 等状态
  void setCurrentPageViewIconStatus(){
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      Log.d("获取当前的导航栏 相关状态resMap444 ${providerMap[state.currentPageViewIdx]} ");
      Map<String, dynamic> resMap = providerMap[state.currentPageViewIdx]?.getCurrentQueryParams(null)??{};
      Log.d("获取当前的导航栏 相关状态resMap $resMap ");
      _queryParams[state.currentPageViewIdx] = resMap;
    });
  }

  tabsRouterChange(){
    // 设置当前导航栏的 图标 等状态
    Log.d("----tabsRouterChange---${tabsRouterKey.currentState?.controller?.activeIndex}-");
    state = state.copyWith(currentPageViewIdx: tabsRouterKey.currentState?.controller?.activeIndex ?? 0);

    setCurrentPageViewIconStatus();
    getPageViewVm();
  }

  // 点击tab 切换tab
  handlerChangeTab(int tabIndex, TabsRouter? tabsRouter, int? categoryIdx) {
    tabsRouter = (tabsRouter?? tabsRouterKey.currentState?.controller)!;
    categoryIdx = categoryIdx ?? state.currentCategoryIdx;
    if(categoryIdx == 0){
      tabsRouter.setActiveIndex(tabIndex);
    }else {
      tabsRouter.setActiveIndex(state.newsFeedTabsList!.length + tabIndex);
    }

  }

  // 获取当前pageView 的vm
  getCurrentPageViewVm(int? pageViewIdx){
    if(pageViewIdx !=null){
      return providerMap[pageViewIdx];
    }else {
      return getCurrentPageViewVm(state.currentPageViewIdx);
    }
  }

  // 切换news feed和garage sale
  handlerSwitchNewsfeedOrGaragesale( int categoryIdx, BuildContext? context, TabsRouter? tabsRouter){
    tabsRouter = (tabsRouter?? tabsRouterKey.currentState?.controller)!;
    categoryIdx = categoryIdx;
    if(categoryIdx == 0){
      tabsRouter.setActiveIndex(state.lastNewsfeedTabIdx);
    }else if (categoryIdx == 1){
      tabsRouter.setActiveIndex(state.newsFeedTabsList!.length + state.lastGarageTabIdx);
    }
  }

  // 设置当前的cat类型
  setCurrentCategoryIdx(BuildContext? context, int categoryIdx, int? lastNewsfeedTabIdx, int? lastGarageTabIdx){
    state = state.copyWith(
        currentCategoryIdx: categoryIdx,
        lastNewsfeedTabIdx: lastNewsfeedTabIdx?? state.lastNewsfeedTabIdx,
        lastGarageTabIdx: lastGarageTabIdx?? state.lastGarageTabIdx
    );
  }

  // 返回当前 pageView 页面的 vm

  // 判断当前pageview 页面正处于显示状态
  Future isCurrentPageViewShowing(int pageViewIdx) async{
    // 延迟获取结果
    bool isShowing = await Future.delayed(const Duration(milliseconds: 500), (){
      return state.currentPageViewIdx == pageViewIdx;
    });
    return isShowing;
  }

  // 获取garage sale 分类选项
  Future<List<Map<String, dynamic>>> getGarageSaleCategoryOptions() async{
    List<Map<String, dynamic>> garageCategoryList = [
    ];
    // 获取分类列表
    try {
      // 加入有缓存 就取缓存
      List<Map<String, dynamic>>? StorageCategoryList = SPUtil.getObjectList(
          AppConstant.storageGarageCategoryList)?.cast<Map<String, dynamic>>();

      if (StorageCategoryList != null && StorageCategoryList.isNotEmpty) {
        Log.d("取StorageCategoryList 缓存: $StorageCategoryList ");
        garageCategoryList = StorageCategoryList;
      } else {
        Map<String, dynamic> params = {};
        final result = await commonGarageRespositoryInstance
            .fetchGarageCateGoryList(params);
        if (result.isSuccess) {
          final listJson = result.getListJson();
          // 将 listJson 转换为 List<Map<String, dynamic>>
          garageCategoryList = (listJson as List?)
              ?.map((item) => item as Map<String, dynamic>)
              .toList() ?? [];
          // 将 garageCategoryList 存入缓存
          Log.d("设置StorageCategoryList 缓存");
          SPUtil.putObjectList(
              AppConstant.storageGarageCategoryList, garageCategoryList);
        }
      }
    } catch(error){

    }
    return garageCategoryList;
  }
  // 选择 garage sale 导航栏点击 选择分类
  handlerChooseGarageCategory(BuildContext context) async {
      List<Map<String, dynamic>> garageCategoryList = await getGarageSaleCategoryOptions();
      // 显示弹框
      handlerShowChooseGarageCategoryDialog(context, garageCategoryList);

      state = state.copyWith(
          garageCategoryList: garageCategoryList
      );
  }

  Future<void> handlerShowChooseGarageCategoryDialog(BuildContext context, List<Map<String, dynamic>> garageCategoryList) async{
    await DialogEngine.show(
        tag: "chooseGarageSaleCategory",
        position: DialogPosition.center,
        widget: AppCustomDialog(
          message: '',
          title: S.current.choose_category,
          dialogWidth: MediaQuery.of(context).size.width * 0.8,
          // contentBoxMaxHeight: 350,
          // contentBoxMinHeight: 300,
          isShowConfirmBtn: garageCategoryList!.length > 0 ? true: false,
          confirmTxt: S.current.confirm,
          messageBuilder: (BuildContext context){
            return Container(
              color: DarkThemeUtil.multiColors(context, context.appColors.textWhite, darkColor: Colors.transparent),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: garageCategoryList!.length > 0 ? [
                  MyCheckboxGroup(
                      isSingleSelect: _isSingleSelect,
                      labelStyle: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                      items: garageCategoryList!,
                      defaultSelectedItems: [],
                      onChanged: (List<Map<String, dynamic>> selectedItems){
                        Log.d("----MyCheckboxGroup onChanged  $selectedItems");
                        _currentSelectedGarageCategory = selectedItems;
                      }
                  )
                ]: [
                  Container(
                    child: CircularProgressIndicator(
                      strokeWidth: 3,
                      valueColor: AlwaysStoppedAnimation(context.appColors.textDarkGray),
                    ),
                  )
                ],
              ),
            );
          },
          isShowCancelBtn:false,
          confirmAction: (){
            // 点击了确定
            Log.d("----点击了确定按钮");
            int? categoryId;
            if(_isSingleSelect){
              if(_currentSelectedGarageCategory.length > 0){
                categoryId = _currentSelectedGarageCategory[0]['id'];
                _queryParams?[state.currentPageViewIdx]?['categoryId'] = categoryId??"";
              }else {
                // 没有选
                _queryParams?[state.currentPageViewIdx]?['categoryId'] = "";
              }
            }

            providerMap[state.currentPageViewIdx]
              ..setCurrentQueryParams({
                "category_id": _queryParams?[state.currentPageViewIdx]?['categoryId'],
              })
              ..directRefresh();
          },
        )
    );
  }

  // 搜索
  handlerSearch(String value){
    Log.d("community_vm 中 搜索 value: $value");
    _queryParams?[state.currentPageViewIdx]?['keyword'] = value;
    providerMap[state.currentPageViewIdx]
      ..setCurrentQueryParams({
        "keyword": _queryParams?[state.currentPageViewIdx]?['keyword'],
      })
      ..directRefresh();
  }

  // 点击了导航栏的 like btn
  handlerClickNavbarLikeBtn(BuildContext? context, int? liked){
    if(state.currentCategoryIdx ==0){
      //
      // ToastEngine.show("点击了 newsfeed like");

    }else if(state.currentCategoryIdx == 1){
      //
      // ToastEngine.show("点击了 garagesale like");

    }

    _queryParams[state.currentPageViewIdx]?['liked'] = liked;

    Log.d("9999  ${_queryParams[state.currentPageViewIdx]?['liked']}");
    // 控制外层滚动和内层滚动
    handlerNestedScrollViewScroll();

    providerMap[state.currentPageViewIdx]
      ..setCurrentQueryParams({
        "liked": _queryParams?[state.currentPageViewIdx]?['liked'],
      })
      ..directRefresh();

    // providerMap[state.currentPageViewIdx].directRefresh();
  }

  handlerNestedScrollViewScroll({double? outerOffset, double? innerOffset=0.0, bool? isOuterScrollAnimated=false, bool? isInnerScrollAnimated=false}){

    if(outerOffset !=null){
      if(isOuterScrollAnimated!){
        extendedNestedScrollViewKey.currentState?.outerController.animateTo(
          outerOffset,
          duration: const Duration(seconds: 1),
          curve: Curves.easeIn,
        );
      }else {
        extendedNestedScrollViewKey.currentState?.outerController.jumpTo(
          outerOffset,
        );
      }
    }

    if(innerOffset !=null){
      extendedNestedScrollViewKey.currentState?.innerPositions.forEach((position) {
        if(isInnerScrollAnimated!){
          position.animateTo(innerOffset,
              duration: Duration(seconds: 1), curve: Curves.easeIn);
        }else {
          position.jumpTo(innerOffset);
        }
      });
    }
  }

  // 点击了导航栏的 filter btn
  handlerClickNavbarFilterBtn(BuildContext? context,){
    handlerChooseGarageCategory(context!);
  }

  // 点击发布的按钮 跳转到 newsfeed 发布的页面
  void handlerGotoNewsfeedPost(BuildContext? context){
    // AutoRouter.of(context).pushNamed(RouterPath.newsFeedPost);
    NewsfeedPostPage.startInstance();
    // MyPostsPage.startInstance();
    // MyFollowingPage.startInstance();
  }

  // 点击发布的按钮 跳转到garagesale 发布的页面
  void handlerGotoGaragePost(BuildContext? context){
    int  type = 1;
    CommunityPageViewIdxData.values.forEach((key, value){
        if(value == "forSale" ){
          if(state.currentPageViewIdx == key){
            type = 1;
          }
        }else if(value == "forRent"){
          if(state.currentPageViewIdx == key){
            type = 2;
          }
        }
    });

    GaragesalePostPage.startInstance(type: type);
  }

  // 点击了 卡片上的 关注按钮
  Future<bool> commonClickCardFollowBtn(BuildContext? context,int to_user_id,bool isFollowed, int? idx) async{
    try{
      Map<String, dynamic> params = {
        "to_user_id": to_user_id
      };
      final result = await commonNewsFeedRespositoryInstance.handlerFollowOrCancel(params);
      if(result.isSuccess){
        return true;
      }else {
        return false;
      }
    }catch(error){
      return false;
    }
  }
}

