import 'package:cs_resources/generated/assets.dart';
import 'package:cs_resources/generated/l10n.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 'package:auto_route/auto_route.dart';

import '../../../router/page/community_page_router.dart';
import 'my_posts_page.dart';
import 'my_posts_state.dart';


part 'my_posts_vm.g.dart';

@riverpod
class MyPostsVm extends _$MyPostsVm {
  // late MyPostsRepository MyPostsRepositoryInstance;

  int _currentPageIndex = 0;

  bool _needShowPlaceholder = false; //是否展示LoadingView
  // Refresh 控制器
  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishRefresh: true,  //允许刷新
    controlFinishLoad: true,   //允许加载
  );

  MyPostsState initState() {
    return MyPostsState(
        currentPageViewIdx: 0,
        tabsList: [
          {
            'code': 'newsFeed',
            'title': S.current.news_feed,
            'publish_num': 0,
          },
          {
            'code': 'forSale',
            'title': S.current.for_sale,
            'publish_num': 0,
          },
          {
            'code': 'forRent',
            'title': S.current.for_rent,
            'publish_num': 0,
          },
        ]
    );
  }

  @override
  MyPostsState build(){
    // 引入数据仓库
    // MyPostsRepositoryInstance = ref.read(newsRepositoryProvider);
    MyPostsState state = initState();
    Log.d("--------------------------build---------------------");
    return state;
  }


  tabsRouterChange(){
    Log.d("----tabsRouterChange---${myPostsPageTabsRouterKey.currentState?.controller?.activeIndex}-");
    state = state.copyWith(currentPageViewIdx: myPostsPageTabsRouterKey.currentState?.controller?.activeIndex ?? 0);
  }

  // 切换tab
  handlerChangeTab(int tabIndex, TabsRouter? tabsRouter,) {
    tabsRouter = (tabsRouter?? myPostsPageTabsRouterKey.currentState?.controller)!;
    tabsRouter.setActiveIndex(tabIndex);
  }

  setCurrentTabIndex(int activeTabIdx){
    state = state.copyWith(
      activeTabIdx: activeTabIdx,
    );
  }

  updateMyPostsTabsNum(String code, int num, int activeTabIdx){
    state = state.copyWith(
      tabsList: state.tabsList?.map((e) {
        if(e['code'] == code){
          e['publish_num'] = num;
        }
        return e;
      }).toList(),
      activeTabIdx: activeTabIdx,
    );
  }

}