70 lines
2.5 KiB
Dart
70 lines
2.5 KiB
Dart
import 'package:dio/dio.dart';
|
||
import 'package:get_it/get_it.dart';
|
||
import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart';
|
||
import 'package:maibu_satabot_v2/core/consts/http_api_consts.dart';
|
||
import 'package:maibu_satabot_v2/core/storage/user_storage.dart';
|
||
import 'package:maibu_satabot_v2/features/v2/home/data/datasources/site_datasource.dart';
|
||
import 'package:maibu_satabot_v2/features/v2/home/domain/entities/site_entity.dart';
|
||
|
||
class SiteDataSourceImpl implements SiteDataSource {
|
||
final Dio dio;
|
||
final UserStorage _userStorage;
|
||
final AppUserCubit _appUserCubit;
|
||
|
||
SiteDataSourceImpl(this.dio, this._userStorage, this._appUserCubit);
|
||
|
||
@override
|
||
Future<List<SiteEntity>> getSiteList(int orgId) async {
|
||
print('🔍 [SiteDataSource] 开始获取 Token...');
|
||
print('🔍 [SiteDataSource] AppUserCubit 当前用户: ${_appUserCubit.state.user?.username}');
|
||
|
||
// 优先从全局状态获取 Token(更快更可靠)
|
||
var token = _appUserCubit.state.user?.token;
|
||
|
||
print('🔍 [SiteDataSource] 从 AppUserCubit 获取的 Token: ${token != null ? "${token.substring(0, 20)}..." : "null"}');
|
||
|
||
// 如果全局状态没有,再从本地存储获取
|
||
if (token == null) {
|
||
print('⚠️ [SiteDataSource] AppUserCubit 没有 Token,尝试从本地存储获取...');
|
||
final user = await _userStorage.getUser();
|
||
token = user?.token;
|
||
print('🔍 [SiteDataSource] 从本地存储获取的 Token: ${token != null ? "${token.substring(0, 20)}..." : "null"}');
|
||
}
|
||
|
||
print('🔑 [SiteDataSource] 获取到的 Token: ${token != null ? "${token.substring(0, 20)}..." : "null"}');
|
||
|
||
// 构建查询参数:orgId 为 0 时不传递
|
||
final queryParams = <String, dynamic>{
|
||
'pageNum': 1,
|
||
'pageSize': 9999,
|
||
};
|
||
|
||
if (orgId != 0) {
|
||
queryParams['orgId'] = orgId;
|
||
}
|
||
|
||
final response = await dio.get(
|
||
HttpApiConsts.getSiteList,
|
||
queryParameters: queryParams,
|
||
options: Options(
|
||
headers: {
|
||
'Authorization': token != null ? 'Bearer $token' : '',
|
||
},
|
||
),
|
||
);
|
||
|
||
if (response.statusCode != 200) {
|
||
throw Exception('网络请求失败: ${response.statusCode}');
|
||
}
|
||
|
||
final responseData = response.data;
|
||
|
||
if (responseData['code'] != 200) {
|
||
throw Exception(responseData['msg'] ?? '业务异常');
|
||
}
|
||
|
||
final List<dynamic> rows = responseData['rows'] ?? [];
|
||
return rows.map((item) => SiteEntity.fromJson(item)).toList();
|
||
}
|
||
}
|