community_vm.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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, dynamic> _queryParams = {};
  39. // 获取当前的查询参数
  40. getCurrentQueryParams(String key) {
  41. return _queryParams[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 getGarageSaleCategoryOptions() async{
  184. final Map<String, dynamic> params = {};
  185. final result = await commonGarageRespositoryInstance.fetchGarageCateGoryList(params);
  186. return result;
  187. }
  188. // 选择 garage sale 导航栏点击 选择分类
  189. handlerChooseGarageCategory(BuildContext context) async {
  190. List<Map<String, dynamic>> garageCategoryList = [
  191. // {
  192. // 'id': '1',
  193. // 'name': 'Kids',
  194. // },
  195. // {
  196. // 'id': '2',
  197. // 'name': 'Homeware',
  198. // },
  199. // {
  200. // 'id': '3',
  201. // 'name': 'Fashion',
  202. // },
  203. // {
  204. // 'id': '4',
  205. // 'name': 'Electronics',
  206. // },
  207. // {
  208. // 'id': '5',
  209. // 'name': 'Sports',
  210. // },
  211. // {
  212. // 'id': '6',
  213. // 'name': 'Furniture',
  214. // },
  215. // {
  216. // 'id': '7',
  217. // 'name': 'Others',
  218. // },
  219. ];
  220. // 获取分类列表
  221. try {
  222. // 加入有缓存 就取缓存
  223. List<Map<String, dynamic>>? StorageCategoryList = SPUtil.getObjectList(AppConstant.storageGarageCategoryList)?.cast<Map<String, dynamic>>();
  224. if(StorageCategoryList != null && StorageCategoryList.isNotEmpty){
  225. Log.d("取StorageCategoryList 缓存: $StorageCategoryList ");
  226. garageCategoryList = StorageCategoryList;
  227. }else {
  228. final result = await getGarageSaleCategoryOptions();
  229. if(result.isSuccess){
  230. final listJson = result.getListJson();
  231. // 将 listJson 转换为 List<Map<String, dynamic>>
  232. List<Map<String, dynamic>> garageCategoryList = (listJson as List?)?.map((item) => item as Map<String, dynamic>).toList() ?? [];
  233. // 将 garageCategoryList 存入缓存
  234. Log.d("设置StorageCategoryList 缓存");
  235. SPUtil.putObjectList(AppConstant.storageGarageCategoryList, garageCategoryList);
  236. }
  237. }
  238. state = state.copyWith(
  239. garageCategoryList: garageCategoryList
  240. );
  241. // 显示弹框
  242. handlerShowChooseGarageCategoryDialog(context, garageCategoryList);
  243. }catch(error){
  244. Log.d("------获取分类列表error---------- $error");
  245. }
  246. }
  247. Future<void> handlerShowChooseGarageCategoryDialog(BuildContext context, List<Map<String, dynamic>> garageCategoryList) async{
  248. await DialogEngine.show(
  249. tag: "chooseGarageSaleCategory",
  250. position: DialogPosition.center,
  251. widget: AppCustomDialog(
  252. message: '',
  253. dialogWidth: MediaQuery.of(context).size.width * 0.8,
  254. // contentBoxMaxHeight: 350,
  255. // contentBoxMinHeight: 300,
  256. isShowConfirmBtn: garageCategoryList!.length > 0 ? true: false,
  257. confirmTxt: "Ok",
  258. messageBuilder: (BuildContext context){
  259. return Container(
  260. color: context.appColors.textWhite,
  261. child: Column(
  262. mainAxisAlignment: MainAxisAlignment.start,
  263. crossAxisAlignment: CrossAxisAlignment.start,
  264. children: garageCategoryList!.length > 0 ? [
  265. MyCheckboxGroup(
  266. isSingleSelect: _isSingleSelect,
  267. labelStyle: const TextStyle(
  268. fontSize: 16,
  269. fontWeight: FontWeight.w500,
  270. ),
  271. items: garageCategoryList!,
  272. defaultSelectedItems: [],
  273. onChanged: (List<Map<String, dynamic>> selectedItems){
  274. Log.d("----MyCheckboxGroup onChanged $selectedItems");
  275. _currentSelectedGarageCategory = selectedItems;
  276. }
  277. )
  278. ]: [
  279. Container(
  280. child: CircularProgressIndicator(
  281. strokeWidth: 3,
  282. valueColor: AlwaysStoppedAnimation(context.appColors.textDarkGray),
  283. ),
  284. )
  285. ],
  286. ),
  287. );
  288. },
  289. isShowCancelBtn:false,
  290. confirmAction: (){
  291. // 点击了确定
  292. Log.d("----点击了确定按钮");
  293. int? categoryId;
  294. if(_isSingleSelect){
  295. if(_currentSelectedGarageCategory.length > 0){
  296. categoryId = _currentSelectedGarageCategory[0]['id'];
  297. }
  298. }
  299. providerMap[state.currentPageViewIdx]
  300. ..setCurrentQueryParams({
  301. "category_id": categoryId!,
  302. })
  303. ..directRefresh();
  304. },
  305. )
  306. );
  307. }
  308. // 搜索
  309. handlerSearch(String value){
  310. providerMap[state.currentPageViewIdx]
  311. ..setCurrentQueryParams({
  312. "keyword": value,
  313. })
  314. ..triggerRefresh();
  315. }
  316. // 点击了导航栏的 like btn
  317. handlerClickNavbarLikeBtn(BuildContext? context){
  318. if(state.currentCategoryIdx ==0){
  319. //
  320. ToastEngine.show("点击了 newsfeed like");
  321. }else if(state.currentCategoryIdx == 1){
  322. //
  323. ToastEngine.show("点击了 garagesale like");
  324. }
  325. _queryParams[state.currentPageViewIdx]['is_liked'] = !(_queryParams?['is_liked']??false);
  326. // 控制外层滚动和内层滚动
  327. handlerNestedScrollViewScroll();
  328. providerMap[state.currentPageViewIdx]
  329. ..setCurrentQueryParams({
  330. "is_liked": _queryParams?['is_liked'],
  331. })
  332. ..directRefresh();
  333. // providerMap[state.currentPageViewIdx].directRefresh();
  334. }
  335. handlerNestedScrollViewScroll({double? outerOffset, double? innerOffset=0.0, bool? isOuterScrollAnimated=false, bool? isInnerScrollAnimated=false}){
  336. if(outerOffset !=null){
  337. if(isOuterScrollAnimated!){
  338. extendedNestedScrollViewKey.currentState?.outerController.animateTo(
  339. outerOffset,
  340. duration: const Duration(seconds: 1),
  341. curve: Curves.easeIn,
  342. );
  343. }else {
  344. extendedNestedScrollViewKey.currentState?.outerController.jumpTo(
  345. outerOffset,
  346. );
  347. }
  348. }
  349. if(innerOffset !=null){
  350. extendedNestedScrollViewKey.currentState?.innerPositions.forEach((position) {
  351. if(isInnerScrollAnimated!){
  352. position.animateTo(innerOffset,
  353. duration: Duration(seconds: 1), curve: Curves.easeIn);
  354. }else {
  355. position.jumpTo(innerOffset);
  356. }
  357. });
  358. }
  359. }
  360. // 点击了导航栏的 filter btn
  361. handlerClickNavbarFilterBtn(BuildContext? context,){
  362. handlerChooseGarageCategory(context!);
  363. }
  364. // 点击发布的按钮 跳转到 newsfeed 发布的页面
  365. void handlerGotoNewsfeedPost(BuildContext? context){
  366. // AutoRouter.of(context).pushNamed(RouterPath.newsFeedPost);
  367. NewsfeedPostPage.startInstance();
  368. // MyPostsPage.startInstance();
  369. // MyFollowingPage.startInstance();
  370. }
  371. // 点击发布的按钮 跳转到garagesale 发布的页面
  372. void handlerGotoGaragePost(BuildContext? context){
  373. int type = 1;
  374. CommunityPageViewIdxData.values.forEach((key, value){
  375. if(value == "forSale" ){
  376. if(state.currentPageViewIdx == key){
  377. type = 1;
  378. }
  379. }else if(value == "forRent"){
  380. if(state.currentPageViewIdx == key){
  381. type = 2;
  382. }
  383. }
  384. });
  385. GaragesalePostPage.startInstance(type: type);
  386. }
  387. // 点击了 卡片上的 关注按钮
  388. Future<bool> commonClickCardFollowBtn(BuildContext? context,int to_user_id,bool isFollowed, int? idx) async{
  389. try{
  390. Map<String, dynamic> params = {
  391. "to_user_id": to_user_id
  392. };
  393. final result = await commonNewsFeedRespositoryInstance.handlerFollowOrCancel(params);
  394. if(result.isSuccess){
  395. return true;
  396. }else {
  397. return false;
  398. }
  399. }catch(error){
  400. return false;
  401. }
  402. }
  403. }