community_vm.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. dialogWidth: MediaQuery.of(context).size.width * 0.8,
  258. // contentBoxMaxHeight: 350,
  259. // contentBoxMinHeight: 300,
  260. isShowConfirmBtn: garageCategoryList!.length > 0 ? true: false,
  261. confirmTxt: "Ok",
  262. messageBuilder: (BuildContext context){
  263. return Container(
  264. color: context.appColors.textWhite,
  265. child: Column(
  266. mainAxisAlignment: MainAxisAlignment.start,
  267. crossAxisAlignment: CrossAxisAlignment.start,
  268. children: garageCategoryList!.length > 0 ? [
  269. MyCheckboxGroup(
  270. isSingleSelect: _isSingleSelect,
  271. labelStyle: const TextStyle(
  272. fontSize: 16,
  273. fontWeight: FontWeight.w500,
  274. ),
  275. items: garageCategoryList!,
  276. defaultSelectedItems: [],
  277. onChanged: (List<Map<String, dynamic>> selectedItems){
  278. Log.d("----MyCheckboxGroup onChanged $selectedItems");
  279. _currentSelectedGarageCategory = selectedItems;
  280. }
  281. )
  282. ]: [
  283. Container(
  284. child: CircularProgressIndicator(
  285. strokeWidth: 3,
  286. valueColor: AlwaysStoppedAnimation(context.appColors.textDarkGray),
  287. ),
  288. )
  289. ],
  290. ),
  291. );
  292. },
  293. isShowCancelBtn:false,
  294. confirmAction: (){
  295. // 点击了确定
  296. Log.d("----点击了确定按钮");
  297. int? categoryId;
  298. if(_isSingleSelect){
  299. if(_currentSelectedGarageCategory.length > 0){
  300. categoryId = _currentSelectedGarageCategory[0]['id'];
  301. }
  302. }
  303. providerMap[state.currentPageViewIdx]
  304. ..setCurrentQueryParams({
  305. "category_id": _queryParams?[state.currentPageViewIdx]?['categoryId'],
  306. })
  307. ..directRefresh();
  308. },
  309. )
  310. );
  311. }
  312. // 搜索
  313. handlerSearch(String value){
  314. Log.d("community_vm 中 搜索 value: $value");
  315. _queryParams?[state.currentPageViewIdx]?['keyword'] = value;
  316. providerMap[state.currentPageViewIdx]
  317. ..setCurrentQueryParams({
  318. "keyword": _queryParams?[state.currentPageViewIdx]?['keyword'],
  319. })
  320. ..directRefresh();
  321. }
  322. // 点击了导航栏的 like btn
  323. handlerClickNavbarLikeBtn(BuildContext? context){
  324. if(state.currentCategoryIdx ==0){
  325. //
  326. // ToastEngine.show("点击了 newsfeed like");
  327. }else if(state.currentCategoryIdx == 1){
  328. //
  329. // ToastEngine.show("点击了 garagesale like");
  330. }
  331. _queryParams[state.currentPageViewIdx]?['is_liked'] = !(_queryParams?[state.currentPageViewIdx]?['is_liked']??false);
  332. // 控制外层滚动和内层滚动
  333. handlerNestedScrollViewScroll();
  334. providerMap[state.currentPageViewIdx]
  335. ..setCurrentQueryParams({
  336. "is_liked": _queryParams?[state.currentPageViewIdx]?['is_liked'],
  337. })
  338. ..directRefresh();
  339. // providerMap[state.currentPageViewIdx].directRefresh();
  340. }
  341. handlerNestedScrollViewScroll({double? outerOffset, double? innerOffset=0.0, bool? isOuterScrollAnimated=false, bool? isInnerScrollAnimated=false}){
  342. if(outerOffset !=null){
  343. if(isOuterScrollAnimated!){
  344. extendedNestedScrollViewKey.currentState?.outerController.animateTo(
  345. outerOffset,
  346. duration: const Duration(seconds: 1),
  347. curve: Curves.easeIn,
  348. );
  349. }else {
  350. extendedNestedScrollViewKey.currentState?.outerController.jumpTo(
  351. outerOffset,
  352. );
  353. }
  354. }
  355. if(innerOffset !=null){
  356. extendedNestedScrollViewKey.currentState?.innerPositions.forEach((position) {
  357. if(isInnerScrollAnimated!){
  358. position.animateTo(innerOffset,
  359. duration: Duration(seconds: 1), curve: Curves.easeIn);
  360. }else {
  361. position.jumpTo(innerOffset);
  362. }
  363. });
  364. }
  365. }
  366. // 点击了导航栏的 filter btn
  367. handlerClickNavbarFilterBtn(BuildContext? context,){
  368. handlerChooseGarageCategory(context!);
  369. }
  370. // 点击发布的按钮 跳转到 newsfeed 发布的页面
  371. void handlerGotoNewsfeedPost(BuildContext? context){
  372. // AutoRouter.of(context).pushNamed(RouterPath.newsFeedPost);
  373. NewsfeedPostPage.startInstance();
  374. // MyPostsPage.startInstance();
  375. // MyFollowingPage.startInstance();
  376. }
  377. // 点击发布的按钮 跳转到garagesale 发布的页面
  378. void handlerGotoGaragePost(BuildContext? context){
  379. int type = 1;
  380. CommunityPageViewIdxData.values.forEach((key, value){
  381. if(value == "forSale" ){
  382. if(state.currentPageViewIdx == key){
  383. type = 1;
  384. }
  385. }else if(value == "forRent"){
  386. if(state.currentPageViewIdx == key){
  387. type = 2;
  388. }
  389. }
  390. });
  391. GaragesalePostPage.startInstance(type: type);
  392. }
  393. // 点击了 卡片上的 关注按钮
  394. Future<bool> commonClickCardFollowBtn(BuildContext? context,int to_user_id,bool isFollowed, int? idx) async{
  395. try{
  396. Map<String, dynamic> params = {
  397. "to_user_id": to_user_id
  398. };
  399. final result = await commonNewsFeedRespositoryInstance.handlerFollowOrCancel(params);
  400. if(result.isSuccess){
  401. return true;
  402. }else {
  403. return false;
  404. }
  405. }catch(error){
  406. return false;
  407. }
  408. }
  409. }