community_vm.dart 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. import 'package:cpt_community/components/comments_dialog.dart';
  2. import 'package:cpt_community/modules/community/following/following_vm.dart';
  3. import 'package:cpt_community/modules/community/news/news_vm.dart';
  4. import 'package:cpt_community/respository/common_garage.dart';
  5. import 'package:cpt_community/respository/common_newsfeed.dart';
  6. import 'package:cpt_community/router/page/community_page_router.dart';
  7. import 'package:cs_resources/generated/assets.dart';
  8. import 'package:cs_resources/theme/app_colors_theme.dart';
  9. import 'package:flutter/cupertino.dart';
  10. import 'package:flutter/material.dart';
  11. import 'package:flutter_riverpod/flutter_riverpod.dart';
  12. import 'package:plugin_basic/constants/app_constant.dart';
  13. import 'package:plugin_platform/engine/dialog/dialog_engine.dart';
  14. import 'package:plugin_platform/engine/sp/sp_util.dart';
  15. import 'package:plugin_platform/engine/toast/toast_engine.dart';
  16. import 'package:riverpod_annotation/riverpod_annotation.dart';
  17. import 'package:router/path/router_path.dart';
  18. import 'package:shared/utils/log_utils.dart';
  19. import 'package:auto_route/auto_route.dart';
  20. import 'package:widgets/dialog/app_custom_dialog.dart';
  21. import 'package:widgets/my_checkbox_group.dart';
  22. import '../garage/for_rent/for_rent_vm.dart';
  23. import '../garage/for_sale/for_sale_vm.dart';
  24. import '../garage/garagesale_post/garagesale_post_page.dart';
  25. import '../my_following/my_following_page.dart';
  26. import '../my_posts/my_posts_page.dart';
  27. import 'community_page.dart';
  28. import 'community_pageview_idx_data.dart';
  29. import 'community_state.dart';
  30. import 'foryou/foryou_vm.dart';
  31. import 'news/news_state.dart';
  32. import 'newsfeed_post/newsfeed_post_page.dart';
  33. part 'community_vm.g.dart';
  34. @riverpod
  35. class CommunityVm extends _$CommunityVm {
  36. get topSectionsData => state.topSectionsData;
  37. late CommonNewsFeedRespository commonNewsFeedRespositoryInstance;
  38. late CommonGarageRespository commonGarageRespositoryInstance;
  39. late Map<int, dynamic> providerMap = {};
  40. bool _isSingleSelect = true;
  41. List<Map<String, dynamic>> _currentSelectedGarageCategory = [];
  42. Map<String, dynamic>? _queryParams = {
  43. 'keyword': null,
  44. 'is_liked': null,
  45. 'category_id': null
  46. };
  47. // 根据索引获取 Provider
  48. ProviderBase getProvider(int index) {
  49. return providerMap[index]!;
  50. }
  51. CommunityVmState initState() {
  52. return CommunityVmState(
  53. currentCategoryIdx: 0,
  54. currentPageViewIdx: 0,
  55. lastGarageTabIdx: 0,
  56. lastNewsfeedTabIdx: 0,
  57. newsFeedTabsList: [
  58. "News",
  59. "Following",
  60. "For You",
  61. ],
  62. garageSaleTabsList: [
  63. "For Sale",
  64. "For Rent",
  65. ],
  66. );
  67. }
  68. @override
  69. CommunityVmState build(){
  70. // 引入数据仓库
  71. commonNewsFeedRespositoryInstance = ref.read(commonNewsFeedRespositoryProvider);
  72. commonGarageRespositoryInstance = ref.read(commonGarageRespositoryProvider);
  73. final state = initState();
  74. // 第一帧渲染完成
  75. WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
  76. // 存入 一组 pageView的 vm
  77. CommunityPageViewIdxData.values.forEach((key, value) {
  78. switch(key){
  79. case 0:
  80. providerMap[key] = ref.read(newsVmProvider.notifier);
  81. break;
  82. case 1:
  83. providerMap[key] = ref.read(followingVmProvider.notifier);
  84. break;
  85. case 2:
  86. providerMap[key] = ref.read(foryouVmProvider.notifier);
  87. break;
  88. case 3:
  89. providerMap[key] = ref.read(forsaleVmProvider.notifier);
  90. break;
  91. case 4:
  92. providerMap[key] = ref.read(forrentVmProvider.notifier);
  93. }
  94. });
  95. });
  96. Log.d("-------------community vm-------------build---------------------");
  97. ref.onDispose((){
  98. providerMap = {};
  99. Log.d("-------------community vm-------------dispose---------------------");
  100. });
  101. return state;
  102. }
  103. tabsRouterChange(){
  104. Log.d("----tabsRouterChange---${tabsRouterKey.currentState?.controller?.activeIndex}-");
  105. state = state.copyWith(currentPageViewIdx: tabsRouterKey.currentState?.controller?.activeIndex ?? 0);
  106. // 设置当前导航栏的 图标 等状态
  107. WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
  108. Log.d("获取当前的导航栏 相关状态resMap444 ${providerMap[state.currentPageViewIdx]} ");
  109. Map<String, dynamic> resMap = providerMap[state.currentPageViewIdx]?.getCurrentQueryParams(null);
  110. Log.d("获取当前的导航栏 相关状态resMap $resMap ");
  111. _queryParams = resMap;
  112. });
  113. }
  114. // 点击tab 切换tab
  115. handlerChangeTab(int tabIndex, TabsRouter? tabsRouter, int? categoryIdx) {
  116. tabsRouter = (tabsRouter?? tabsRouterKey.currentState?.controller)!;
  117. categoryIdx = categoryIdx ?? state.currentCategoryIdx;
  118. if(categoryIdx == 0){
  119. tabsRouter.setActiveIndex(tabIndex);
  120. }else {
  121. tabsRouter.setActiveIndex(state.newsFeedTabsList!.length + tabIndex);
  122. }
  123. }
  124. // 获取当前pageView 的vm
  125. getCurrentPageViewVm(int? pageViewIdx){
  126. if(pageViewIdx !=null){
  127. return providerMap[pageViewIdx];
  128. }else {
  129. return getCurrentPageViewVm(state.currentPageViewIdx);
  130. }
  131. }
  132. // 切换news feed和garage sale
  133. handlerSwitchNewsfeedOrGaragesale( int categoryIdx, BuildContext? context, TabsRouter? tabsRouter){
  134. tabsRouter = (tabsRouter?? tabsRouterKey.currentState?.controller)!;
  135. categoryIdx = categoryIdx;
  136. if(categoryIdx == 0){
  137. tabsRouter.setActiveIndex(state.lastNewsfeedTabIdx);
  138. }else if (categoryIdx == 1){
  139. tabsRouter.setActiveIndex(state.newsFeedTabsList!.length + state.lastGarageTabIdx);
  140. }
  141. }
  142. // 设置当前的cat类型
  143. setCurrentCategoryIdx(BuildContext? context, int categoryIdx, int? lastNewsfeedTabIdx, int? lastGarageTabIdx){
  144. state = state.copyWith(
  145. currentCategoryIdx: categoryIdx,
  146. lastNewsfeedTabIdx: lastNewsfeedTabIdx?? state.lastNewsfeedTabIdx,
  147. lastGarageTabIdx: lastGarageTabIdx?? state.lastGarageTabIdx
  148. );
  149. }
  150. // 返回当前 pageView 页面的 vm
  151. // 判断当前pageview 页面正处于显示状态
  152. Future isCurrentPageViewShowing(int pageViewIdx) async{
  153. // 延迟获取结果
  154. bool isShowing = await Future.delayed(const Duration(milliseconds: 500), (){
  155. return state.currentPageViewIdx == pageViewIdx;
  156. });
  157. return isShowing;
  158. }
  159. // 获取garage sale 分类选项
  160. Future getGarageSaleCategoryOptions() async{
  161. final Map<String, dynamic> params = {};
  162. final result = await commonGarageRespositoryInstance.fetchGarageCateGoryList(params);
  163. return result;
  164. }
  165. // 选择 garage sale 导航栏点击 选择分类
  166. handlerChooseGarageCategory(BuildContext context) async {
  167. List<Map<String, dynamic>> garageCategoryList = [
  168. // {
  169. // 'id': '1',
  170. // 'name': 'Kids',
  171. // },
  172. // {
  173. // 'id': '2',
  174. // 'name': 'Homeware',
  175. // },
  176. // {
  177. // 'id': '3',
  178. // 'name': 'Fashion',
  179. // },
  180. // {
  181. // 'id': '4',
  182. // 'name': 'Electronics',
  183. // },
  184. // {
  185. // 'id': '5',
  186. // 'name': 'Sports',
  187. // },
  188. // {
  189. // 'id': '6',
  190. // 'name': 'Furniture',
  191. // },
  192. // {
  193. // 'id': '7',
  194. // 'name': 'Others',
  195. // },
  196. ];
  197. // 获取分类列表
  198. try {
  199. // 加入有缓存 就取缓存
  200. List<Map<String, dynamic>>? StorageCategoryList = SPUtil.getObjectList(AppConstant.storageGarageCategoryList)?.cast<Map<String, dynamic>>();
  201. if(StorageCategoryList != null && StorageCategoryList.isNotEmpty){
  202. Log.d("取StorageCategoryList 缓存: $StorageCategoryList ");
  203. garageCategoryList = StorageCategoryList;
  204. }else {
  205. final result = await getGarageSaleCategoryOptions();
  206. if(result.isSuccess){
  207. final listJson = result.getListJson();
  208. // 将 listJson 转换为 List<Map<String, dynamic>>
  209. List<Map<String, dynamic>> garageCategoryList = (listJson as List?)?.map((item) => item as Map<String, dynamic>).toList() ?? [];
  210. // 将 garageCategoryList 存入缓存
  211. Log.d("设置StorageCategoryList 缓存");
  212. SPUtil.putObjectList(AppConstant.storageGarageCategoryList, garageCategoryList);
  213. }
  214. }
  215. state = state.copyWith(
  216. garageCategoryList: garageCategoryList
  217. );
  218. // 显示弹框
  219. handlerShowChooseGarageCategoryDialog(context, garageCategoryList);
  220. }catch(error){
  221. Log.d("------获取分类列表error---------- $error");
  222. }
  223. }
  224. Future<void> handlerShowChooseGarageCategoryDialog(BuildContext context, List<Map<String, dynamic>> garageCategoryList) async{
  225. await DialogEngine.show(
  226. tag: "chooseGarageSaleCategory",
  227. position: DialogPosition.center,
  228. widget: AppCustomDialog(
  229. message: '',
  230. dialogWidth: MediaQuery.of(context).size.width * 0.8,
  231. // contentBoxMaxHeight: 350,
  232. // contentBoxMinHeight: 300,
  233. isShowConfirmBtn: state.garageCategoryList!.length > 0 ? true: false,
  234. confirmTxt: "Ok",
  235. messageBuilder: (BuildContext context){
  236. return Container(
  237. color: context.appColors.textWhite,
  238. child: Column(
  239. mainAxisAlignment: MainAxisAlignment.start,
  240. crossAxisAlignment: CrossAxisAlignment.start,
  241. children: state.garageCategoryList!.length > 0 ? [
  242. MyCheckboxGroup(
  243. isSingleSelect: _isSingleSelect,
  244. labelStyle: const TextStyle(
  245. fontSize: 16,
  246. fontWeight: FontWeight.w500,
  247. ),
  248. items: state.garageCategoryList!,
  249. defaultSelectedItems: [],
  250. onChanged: (List<Map<String, dynamic>> selectedItems){
  251. Log.d("----MyCheckboxGroup onChanged $selectedItems");
  252. _currentSelectedGarageCategory = selectedItems;
  253. }
  254. )
  255. ]: [
  256. Container(
  257. child: CircularProgressIndicator(
  258. strokeWidth: 3,
  259. valueColor: AlwaysStoppedAnimation(context.appColors.textDarkGray),
  260. ),
  261. )
  262. ],
  263. ),
  264. );
  265. },
  266. isShowCancelBtn:false,
  267. confirmAction: (){
  268. // 点击了确定
  269. Log.d("----点击了确定按钮");
  270. int? categoryId;
  271. if(_isSingleSelect){
  272. if(_currentSelectedGarageCategory.length > 0){
  273. categoryId = _currentSelectedGarageCategory[0]['id'];
  274. }
  275. }
  276. providerMap[state.currentPageViewIdx]
  277. ..setCurrentQueryParams({
  278. "category_id": categoryId!,
  279. })
  280. ..retryRequest();
  281. },
  282. )
  283. );
  284. }
  285. // 点击了导航栏的 like btn
  286. handlerClickNavbarLikeBtn(BuildContext? context){
  287. if(state.currentCategoryIdx ==0){
  288. //
  289. ToastEngine.show("点击了 newsfeed like");
  290. }else if(state.currentCategoryIdx == 1){
  291. //
  292. ToastEngine.show("点击了 garagesale like");
  293. }
  294. _queryParams?['is_liked'] = !(_queryParams?['is_liked']??false);
  295. providerMap[state.currentPageViewIdx]
  296. ..setCurrentQueryParams({
  297. "is_liked": _queryParams?['is_liked'],
  298. })
  299. ..retryRequest();
  300. }
  301. // 点击了导航栏的 filter btn
  302. handlerClickNavbarFilterBtn(BuildContext? context,){
  303. handlerChooseGarageCategory(context!);
  304. }
  305. // 点击发布的按钮 跳转到 newsfeed 发布的页面
  306. void handlerGotoNewsfeedPost(BuildContext? context){
  307. // AutoRouter.of(context).pushNamed(RouterPath.newsFeedPost);
  308. NewsfeedPostPage.startInstance();
  309. // MyPostsPage.startInstance();
  310. // MyFollowingPage.startInstance();
  311. }
  312. // 点击发布的按钮 跳转到garagesale 发布的页面
  313. void handlerGotoGaragePost(BuildContext? context){
  314. int type = 1;
  315. CommunityPageViewIdxData.values.forEach((key, value){
  316. if(value == "forSale" ){
  317. if(state.currentPageViewIdx == key){
  318. type = 1;
  319. }
  320. }else if(value == "forRent"){
  321. if(state.currentPageViewIdx == key){
  322. type = 2;
  323. }
  324. }
  325. });
  326. GaragesalePostPage.startInstance(type: type);
  327. }
  328. // 点击了 卡片上的 关注按钮
  329. Future<bool> commonClickCardFollowBtn(BuildContext? context,int to_user_id,bool isFollowed, int? idx) async{
  330. try{
  331. Map<String, dynamic> params = {
  332. "to_user_id": to_user_id
  333. };
  334. final result = await commonNewsFeedRespositoryInstance.handlerFollowOrCancel(params);
  335. if(result.isSuccess){
  336. return true;
  337. }else {
  338. return false;
  339. }
  340. }catch(error){
  341. return false;
  342. }
  343. }
  344. }