123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463 |
- 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/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 '../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 = [
- "News",
- "Following",
- "For You",
- ];
- List<String> garageSaleTabsList = [
- "For Sale",
- "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': null,
- 'is_liked': null,
- 'category_id': null,
- 'category_name': null,
- '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 = [
- // {
- // 'id': '1',
- // 'name': 'Kids',
- // },
- // {
- // 'id': '2',
- // 'name': 'Homeware',
- // },
- // {
- // 'id': '3',
- // 'name': 'Fashion',
- // },
- // {
- // 'id': '4',
- // 'name': 'Electronics',
- // },
- // {
- // 'id': '5',
- // 'name': 'Sports',
- // },
- // {
- // 'id': '6',
- // 'name': 'Furniture',
- // },
- // {
- // 'id': '7',
- // 'name': 'Others',
- // },
- ];
- // 获取分类列表
- 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: 'Choose a Category',
- dialogWidth: MediaQuery.of(context).size.width * 0.8,
- // contentBoxMaxHeight: 350,
- // contentBoxMinHeight: 300,
- isShowConfirmBtn: garageCategoryList!.length > 0 ? true: false,
- confirmTxt: "Ok",
- messageBuilder: (BuildContext context){
- return Container(
- color: context.appColors.textWhite,
- 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'];
- }
- }
- 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){
- if(state.currentCategoryIdx ==0){
- //
- // ToastEngine.show("点击了 newsfeed like");
- }else if(state.currentCategoryIdx == 1){
- //
- // ToastEngine.show("点击了 garagesale like");
- }
- _queryParams[state.currentPageViewIdx]?['is_liked'] = !(_queryParams?[state.currentPageViewIdx]?['is_liked']??false);
- // 控制外层滚动和内层滚动
- handlerNestedScrollViewScroll();
- providerMap[state.currentPageViewIdx]
- ..setCurrentQueryParams({
- "is_liked": _queryParams?[state.currentPageViewIdx]?['is_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;
- }
- }
- }
|