home_service_vm.dart 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. import 'package:cs_resources/generated/assets.dart';
  2. import 'package:cs_resources/theme/app_colors_theme.dart';
  3. import 'package:domain/entity/garage_sale_rent_entity.dart';
  4. import 'package:domain/entity/newsfeed_detail_entity.dart';
  5. import 'package:domain/entity/paid_service_entity.dart';
  6. import 'package:flutter/cupertino.dart';
  7. import 'package:flutter/material.dart';
  8. import 'package:plugin_basic/constants/app_constant.dart';
  9. import 'package:plugin_platform/engine/dialog/dialog_engine.dart';
  10. import 'package:plugin_platform/engine/sp/sp_util.dart';
  11. import 'package:plugin_platform/engine/toast/toast_engine.dart';
  12. import 'package:riverpod_annotation/riverpod_annotation.dart';
  13. import 'package:router/ext/auto_router_extensions.dart';
  14. import 'package:shared/utils/log_utils.dart';
  15. import 'package:widgets/dialog/app_custom_dialog.dart';
  16. import 'package:widgets/load_state_layout.dart';
  17. import 'package:widgets/my_checkbox_group.dart';
  18. import 'package:widgets/picker/option_pick_util.dart';
  19. import 'package:widgets/widget_export.dart';
  20. import '../../../constants_services.dart';
  21. import '../../../respository/services_respository.dart';
  22. import '../../../router/page/services_page_router.dart';
  23. import '../services_main_vm.dart';
  24. import '../services_vm.dart';
  25. import 'home_service_state.dart';
  26. part 'home_service_vm.g.dart';
  27. enum SortByType {
  28. likes_count,
  29. orders_count,
  30. clicks_count,
  31. }
  32. enum SortType {
  33. desc,
  34. asc,
  35. }
  36. const SortType defaultSortType = SortType.desc;
  37. const SortByType defaultSortByType = SortByType.clicks_count;
  38. @riverpod
  39. class HomeServiceVm extends _$HomeServiceVm {
  40. late ServicesRespository servicesRespositoryInstance;
  41. bool _needShowPlaceholder = false; //是否展示LoadingView
  42. int _page = 1; // 当前页
  43. int _limit = 10; // 每页数量
  44. int _count = 0; // 总条数
  45. bool _isSingleSelect = true;
  46. List<Map<String, dynamic>> _currentSelectedCategory = [];
  47. final Map<String, dynamic> _queryParams = {
  48. 'category_id': '',
  49. 'keyword': '',
  50. 'sort': defaultSortType.name, // 排序(desc=降序,asc=升序)
  51. 'sort_by': defaultSortByType.name, // 排序(likes_count=点赞量,orders_count=下单量,clicks_count=点击量)
  52. 'is_liked': '',
  53. };
  54. // Refresh 控制器
  55. final EasyRefreshController refreshController = EasyRefreshController(
  56. controlFinishRefresh: true, //允许刷新
  57. controlFinishLoad: true, //允许加载
  58. );
  59. HomeServiceState initState() {
  60. return HomeServiceState(
  61. sort: defaultSortType.name,
  62. list: []
  63. );
  64. }
  65. @override
  66. HomeServiceState build(){
  67. // 引入数据仓库
  68. servicesRespositoryInstance = ref.read(servicesRespositoryProvider);
  69. final state = initState();
  70. Log.d("--------------------------build---------------------");
  71. return state;
  72. }
  73. //刷新页面状态
  74. void changeLoadingState(LoadState loadState, String? errorMsg) {
  75. state = state.copyWith(
  76. loadingState: loadState,
  77. errorMessage: errorMsg
  78. );
  79. }
  80. // 初始化页面数据
  81. initPageData() {
  82. Log.d("----home_service_vm-----initPageData ${state.loadingState}");
  83. onRefresh();
  84. }
  85. // 上拉加载 更多
  86. Future loadMore() async {
  87. Log.d("----home_service_vm-----loadMore");
  88. _page++;
  89. getListData();
  90. }
  91. // 下拉刷新
  92. Future onRefresh() async {
  93. // 当前pageView 页面正处于显示状态
  94. Log.d("----forsale_vm-----onRefresh ");
  95. // await Future.delayed(const Duration(seconds: 2));
  96. _page = 1;
  97. getListData();
  98. }
  99. // 手动进行刷新
  100. Future triggerRefresh() async {
  101. Log.d("trggerRefresh");
  102. refreshController.callRefresh();
  103. }
  104. // 手动进行刷新
  105. Future directRefresh() async {
  106. state = state.copyWith(list:[]);
  107. // 注意:由于 nestedscrollview 嵌套easyfresh 组件 refreshController.callRefresh() 自动刷新只能滚动顶部但是不会触发下拉刷新,这里调用是 用到了将其滚动到顶部的作用,进而刷新操作主动掉接口
  108. // https://github.com/xuelongqy/flutter_easy_refresh/issues/692
  109. refreshController.callRefresh();
  110. refreshController.resetFooter();
  111. _page = 1;
  112. _needShowPlaceholder = true;
  113. getListData();
  114. }
  115. // 重试请求
  116. Future retryRequest() async {
  117. _page = 1;
  118. _needShowPlaceholder = true;
  119. getListData();
  120. }
  121. // 获取list 列表数据
  122. Future getListData<T>({bool? isLoadMore}) async {
  123. if (_needShowPlaceholder) {
  124. changeLoadingState(LoadState.State_Loading, null);
  125. }
  126. // List<Map<String, dynamic>> list = [
  127. // {
  128. // 'id':1,
  129. // 'service_type': 0, // 0 房屋保洁 1 空调保洁 2 维修
  130. // 'cover_img': 'https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500',
  131. // 'resources': ['https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500'],
  132. // 'title': 'House Cleaning Services',
  133. // 'price': 30,
  134. // 'unit': '/hr',
  135. // 'liked': true,
  136. // 'likes_count': 12,
  137. // 'company_name': 'HONG YE GROUP PTE LTD',
  138. // },
  139. // {
  140. // 'id':2,
  141. // 'service_type': 1, // 0 房屋保洁 1 空调保洁 2 维修
  142. // 'cover_img': 'https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500',
  143. // 'resources': ['https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500'],
  144. // 'title': 'Air Conditioning Cleaning',
  145. // 'price': 10,
  146. // 'unit': '/unit',
  147. // 'liked': false,
  148. // 'likes_count': 10,
  149. // 'company_name': 'HONG YE GROUP PTE LTD',
  150. // },
  151. // {
  152. // 'id':3,
  153. // 'service_type': 1, // 0 房屋保洁 1 空调保洁 2 维修
  154. // 'cover_img': 'https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500',
  155. // 'resources': ['https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500'],
  156. // 'title': 'Cleaning Services',
  157. // 'price': 200,
  158. // 'unit': '/hr',
  159. // 'liked': true,
  160. // 'likes_count': 1212,
  161. // 'company_name': 'HONG YE GROUP PTE LTD',
  162. // },
  163. // ];
  164. // handlerResultData(true, list:list);
  165. Log.d("-----55555-------$_queryParams");
  166. try {
  167. //请求网络
  168. Map<String, dynamic> params = {
  169. "sort": _queryParams['sort']?? SortType.desc.name, // 排序(desc=降序,asc=升序)
  170. "sort_by": _queryParams['sort_by']?? SortByType.clicks_count.name, // 排序(likes_count=点赞量,orders_count=下单量,clicks_count=点击量)
  171. "category_id": _queryParams['category_id']??'',
  172. "keyword": _queryParams['keyword']??'',
  173. "page": _page,
  174. "limit": _limit,
  175. };
  176. Log.d("请求参数------$params");
  177. final result = await servicesRespositoryInstance.fetchPaidServiceDataList(params);
  178. //校验成功失败
  179. if (result.isSuccess) {
  180. handlerResultList((result.data as PaidServiceEntity)?.list as List<PaidServiceList>?, isLoadMore ?? false);
  181. } else {
  182. String errorMessage = result.errorMsg!;
  183. changeLoadingState(LoadState.State_Error, errorMessage);
  184. ToastEngine.show(result.errorMsg ?? "Network Load Error");
  185. }
  186. } catch (e) {
  187. ToastEngine.show("Error: $e");
  188. }
  189. // 最后赋值
  190. _needShowPlaceholder = false;
  191. }
  192. handlerResultData(bool isList, {List<PaidServiceList>? list, dynamic? data}){
  193. Future.delayed(const Duration(seconds: 1)).then((value) {
  194. if(isList){
  195. // list 数据模式
  196. if(list != null && list.isNotEmpty){
  197. if(_page == 1){
  198. state.list.clear();
  199. state.list!.addAll(list);
  200. refreshController.finishRefresh();
  201. changeLoadingState(LoadState.State_Success, null);
  202. }else {
  203. final allList = state.list;
  204. allList!.addAll(list);
  205. state = state.copyWith(list: allList);
  206. refreshController.finishLoad();
  207. }
  208. }else {
  209. if(_page == 1){
  210. state.list.clear();
  211. changeLoadingState(LoadState.State_Empty, null);
  212. refreshController.finishRefresh();
  213. }else {
  214. refreshController.finishLoad(IndicatorResult.noMore);
  215. }
  216. }
  217. }else {
  218. // 单个数据模式
  219. if(data!=null){
  220. if(_page == 1){
  221. refreshController.finishRefresh();
  222. }else{
  223. refreshController.finishLoad();
  224. }
  225. changeLoadingState(LoadState.State_Success, null);
  226. }else {
  227. if(_page == 1){
  228. refreshController.finishRefresh();
  229. }else{
  230. refreshController.finishLoad();
  231. }
  232. changeLoadingState(LoadState.State_Empty, null);
  233. }
  234. }
  235. });
  236. }
  237. void handlerResultList(List<PaidServiceList>? list, bool isLoadMore) {
  238. if (list != null && list.isNotEmpty) {
  239. //有数据,判断是刷新还是加载更多的数据
  240. if (_page == 1) {
  241. //刷新的方式
  242. state.list!.clear();
  243. state.list!.addAll(list);
  244. refreshController.finishRefresh();
  245. //更新展示的状态
  246. changeLoadingState(LoadState.State_Success, null);
  247. } else {
  248. //加载更多
  249. final allList = state.list;
  250. allList!.addAll(list);
  251. state = state.copyWith(list: allList);
  252. refreshController.finishLoad();
  253. }
  254. } else {
  255. if (_page == 1) {
  256. //展示无数据的布局
  257. state.list!.clear();
  258. changeLoadingState(LoadState.State_Empty, null);
  259. refreshController.finishRefresh();
  260. } else {
  261. //展示加载完成,没有更多数据了
  262. if (_page == 1) {
  263. //展示无数据的布局
  264. state.list!.clear();
  265. changeLoadingState(LoadState.State_Empty, null);
  266. refreshController.finishRefresh();
  267. } else {
  268. //展示加载完成,没有更多数据了
  269. if(state.list!.length == 0){
  270. changeLoadingState(LoadState.State_Empty, null);
  271. refreshController.finishLoad();
  272. }else {
  273. if(_needShowPlaceholder){
  274. changeLoadingState(LoadState.State_Success, null);
  275. }
  276. }
  277. //更新展示的状态
  278. refreshController.finishLoad(IndicatorResult.noMore);
  279. }
  280. }
  281. }
  282. }
  283. // 获取 homeservice 的分类选项
  284. Future<List<Map<String, dynamic>>> getHomeServiceCategoryOptions() async{
  285. // await Future.delayed(const Duration(milliseconds: 300));
  286. // ToastEngine.dismiss();
  287. List<Map<String, dynamic>> serviceCategoryList = [
  288. // {
  289. // 'id': 1,
  290. // 'name': 'House Cleaning Serivces',
  291. // },
  292. // {
  293. // 'id': 2,
  294. // 'name': 'Household Appliance Cleaning',
  295. // },
  296. ];
  297. // 获取分类列表
  298. try {
  299. // 加入有缓存 就取缓存
  300. List<Map<String, dynamic>>? StorageCategoryList = SPUtil.getObjectList(
  301. AppConstant.storagePaidServiceCategoryList)?.cast<Map<String, dynamic>>();
  302. if (StorageCategoryList != null && StorageCategoryList.isNotEmpty) {
  303. Log.d("取StorageCategoryList 缓存: $StorageCategoryList ");
  304. serviceCategoryList = StorageCategoryList;
  305. } else {
  306. // final paidServiceLayoutVm = ref.watch(servicesVmProvider.notifier);
  307. // Map<String, dynamic> params = {
  308. // 'parent_id': paidServiceLayoutVm?.state.parentCategoryId,
  309. // };
  310. final serviceMainVm = ref.read(serviceMainVmProvider.notifier);
  311. Map<String, dynamic> params = {
  312. 'parent_id': serviceMainVm?.state.curId,
  313. };
  314. final result = await servicesRespositoryInstance.fetchServiceCateGoryList(params);
  315. if (result.isSuccess) {
  316. final listJson = result.getListJson();
  317. // 将 listJson 转换为 List<Map<String, dynamic>>
  318. serviceCategoryList = (listJson as List?)
  319. ?.map((item) => item as Map<String, dynamic>)
  320. .toList() ?? [];
  321. // 将 serviceCategoryList 存入缓存
  322. Log.d("设置StorageCategoryList 缓存");
  323. SPUtil.putObjectList(
  324. AppConstant.storagePaidServiceCategoryList, serviceCategoryList);
  325. }
  326. }
  327. } catch(error){
  328. Log.d("获取分类列表失败: $error");
  329. }
  330. return serviceCategoryList;
  331. }
  332. // 点击了filter icon
  333. handlerClickFilterIcon(BuildContext context) async{
  334. List<Map<String, dynamic>> serviceCategoryList = await getHomeServiceCategoryOptions();
  335. // 显示弹框
  336. handlerShowChooseServiceCategoryDialog(context, serviceCategoryList);
  337. }
  338. Future<void> handlerShowChooseServiceCategoryDialog(BuildContext context, List<Map<String, dynamic>> categoryList) async{
  339. await DialogEngine.show(
  340. tag: "chooseServiceCategory",
  341. position: DialogPosition.center,
  342. widget: AppCustomDialog(
  343. message: '',
  344. title: 'Choose a Category',
  345. dialogWidth: MediaQuery.of(context).size.width * 0.8,
  346. // contentBoxMaxHeight: 350,
  347. // contentBoxMinHeight: 300,
  348. isShowConfirmBtn: categoryList!.length > 0 ? true: false,
  349. confirmTxt: "Ok",
  350. messageBuilder: (BuildContext context){
  351. return Container(
  352. child: Column(
  353. mainAxisAlignment: MainAxisAlignment.start,
  354. crossAxisAlignment: CrossAxisAlignment.start,
  355. children: categoryList!.length > 0 ? [
  356. MyCheckboxGroup(
  357. isSingleSelect: _isSingleSelect,
  358. labelStyle: const TextStyle(
  359. fontSize: 16,
  360. fontWeight: FontWeight.w500,
  361. ),
  362. items: categoryList!,
  363. defaultSelectedItems: [],
  364. onChanged: (List<Map<String, dynamic>> selectedItems){
  365. Log.d("----MyCheckboxGroup onChanged $selectedItems");
  366. _currentSelectedCategory = selectedItems;
  367. }
  368. )
  369. ]: [
  370. Container(
  371. child: CircularProgressIndicator(
  372. strokeWidth: 3,
  373. valueColor: AlwaysStoppedAnimation(context.appColors.textDarkGray),
  374. ),
  375. )
  376. ],
  377. ),
  378. );
  379. },
  380. isShowCancelBtn:false,
  381. confirmAction: (){
  382. // 点击了确定
  383. Log.d("----点击了确定按钮 _isSingleSelect:$_isSingleSelect _currentSelectedCategory: $_currentSelectedCategory");
  384. int? categoryId;
  385. if(_isSingleSelect){
  386. if(_currentSelectedCategory.length > 0){
  387. categoryId = _currentSelectedCategory[0]['id'];
  388. _queryParams['categoryId'] = categoryId;
  389. }else {
  390. // 一个都没有选
  391. _queryParams['categoryId'] = '';
  392. }
  393. }
  394. setCurrentQueryParams({
  395. "category_id": _queryParams?['categoryId']??'',
  396. });
  397. directRefresh();
  398. },
  399. )
  400. );
  401. }
  402. // 点击 收藏/取消收藏
  403. Future<bool?> handlerClickCollection(int id, bool? isCollection) async{
  404. try {
  405. //请求网络
  406. Map<String, dynamic> params = {
  407. "id": id,
  408. "type": 'paid', // 类型(paid=付费服务,inquiry=询价服务)
  409. };
  410. Log.d("请求参数------$params");
  411. final result = await servicesRespositoryInstance.fetchServiceLiked(params);
  412. //校验成功失败
  413. if (result.isSuccess) {
  414. // 修改 该id 的 liked 和 likes_count 字段
  415. state.list!.forEach((PaidServiceList elementEntity) {
  416. if(elementEntity.id == id){
  417. elementEntity.liked = !elementEntity.liked!;
  418. elementEntity.likesCount = elementEntity.liked! ? (elementEntity.likesCount! + 1) : (elementEntity.likesCount! - 1);
  419. }
  420. });
  421. return true;
  422. } else {
  423. String errorMessage = result.errorMsg!;
  424. changeLoadingState(LoadState.State_Error, errorMessage);
  425. ToastEngine.show(result.errorMsg ?? "Network Load Error");
  426. }
  427. } catch (e) {
  428. Log.e("Error: $e");
  429. ToastEngine.show("Error: $e");
  430. }
  431. }
  432. // 设置当前的 _queryParams
  433. setCurrentQueryParams(Map<String, dynamic> params){
  434. _queryParams.addAll(params);
  435. }
  436. // 获取当前的 _queryParams
  437. Map<String, dynamic> getCurrentQueryParams(String? key){
  438. if(key!=null && key!.isNotEmpty){
  439. return _queryParams[key];
  440. }
  441. return _queryParams;
  442. }
  443. handlerClickDescSort(BuildContext context, String sort) {
  444. String sortStr = defaultSortType.name;
  445. if(sort == SortType.desc.name){
  446. sortStr = SortType.asc.name;
  447. }else {
  448. sortStr = SortType.desc.name;
  449. }
  450. // 遍历 servicesConstants.sortByOptionsList 找到
  451. _queryParams['sort'] = sortStr;
  452. state = state.copyWith(sort: sortStr);
  453. // 调用list 接口
  454. directRefresh();
  455. }
  456. // 点击 sort icon
  457. handlerClickSortByIcon(BuildContext context) async{
  458. // await SmartDialog.showAttach(
  459. // targetContext: context,
  460. // alignment: Alignment.bottomCenter,
  461. // highlightBuilder: (Offset targetOffset, Size targetSize) {
  462. // Log.d("666 ${targetOffset} ${targetSize}");
  463. // return Positioned(
  464. // right: 0,
  465. // top: 0,
  466. // child: Container(height: targetOffset.dy + 50, width: targetSize.width, color: Colors.white),
  467. // );
  468. // },
  469. // builder: (_) => _listDialog(),
  470. // );
  471. // DialogEngine.showAttach(
  472. // targetContext: context,
  473. // position: DialogPosition.top,
  474. // clickMaskDismiss:false,
  475. // usePenetrate: true,
  476. // widget: _listDialog()
  477. // );
  478. OptionPickerUtil.showCupertinoOptionPicker(
  479. items: state.sortByOptionsList,
  480. initialSelectIndex: 0,
  481. onPickerChanged: (_, index) {
  482. Log.d("----7777--${state.sortByOptionsList?[index]}-----");
  483. String sortByStr = state.sortByOptionsList?[index]??'';
  484. // 遍历 servicesConstants.sortByOptionsList 找到
  485. _queryParams['sort_by'] = servicesConstants.sortByOptionsMap[sortByStr]??'';
  486. state = state.copyWith(sortBySelectedOption: state.sortByOptionsList?[index]);
  487. // 调用list 接口
  488. directRefresh();
  489. },
  490. );
  491. }
  492. Widget _listDialog() {
  493. return Container(
  494. width: 200,
  495. height: 200,
  496. color: Colors.white,
  497. child: Column(
  498. children: [
  499. Text("排序方式"),
  500. Text("价格从低到高"),
  501. Text("价格从高到低"),
  502. Text("距离最近"),
  503. Text("距离最远"),
  504. ],
  505. ),
  506. );
  507. }
  508. // 去详情页面
  509. void handlerGotoDetail({
  510. BuildContext? context,
  511. required int id,
  512. required PaidServiceListCategory paidServiceCategory,
  513. liked,
  514. likesCount,
  515. }){
  516. int cleanServiceTypeId = paidServiceCategory.id!;
  517. Log.d("去详情页面: paidServiceCategory:$paidServiceCategory $id $cleanServiceTypeId");
  518. if(cleanServiceTypeId == servicesConstants.paidServicesType['houseCleaning']!['id'] || cleanServiceTypeId == servicesConstants.paidServicesType['airConditioner']!['id']){
  519. // clean service 跳转到 clean 详情页
  520. appRouter.push(ServiceCleanDetailPageRoute(id: id, cleanServiceTypeId: cleanServiceTypeId,liked: liked,likesCount: likesCount));
  521. }else {
  522. // other service 跳转到 other 详情页
  523. ToastEngine.show("${cleanServiceTypeId} 类型的详情暂未开放");
  524. }
  525. }
  526. }