import 'dart:io'; import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:dio/dio.dart'; import 'package:ttstd_family_care/app/constants/app_constants.dart'; import 'package:ttstd_family_care/core/network/api_exception.dart'; import 'package:ttstd_family_care/core/network/dio_client.dart'; import 'package:ttstd_family_care/features/device/domain/device_models.dart'; /// 客户端(家属端)设备接口访问层。 /// /// 后端接口前缀为 `/api/v1/client/sn`(与登录接口所在的 `/api/v1/open` 不同), /// 由于 Dio 在 path 以 `/` 开头时会替换 baseUrl 的完整 path 段(保留 host), /// 这里直接使用绝对路径即可正确命中 client 接口。 /// [DioClient.get] 已统一解析为后台返回体中的 `data` 字段;业务失败时抛出 /// [ApiException],本层将其降级为「空数据」以适配家属端展示。 class DeviceApi { const DeviceApi(); /// 获取当前用户已绑定的设备列表。 Future> getMyDevices() async { try { final data = await DioClient.get( 'v1/client/sn/my-devices', allowStale: true, ); return _parseList(data, DeviceBrief.fromJson); } on ApiException { return const []; } } /// 请求绑定设备(手动输入 SN 或扫码得到 SN 后调用)。 /// /// 对应后台 `POST /api/v1/client/sn/bind-request`: /// 后端校验设备存在后推送绑定请求到设备端,由设备端弹窗确认; /// 设备同意后完成绑定。因此本接口成功仅表示「绑定请求已发送」。 /// /// 成功返回 null;失败返回后台错误提示。 Future bindDevice(String sn, {String? remark}) async { try { final queryParameters = {'sn': sn}; if (remark != null && remark.isNotEmpty) { queryParameters['remark'] = remark; } final data = await DioClient.post( 'v1/client/sn/bind-request', queryParameters: queryParameters, ); debugPrint('[DeviceApi] bindDevice sn=$sn data=$data'); return null; } on ApiException catch (e) { debugPrint('[DeviceApi] bindDevice sn=$sn failed: ${e.message}'); return e.message; } } /// 解绑设备。 /// /// 成功返回 null;失败返回后台错误提示。 Future unbindDevice(String sn) async { try { final data = await DioClient.post( 'v1/client/sn/unbind', queryParameters: {'sn': sn}, ); await DioClient.invalidateReadCache('v1/client/sn/my-devices'); debugPrint('[DeviceApi] unbindDevice sn=$sn data=$data'); return null; } on ApiException catch (e) { debugPrint('[DeviceApi] unbindDevice sn=$sn failed: ${e.message}'); return e.message; } } /// 获取已绑定设备基本信息(无上报数据时返回 null)。 Future getDeviceInfo(String sn) async { try { final data = await DioClient.get( 'v1/client/sn/device-info', allowStale: true, queryParameters: {'sn': sn}, ); return data is Map ? DeviceSystemInfo.fromJson(data) : null; } on ApiException { return null; } } /// 获取已绑定设备最新定位信息(无上报数据时返回 null)。 Future getLocation(String sn) async { try { final data = await DioClient.get( 'v1/client/sn/location', allowStale: true, queryParameters: {'sn': sn}, ); return data is Map ? DeviceLocation.fromJson(data) : null; } on ApiException { return null; } } /// 获取已绑定设备已安装应用列表。 Future> getApks(String sn) async { try { final data = await DioClient.get( 'v1/client/sn/apks', allowStale: true, queryParameters: {'sn': sn}, ); return _parseList(data, DeviceApkInfo.fromJson); } on ApiException { return const []; } } /// 获取已绑定设备策略信息(功能开关)。 /// /// 对应后台 `GET /api/v1/client/sn/policy?sn=xxx`;SN 合法且无记录时自动新建默认策略。 /// 失败时返回 null。 Future getPolicy(String sn) async { try { final data = await DioClient.get( 'v1/client/sn/policy', allowStale: true, queryParameters: {'sn': sn}, ); return data is Map ? DevicePolicy.fromJson(data) : null; } on ApiException { return null; } } /// 读取本地策略快照,不发起网络请求。 Future getCachedPolicy(String sn) async { final data = await DioClient.readCachedGet( 'v1/client/sn/policy', queryParameters: {'sn': sn}, ); return data is Map ? DevicePolicy.fromJson(data) : null; } /// 单独设置某个策略开关。 /// /// 对应后台 `PUT /api/v1/client/sn/policy/toggle`,请求体 `{field, value}`。 /// 成功返回 null;失败返回后台错误提示。 Future togglePolicy(String sn, String field, int value) async { try { final data = await DioClient.put( 'v1/client/sn/policy/toggle?sn=${Uri.encodeQueryComponent(sn)}', data: {'field': field, 'value': value}, ); debugPrint('[DeviceApi] togglePolicy sn=$sn field=$field value=$value data=$data'); await DioClient.invalidateReadCache( 'v1/client/sn/policy', queryParameters: {'sn': sn}, ); return null; } on ApiException catch (e) { debugPrint('[DeviceApi] togglePolicy sn=$sn field=$field value=$value failed: ${e.message}'); return e.message; } } /// 向设备下发操作指令(重启/关机/截屏/刷新/定位/拍照等)。 /// /// [op] 为后端操作标识,如 `reboot` / `shutdown` / `screenshot` / `refresh` / `locate` / `take_photo`, /// 对应接口路径 `/api/v1/client/sn/ops/{op}?sn=xxx`。 /// [extra] 为可选的附加 query 参数(如远程拍照时的 `camera`:`0` 后置 / `1` 前置)。 /// 成功返回 null;失败返回后台错误提示。 Future sendDeviceOp(String sn, String op, {Map? extra}) async { try { final queryParameters = {'sn': sn}; if (extra != null) queryParameters.addAll(extra); final data = await DioClient.post( 'v1/client/sn/ops/$op', queryParameters: queryParameters, ); debugPrint('[DeviceApi] sendDeviceOp op=$op sn=$sn extra=$extra data=$data'); return null; } on ApiException catch (e) { debugPrint('[DeviceApi] sendDeviceOp op=$op sn=$sn failed: ${e.message}'); return e.message; } } /// 反向拨号:向设备下发拨号指令,由设备主动呼叫指定手机号。 /// /// 对应后台 `POST /api/v1/client/sn/reverse-dial?sn=xxx&phone=xxx`。 /// 成功返回 null;失败返回后台错误提示。 Future reverseDial(String sn, String phone) async { try { await DioClient.post( 'v1/client/sn/reverse-dial', queryParameters: {'sn': sn, 'phone': phone}, ); debugPrint('[DeviceApi] reverseDial sn=$sn phone=$phone success'); return null; } on ApiException catch (e) { debugPrint('[DeviceApi] reverseDial sn=$sn phone=$phone failed: ${e.message}'); return e.message; } } /// 上传单个壁纸(家属端),保存为设备单个壁纸并推送设备。 /// /// 对应后台 `POST /api/v1/client/sn/wallpaper/single?sn=xxx`(multipart)。 /// 返回记录:成功时 [url] 为保存后的图片 URL、[fileSize] 为文件大小(字节), /// 失败时 [error] 为错误提示。 Future<({String? url, int? fileSize, String? error})> uploadWallpaperSingle( String sn, File file) async { try { final formData = FormData.fromMap({ 'file': await MultipartFile.fromFile(file.path, filename: file.uri.pathSegments.last), }); final data = await DioClient.postMultipart( 'v1/client/sn/wallpaper/single', formData: formData, queryParameters: {'sn': sn}, ); debugPrint('[DeviceApi] uploadWallpaperSingle sn=$sn success'); final map = data is Map ? data : null; final rawSize = map?['fileSize']; return ( url: map?['url'] as String?, fileSize: (rawSize is int) ? rawSize : null, error: null, ); } on ApiException catch (e) { debugPrint( '[DeviceApi] uploadWallpaperSingle sn=$sn failed: ${e.message}'); return (url: null, fileSize: null, error: e.message); } } /// 上传轮换壁纸(家属端),保存为设备轮换壁纸(最多 7 张)并推送设备。 /// /// 对应后台 `POST /api/v1/client/sn/wallpaper/rotation?sn=xxx`(multipart)。 /// 返回记录:成功时 [urls] 为按顺序保存的图片 URL 列表,失败时 [error] 为错误提示。 Future<({List? urls, String? error})> uploadWallpaperRotation( String sn, List files) async { try { final formData = FormData(); for (final file in files) { formData.files.add(MapEntry( 'files', await MultipartFile.fromFile(file.path, filename: file.uri.pathSegments.last), )); } final data = await DioClient.postMultipart( 'v1/client/sn/wallpaper/rotation', formData: formData, queryParameters: {'sn': sn}, ); final urls = data is List ? data .whereType() .map((e) => e['url'] as String?) .whereType() .toList() : null; debugPrint( '[DeviceApi] uploadWallpaperRotation sn=$sn count=${files.length} success'); return (urls: urls, error: null); } on ApiException catch (e) { debugPrint( '[DeviceApi] uploadWallpaperRotation sn=$sn failed: ${e.message}'); return (urls: null, error: e.message); } } /// 调整壁纸展示顺序(家属端)。 /// /// 对应后台 `POST /api/v1/client/sn/wallpaper/reorder?sn=xxx`,body 携带按新顺序排列的图片URL。 /// 成功返回 null;失败返回后台错误提示。 Future reorderWallpaper(String sn, List urls) async { try { await DioClient.post( 'v1/client/sn/wallpaper/reorder', data: {'images': urls}, queryParameters: {'sn': sn}, ); debugPrint('[DeviceApi] reorderWallpaper sn=$sn success, order=$urls'); return null; } on ApiException catch (e) { debugPrint('[DeviceApi] reorderWallpaper sn=$sn failed: ${e.message}'); return e.message; } } /// 获取设备壁纸配置(家属端)。 /// /// 对应后台 `GET /api/v1/client/sn/wallpaper?sn=xxx`。 /// 未配置或无数据时返回 null。 Future getWallpaperConfig(String sn) async { try { final data = await DioClient.get( 'v1/client/sn/wallpaper', allowStale: true, queryParameters: {'sn': sn}, ); return data is Map ? WallpaperConfig.fromJson(data) : null; } on ApiException { return null; } } /// 发送图片到设备(家属端),设备收到推送后弹窗显示图片。 /// /// 独立于壁纸接口:对应后台 `POST /api/v1/client/sn/picture/send?sn=xxx`(multipart)。 /// [favorite] 是否标记收藏,默认 false。 /// 成功返回 null;失败返回后台错误提示。 Future sendPicture(String sn, File file, {bool favorite = false}) async { try { final formData = FormData.fromMap({ 'file': await MultipartFile.fromFile(file.path, filename: file.uri.pathSegments.last), }); await DioClient.postMultipart( 'v1/client/sn/picture/send', formData: formData, queryParameters: {'sn': sn, 'favorite': favorite ? 1 : 0}, ); debugPrint('[DeviceApi] sendPicture sn=$sn favorite=$favorite success'); return null; } on ApiException catch (e) { debugPrint('[DeviceApi] sendPicture sn=$sn failed: ${e.message}'); return e.message; } } /// 查询已发送到设备的图片列表(家属端)。 /// /// 对应后台 `GET /api/v1/client/sn/picture/list?sn=xxx`(按发送时间倒序)。 /// 返回补全源地址的图片信息列表(含收藏状态)。 Future> getPictureList(String sn) async { final payload = await DioClient.get( 'v1/client/sn/picture/list', allowStale: true, queryParameters: {'sn': sn}, ); final list = payload is Map ? payload['data'] : payload; if (list is! List) throw const FormatException('Invalid picture list'); final base = Uri.parse(AppConstants.kBaseUrl); final pictures = []; for (final row in list.whereType()) { if (row['url'] is! String) continue; final picture = DevicePictureInfo.fromJson(Map.from(row)); final path = picture.url.trim(); if (path.isEmpty) continue; final relative = Uri.tryParse(path); if (relative == null) continue; final uri = base.resolveUri(relative); if (!uri.isScheme('http') && !uri.isScheme('https')) continue; pictures.add(DevicePictureInfo( url: uri.toString(), sourceUrl: picture.url, favorite: picture.favorite, fileSize: picture.fileSize, )); } return pictures; } Future deletePicture(String sn, String url) async { final uri = Uri( path: 'v1/client/sn/picture', queryParameters: {'sn': sn, 'url': url}, ); await DioClient.delete(uri.toString()); await DioClient.invalidateReadCache( 'v1/client/sn/picture/list', queryParameters: {'sn': sn}, ); } /// 设置图片收藏状态(家属端)。 /// /// 对应后台 `POST /api/v1/client/sn/picture/favorite?sn=xxx&url=xxx&favorite=0|1`。 /// 成功返回 null;失败返回后台错误提示。 Future setPictureFavorite( String sn, String url, bool favorite) async { try { await DioClient.post( 'v1/client/sn/picture/favorite', queryParameters: { 'sn': sn, 'url': url, 'favorite': favorite ? 1 : 0, }, ); debugPrint( '[DeviceApi] setPictureFavorite sn=$sn favorite=$favorite success'); return null; } on ApiException catch (e) { debugPrint( '[DeviceApi] setPictureFavorite sn=$sn failed: ${e.message}'); return e.message; } } /// 对指定应用执行操作(打开/停止/卸载/清除数据)。 /// /// [op] 为后端操作标识:`launch` / `stop` / `uninstall` / `clear_data`, /// 对应接口路径 `/api/v1/client/sn/ops/app/{op}?sn=xxx`,请求体携带应用包名。 /// 成功返回 null;失败返回后台错误提示。 Future sendAppOp(String sn, String op, String packageName) async { try { final data = await DioClient.post( 'v1/client/sn/ops/app/$op', queryParameters: {'sn': sn}, data: {'packageName': packageName}, ); debugPrint('[DeviceApi] sendAppOp op=$op sn=$sn pkg=$packageName data=$data'); return null; } on ApiException catch (e) { debugPrint('[DeviceApi] sendAppOp op=$op sn=$sn pkg=$packageName failed: ${e.message}'); return e.message; } } // --------------------------------------------------------------------------- static List _parseList( dynamic data, T Function(Map) fromJson, ) { if (data is! List) return const []; return data .whereType>() .map(fromJson) .toList(growable: false); } // --------------------------------------------------------------------------- /// 获取设备最近截图列表(家属端)。 /// /// [sn] 为设备序列号(可空,由后台按绑定关系补全)。 /// 返回 [ScreenshotVO] 列表,并自动补全图片可访问的完整 URL(拼接 baseUrl)。 Future> getRecentScreenshots({String? sn}) async { final query = sn != null && sn.isNotEmpty ? {'sn': sn} : {}; // DioClient.get 已统一解析出响应体中的 data 字段, // 后台返回结构为 { code, msg, data: [...] },故此处 payload 即为截图数组。 final payload = await DioClient.get( 'v1/client/sn/upload-screenshot', allowStale: true, queryParameters: query, ); // 防御性提取:兼容后台直接返回 List,或返回 { data: [...] } 的包裹结构。 final List listData; if (payload is List) { listData = payload; } else if (payload is Map && payload['data'] is List) { listData = payload['data'] as List; } else { debugPrint('[DeviceApi] getRecentScreenshots 返回非预期结构: sn=$sn payload=$payload'); return const []; } debugPrint('[DeviceApi] getRecentScreenshots sn=$sn count=${listData.length}'); final origin = Uri.parse(AppConstants.kBaseUrl).origin; return listData.whereType>().map((e) { final vo = ScreenshotVO.fromJson(e); // 后台返回的 url 为相对路径(如 /static/screenshot/xxx),补全为完整地址。 final raw = vo.url; final fullUrl = (raw != null && raw.startsWith('/')) ? '$origin$raw' : (raw ?? ''); return ScreenshotVO( id: vo.id, sn: vo.sn, fileName: vo.fileName, fileSize: vo.fileSize, url: fullUrl, uploadTime: vo.uploadTime, ); }).toList(growable: false); } /// 删除单张设备截图(家属端 client 接口)。 /// /// [sn] 设备序列号,[id] 截图ID。成功返回 null;失败返回后台错误提示。 Future deleteScreenshot(String sn, int id) async { try { await DioClient.delete( 'v1/client/sn/ops/screenshots/$id?sn=${Uri.encodeQueryComponent(sn)}', ); debugPrint('[DeviceApi] deleteScreenshot sn=$sn id=$id success'); return null; } on ApiException catch (e) { debugPrint('[DeviceApi] deleteScreenshot sn=$sn id=$id failed: ${e.message}'); return e.message; } } /// 清空设备全部截图(家属端 client 接口)。 /// /// [sn] 设备序列号。成功返回 null;失败返回后台错误提示。 Future clearScreenshots(String sn) async { try { await DioClient.delete( 'v1/client/sn/ops/screenshots?sn=${Uri.encodeQueryComponent(sn)}', ); debugPrint('[DeviceApi] clearScreenshots sn=$sn success'); return null; } on ApiException catch (e) { debugPrint('[DeviceApi] clearScreenshots sn=$sn failed: ${e.message}'); return e.message; } } }