community_vm.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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:shared/utils/log_utils.dart';
  18. import 'package:auto_route/auto_route.dart';
  19. import 'package:widgets/dialog/app_custom_dialog.dart';
  20. import 'package:widgets/my_checkbox_group.dart';
  21. import '../garage/for_rent/for_rent_vm.dart';
  22. import '../garage/for_sale/for_sale_vm.dart';
  23. import '../garage/garagesale_post/garagesale_post_page.dart';
  24. import 'community_page.dart';
  25. import 'community_pageview_idx_data.dart';
  26. import 'community_state.dart';
  27. import 'foryou/foryou_vm.dart';
  28. import 'newsfeed_post/newsfeed_post_page.dart';
  29. part 'community_vm.g.dart';
  30. @riverpod
  31. class CommunityVm extends _$CommunityVm {
  32. get topSectionsData => state.topSectionsData;
  33. late CommonNewsFeedRespository commonNewsFeedRespositoryInstance;
  34. late CommonGarageRespository commonGarageRespositoryInstance;
  35. late Map<int, dynamic> providerMap = {};
  36. bool _isSingleSelect = true;
  37. List<Map<String, dynamic>> _currentSelectedGarageCategory = [];
  38. Map<int, Map<String, dynamic>> _queryParams = {};
  39. // 获取当前的查询参数
  40. getCurrentQueryParams(String key) {
  41. return _queryParams[state.currentPageViewIdx]?[key];
  42. }
  43. // 根据索引获取 Provider
  44. ProviderBase getProvider(int index) {
  45. return providerMap[index]!;
  46. }
  47. CommunityVmState initState() {
  48. List<String> newsFeedTabsList = [
  49. "News",
  50. "Following",
  51. "For You",
  52. ];
  53. List<String> garageSaleTabsList = [
  54. "For Sale",
  55. "For Rent",
  56. ];
  57. List<String> COMMUNITY_TABS_LIST = [...newsFeedTabsList];
  58. COMMUNITY_TABS_LIST.addAll(garageSaleTabsList);
  59. // s.add(garageSaleTabsList);
  60. Log.d("COMMUNITY_TABS_LIST $COMMUNITY_TABS_LIST");
  61. // Log.d("s $newsFeedTabsList");
  62. COMMUNITY_TABS_LIST.asMap().forEach((index, value) {
  63. _queryParams[index] = {
  64. 'keyword': null,
  65. 'is_liked': null,
  66. 'category_id': null,
  67. 'category_name': null,
  68. 'page_view_idx': index,
  69. 'page_view_name': value,
  70. };
  71. });
  72. return CommunityVmState(
  73. currentCategoryIdx: 0,
  74. currentPageViewIdx: 0,
  75. lastGarageTabIdx: 0,
  76. lastNewsfeedTabIdx: 0,
  77. newsFeedTabsList: newsFeedTabsList,
  78. garageSaleTabsList: garageSaleTabsList,
  79. );
  80. }
  81. @override
  82. CommunityVmState build(){
  83. // 引入数据仓库
  84. commonNewsFeedRespositoryInstance = ref.read(commonNewsFeedRespositoryProvider);
  85. commonGarageRespositoryInstance = ref.read(commonGarageRespositoryProvider);
  86. final state = initState();
  87. setCurrentPageViewIconStatus();
  88. getPageViewVm();
  89. Log.d("-------------community vm-------------build---------------------");
  90. ref.onDispose((){
  91. providerMap = {};
  92. Log.d("-------------community vm-------------dispose---------------------");
  93. });
  94. return state;
  95. }
  96. // 搜集pageView 对应的vm
  97. void getPageViewVm(){
  98. // 每次切换后需要重新获取 一组 pageView的 vm
  99. WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
  100. // 存入 一组 pageView的 vm
  101. CommunityPageViewIdxData.values.forEach((key, value) {
  102. switch(key){
  103. case 0:
  104. providerMap[key] = ref.read(newsVmProvider.notifier);
  105. break;
  106. case 1:
  107. providerMap[key] = ref.read(followingVmProvider.notifier);
  108. break;
  109. case 2:
  110. providerMap[key] = ref.read(foryouVmProvider.notifier);
  111. break;
  112. case 3:
  113. providerMap[key] = ref.read(forsaleVmProvider.notifier);
  114. break;
  115. case 4:
  116. providerMap[key] = ref.read(forrentVmProvider.notifier);
  117. }
  118. });
  119. });
  120. }
  121. // 设置当前导航栏的 图标 等状态
  122. void setCurrentPageViewIconStatus(){
  123. WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
  124. Log.d("获取当前的导航栏 相关状态resMap444 ${providerMap[state.currentPageViewIdx]} ");
  125. Map<String, dynamic> resMap = providerMap[state.currentPageViewIdx]?.getCurrentQueryParams(null)??{};
  126. Log.d("获取当前的导航栏 相关状态resMap $resMap ");
  127. _queryParams[state.currentPageViewIdx] = resMap;
  128. });
  129. }
  130. tabsRouterChange(){
  131. // 设置当前导航栏的 图标 等状态
  132. Log.d("----tabsRouterChange---${tabsRouterKey.currentState?.controller?.activeIndex}-");
  133. state = state.copyWith(currentPageViewIdx: tabsRouterKey.currentState?.controller?.activeIndex ?? 0);
  134. setCurrentPageViewIconStatus();
  135. getPageViewVm();
  136. }
  137. // 点击tab 切换tab
  138. handlerChangeTab(int tabIndex, TabsRouter? tabsRouter, int? categoryIdx) {
  139. tabsRouter = (tabsRouter?? tabsRouterKey.currentState?.controller)!;
  140. categoryIdx = categoryIdx ?? state.currentCategoryIdx;
  141. if(categoryIdx == 0){
  142. tabsRouter.setActiveIndex(tabIndex);
  143. }else {
  144. tabsRouter.setActiveIndex(state.newsFeedTabsList!.length + tabIndex);
  145. }
  146. }
  147. // 获取当前pageView 的vm
  148. getCurrentPageViewVm(int? pageViewIdx){
  149. if(pageViewIdx !=null){
  150. return providerMap[pageViewIdx];
  151. }else {
  152. return getCurrentPageViewVm(state.currentPageViewIdx);
  153. }
  154. }
  155. // 切换news feed和garage sale
  156. handlerSwitchNewsfeedOrGaragesale( int categoryIdx, BuildContext? context, TabsRouter? tabsRouter){
  157. tabsRouter = (tabsRouter?? tabsRouterKey.currentState?.controller)!;
  158. categoryIdx = categoryIdx;
  159. if(categoryIdx == 0){
  160. tabsRouter.setActiveIndex(state.lastNewsfeedTabIdx);
  161. }else if (categoryIdx == 1){
  162. tabsRouter.setActiveIndex(state.newsFeedTabsList!.length + state.lastGarageTabIdx);
  163. }
  164. }
  165. // 设置当前的cat类型
  166. setCurrentCategoryIdx(BuildContext? context, int categoryIdx, int? lastNewsfeedTabIdx, int? lastGarageTabIdx){
  167. state = state.copyWith(
  168. currentCategoryIdx: categoryIdx,
  169. lastNewsfeedTabIdx: lastNewsfeedTabIdx?? state.lastNewsfeedTabIdx,
  170. lastGarageTabIdx: lastGarageTabIdx?? state.lastGarageTabIdx
  171. );
  172. }
  173. // 返回当前 pageView 页面的 vm
  174. // 判断当前pageview 页面正处于显示状态
  175. Future isCurrentPageViewShowing(int pageViewIdx) async{
  176. // 延迟获取结果
  177. bool isShowing = await Future.delayed(const Duration(milliseconds: 500), (){
  178. return state.currentPageViewIdx == pageViewIdx;
  179. });
  180. return isShowing;
  181. }
  182. // 获取garage sale 分类选项
  183. Future<List<Map<String, dynamic>>> getGarageSaleCategoryOptions() async{
  184. List<Map<String, dynamic>> garageCategoryList = [
  185. // {
  186. // 'id': '1',
  187. // 'name': 'Kids',
  188. // },
  189. // {
  190. // 'id': '2',
  191. // 'name': 'Homeware',
  192. // },
  193. // {
  194. // 'id': '3',
  195. // 'name': 'Fashion',
  196. // },
  197. // {
  198. // 'id': '4',
  199. // 'name': 'Electronics',
  200. // },
  201. // {
  202. // 'id': '5',
  203. // 'name': 'Sports',
  204. // },
  205. // {
  206. // 'id': '6',
  207. // 'name': 'Furniture',
  208. // },
  209. // {
  210. // 'id': '7',
  211. // 'name': 'Others',
  212. // },
  213. ];
  214. // 获取分类列表
  215. try {
  216. // 加入有缓存 就取缓存
  217. List<Map<String, dynamic>>? StorageCategoryList = SPUtil.getObjectList(
  218. AppConstant.storageGarageCategoryList)?.cast<Map<String, dynamic>>();
  219. if (StorageCategoryList != null && StorageCategoryList.isNotEmpty) {
  220. Log.d("取StorageCategoryList 缓存: $StorageCategoryList ");
  221. garageCategoryList = StorageCategoryList;
  222. } else {
  223. Map<String, dynamic> params = {};
  224. final result = await commonGarageRespositoryInstance
  225. .fetchGarageCateGoryList(params);
  226. if (result.isSuccess) {
  227. final listJson = result.getListJson();
  228. // 将 listJson 转换为 List<Map<String, dynamic>>
  229. garageCategoryList = (listJson as List?)
  230. ?.map((item) => item as Map<String, dynamic>)
  231. .toList() ?? [];
  232. // 将 garageCategoryList 存入缓存
  233. Log.d("设置StorageCategoryList 缓存");
  234. SPUtil.putObjectList(
  235. AppConstant.storageGarageCategoryList, garageCategoryList);
  236. }
  237. }
  238. } catch(error){
  239. }
  240. return garageCategoryList;
  241. }
  242. // 选择 garage sale 导航栏点击 选择分类
  243. handlerChooseGarageCategory(BuildContext context) async {
  244. List<Map<String, dynamic>> garageCategoryList = await getGarageSaleCategoryOptions();
  245. // 显示弹框
  246. handlerShowChooseGarageCategoryDialog(context, garageCategoryList);
  247. state = state.copyWith(
  248. garageCategoryList: garageCategoryList
  249. );
  250. }
  251. Future<void> handlerShowChooseGarageCategoryDialog(BuildContext context, List<Map<String, dynamic>> garageCategoryList) async{
  252. await DialogEngine.show(
  253. tag: "chooseGarageSaleCategory",
  254. position: DialogPosition.center,
  255. widget: AppCustomDialog(
  256. message: '',
  257. title: 'Choose a Category',
  258. dialogWidth: MediaQuery.of(context).size.width * 0.8,
  259. // contentBoxMaxHeight: 350,
  260. // contentBoxMinHeight: 300,
  261. isShowConfirmBtn: garageCategoryList!.length > 0 ? true: false,
  262. confirmTxt: "Ok",
  263. messageBuilder: (BuildContext context){
  264. return Container(
  265. color: context.appColors.textWhite,
  266. child: Column(
  267. mainAxisAlignment: MainAxisAlignment.start,
  268. crossAxisAlignment: CrossAxisAlignment.start,
  269. children: garageCategoryList!.length > 0 ? [
  270. MyCheckboxGroup(
  271. isSingleSelect: _isSingleSelect,
  272. labelStyle: const TextStyle(
  273. fontSize: 16,
  274. fontWeight: FontWeight.w500,
  275. ),
  276. items: garageCategoryList!,
  277. defaultSelectedItems: [],
  278. onChanged: (List<Map<String, dynamic>> selectedItems){
  279. Log.d("----MyCheckboxGroup onChanged $selectedItems");
  280. _currentSelectedGarageCategory = selectedItems;
  281. }
  282. )
  283. ]: [
  284. Container(
  285. child: CircularProgressIndicator(
  286. strokeWidth: 3,
  287. valueColor: AlwaysStoppedAnimation(context.appColors.textDarkGray),
  288. ),
  289. )
  290. ],
  291. ),
  292. );
  293. },
  294. isShowCancelBtn:false,
  295. confirmAction: (){
  296. // 点击了确定
  297. Log.d("----点击了确定按钮");
  298. int? categoryId;
  299. if(_isSingleSelect){
  300. if(_currentSelectedGarageCategory.length > 0){
  301. categoryId = _currentSelectedGarageCategory[0]['id'];
  302. }
  303. }
  304. providerMap[state.currentPageViewIdx]
  305. ..setCurrentQueryParams({
  306. "category_id": _queryParams?[state.currentPageViewIdx]?['categoryId'],
  307. })
  308. ..directRefresh();
  309. },
  310. )
  311. );
  312. }
  313. // 搜索
  314. handlerSearch(String value){
  315. Log.d("community_vm 中 搜索 value: $value");
  316. _queryParams?[state.currentPageViewIdx]?['keyword'] = value;
  317. providerMap[state.currentPageViewIdx]
  318. ..setCurrentQueryParams({
  319. "keyword": _queryParams?[state.currentPageViewIdx]?['keyword'],
  320. })
  321. ..directRefresh();
  322. }
  323. // 点击了导航栏的 like btn
  324. handlerClickNavbarLikeBtn(BuildContext? context){
  325. if(state.currentCategoryIdx ==0){
  326. //
  327. // ToastEngine.show("点击了 newsfeed like");
  328. }else if(state.currentCategoryIdx == 1){
  329. //
  330. // ToastEngine.show("点击了 garagesale like");
  331. }
  332. _queryParams[state.currentPageViewIdx]?['is_liked'] = !(_queryParams?[state.currentPageViewIdx]?['is_liked']??false);
  333. // 控制外层滚动和内层滚动
  334. handlerNestedScrollViewScroll();
  335. providerMap[state.currentPageViewIdx]
  336. ..setCurrentQueryParams({
  337. "is_liked": _queryParams?[state.currentPageViewIdx]?['is_liked'],
  338. })
  339. ..directRefresh();
  340. // providerMap[state.currentPageViewIdx].directRefresh();
  341. }
  342. handlerNestedScrollViewScroll({double? outerOffset, double? innerOffset=0.0, bool? isOuterScrollAnimated=false, bool? isInnerScrollAnimated=false}){
  343. if(outerOffset !=null){
  344. if(isOuterScrollAnimated!){
  345. extendedNestedScrollViewKey.currentState?.outerController.animateTo(
  346. outerOffset,
  347. duration: const Duration(seconds: 1),
  348. curve: Curves.easeIn,
  349. );
  350. }else {
  351. extendedNestedScrollViewKey.currentState?.outerController.jumpTo(
  352. outerOffset,
  353. );
  354. }
  355. }
  356. if(innerOffset !=null){
  357. extendedNestedScrollViewKey.currentState?.innerPositions.forEach((position) {
  358. if(isInnerScrollAnimated!){
  359. position.animateTo(innerOffset,
  360. duration: Duration(seconds: 1), curve: Curves.easeIn);
  361. }else {
  362. position.jumpTo(innerOffset);
  363. }
  364. });
  365. }
  366. }
  367. // 点击了导航栏的 filter btn
  368. handlerClickNavbarFilterBtn(BuildContext? context,){
  369. handlerChooseGarageCategory(context!);
  370. }
  371. // 点击发布的按钮 跳转到 newsfeed 发布的页面
  372. void handlerGotoNewsfeedPost(BuildContext? context){
  373. // AutoRouter.of(context).pushNamed(RouterPath.newsFeedPost);
  374. NewsfeedPostPage.startInstance();
  375. // MyPostsPage.startInstance();
  376. // MyFollowingPage.startInstance();
  377. }
  378. // 点击发布的按钮 跳转到garagesale 发布的页面
  379. void handlerGotoGaragePost(BuildContext? context){
  380. int type = 1;
  381. CommunityPageViewIdxData.values.forEach((key, value){
  382. if(value == "forSale" ){
  383. if(state.currentPageViewIdx == key){
  384. type = 1;
  385. }
  386. }else if(value == "forRent"){
  387. if(state.currentPageViewIdx == key){
  388. type = 2;
  389. }
  390. }
  391. });
  392. GaragesalePostPage.startInstance(type: type);
  393. }
  394. // 点击了 卡片上的 关注按钮
  395. Future<bool> commonClickCardFollowBtn(BuildContext? context,int to_user_id,bool isFollowed, int? idx) async{
  396. try{
  397. Map<String, dynamic> params = {
  398. "to_user_id": to_user_id
  399. };
  400. final result = await commonNewsFeedRespositoryInstance.handlerFollowOrCancel(params);
  401. if(result.isSuccess){
  402. return true;
  403. }else {
  404. return false;
  405. }
  406. }catch(error){
  407. return false;
  408. }
  409. }
  410. }