import 'dart:async'; import 'package:dating_touchme_app/generated/assets.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; import 'package:location_plugin/location_plugin.dart'; import '../../network/home_api.dart'; import '../../model/home/marriage_data.dart'; class HomeController extends GetxController { // 推荐列表数据 final recommendFeed = [].obs; // 同城列表数据 final nearbyFeed = [].obs; // 推荐列表的加载状态和分页信息 final recommendIsLoading = false.obs; final recommendPage = 1.obs; final recommendHasMore = true.obs; // 同城列表的加载状态和分页信息 final nearbyIsLoading = false.obs; final nearbyPage = 1.obs; final nearbyHasMore = true.obs; // 当前标签页索引 final selectedTabIndex = 0.obs; // 分页大小 final pageSize = 10; // 从GetX依赖注入中获取HomeApi实例 late final HomeApi _homeApi; final timelineTab = 0.obs; final RxnInt cityCode = RxnInt(); final _locationPlugin = LocationPlugin(); String _status = 'Idle'; String _cityStatus = 'Idle'; Map? _location; CityInfo? _cityInfo; @override void onInit() { super.onInit(); // 从全局依赖中获取HomeApi _homeApi = Get.find(); // 初始化时加载数据 loadInitialData(); } Future _fetchLocation() async { _status = 'Fetching location...'; try { final location = await _locationPlugin.getCurrentLocation(); if (location == null) { _status = 'Location unavailable'; _cityStatus = 'Skip city lookup'; _cityInfo = null; return; } _location = location; _status = 'Success'; _cityStatus = 'Fetching city info...'; await _fetchCityInfo(location['latitude']!, location['longitude']!); } on PlatformException catch (e) { _status = 'Failed: ${e.code} ${e.message ?? ''}'.trim(); _cityStatus = 'Skip city lookup'; _cityInfo = null; } catch (e) { _status = 'Failed: $e'; _cityStatus = 'Skip city lookup'; _cityInfo = null; } } Future _fetchCityInfo(double latitude, double longitude) async { try { final info = await _locationPlugin.getCityInfo(latitude: latitude, longitude: longitude); print(info); _cityInfo = info; _cityStatus = info == null ? 'No city info' : 'Success'; cityCode.value = ((_cityInfo?.code ?? 0) ~/ 100) * 100; } on CityInfoLookupException catch (e) { _cityInfo = null; _cityStatus = 'Failed: ${e.code}'; } catch (e) { _cityInfo = null; _cityStatus = 'Failed: $e'; } } /// 加载初始数据(同时加载两个标签页的数据) void loadInitialData() async { // 并行加载两个标签页的数据 print(12121); await Future.wait([ loadRecommendInitialData(), ]); } /// 加载推荐列表初始数据 Future loadRecommendInitialData() async { if (recommendIsLoading.value) return; try { recommendIsLoading.value = true; recommendPage.value = 1; recommendHasMore.value = true; // 获取推荐数据 (type=0) final result = await _fetchMarriageData( pageNum: 1, type: 0, ); // 重置并更新推荐列表 recommendFeed.clear(); recommendFeed.addAll(result['records']); // 根据返回的分页信息判断是否还有更多数据 final int currentPage = result['current'] ?? 1; // final int totalPages = result['pages'] ?? 1; final int totalPages = 100; recommendHasMore.value = currentPage < totalPages; print(recommendHasMore.value); } catch (e) { _handleError('获取推荐列表异常', e, '推荐列表加载失败,请稍后重试'); } finally { recommendIsLoading.value = false; } } /// 加载同城列表初始数据 Future loadNearbyInitialData() async { if(cityCode.value == null || cityCode.value == 0){ return; } if (nearbyIsLoading.value) return; try { nearbyIsLoading.value = true; nearbyPage.value = 1; nearbyHasMore.value = true; // 获取同城数据 (type=1) final result = await _fetchMarriageData( pageNum: 1, type: 1, code: cityCode.value ); // 重置并更新同城列表 nearbyFeed.clear(); nearbyFeed.addAll(result['records']); // 根据返回的分页信息判断是否还有更多数据 final int currentPage = result['current'] ?? 1; // final int totalPages = result['pages'] ?? 1; final int totalPages = 100; nearbyHasMore.value = currentPage < totalPages; } catch (e) { _handleError('获取同城列表异常', e, '同城列表加载失败,请稍后重试'); } finally { nearbyIsLoading.value = false; } } /// 加载更多数据 Future loadMoreData([int? tabIndex]) async { final targetTab = tabIndex ?? selectedTabIndex.value; if (targetTab == 0) { // 加载推荐列表更多数据 await loadRecommendMoreData(); } else { // 加载同城列表更多数据 await loadNearbyMoreData(); } } /// 加载推荐列表更多数据 Future loadRecommendMoreData() async { if (recommendIsLoading.value || !recommendHasMore.value) return; try { recommendIsLoading.value = true; // final nextPage = recommendPage.value + 1; final nextPage = recommendPage.value; print('推荐列表加载更多 - 当前页: ${recommendPage.value}, 下一页: $nextPage'); // 获取推荐数据 (type=0) final result = await _fetchMarriageData( pageNum: nextPage, type: 0, ); // 更新页码 recommendPage.value = nextPage; // 更新推荐列表 recommendFeed.addAll(result['records']); // 根据返回的分页信息判断是否还有更多数据 final int currentPage = result['current'] as int; // final int totalPages = result['pages'] as int; final int totalPages = 100; recommendHasMore.value = currentPage < totalPages; print('推荐列表加载更多完成 - 当前页: $currentPage, 总页数: $totalPages, 还有更多: ${recommendHasMore.value}'); } catch (e) { _handleError('加载推荐更多异常', e, '加载更多失败'); } finally { recommendIsLoading.value = false; } } /// 加载同城列表更多数据 Future loadNearbyMoreData() async { if (nearbyIsLoading.value || !nearbyHasMore.value) return; try { nearbyIsLoading.value = true; // final nextPage = nearbyPage.value + 1; final nextPage = nearbyPage.value; print('同城列表加载更多 - 当前页: ${nearbyPage.value}, 下一页: $nextPage'); // 获取同城数据 (type=1) final result = await _fetchMarriageData( pageNum: nextPage, type: 1, code: cityCode.value ); // 更新页码 nearbyPage.value = nextPage; // 更新同城列表 nearbyFeed.addAll(result['records']); // 根据返回的分页信息判断是否还有更多数据 final int currentPage = result['current'] as int; // final int totalPages = result['pages'] as int; final int totalPages = 100; nearbyHasMore.value = currentPage < totalPages; print('同城列表加载更多完成 - 当前页: $currentPage, 总页数: $totalPages, 还有更多: ${nearbyHasMore.value}'); } catch (e) { _handleError('加载同城更多异常', e, '加载更多失败'); } finally { nearbyIsLoading.value = false; } } /// 刷新数据 Future refreshData([int? tabIndex]) async { final targetTab = tabIndex ?? selectedTabIndex.value; if (targetTab == 0) { // 刷新推荐列表 await refreshRecommendData(); } else { // 刷新同城列表 await refreshNearbyData(); } } /// 刷新推荐列表数据 Future refreshRecommendData() async { if (recommendIsLoading.value) return; try { recommendIsLoading.value = true; recommendPage.value = 1; recommendHasMore.value = true; // 获取推荐数据 (type=0) final result = await _fetchMarriageData( pageNum: 1, type: 0, ); // 更新推荐列表 recommendFeed.clear(); recommendFeed.addAll(result['records']); // 根据返回的分页信息判断是否还有更多数据 final int currentPage = result['current'] ?? 1; // final int totalPages = result['pages'] ?? 1; final int totalPages = 100; recommendHasMore.value = currentPage < totalPages; } catch (e) { _handleError('刷新推荐数据异常', e, '刷新失败,请稍后重试'); } finally { recommendIsLoading.value = false; } } /// 刷新同城列表数据 Future refreshNearbyData() async { if (nearbyIsLoading.value) return; try { nearbyIsLoading.value = true; nearbyPage.value = 1; nearbyHasMore.value = true; // 获取同城数据 (type=1) final result = await _fetchMarriageData( pageNum: 1, type: 1, code: cityCode.value ); // 更新同城列表 nearbyFeed.clear(); nearbyFeed.addAll(result['records']); // 根据返回的分页信息判断是否还有更多数据 final int currentPage = result['current'] ?? 1; // final int totalPages = result['pages'] ?? 1; final int totalPages = 100; nearbyHasMore.value = currentPage < totalPages; } catch (e) { _handleError('刷新同城数据异常', e, '刷新失败,请稍后重试'); } finally { nearbyIsLoading.value = false; } } /// 设置当前标签页 void setSelectedTabIndex(int index) async { print('Setting selected tab index to: $index'); selectedTabIndex.value = index; // 确保UI能够更新 update(); if(index == 2 && nearbyFeed.isEmpty){ if(cityCode.value == null || cityCode.value == 0){ await _fetchLocation(); } loadNearbyInitialData(); } } /// 获取当前标签页的列表数据 List getFeedListByTab(int tabIndex) { return tabIndex == 0 ? List.from(recommendFeed) : List.from(nearbyFeed); } /// 私有方法:获取婚姻数据(统一的数据获取逻辑) /// 返回包含records(数据列表)、current(当前页)、pages(总页数)的Map Future> _fetchMarriageData({ required int pageNum, required int type, int? code }) async { try { print('_fetchMarriageData - pageNum: $pageNum, pageSize: $pageSize, type: $type'); // 调用API获取数据 var response = await _homeApi.getMarriageList( pageNum: pageNum, pageSize: pageSize, type: type, cityCode: type == 1 ? code : null ); if (response.data.isSuccess) { final paginatedData = response.data.data; // 检查data是否为空 if (paginatedData == null) { return { 'records': [], 'current': pageNum, 'pages': 1, 'total': 0, 'size': pageSize, }; } // data 是 PaginatedResponse,直接使用其属性 // records 中的每个项是 dynamic,需要转换为 MarriageData final allRecords = paginatedData.records .map((item) => MarriageData.fromJson(item as Map)) .toList(); // 过滤掉直播类型的项 final records = allRecords.where((item) => !item.isLive).toList(); print('_fetchMarriageData 返回 - 请求页码: $pageNum, 返回当前页: ${paginatedData.current}, 总页数: ${paginatedData.pages}, 原始记录数: ${allRecords.length}, 过滤后记录数: ${records.length}'); return { 'records': records, 'current': paginatedData.current, 'pages': paginatedData.pages, 'total': paginatedData.total, 'size': paginatedData.size, }; } else { // 响应失败,抛出异常 throw Exception(response.data.message); } } catch (e) { // 向上抛出异常,让调用方处理 rethrow; } } /// 私有方法:统一的错误处理 void _handleError(String logMessage, dynamic error, String toastMessage) { // 打印错误日志 print('$logMessage: $error'); // 显示错误提示 SmartDialog.showToast(toastMessage); } }