diff --git a/docs/9.9.1/review/product-comparison/current-baseline.md b/docs/9.9.1/review/product-comparison/current-baseline.md index 6bfd142..8b55b60 100644 --- a/docs/9.9.1/review/product-comparison/current-baseline.md +++ b/docs/9.9.1/review/product-comparison/current-baseline.md @@ -35,6 +35,8 @@ | C18 | 执行中切换景区 | 允许切换景区,原任务继续执行;切换后展示新景区订单,需要查看原任务时切回原景区。 | 不增加执行中禁止切景区的限制;各景区数据与任务上下文分开。 | | C19 | 主动紧急暂停 | 点击“紧急暂停”直接提交暂停请求,不弹二次确认;提交后显示“暂停处理中”,设备确认后再显示已暂停/已悬停。 | 指令处理中、明确生效、失败、结果未知分别展示;防重复点击。 | | C20 | 现场收款页范围 | **必须新增一个支持选择套餐的收款页面,不能直接复用原有不支持套餐选择的收款页面。** 用户在本次要求中已明确。 | 新收款入口、套餐选择、收款码及支付过程的状态需完整覆盖;详细交互以产品原型实测补齐。 | +| C21 | 主动立即返航 | 2026-10-23 用户要求到产品体验网页核对。实际点击后不弹二次确认,直接显示“正在发送返航指令/尚未确认返航”;原型随后模拟设备回执。App 界面采用直接提交,仍须区分提交和设备确认。 | 点击后禁重复发送;收到明确回执前不宣称已返航。原 U02 已补齐。 | +| C22 | 本轮搭建范围 | 2026-10-23 用户明确先跳过收款页面,继续搭建拍摄准备和当前任务,暂不接真实接口。 | 收款入口继续占位;本地演示事件不发送真实设备指令。 | 说明:C10/C11 是对之前“当前任务订单置顶”规则的明确例外:剩余次数为 0 的订单立即退出首页,未结束任务入口转移到“已完成”订单卡片,不继续留首页。 @@ -123,10 +125,11 @@ | 编号 | 事项 | 当前边界 | | --- | --- | --- | | U01 | “交付成片”点击事件 | 用户明确说稍后再告知、先跳过。原型即使展示二维码、分享或交付标记,也只能记为产品原型行为,不能当作用户已确认。 | -| U02 | 主动“立即返航”是否二次确认 | 最后提出的 A/B 问题尚未回答,随后用户要求暂停提问。A 是二次确认,B 是直接提交;两者都不能标成已确认。保护性自动返航无需此人工决策。 | | U03 | 新收款页的完整页面状态 | 新增并支持选择套餐已经明确;套餐列表、选中、收款码、支付结果、异常与返回等具体状态,需要本次跑产品原型后整理。 | | U04 | App 与后端/设备的契约 | 任务成功判据、部分拍摄结算、原子占用、命令能力、最终上传失败处理等仍需接口对齐;不应擅自落成 App 自行判断的业务规则。 | +原 U02 已按 2026-10-23 用户指示实际核对产品网页,移入 C21;核对结果见新增页面实现说明及 `../../shooting-ui-2026-10-23/prototype-return-result.txt`。 + ## 五、对本次原型比对的使用建议 1. 将每项原型观察记录成“页面入口 → 操作 → 可见状态 → 可执行按钮 → 返回/恢复”,标明实际点击到、仅状态模拟器提供或未验证。 diff --git a/docs/9.9.1/shooting-ui-2026-10-23/preparation-occupied.png b/docs/9.9.1/shooting-ui-2026-10-23/preparation-occupied.png new file mode 100644 index 0000000..dbfa694 Binary files /dev/null and b/docs/9.9.1/shooting-ui-2026-10-23/preparation-occupied.png differ diff --git a/docs/9.9.1/shooting-ui-2026-10-23/preparation-ready.png b/docs/9.9.1/shooting-ui-2026-10-23/preparation-ready.png new file mode 100644 index 0000000..aa7a73c Binary files /dev/null and b/docs/9.9.1/shooting-ui-2026-10-23/preparation-ready.png differ diff --git a/docs/9.9.1/shooting-ui-2026-10-23/preparation-unknown.png b/docs/9.9.1/shooting-ui-2026-10-23/preparation-unknown.png new file mode 100644 index 0000000..02011f8 Binary files /dev/null and b/docs/9.9.1/shooting-ui-2026-10-23/preparation-unknown.png differ diff --git a/docs/9.9.1/shooting-ui-2026-10-23/prototype-return-result.jpg b/docs/9.9.1/shooting-ui-2026-10-23/prototype-return-result.jpg new file mode 100644 index 0000000..9e46a34 Binary files /dev/null and b/docs/9.9.1/shooting-ui-2026-10-23/prototype-return-result.jpg differ diff --git a/docs/9.9.1/shooting-ui-2026-10-23/prototype-return-result.txt b/docs/9.9.1/shooting-ui-2026-10-23/prototype-return-result.txt new file mode 100644 index 0000000..b7b7044 --- /dev/null +++ b/docs/9.9.1/shooting-ui-2026-10-23/prototype-return-result.txt @@ -0,0 +1,74 @@ +Browser tab: 1, Title: "机巢 · 页面内交互体验", URL: "https://voicestudio.suixinkan.cn/". +0 AXWebArea 机巢 · 页面内交互体验, URL: voicestudio.suixinkan.cn/ + 1 container + 2 pop up button (collapsed) Description: Preview device: iPhone, ID: radix-_r_0_, Secondary Actions: Expand + 3 container + 4 container Device status bar + 5 text 4:14 + 6 container + 207 container + 208 button 返回 + 209 image + 210 heading 拍摄任务, Value: 1 + 211 text 拍摄任务 + 212 text 交互原型 · 无真实操作 + 213 button 体验本页其他状态 + 214 image + 215 text 体验其他状态 + 216 container + 217 heading 三皇寨 · 经典航线, Value: 2 + 218 text 三皇寨 · 经典航线 + 219 container + 220 text 游客 136****2806 · 含 1 次拍摄 + 221 container 无人机直播画面 + 222 image 无人机视角的游客取景演示画面 + 271 image + 224 text 上次任务画面 + 225 button 放大直播画面 + 226 image + 227 container 无人机六项状态 + 228 text 电池电量 + 229 container + 230 image + 231 text 95% + 232 text 环境温度 + 233 container + 234 image + 235 text 20.3°C + 236 text 风速 + 237 container + 238 image + 239 text 0m/s + 240 text 雨量 + 241 container + 242 image + 243 text 无雨 + 244 text 信号状态 + 245 container + 246 image + 247 text 良好 + 248 text 搜星状态 + 249 container + 250 image + 251 text 36颗 + 252 container + 272 image + 254 heading 本次拍摄已中断, Value: 2 + 255 text 本次拍摄已中断 + 258 text 无人机已返回机巢,本次未扣减拍摄次数。 +可重新选择点位和航线开始任务。 + 259 button 重新召唤无人机 + 260 image + 261 text 重新召唤无人机 + 262 text 安全控制 + 263 button (disabled) 紧急暂停 当前未执行任务 + 264 image + 265 text 紧急暂停 + 266 text 当前未执行任务 + 267 button (disabled) 立即返航 当前未执行任务 + 273 image + 269 text 立即返航 + 270 text 当前未执行任务 + 206 image + +The focused UI element is 0 AXWebArea 机巢 · 页面内交互体验, URL: voicestudio.suixinkan.cn/ \ No newline at end of file diff --git a/docs/9.9.1/shooting-ui-2026-10-23/task-arrived.png b/docs/9.9.1/shooting-ui-2026-10-23/task-arrived.png new file mode 100644 index 0000000..92c210d Binary files /dev/null and b/docs/9.9.1/shooting-ui-2026-10-23/task-arrived.png differ diff --git a/docs/9.9.1/shooting-ui-2026-10-23/task-command-unconfirmed.png b/docs/9.9.1/shooting-ui-2026-10-23/task-command-unconfirmed.png new file mode 100644 index 0000000..3dd0a43 Binary files /dev/null and b/docs/9.9.1/shooting-ui-2026-10-23/task-command-unconfirmed.png differ diff --git a/docs/9.9.1/shooting-ui-2026-10-23/task-paused.png b/docs/9.9.1/shooting-ui-2026-10-23/task-paused.png new file mode 100644 index 0000000..7a7d60e Binary files /dev/null and b/docs/9.9.1/shooting-ui-2026-10-23/task-paused.png differ diff --git a/docs/9.9.1/shooting-ui-2026-10-23/task-phone-offline.png b/docs/9.9.1/shooting-ui-2026-10-23/task-phone-offline.png new file mode 100644 index 0000000..e714239 Binary files /dev/null and b/docs/9.9.1/shooting-ui-2026-10-23/task-phone-offline.png differ diff --git a/docs/9.9.1/shooting-ui-2026-10-23/task-stream-lost.png b/docs/9.9.1/shooting-ui-2026-10-23/task-stream-lost.png new file mode 100644 index 0000000..06ed071 Binary files /dev/null and b/docs/9.9.1/shooting-ui-2026-10-23/task-stream-lost.png differ diff --git a/docs/9.9.1/shooting-ui-2026-10-23/task-success-return-paused.png b/docs/9.9.1/shooting-ui-2026-10-23/task-success-return-paused.png new file mode 100644 index 0000000..c5221fc Binary files /dev/null and b/docs/9.9.1/shooting-ui-2026-10-23/task-success-return-paused.png differ diff --git a/docs/9.9.1/shooting-ui-2026-10-23/task-zero-quota-returning.png b/docs/9.9.1/shooting-ui-2026-10-23/task-zero-quota-returning.png new file mode 100644 index 0000000..a93f774 Binary files /dev/null and b/docs/9.9.1/shooting-ui-2026-10-23/task-zero-quota-returning.png differ diff --git a/docs/9.9.1/拍摄流程UI实现说明.md b/docs/9.9.1/拍摄流程UI实现说明.md new file mode 100644 index 0000000..859b6ce --- /dev/null +++ b/docs/9.9.1/拍摄流程UI实现说明.md @@ -0,0 +1,73 @@ +# 9.9.1 拍摄准备与当前任务 UI + +实现日期:2026-10-23。分支:`dev_9_9_1`。 + +## 本轮范围 + +已从工作台和“我的拍摄订单”的拍摄按钮接通以下本地页面: + +- 拍摄准备:订单额度、横向拍摄点、纵向航线单选、底部机巢连接/范围/设备许可、召唤及阻断提示。 +- 当前任务:点位航线及游客摘要、原型同款本地演示画面及放大、六项遥测、任务状态、指令回执、开始/暂停/继续/返航、成功及失败提示。 +- 页面共用同一内存数据源,不调用真实拍摄接口,不控制无人机,不请求定位或相机权限。静态演示画面不表示真实图传。 +- 收款继续暂缓,素材及交付继续保留入口提示;本轮不实现这些下级业务。 + +## 与原型及确认规则的对应 + +| 场景 | 已实现的交互 | +| --- | --- | +| 点位和航线 | 整卡/整行单选;切点读取该点航线,切回恢复仍有效的选择;配置失效清空选择;范围外仍可浏览和选择,但不能召唤。 | +| A 订单正在执行,打开 B | B 可进入准备并选择点位航线;底部显示占用,召唤禁用,不增加排队或自动起飞。 | +| 召唤提交 | 先显示处理中,冻结此次选择、防重复提交;明确确认后进入原任务;超时只提示待确认与同步,不自动重新召唤。 | +| 从任务返回 | 左上返回直接回工作台,不弹确认、不取消任务、不扣次;再点“查看当前任务”恢复同一个任务身份。 | +| 开始/暂停/继续/返航 | 点击仅提交指令;设备回执与按钮点击分开建模,明确回执后才改变执行阶段。 | +| 立即返航是否确认 | 用户要求按产品体验网页核对;2026-10-23 实际点击无二次确认,先出现“正在发送返航指令/尚未确认返航”。本轮按直接提交实现。见[核对证据](shooting-ui-2026-10-23/prototype-return-result.txt)。 | +| 成功与返航 | 确认成功只扣一次;结果与飞行独立;0 次立即移出首页,但已完成订单仍能查看未结束的原任务。返航暂停时可继续返航,仍保留素材入口。 | +| 失败后重试 | 失败不扣次;飞行未结束或设备未恢复可用时禁止重新准备;允许后回准备页恢复有效选择,需再次手动召唤。 | +| 手机网络与图传 | 仅断流可重连画面,状态和控制保持独立;手机离线显示未更新与“—”,禁发指令,恢复后先同步原任务。 | +| 未知/保护性返航 | 指令未知不等于失败、不自动重发;保护性返航展示原因,拍摄结果仍独立确认。 | + +原型离页确认、“重新召唤”直重试等行为与既定规则不一致,本轮继续以已确认规则为准。完整依据见[当前方案基线](review/product-comparison/current-baseline.md)。 + +## 如何演示 + +Debug 版“全部功能 → 机巢预览”,点击订单“开始拍摄/继续拍摄”,或从订单列表进入。 + +1. 准备页右上角可选正常、占用、未连接、无信号、低电量、未知、范围外、位置未知、无点位、无航线、次数用完等本地场景。 +2. 正常选择后点击“确认并召唤无人机”,页面停留在召唤处理中。右上角选择“模拟召唤确认”才进入任务页。 +3. 任务页的“模拟状态”菜单可明确注入到达、拍摄、暂停/恢复处理中、返航、成功/失败、断流、手机断网、保护返航及指令待确认等回执。 +4. 演示不使用定时器自动推进。点击真实样式的操作按钮先保留处理中,再用模拟状态菜单提供明确设备回执。刷新和重连仅开始同步过程,不伪装已经恢复。 + +可选启动参数: + +| 参数 | 入口 | +| --- | --- | +| `--dock-ui-preparation-preview` | 直达本地准备页 | +| `--dock-preparation-scenario=occupied` | 准备页初始占用 | +| `--dock-ui-task-preview` | 直达本地任务,默认已到达 | +| `--dock-task-scenario=phoneOffline` | 任务页初始手机断网 | +| `--dock-task-scenario=succeededReturning` | 成功但仍返航 | + +这些入口仅在 Debug 生效,不改变正常启动规则或真实登录身份;关闭启动参数后恢复原有首页。 + +## 素材与验证 + +- 三张静态图片直接取自用户指定的产品原型可见素材:`assets/tourist-photo.png`、`assets/point-mountain.png`、`assets/point-pagoda.png`,保存为 Asset Catalog 本地演示资源。不是从网页截图裁出 UI,也不发起远程图传。 +- 真机截图由 XCTest 临时窗口渲染,系统状态栏不在截图内。 +- iPhone 11 真机验证通过:`DroneShootingSessionViewModelTests` 24 项、`DroneShootingFlowViewTests` 6 项,以及上一轮机巢测试 15 项,共 **45 项、0 失败**;未运行模拟器单元测试,也未进行全工程回归。 +- 测试覆盖按身份恢复选择、占用准入、显式指令回执、防重复提交、成功幂等扣次、失败重试边界、离页恢复原任务、连接独立和可见约束布局;修复后重新验证通过。 + +## 真机截图 + +| 准备正常 | 占用仍可选线 | 设备未知 | +| --- | --- | --- | +| ![准备正常](shooting-ui-2026-10-23/preparation-ready.png) | ![占用](shooting-ui-2026-10-23/preparation-occupied.png) | ![未知](shooting-ui-2026-10-23/preparation-unknown.png) | + +| 任务已到达 | 已暂停 | 零次仍返航 | +| --- | --- | --- | +| ![已到达](shooting-ui-2026-10-23/task-arrived.png) | ![已暂停](shooting-ui-2026-10-23/task-paused.png) | ![零次返航](shooting-ui-2026-10-23/task-zero-quota-returning.png) | + +| 手机离线 | 仅图传断流 | 指令结果待确认 | +| --- | --- | --- | +| ![手机离线](shooting-ui-2026-10-23/task-phone-offline.png) | ![断流](shooting-ui-2026-10-23/task-stream-lost.png) | ![指令未知](shooting-ui-2026-10-23/task-command-unconfirmed.png) | + +[成功后返航暂停,保留继续返航与素材入口](shooting-ui-2026-10-23/task-success-return-paused.png)。 diff --git a/docs/9.9.1/机巢UI首轮实现说明.md b/docs/9.9.1/机巢UI首轮实现说明.md index 9bb0d56..f64f614 100644 --- a/docs/9.9.1/机巢UI首轮实现说明.md +++ b/docs/9.9.1/机巢UI首轮实现说明.md @@ -2,6 +2,8 @@ 实现日期:2026-10-23。当前分支:`dev_9_9_1`。 +后续更新:拍摄准备与当前任务已在第二轮补齐,参见[拍摄流程 UI 实现说明](拍摄流程UI实现说明.md)。本文记录首轮交付范围。 + ## 范围 - 机巢工作台:景区与工作人员、无人机遥测卡、设备横向翻页、余次订单、素材摘要、查看全部、今日统计。 diff --git a/suixinkan/Assets.xcassets/DroneDock/Contents.json b/suixinkan/Assets.xcassets/DroneDock/Contents.json new file mode 100644 index 0000000..d8b757a --- /dev/null +++ b/suixinkan/Assets.xcassets/DroneDock/Contents.json @@ -0,0 +1,3 @@ +{ + "info" : { "author" : "xcode", "version" : 1 } +} diff --git a/suixinkan/Assets.xcassets/DroneDock/drone_demo_mountain.imageset/Contents.json b/suixinkan/Assets.xcassets/DroneDock/drone_demo_mountain.imageset/Contents.json new file mode 100644 index 0000000..f7fd426 --- /dev/null +++ b/suixinkan/Assets.xcassets/DroneDock/drone_demo_mountain.imageset/Contents.json @@ -0,0 +1,4 @@ +{ + "images" : [ { "filename" : "drone_demo_mountain.png", "idiom" : "universal" } ], + "info" : { "author" : "xcode", "version" : 1 } +} diff --git a/suixinkan/Assets.xcassets/DroneDock/drone_demo_mountain.imageset/drone_demo_mountain.png b/suixinkan/Assets.xcassets/DroneDock/drone_demo_mountain.imageset/drone_demo_mountain.png new file mode 100644 index 0000000..bfe1fe9 Binary files /dev/null and b/suixinkan/Assets.xcassets/DroneDock/drone_demo_mountain.imageset/drone_demo_mountain.png differ diff --git a/suixinkan/Assets.xcassets/DroneDock/drone_demo_pagoda.imageset/Contents.json b/suixinkan/Assets.xcassets/DroneDock/drone_demo_pagoda.imageset/Contents.json new file mode 100644 index 0000000..7affda8 --- /dev/null +++ b/suixinkan/Assets.xcassets/DroneDock/drone_demo_pagoda.imageset/Contents.json @@ -0,0 +1,4 @@ +{ + "images" : [ { "filename" : "drone_demo_pagoda.png", "idiom" : "universal" } ], + "info" : { "author" : "xcode", "version" : 1 } +} diff --git a/suixinkan/Assets.xcassets/DroneDock/drone_demo_pagoda.imageset/drone_demo_pagoda.png b/suixinkan/Assets.xcassets/DroneDock/drone_demo_pagoda.imageset/drone_demo_pagoda.png new file mode 100644 index 0000000..36ba9cf Binary files /dev/null and b/suixinkan/Assets.xcassets/DroneDock/drone_demo_pagoda.imageset/drone_demo_pagoda.png differ diff --git a/suixinkan/Assets.xcassets/DroneDock/drone_demo_tourists.imageset/Contents.json b/suixinkan/Assets.xcassets/DroneDock/drone_demo_tourists.imageset/Contents.json new file mode 100644 index 0000000..69479a4 --- /dev/null +++ b/suixinkan/Assets.xcassets/DroneDock/drone_demo_tourists.imageset/Contents.json @@ -0,0 +1,4 @@ +{ + "images" : [ { "filename" : "drone_demo_tourists.png", "idiom" : "universal" } ], + "info" : { "author" : "xcode", "version" : 1 } +} diff --git a/suixinkan/Assets.xcassets/DroneDock/drone_demo_tourists.imageset/drone_demo_tourists.png b/suixinkan/Assets.xcassets/DroneDock/drone_demo_tourists.imageset/drone_demo_tourists.png new file mode 100644 index 0000000..2e24fb8 Binary files /dev/null and b/suixinkan/Assets.xcassets/DroneDock/drone_demo_tourists.imageset/drone_demo_tourists.png differ diff --git a/suixinkan/Features/DroneDock/Models/DroneShootingSessionModels.swift b/suixinkan/Features/DroneDock/Models/DroneShootingSessionModels.swift new file mode 100644 index 0000000..99c6245 --- /dev/null +++ b/suixinkan/Features/DroneDock/Models/DroneShootingSessionModels.swift @@ -0,0 +1,305 @@ +import Foundation + +/// 点位范围来自有效定位快照;选择点位不会改变范围判定。 +enum DroneShootingRange: Hashable, Sendable { + case inside + case outside(distanceText: String?) + case unknown + + /// 横向点位卡的距离或范围文字。 + var title: String { + switch self { + case .inside: "范围内" + case .outside(let distance): distance ?? "范围外" + case .unknown: "位置待确认" + } + } + + /// 底部许可栏的范围描述。 + var admissionTitle: String { + switch self { + case .inside: "点位范围内" + case .outside: "尚未进入范围" + case .unknown: "位置待确认" + } + } + + /// 范围标签的语义色。 + var tone: DroneDockStatusTone { self == .inside ? .green : .orange } +} + +/// 准备页一个稳定身份的拍摄点;同名点位不共享选择。 +struct DroneShootingPoint: Hashable, Sendable { + /// 点位标识。 + let id: String + /// 点位名称。 + let name: String + /// 最新有效的定位与范围判定。 + let range: DroneShootingRange + /// 本订单在该点已确认成功的次数。 + let successfulCount: Int + + /// 点位卡的拍摄记录摘要。 + var successfulCountText: String { successfulCount > 0 ? "已拍 \(successfulCount) 次" : "未拍摄" } +} + +/// 一条归属于单个点位的拍摄航线。 +struct DroneShootingRoute: Hashable, Sendable { + /// 航线标识,在点位内匹配,不以名称恢复选择。 + let id: String + /// 航线名称。 + let name: String +} + +/// 准备页召唤准入结果,页面只展示该结果,不自行合并设备和额度。 +enum DroneShootingAdmission: Hashable, Sendable { + case ready, currentTask, summoning, summonUnconfirmed, orderUnavailable, noQuota, noPoints, noPoint, noRoutes, noRoute + case outOfRange, unknownRange, occupied, disconnected, noSignal, lowBattery, unknownDevice + + /// 底部操作标题。 + var title: String { + switch self { + case .currentTask: "查看当前任务" + case .summoning: "召唤处理中" + case .summonUnconfirmed: "召唤结果待确认" + default: "确认并召唤无人机" + } + } + /// 当前是否允许创建新任务。 + var canSummon: Bool { self == .ready } + /// 准入提示语义色。 + var tone: DroneDockStatusTone { + switch self { + case .ready: .gray + case .currentTask: .blue + case .noSignal: .red + default: .orange + } + } + /// 明确说明当前许可或阻断原因。 + var message: String { + switch self { + case .ready: "每次拍摄成功后扣减 1 次,未成功不扣次数。" + case .currentTask: "本订单已有当前任务,请继续查看原任务。" + case .summoning: "等待设备确认召唤结果,请勿重复发送指令。" + case .summonUnconfirmed: "暂未确认是否已执行召唤,请同步原任务状态,勿重复召唤。" + case .orderUnavailable: "当前订单不可用,请返回工作台刷新。" + case .noQuota: "当前订单拍摄次数已用完" + case .noPoints: "当前景区暂无可用拍摄点,请稍后刷新。" + case .noPoint: "请选择拍摄点" + case .noRoutes: "当前拍摄点暂无可用航线" + case .noRoute: "请选择一条有效航线" + case .outOfRange: "请先进入所选拍摄点的范围" + case .unknownRange: "位置待确认,暂时无法召唤" + case .occupied: "无人机占用中,请稍后再试" + case .disconnected: "机巢未连接,请连接后重试" + case .noSignal: "无人机无信号,暂时无法召唤" + case .lowBattery: "电量不足,设备暂不允许执行" + case .unknownDevice: "无人机状态未知,请刷新确认" + } + } +} + +/// 手机网络和图传分别保存连接过程;点击重连不代表已经恢复。 +enum DroneShootingConnectionState: Hashable, Sendable { + case connected, disconnected, reconnecting, synchronizing +} + +/// 可独立追踪结果的设备指令。 +enum DroneShootingCommandKind: Hashable, Sendable { + case summon, start, pause, resume, returnHome + + /// 指令进行中的展示文字。 + var processingTitle: String { + switch self { + case .summon: "召唤处理中" + case .start: "开始拍摄处理中" + case .pause: "暂停处理中" + case .resume: "正在继续任务" + case .returnHome: "返航处理中" + } + } +} + +/// 指令处理与任务失败分离,超时只能表达结果未知。 +enum DroneShootingCommandStatus: Hashable, Sendable { + case processing, confirmed, unconfirmed, rejected(message: String) + + /// 尚无明确回执时禁止重复发送同一指令。 + var isUnresolved: Bool { self == .processing || self == .unconfirmed } +} + +/// 某一种操作最近一次指令的回执状态。 +struct DroneShootingCommand: Hashable, Sendable { + /// 操作类型。 + let kind: DroneShootingCommandKind + /// 当前处理结果。 + var status: DroneShootingCommandStatus +} + +/// 一个本地拍摄会话,飞行、拍摄结果、连接与指令各自独立。 +struct DroneShootingSession: Hashable, Sendable { + /// 任务稳定标识,重进页面不会变化。 + let id: String + /// 本次任务固定的拍摄点快照。 + let point: DroneShootingPoint + /// 本次任务固定的航线快照。 + let route: DroneShootingRoute + /// 最近一次明确设备回执的飞行阶段。 + var phase: DroneShootingTaskPhase + /// 拍摄结果,不通过飞行结束或超时推断成功。 + var result: DroneShootingResult + /// 明确回执的飞行结束标记。 + var isFlightFinished: Bool + /// 设备是否明确允许再次执行;不由电量百分比推导。 + var deviceReady: Bool + /// 该会话成功是否已经入账,用于重复成功回执去重。 + var successRecorded: Bool + /// 手机网络连接,不与图传合并。 + var phoneConnection: DroneShootingConnectionState + /// 独立的图传连接。 + var feedConnection: DroneShootingConnectionState + /// 最近有效的遥测;手机断网时页面显示未知占位。 + var telemetry: DroneDockTelemetry + /// 各操作分别记录回执,安全指令不覆盖开始指令的未知结果。 + var commands: [DroneShootingCommandKind: DroneShootingCommand] + /// 暂停前的明确阶段,用于恢复拍摄或返航。 + var phaseBeforePause: DroneShootingTaskPhase? + /// 设备给出的明确失败原因。 + var failureReason: String? + /// 设备触发的保护性返航原因。 + var protectiveReturnReason: String? + /// 结果弹窗已由工作人员关闭;刷新不会重复弹出。 + var resultNoticeDismissed: Bool + + /// 优先呈现尚未解决的操作,保留其他类型的独立回执。 + var command: DroneShootingCommand? { + let ordered = [DroneShootingCommandKind.returnHome, .pause, .resume, .start, .summon] + return ordered.compactMap { commands[$0] }.first { $0.status.isUnresolved } + ?? ordered.compactMap { commands[$0] }.first { + if case .rejected = $0.status { return true } + return false + } + } + + /// 飞行结束且结果明确后才移除当前任务入口。 + var hasCurrentTask: Bool { + !isFlightFinished || result == .unknown || result == .inProgress + } + + /// 卡片同步状态与手机连接、命令待确认保持一致,保留原设备阶段快照。 + var taskReference: DroneShootingTask? { + guard hasCurrentTask else { return nil } + let isUnknown = phoneConnection != .connected || commands.values.contains { $0.status == .unconfirmed } + return DroneShootingTask(id: id, phase: isUnknown ? .unconfirmed : phase, shootingResult: result) + } +} + +/// UI 主按钮的语义;导航由 Controller 执行。 +enum DroneShootingTaskPrimaryAction: Hashable, Sendable { + case start, resume, viewMaterials, prepareAgain, none +} + +/// 可去重展示的设备结果通知。 +struct DroneShootingResultNotice: Hashable, Sendable { + /// 由任务及结果组成的稳定通知身份。 + let id: String + /// 弹窗标题。 + let title: String + /// 弹窗详情。 + let message: String + /// 是否为明确拍摄成功。 + let isSuccess: Bool +} + +/// 显式本地设备回执;没有计时器,也不会向实际设备发送命令。 +enum DroneShootingSessionEvent: Hashable, Sendable { + case commandConfirmed(DroneShootingCommandKind) + case commandRejected(DroneShootingCommandKind, message: String) + case commandResultUnknown(DroneShootingCommandKind) + case phaseConfirmed(DroneShootingTaskPhase) + case shootingSucceeded + case shootingFailed(reason: String) + case flightFinished(deviceReady: Bool) + case protectiveReturn(reason: String) + case phoneConnectionChanged(DroneShootingConnectionState) + case feedConnectionChanged(DroneShootingConnectionState) + case telemetryUpdated(DroneDockTelemetry) + case synchronized(phase: DroneShootingTaskPhase, result: DroneShootingResult, flightFinished: Bool, deviceReady: Bool) +} + +/// 本地准备选择,按订单与点位身份保存。 +struct DroneShootingPreparationState { + /// 当前订单可用点位及其范围快照。 + var points: [DroneShootingPoint] + /// 每个点位当前有效的航线配置。 + var routesByPointID: [String: [DroneShootingRoute]] + /// 所选点位身份,配置移除时清空。 + var selectedPointID: String? + /// 按点位分别保存航线身份,失效时清除。 + var selectedRouteIDs: [String: String] +} + +/// 避免同名订单或景区切换共享错误会话的数据源键。 +struct DroneShootingSessionKey: Hashable { + /// 会话所属的景区和工作人员。 + let context: DroneDockContext + /// 本范围内的稳定订单标识。 + let orderID: String +} + +#if DEBUG +/// 准备页仅 Debug 可用的本地验收场景。 +enum DroneShootingPreparationScenario: String, CaseIterable { + case ready, occupied, disconnected, noSignal, lowBattery, unknown + case outOfRange, unknownRange, noPoints, noRoutes, noQuota + + /// 验收菜单标题。 + var title: String { + switch self { + case .ready: "恢复正常准备" + case .occupied: "无人机占用中" + case .disconnected: "机巢未连接" + case .noSignal: "无人机无信号" + case .lowBattery: "电量不足" + case .unknown: "设备状态未知" + case .outOfRange: "不在拍摄范围" + case .unknownRange: "位置待确认" + case .noPoints: "暂无拍摄点" + case .noRoutes: "暂无可用航线" + case .noQuota: "拍摄次数用完" + } + } +} + +/// 任务页仅 Debug 可用的显式设备事件组合。 +enum DroneShootingTaskScenario: String, CaseIterable { + case navigating, arrived, shooting, pauseProcessing, shootingPaused, resumeProcessing + case returning, returnPaused, succeededReturning, succeededFinished, failedReturning, failedReady + case streamLost, phoneOffline, protectiveReturn, commandUnconfirmed, commandRejected, synchronized + + /// 验收菜单标题。 + var title: String { + switch self { + case .navigating: "前往拍摄点中" + case .arrived: "已到达,待拍摄" + case .shooting: "拍摄中" + case .pauseProcessing: "暂停处理中" + case .shootingPaused: "拍摄已暂停" + case .resumeProcessing: "恢复处理中" + case .returning: "返航中" + case .returnPaused: "返航已暂停" + case .succeededReturning: "拍摄成功 · 返航中" + case .succeededFinished: "拍摄成功 · 飞行结束" + case .failedReturning: "执行失败 · 返航中" + case .failedReady: "执行失败 · 设备可用" + case .streamLost: "画面断流" + case .phoneOffline: "手机断网" + case .protectiveReturn: "保护性返航" + case .commandUnconfirmed: "指令执行结果待确认" + case .commandRejected: "指令明确拒绝" + case .synchronized: "同步当前任务回执" + } + } +} +#endif diff --git a/suixinkan/Features/DroneDock/ViewModels/DroneDockViewModels.swift b/suixinkan/Features/DroneDock/ViewModels/DroneDockViewModels.swift index bbccadf..dfc7634 100644 --- a/suixinkan/Features/DroneDock/ViewModels/DroneDockViewModels.swift +++ b/suixinkan/Features/DroneDock/ViewModels/DroneDockViewModels.swift @@ -1,6 +1,6 @@ import Foundation -/// 两个机巢页面共享的本地数据源,不请求接口、不发送设备指令,也不自动推进任务。 +/// 机巢工作台、订单、准备和任务页面共享的本地数据源;不请求接口或自动推进任务。 final class DroneDockDemoStore { /// 当前登录用户与景区范围。 private(set) var context: DroneDockContext @@ -8,6 +8,15 @@ final class DroneDockDemoStore { private var ordersByContext: [DroneDockContext: [DroneShootingOrder]] = [:] private var devicesByContext: [DroneDockContext: [DroneDockDevice]] = [:] + /// 按上下文与订单保存的点位、航线和人工选择。 + var shootingPreparations: [DroneShootingSessionKey: DroneShootingPreparationState] = [:] + /// 当前或最近一次本地任务;飞行结束后仍保留结果页快照。 + var shootingSessions: [DroneShootingSessionKey: DroneShootingSession] = [:] + #if DEBUG + /// 预览切换前的订单,恢复正常场景时不累计演示扣次。 + var shootingScenarioBaselines: [DroneShootingSessionKey: DroneShootingOrder] = [:] + #endif + /// 注入初始上下文及可选数据,便于页面演示与独立规则测试。 init( context: DroneDockContext = .demo, @@ -29,6 +38,24 @@ final class DroneDockDemoStore { /// 当前景区的无人机,不将横向浏览等同于执行资源选择。 var devices: [DroneDockDevice] { devicesByContext[context] ?? [] } + /// 读取当前用户、当前景区内的指定订单。 + func shootingOrder(id: String) -> DroneShootingOrder? { orders.first { $0.id == id } } + + /// 写回一个已校验归属的本地订单,使工作台与列表主动刷新时得到相同结果。 + func replaceShootingOrder(_ order: DroneShootingOrder) { + guard order.scenicID == context.scenicID, order.assignedUserID == context.userID, + let index = ordersByContext[context]?.firstIndex(where: { $0.id == order.id }) else { return } + ordersByContext[context]?[index] = order + } + + /// 更新本地执行资源状态;仅使用明确状态,不从电量或卡片浏览位置推导许可。 + func setShootingDeviceState(_ state: DroneDockDeviceState, telemetry: DroneDockTelemetry? = nil) { + guard let device = devices.first else { return } + devicesByContext[context]?[0] = DroneDockDevice( + id: device.id, name: device.name, state: state, telemetry: telemetry ?? device.telemetry + ) + } + /// 当前演示上下文的今日统计;空场景不保留误导的数值。 var statistics: DroneDockDailyStatistics { orders.isEmpty @@ -48,6 +75,9 @@ final class DroneDockDemoStore { #if DEBUG /// 只在 Debug 提供场景切换;不会触发扣次、真实设备或网络操作。 func applyScenario(_ scenario: DroneDockDemoScenario) { + shootingPreparations = shootingPreparations.filter { $0.key.context != context } + shootingSessions = shootingSessions.filter { $0.key.context != context } + shootingScenarioBaselines = shootingScenarioBaselines.filter { $0.key.context != context } var orders = DroneDockDemoData.orders(context: context) var devices = DroneDockDemoData.devices() switch scenario { diff --git a/suixinkan/Features/DroneDock/ViewModels/DroneShootingSessionViewModels.swift b/suixinkan/Features/DroneDock/ViewModels/DroneShootingSessionViewModels.swift new file mode 100644 index 0000000..8024dc9 --- /dev/null +++ b/suixinkan/Features/DroneDock/ViewModels/DroneShootingSessionViewModels.swift @@ -0,0 +1,803 @@ +import Foundation + +/// 准备页的选择、恢复和准入规则;读取共享数据源后由 View 主动刷新。 +final class DroneShootingPreparationViewModel { + /// 与工作台、订单及任务页面共享的本地数据源。 + let store: DroneDockDemoStore + /// 固定入口订单,避免通过列表位置恢复错误任务。 + let orderID: String + private let context: DroneDockContext + + /// 当前可访问订单;切换到其他上下文时不可继续操作旧页面。 + var order: DroneShootingOrder? { isCurrentContext ? store.shootingOrder(id: orderID) : nil } + /// 按配置顺序展示,不因距离更新自动重排。 + var points: [DroneShootingPoint] { preparation?.points ?? [] } + /// 当前选择的点位。 + var selectedPoint: DroneShootingPoint? { points.first { $0.id == preparation?.selectedPointID } } + /// 所选点的航线,不包含其他点位的同名航线。 + var routes: [DroneShootingRoute] { selectedPoint.flatMap { preparation?.routesByPointID[$0.id] } ?? [] } + /// 当前有效航线,配置失效时为空。 + var selectedRoute: DroneShootingRoute? { + guard let point = selectedPoint, let id = preparation?.selectedRouteIDs[point.id] else { return nil } + return routes.first { $0.id == id } + } + /// 当前设备明确状态;其他订单执行时仍允许浏览选择。 + var deviceState: DroneDockDeviceState { + guard isCurrentContext else { return .unknown } + if store.orders.contains(where: { $0.activeTask != nil }) { return .occupied } + return store.devices.first?.state ?? .unknown + } + /// 本单已有尚未结束的任务,召唤确认处理中也保持唯一引用。 + var hasCurrentTask: Bool { order?.activeTask != nil } + /// 召唤已经提交但尚无明确回执。 + var hasPendingSummon: Bool { + guard let command = session?.commands[.summon] else { return false } + return command.status.isUnresolved + } + /// 超时只提供同步入口,不以超时当作召唤失败。 + var shouldShowSummonRefresh: Bool { session?.commands[.summon]?.status == .unconfirmed } + /// 底部唯一准入结果。 + var admission: DroneShootingAdmission { + guard let order else { return .orderUnavailable } + if hasPendingSummon { + return shouldShowSummonRefresh ? .summonUnconfirmed : .summoning + } + if hasCurrentTask { return .currentTask } + if order.remainingShootingCount == 0 { return .noQuota } + if points.isEmpty { return .noPoints } + guard let point = selectedPoint else { return .noPoint } + if routes.isEmpty { return .noRoutes } + guard selectedRoute != nil else { return .noRoute } + switch point.range { + case .outside: return .outOfRange + case .unknown: return .unknownRange + case .inside: break + } + switch deviceState { + case .ready: return .ready + case .occupied: return .occupied + case .disconnected: return .disconnected + case .noSignal: return .noSignal + case .lowBattery: return .lowBattery + case .unknown: return .unknownDevice + } + } + /// 底部连接文字,设备未知时不误报已连接。 + var connectionTitle: String { + switch deviceState { + case .disconnected: "机巢未连接" + case .unknown: "机巢连接待确认" + default: "机巢已连接" + } + } + /// 底部连接语义色。 + var connectionTone: DroneDockStatusTone { + switch deviceState { + case .disconnected, .unknown: .gray + default: .green + } + } + /// 底部所选点位范围文字。 + var rangeTitle: String { selectedPoint?.range.admissionTitle ?? "未选择拍摄点" } + /// 底部范围语义色。 + var rangeTone: DroneDockStatusTone { selectedPoint?.range.tone ?? .gray } + /// 设备与有效电量摘要,未知值不显示为零。 + var deviceStatusText: String { + let value = store.devices.first?.telemetry.batteryText ?? "—" + return value == "—" ? deviceState.title : "\(deviceState.title) · 电量 \(value)" + } + /// 当前选择的点位与航线。 + var selectionSummary: String { "\(selectedPoint?.name ?? "未选择拍摄点") · \(selectedRoute?.name ?? "未选择航线")" } + /// 主要按钮标题由准入结果统一提供。 + var primaryButtonTitle: String { admission.title } + /// 仅有效召唤或查看已确认任务允许点击。 + var primaryButtonEnabled: Bool { admission.canSummon || admission == .currentTask } + + private var isCurrentContext: Bool { store.context == context } + private var key: DroneShootingSessionKey { DroneShootingSessionKey(context: context, orderID: orderID) } + private var preparation: DroneShootingPreparationState? { isCurrentContext ? store.shootingPreparations[key] : nil } + private var session: DroneShootingSession? { isCurrentContext ? store.shootingSession(orderID: orderID) : nil } + + /// 载入指定订单的本地选择,不创建任务。 + init(store: DroneDockDemoStore, orderID: String) { + self.store = store + self.orderID = orderID + context = store.context + refresh() + } + + /// 页面出现时校验选择与当前订单;不自动补选失效航线。 + func refresh() { + guard isCurrentContext, order != nil else { return } + store.ensureShootingPreparation(orderID: orderID) + _ = store.shootingSession(orderID: orderID) + store.validateShootingSelection(orderID: orderID) + } + + /// 整卡选点;切回已选点恢复其仍有效的航线,不把上一点航线带过来。 + func selectPoint(id: String) { + guard !hasPendingSummon, var state = preparation, state.points.contains(where: { $0.id == id }) else { return } + state.selectedPointID = id + let routes = state.routesByPointID[id] ?? [] + if state.selectedRouteIDs[id] == nil { state.selectedRouteIDs[id] = routes.first?.id } + store.shootingPreparations[key] = state + store.validateShootingSelection(orderID: orderID) + } + + /// 选择本点有效航线,重复点击不取消。 + func selectRoute(id: String) { + guard !hasPendingSummon, var state = preparation, let point = selectedPoint, + routes.contains(where: { $0.id == id }) else { return } + state.selectedRouteIDs[point.id] = id + store.shootingPreparations[key] = state + } + + /// 首次只提交本地召唤并返回 false;已有明确任务时返回 true 供页面导航。 + @discardableResult + func summon() -> Bool { + refresh() + if admission == .currentTask { return true } + guard admission.canSummon, let point = selectedPoint, let route = selectedRoute else { return false } + store.beginShootingSession(orderID: orderID, point: point, route: route) + return false + } + + /// 请求同步原召唤,不自动判定设备已执行。 + func refreshSummonStatus() { + guard isCurrentContext, hasPendingSummon else { return } + store.receiveShootingEvent(.phoneConnectionChanged(.synchronizing), orderID: orderID, taskID: session?.id) + } + + #if DEBUG + /// 显式模拟设备召唤确认;确认后才进入任务页。 + @discardableResult + func confirmSummon() -> Bool { + guard isCurrentContext, let session, session.commands[.summon]?.status.isUnresolved == true else { return false } + store.receiveShootingEvent(.commandConfirmed(.summon), orderID: orderID, taskID: session.id) + store.receiveShootingEvent(.phoneConnectionChanged(.connected), orderID: orderID, taskID: session.id) + return true + } + + /// 准备页本地验收入口;不连接网络或实际设备。 + func applyScenario(_ scenario: DroneShootingPreparationScenario) { + guard isCurrentContext, order != nil else { return } + store.applyPreparationScenario(scenario, orderID: orderID) + refresh() + } + #endif +} + +/// 当前任务的展示及指令入口;提交与设备确认严格分开。 +final class DroneShootingTaskViewModel { + /// 与入口页面共享的本地数据源。 + let store: DroneDockDemoStore + /// 本次入口订单。 + let orderID: String + private let context: DroneDockContext + + /// 当前上下文仍可访问的订单。 + var order: DroneShootingOrder? { isCurrentContext ? store.shootingOrder(id: orderID) : nil } + /// 原任务或最近一次结果快照。 + var session: DroneShootingSession? { isCurrentContext ? store.shootingSession(orderID: orderID) : nil } + /// 点位与航线标题。 + var title: String { session.map { "\($0.point.name) · \($0.route.name)" } ?? "当前任务" } + /// 订单游客和次数摘要。 + var subtitle: String { order.map { "\($0.customerName) · 含\($0.totalShootingCount)次拍摄" } ?? "当前订单不可用" } + /// 手机状态未同步时隐藏过期遥测,不将未知当作零。 + var telemetry: DroneDockTelemetry { phoneConnection == .connected ? (session?.telemetry ?? .unknown) : .unknown } + /// 卡片一致的七阶段状态;手机断网时为待确认。 + var phase: DroneShootingTaskPhase? { session?.taskReference?.phase ?? session?.phase } + /// 手机网络连接。 + var phoneConnection: DroneShootingConnectionState { session?.phoneConnection ?? .disconnected } + /// 图传独立连接。 + var feedConnection: DroneShootingConnectionState { session?.feedConnection ?? .disconnected } + /// 当前待处理或明确拒绝的指令,不混成拍摄失败。 + var commandTitle: String? { + guard let command = session?.command else { return nil } + switch command.status { + case .processing: return command.kind.processingTitle + case .unconfirmed: return "执行结果待确认" + case .rejected: return "指令未执行" + case .confirmed: return nil + } + } + /// 指令处理提示,避免点击按钮后误称已经生效。 + var commandMessage: String? { + guard let command = session?.command else { return nil } + switch command.status { + case .processing: return "等待设备确认,请勿重复发送指令。" + case .unconfirmed: return "暂未确认执行结果,请刷新任务状态,勿重复发送指令。" + case .rejected(let message): return message + case .confirmed: return nil + } + } + /// 用于按钮或提示区的处理指示器。 + var commandIsProcessing: Bool { session?.command?.status == .processing } + /// 只有结果未知才提示同步原任务。 + var shouldShowCommandRefresh: Bool { session?.commands.values.contains { $0.status == .unconfirmed } ?? false } + /// 主状态标题,拍摄结果和飞行返航同时可见。 + var statusTitle: String { + guard let session else { return "当前任务不可用" } + if phoneConnection != .connected { return "任务状态待确认" } + if session.result == .succeeded { return "拍摄已完成" } + if session.result == .failed { return "任务执行失败" } + if session.isFlightFinished { return session.result == .unknown ? "拍摄结果待确认" : "本次任务已结束" } + if session.protectiveReturnReason != nil { return "无人机自动返航" } + switch session.phase { + case .navigating: return "无人机正在前往拍摄点" + case .arrived: return "无人机已到达" + case .shooting: return "无人机正在拍摄中" + case .shootingPaused: return "无人机已暂停" + case .returning: return "无人机正在返航" + case .returnPaused: return "无人机返航已暂停" + case .unconfirmed: return "任务状态待确认" + } + } + /// 独立说明结果、飞行或连接状态。 + var statusMessage: String { + guard let session else { return "请返回工作台刷新当前订单。" } + if phoneConnection != .connected { return "连接中断不代表任务失败。恢复连接后需同步原任务。" } + if session.result == .succeeded { + if session.isFlightFinished { return "本次拍摄已结束,可前往查看素材。" } + let flightMessage: String + switch session.phase { + case .returning: flightMessage = "无人机返航中" + case .returnPaused: flightMessage = "无人机返航已暂停" + default: flightMessage = "无人机飞行任务尚未结束" + } + return "本次拍摄已完成。\(flightMessage),请留意现场。" + } + if session.result == .failed { + let reason = "失败原因:\(session.failureReason ?? "设备已确认本次拍摄失败")。" + if !session.isFlightFinished { return reason + "无人机尚未结束飞行,暂不可重新准备。" } + if order?.remainingShootingCount == 0 { return reason + "当前订单拍摄次数已用完。" } + return reason + (session.deviceReady ? "请排查后重新准备拍摄。" : "设备尚未恢复可用,请稍后刷新。") + } + if session.isFlightFinished { + if session.result == .unknown || session.result == .inProgress { return "飞行任务已结束,拍摄结果仍待确认。请同步原任务,勿重复召唤。" } + return "本次未开始拍摄,未扣减次数。\(session.deviceReady ? "可重新准备拍摄。" : "设备尚未恢复可用。")" + } + if let reason = session.protectiveReturnReason { return "返航原因:\(reason)。拍摄结果待确认,请留意现场。" } + switch session.phase { + case .navigating: return "请关注现场,等待设备确认到达。" + case .arrived: return "是否开始拍摄?确认游客站位与取景后开始。" + case .shooting: return feedConnection == .connected ? "请关注现场及实时画面。" : "当前仅画面中断,无人机状态仍在更新。" + case .shootingPaused: return "当前悬停待命。确认安全后,可继续任务或立即返航。" + case .returning: return "无人机返航中,请留意现场。拍摄结果单独确认。" + case .returnPaused: return "当前悬停待命,确认安全后可继续返航。" + case .unconfirmed: return "请同步原任务状态,勿重复创建任务。" + } + } + /// 主状态的语义色。 + var statusTone: DroneDockStatusTone { + guard let session else { return .gray } + if phoneConnection != .connected { return .orange } + if session.result == .succeeded { return .green } + if session.result == .failed { return .red } + return session.phase.tone + } + /// 导航和指令的主按钮语义。 + var primaryAction: DroneShootingTaskPrimaryAction { + guard let session, order != nil else { return .none } + if !session.isFlightFinished, session.phase == .returnPaused || session.phase == .shootingPaused { return .resume } + if session.result == .succeeded { return .viewMaterials } + if session.isFlightFinished, session.result == .failed || session.result == .notStarted { return .prepareAgain } + if session.result == .failed { return .prepareAgain } + switch session.phase { + case .arrived: return .start + case .shootingPaused, .returnPaused: return .resume + default: return .none + } + } + /// 主按钮标题,指令处理中与待确认时阻止重复操作。 + var primaryTitle: String { + if phoneConnection != .connected { return "等待任务同步" } + switch primaryAction { + case .start: + if let command = session?.commands[.start], command.status.isUnresolved { + return command.status == .unconfirmed ? "执行结果待确认" : command.kind.processingTitle + } + return "开始拍摄" + case .resume: + if let command = session?.commands[.resume], command.status.isUnresolved { + return command.status == .unconfirmed ? "执行结果待确认" : command.kind.processingTitle + } + return session?.phase == .returnPaused ? "继续返航" : "继续任务" + case .viewMaterials: return "查看素材" + case .prepareAgain: return "重新准备拍摄" + case .none: + if session?.result == .unknown { return "结果待确认" } + if session?.phase == .navigating { return "前往拍摄点中" } + if session?.phase == .returning { return "返航中" } + return "拍摄中" + } + } + /// 新任务必须等待飞行结束、设备可用并有剩余次数。 + var primaryEnabled: Bool { + guard let session, phoneConnection == .connected else { return false } + switch primaryAction { + case .viewMaterials: return true + case .prepareAgain: + return session.isFlightFinished && !session.hasCurrentTask && session.deviceReady + && (order?.remainingShootingCount ?? 0) > 0 && store.shootingDeviceState(orderID: orderID) == .ready + case .start: return canSend(.start) + case .resume: return canSend(.resume) + case .none: return false + } + } + /// 暂停按钮标题,提交后仍不展示已暂停。 + var pauseTitle: String { + if let command = session?.commands[.pause], command.status.isUnresolved { + return command.status == .processing ? "暂停处理中" : "暂停结果待确认" + } + return session?.phase == .shootingPaused || session?.phase == .returnPaused ? "已暂停" : "紧急暂停" + } + /// 暂停按钮补充说明。 + var pauseSubtitle: String { + if phoneConnection != .connected { return "当前无法发送指令" } + if session?.isFlightFinished != false { return "当前未执行任务" } + if session?.commands[.pause]?.status.isUnresolved == true { return "尚未确认悬停" } + return "悬停待命" + } + /// 暂停按钮许可,不因图传断流而禁用。 + var canPause: Bool { canSend(.pause) } + /// 返航按钮标题,等待明确回执才显示返航中。 + var returnTitle: String { + if let command = session?.commands[.returnHome], command.status.isUnresolved { + return command.status == .processing ? "正在发送返航指令" : "返航结果待确认" + } + return session?.phase == .returning ? "返航中" : "立即返航" + } + /// 返航按钮补充说明。 + var returnSubtitle: String { + if phoneConnection != .connected { return "当前无法发送指令" } + if session?.isFlightFinished != false { return "当前未执行任务" } + if session?.commands[.returnHome]?.status.isUnresolved == true { return "尚未确认返航" } + return session?.phase == .returning ? "返回机巢" : "中断任务" + } + /// 返航直接提交,无二次确认;提交与执行结果分开。 + var canReturn: Bool { canSend(.returnHome) } + /// 结果弹窗是任务快照的一部分,关闭后重进不重复展示。 + var resultNotice: DroneShootingResultNotice? { + guard let session, !session.resultNoticeDismissed else { return nil } + switch session.result { + case .succeeded: + return DroneShootingResultNotice(id: "\(session.id)-success", title: "拍摄完成", message: "本次拍摄已成功,扣减 1 次拍摄次数。飞行状态请继续留意现场。", isSuccess: true) + case .failed: + return DroneShootingResultNotice(id: "\(session.id)-failure", title: "任务执行失败", message: "\(session.failureReason ?? "设备已确认失败"),本次未扣减拍摄次数。", isSuccess: false) + default: return nil + } + } + + private var isCurrentContext: Bool { store.context == context } + + /// 只恢复原任务,构造页面不会自动创建、扣次或恢复执行。 + init(store: DroneDockDemoStore, orderID: String) { + self.store = store + self.orderID = orderID + context = store.context + refresh() + } + + /// 页面出现或手动操作后重新读取共享状态;没有自动进度。 + func refresh() { + guard isCurrentContext else { return } + _ = store.shootingSession(orderID: orderID) + } + + /// 直接提交开始请求,明确设备确认后才进入拍摄中。 + @discardableResult + func startShooting() -> Bool { send(.start) } + /// 直接提交紧急暂停,不弹二次确认,不提前宣称悬停。 + @discardableResult + func pause() -> Bool { send(.pause) } + /// 请求恢复暂停前阶段,收到回执前保持暂停。 + @discardableResult + func resume() -> Bool { send(.resume) } + /// 按已确认交互直接提交返航请求,收到回执前保持原阶段。 + @discardableResult + func requestReturn() -> Bool { send(.returnHome) } + /// 只开始手机重连,需明确同步回执才能恢复操作。 + func reconnectPhone() { receive(.phoneConnectionChanged(.reconnecting)) } + /// 图传重连不改变任务结果、飞行阶段或手机连接。 + func reconnectFeed() { receive(.feedConnectionChanged(.reconnecting)) } + /// 手动发起原任务同步;不清除未知结果或重复发送设备指令。 + func refreshTaskStatus() { receive(.phoneConnectionChanged(.synchronizing)) } + /// 关闭本任务的结果通知,写回共享快照防止重复弹窗。 + func dismissResultNotice() { + guard let session, isCurrentContext else { return } + store.dismissShootingResultNotice(orderID: orderID, taskID: session.id) + } + /// 注入显式本地回执,便于规则验证或后续数据源适配;过期任务回执会忽略。 + func receive(_ event: DroneShootingSessionEvent) { + guard let session, isCurrentContext else { return } + store.receiveShootingEvent(event, orderID: orderID, taskID: session.id) + } + + private func canSend(_ kind: DroneShootingCommandKind) -> Bool { + guard let session, order != nil, phoneConnection == .connected, !session.isFlightFinished, + session.commands[kind]?.status.isUnresolved != true, + session.commands[.summon]?.status.isUnresolved != true else { return false } + switch kind { + case .summon: return false + case .start: + return session.phase == .arrived && session.result == .notStarted + && !session.commands.values.contains { $0.status.isUnresolved } + case .resume: + return (session.phase == .shootingPaused || session.phase == .returnPaused) + && !session.commands.values.contains { $0.status.isUnresolved } + case .pause: + return session.phase != .shootingPaused && session.phase != .returnPaused && session.phase != .unconfirmed + case .returnHome: return session.phase != .returning && session.phase != .returnPaused && session.phase != .unconfirmed + } + } + + private func send(_ kind: DroneShootingCommandKind) -> Bool { + guard canSend(kind) else { return false } + return store.submitShootingCommand(kind, orderID: orderID) + } + + #if DEBUG + /// 显式模拟设备状态;场景切换不包含任何自动计时。 + func applyScenario(_ scenario: DroneShootingTaskScenario) { + guard isCurrentContext else { return } + store.applyTaskScenario(scenario, orderID: orderID) + refresh() + } + #endif +} + +/// 准备配置、会话与订单投影共享同一存储;页面间不存在独立任务副本。 +extension DroneDockDemoStore { + /// 当前上下文中读取或恢复原任务,已有任务引用只补齐本地展示快照。 + func shootingSession(orderID: String) -> DroneShootingSession? { + guard let order = shootingOrder(id: orderID) else { return nil } + let key = shootingKey(orderID) + if let session = shootingSessions[key], order.activeTask == nil || order.activeTask?.id == session.id { return session } + guard let task = order.activeTask else { return nil } + ensureShootingPreparation(orderID: orderID) + guard let state = shootingPreparations[key], + let point = state.points.first(where: { $0.id == state.selectedPointID }), + let route = state.routesByPointID[point.id]?.first(where: { $0.id == state.selectedRouteIDs[point.id] }) else { return nil } + let session = makeSession(id: task.id, point: point, route: route, phase: task.phase, result: task.shootingResult) + shootingSessions[key] = session + return session + } + + /// 外部明确的点位配置或定位快照;原选择失效时清空而不偷偷换航线。 + func updateShootingPoints(_ points: [DroneShootingPoint], routesByPointID: [String: [DroneShootingRoute]], orderID: String) { + guard shootingOrder(id: orderID) != nil else { return } + ensureShootingPreparation(orderID: orderID) + let key = shootingKey(orderID) + shootingPreparations[key]?.points = points + shootingPreparations[key]?.routesByPointID = routesByPointID + validateShootingSelection(orderID: orderID) + } + + /// 明确范围与设备都有效后创建唯一待确认会话;不扣次、不假称起飞。 + func beginShootingSession(orderID: String, point: DroneShootingPoint, route: DroneShootingRoute) { + guard let order = shootingOrder(id: orderID), order.activeTask == nil, + order.remainingShootingCount > 0, !orders.contains(where: { $0.activeTask != nil }), + point.range == .inside, shootingDeviceState(orderID: orderID) == .ready, + let state = shootingPreparations[shootingKey(orderID)], + state.points.contains(point), state.routesByPointID[point.id]?.contains(route) == true else { return } + var session = makeSession(id: UUID().uuidString, point: point, route: route, phase: .unconfirmed, result: .notStarted) + session.commands[.summon] = DroneShootingCommand(kind: .summon, status: .processing) + session.deviceReady = false + shootingSessions[shootingKey(orderID)] = session + setShootingDeviceState(.occupied) + projectShootingSession(orderID: orderID) + } + + /// 记录一种已通过页面许可校验的本地指令,防止同一种指令重复提交。 + @discardableResult + func submitShootingCommand(_ kind: DroneShootingCommandKind, orderID: String) -> Bool { + guard var session = shootingSession(orderID: orderID), !session.isFlightFinished, + session.phoneConnection == .connected, session.commands[kind]?.status.isUnresolved != true else { return false } + session.commands[kind] = DroneShootingCommand(kind: kind, status: .processing) + shootingSessions[shootingKey(orderID)] = session + projectShootingSession(orderID: orderID) + return true + } + + /// 显式设备事件入口,任务身份不匹配时忽略迟到回执。 + func receiveShootingEvent(_ event: DroneShootingSessionEvent, orderID: String, taskID: String?) { + guard var session = shootingSession(orderID: orderID), session.id == taskID else { return } + switch event { + case .commandConfirmed(let kind): + guard session.commands[kind]?.status.isUnresolved == true else { return } + session.commands[kind]?.status = .confirmed + if !session.isFlightFinished { + switch kind { + case .summon: session.phase = .navigating + case .start: + if session.result != .succeeded && session.result != .failed { + session.phase = .shooting + session.result = .inProgress + } + case .pause: + session.phaseBeforePause = session.phase + session.phase = session.phase == .returning ? .returnPaused : .shootingPaused + case .resume: + session.phase = session.phaseBeforePause ?? (session.phase == .returnPaused ? .returning : .shooting) + session.phaseBeforePause = nil + case .returnHome: + session.phase = .returning + if session.result == .inProgress { session.result = .unknown } + } + } + case .commandRejected(let kind, let message): + guard session.commands[kind]?.status.isUnresolved == true else { return } + session.commands[kind]?.status = .rejected(message: message) + if kind == .summon { + session.isFlightFinished = true + session.deviceReady = true + } + case .commandResultUnknown(let kind): + guard session.commands[kind]?.status.isUnresolved == true else { return } + session.commands[kind]?.status = .unconfirmed + case .phaseConfirmed(let phase): session.phase = phase + case .shootingSucceeded: + guard session.result != .failed else { return } + session.result = .succeeded + case .shootingFailed(let reason): + guard session.result != .succeeded else { return } + session.result = .failed + session.failureReason = reason + case .flightFinished(let deviceReady): + session.isFlightFinished = true + session.deviceReady = deviceReady + case .protectiveReturn(let reason): + session.phase = .returning + session.protectiveReturnReason = reason + if session.result != .succeeded && session.result != .failed { session.result = .unknown } + case .phoneConnectionChanged(let state): session.phoneConnection = state + case .feedConnectionChanged(let state): session.feedConnection = state + case .telemetryUpdated(let telemetry): session.telemetry = telemetry + case .synchronized(let phase, let result, let finished, let ready): + session.phase = phase + // 终态回执不被随后到达的非终态快照覆盖。 + if session.result != .succeeded && session.result != .failed { session.result = result } + session.isFlightFinished = session.isFlightFinished || finished + session.deviceReady = ready + session.phoneConnection = .connected + for kind in session.commands.keys { session.commands[kind]?.status = .confirmed } + } + shootingSessions[shootingKey(orderID)] = session + projectShootingSession(orderID: orderID) + } + + /// 关闭结果通知,后续页面只读取已关闭的同一快照。 + func dismissShootingResultNotice(orderID: String, taskID: String) { + let key = shootingKey(orderID) + guard shootingSessions[key]?.id == taskID else { return } + shootingSessions[key]?.resultNoticeDismissed = true + } + + /// 本地执行许可优先考虑其他活跃订单,不绑定工作台横向浏览的设备卡。 + func shootingDeviceState(orderID: String) -> DroneDockDeviceState { + if orders.contains(where: { $0.id != orderID && $0.activeTask != nil }) { return .occupied } + return devices.first?.state ?? .unknown + } + + /// 首次创建演示选择;后续进入保留每个点位的航线身份。 + func ensureShootingPreparation(orderID: String) { + let key = shootingKey(orderID) + guard shootingPreparations[key] == nil, let order = shootingOrder(id: orderID) else { return } + shootingPreparations[key] = DroneShootingSessionDemoData.preparation(successfulCount: order.successfulShootingCount) + } + + /// 配置失效时清除选择,不从其他同名点位恢复。 + func validateShootingSelection(orderID: String) { + let key = shootingKey(orderID) + guard var state = shootingPreparations[key] else { return } + if !state.points.contains(where: { $0.id == state.selectedPointID }) { state.selectedPointID = nil } + state.selectedRouteIDs = state.selectedRouteIDs.filter { pointID, routeID in + state.points.contains { $0.id == pointID } && (state.routesByPointID[pointID] ?? []).contains { $0.id == routeID } + } + shootingPreparations[key] = state + } + + private func shootingKey(_ orderID: String) -> DroneShootingSessionKey { + DroneShootingSessionKey(context: context, orderID: orderID) + } + + private func makeSession(id: String, point: DroneShootingPoint, route: DroneShootingRoute, phase: DroneShootingTaskPhase, result: DroneShootingResult) -> DroneShootingSession { + DroneShootingSession( + id: id, point: point, route: route, phase: phase, result: result, isFlightFinished: false, + deviceReady: false, successRecorded: result == .succeeded, phoneConnection: .connected, + feedConnection: .connected, telemetry: devices.first?.telemetry ?? .unknown, + commands: [:], phaseBeforePause: nil, failureReason: nil, protectiveReturnReason: nil, + resultNoticeDismissed: result == .succeeded || result == .failed + ) + } + + private func projectShootingSession(orderID: String) { + let key = shootingKey(orderID) + guard var session = shootingSessions[key], let order = shootingOrder(id: orderID) else { return } + let shouldRecordSuccess = session.result == .succeeded && !session.successRecorded + if shouldRecordSuccess { + session.successRecorded = true + incrementShootingPointCount(orderID: orderID, pointID: session.point.id) + } + shootingSessions[key] = session + let successfulCount = shouldRecordSuccess ? min(order.totalShootingCount, order.successfulShootingCount + 1) : order.successfulShootingCount + replaceShootingOrder(order.replacingShootingState( + successfulCount: successfulCount, task: session.taskReference, + needsRepreparation: !session.hasCurrentTask && session.result != .succeeded, + materialState: shouldRecordSuccess ? .uploading : order.materialState + )) + if !session.hasCurrentTask { + let hasOtherTask = orders.contains { $0.id != orderID && $0.activeTask != nil } + setShootingDeviceState(hasOtherTask ? .occupied : (session.deviceReady ? .ready : .unknown), telemetry: session.telemetry) + } + } + + private func incrementShootingPointCount(orderID: String, pointID: String) { + let key = shootingKey(orderID) + guard var state = shootingPreparations[key], let index = state.points.firstIndex(where: { $0.id == pointID }) else { return } + let point = state.points[index] + state.points[index] = DroneShootingPoint(id: point.id, name: point.name, range: point.range, successfulCount: point.successfulCount + 1) + shootingPreparations[key] = state + } +} + +/// 复制订单的会话相关字段,其余原素材和成片交付信息原样保留。 +private extension DroneShootingOrder { + func replacingShootingState(successfulCount: Int, task: DroneShootingTask?, needsRepreparation: Bool, materialState: DroneShootingMaterialState) -> DroneShootingOrder { + DroneShootingOrder( + id: id, scenicID: scenicID, assignedUserID: assignedUserID, customerName: customerName, + orderNumber: orderNumber, createdAtText: createdAtText, packageName: packageName, + totalShootingCount: totalShootingCount, successfulShootingCount: successfulCount, + activeTask: task, needsRepreparation: needsRepreparation, materialState: materialState, + deliveredVideoCount: deliveredVideoCount, visitorConfirmationState: visitorConfirmationState + ) + } +} + +/// 无真实接口的首轮 UI 配置;航线数量严格来自各点自己的配置。 +private enum DroneShootingSessionDemoData { + static func preparation(successfulCount: Int) -> DroneShootingPreparationState { + let points = [ + DroneShootingPoint(id: "point-sanhuang", name: "三皇寨", range: .inside, successfulCount: successfulCount), + DroneShootingPoint(id: "point-jinque", name: "金阙云宫", range: .outside(distanceText: "800 m"), successfulCount: 0), + DroneShootingPoint(id: "point-shaoshi", name: "少室山", range: .outside(distanceText: "1.2 km"), successfulCount: 0), + DroneShootingPoint(id: "point-yingke", name: "迎客峰", range: .outside(distanceText: "1.8 km"), successfulCount: 0) + ] + let routeNames = [ + ["经典航线", "环绕专线", "远景拉升", "全景环绕", "高空俯瞰", "山峰渐远", "峡谷穿行", "山脊侧拍"], + ["云宫环绕", "金顶渐远", "云海全景"], + ["山峦全景", "山间渐远"], + ["迎客环绕", "山峰远景", "山谷俯瞰"] + ] + var routesByPointID: [String: [DroneShootingRoute]] = [:] + for (index, point) in points.enumerated() { + routesByPointID[point.id] = routeNames[index].enumerated().map { DroneShootingRoute(id: "\(point.id)-route-\($0.offset)", name: $0.element) } + } + return DroneShootingPreparationState(points: points, routesByPointID: routesByPointID, selectedPointID: points.first?.id, selectedRouteIDs: [points[0].id: routesByPointID[points[0].id]![0].id]) + } +} + +#if DEBUG +/// 所有演示均由明确点击触发,不执行计时、API 或真实设备操作。 +private extension DroneDockDemoStore { + func applyPreparationScenario(_ scenario: DroneShootingPreparationScenario, orderID: String) { + guard let order = shootingOrder(id: orderID) else { return } + let key = shootingKey(orderID) + if shootingScenarioBaselines[key] == nil { shootingScenarioBaselines[key] = order } + guard let baseline = shootingScenarioBaselines[key] else { return } + let count = scenario == .noQuota ? baseline.totalShootingCount : baseline.successfulShootingCount + replaceShootingOrder(baseline.replacingShootingState(successfulCount: count, task: baseline.activeTask, needsRepreparation: baseline.needsRepreparation, materialState: baseline.materialState)) + if baseline.activeTask == nil { shootingSessions[key] = nil } + var state = DroneShootingSessionDemoData.preparation(successfulCount: count) + if let previous = shootingPreparations[key], state.points.contains(where: { $0.id == previous.selectedPointID }) { + state.selectedPointID = previous.selectedPointID + state.selectedRouteIDs.merge(previous.selectedRouteIDs) { _, previous in previous } + } + if let pointID = state.selectedPointID, let index = state.points.firstIndex(where: { $0.id == pointID }) { + let point = state.points[index] + let range: DroneShootingRange + switch scenario { + case .outOfRange: range = .outside(distanceText: "800 m") + case .unknownRange: range = .unknown + default: range = .inside + } + state.points[index] = DroneShootingPoint(id: point.id, name: point.name, range: range, successfulCount: point.successfulCount) + if scenario == .noRoutes { + state.routesByPointID[pointID] = [] + state.selectedRouteIDs[pointID] = nil + } + } + shootingPreparations[key] = state + if scenario == .noPoints { + shootingPreparations[key]?.points = [] + shootingPreparations[key]?.selectedPointID = nil + shootingPreparations[key]?.selectedRouteIDs = [:] + shootingPreparations[key]?.routesByPointID = [:] + } + let deviceState: DroneDockDeviceState + switch scenario { + case .occupied: deviceState = .occupied + case .disconnected: deviceState = .disconnected + case .noSignal: deviceState = .noSignal + case .lowBattery: deviceState = .lowBattery + case .unknown: deviceState = .unknown + default: deviceState = .ready + } + let telemetry = scenario == .unknown || scenario == .disconnected || scenario == .noSignal + ? DroneDockTelemetry.unknown + : DroneDockTelemetry(batteryPercent: scenario == .lowBattery ? 18 : 95, temperatureCelsius: 20.3, windSpeed: 0, rainDescription: "无雨", signalDescription: "良好", satelliteCount: 36) + setShootingDeviceState(deviceState, telemetry: telemetry) + } + + func applyTaskScenario(_ scenario: DroneShootingTaskScenario, orderID: String) { + guard var session = shootingSession(orderID: orderID) else { return } + let key = shootingKey(orderID) + if scenario == .synchronized { + let unresolvedStart = session.commands[.start]?.status.isUnresolved == true + receiveShootingEvent(.synchronized( + phase: unresolvedStart ? .shooting : session.phase, + result: unresolvedStart ? .inProgress : session.result, + flightFinished: session.isFlightFinished, deviceReady: session.deviceReady + ), orderID: orderID, taskID: session.id) + return + } + session.phase = .arrived + session.result = .notStarted + session.isFlightFinished = false + session.deviceReady = false + session.phoneConnection = .connected + session.feedConnection = .connected + session.commands = [:] + session.failureReason = nil + session.protectiveReturnReason = nil + session.phaseBeforePause = nil + session.resultNoticeDismissed = false + session.telemetry = DroneDockTelemetry(batteryPercent: 95, temperatureCelsius: 20.3, windSpeed: 0, rainDescription: "无雨", signalDescription: "良好", satelliteCount: 36) + switch scenario { + case .navigating: session.phase = .navigating + case .arrived: break + case .shooting, .pauseProcessing, .streamLost: + session.phase = .shooting + session.result = .inProgress + if scenario == .pauseProcessing { session.commands[.pause] = DroneShootingCommand(kind: .pause, status: .processing) } + if scenario == .streamLost { session.feedConnection = .disconnected } + case .shootingPaused, .resumeProcessing: + session.phase = .shootingPaused + session.phaseBeforePause = .shooting + session.result = .inProgress + if scenario == .resumeProcessing { session.commands[.resume] = DroneShootingCommand(kind: .resume, status: .processing) } + case .returning: session.phase = .returning + case .returnPaused: + session.phase = .returnPaused + session.phaseBeforePause = .returning + case .succeededReturning, .succeededFinished: + session.phase = .returning + session.result = .succeeded + session.isFlightFinished = scenario == .succeededFinished + session.deviceReady = session.isFlightFinished + case .failedReturning, .failedReady: + session.phase = .returning + session.result = .failed + session.failureReason = "拍摄指令执行失败" + session.isFlightFinished = scenario == .failedReady + session.deviceReady = session.isFlightFinished + case .phoneOffline: + session.phase = .shooting + session.result = .inProgress + session.phoneConnection = .disconnected + case .protectiveReturn: + session.phase = .returning + session.result = .unknown + session.protectiveReturnReason = "电量不足" + session.telemetry = DroneDockTelemetry(batteryPercent: 18, temperatureCelsius: 20.3, windSpeed: 0, rainDescription: "无雨", signalDescription: "良好", satelliteCount: 36) + case .commandUnconfirmed: session.commands[.start] = DroneShootingCommand(kind: .start, status: .unconfirmed) + case .commandRejected: session.commands[.start] = DroneShootingCommand(kind: .start, status: .rejected(message: "设备拒绝开始拍摄,请检查当前状态。")) + case .synchronized: break + } + shootingSessions[key] = session + setShootingDeviceState(.occupied, telemetry: session.telemetry) + projectShootingSession(orderID: orderID) + } +} +#endif diff --git a/suixinkan/UI/DroneDock/DroneDockPreview.swift b/suixinkan/UI/DroneDock/DroneDockPreview.swift index 4952a71..015535b 100644 --- a/suixinkan/UI/DroneDock/DroneDockPreview.swift +++ b/suixinkan/UI/DroneDock/DroneDockPreview.swift @@ -6,7 +6,8 @@ import UIKit enum DroneDockPreview { /// 启动参数存在时返回预览导航,正常冷启动继续使用原业务根页面。 static func navigationController(arguments: [String]) -> UINavigationController? { - guard arguments.contains("--dock-ui-preview") || arguments.contains("--dock-ui-orders-preview") else { return nil } + let entryFlags = ["--dock-ui-preview", "--dock-ui-orders-preview", "--dock-ui-preparation-preview", "--dock-ui-task-preview"] + guard arguments.contains(where: { entryFlags.contains($0) }) else { return nil } let store = DroneDockDemoStore() if let argument = arguments.first(where: { $0.hasPrefix("--dock-ui-scenario=") }), let scenario = DroneDockDemoScenario(rawValue: String(argument.dropFirst("--dock-ui-scenario=".count))) { @@ -21,6 +22,32 @@ enum DroneDockPreview { orders.delegate = workbench navigation.setViewControllers([workbench, orders], animated: false) } + if arguments.contains("--dock-ui-preparation-preview") || arguments.contains("--dock-ui-task-preview") { + guard let order = store.orders.first(where: { $0.activeTask != nil }) + ?? store.orders.first(where: { $0.id.hasSuffix("-order-2") }) else { return navigation } + let preparationViewModel = DroneShootingPreparationViewModel(store: store, orderID: order.id) + if let argument = arguments.first(where: { $0.hasPrefix("--dock-preparation-scenario=") }), + let scenario = DroneShootingPreparationScenario(rawValue: String(argument.dropFirst("--dock-preparation-scenario=".count))) { + preparationViewModel.applyScenario(scenario) + } + let preparation = DroneShootingPreparationViewController(viewModel: preparationViewModel) + preparation.delegate = workbench + var controllers: [UIViewController] = [workbench, preparation] + if arguments.contains("--dock-ui-task-preview") { + if store.shootingSession(orderID: order.id) == nil { + _ = preparationViewModel.summon() + _ = preparationViewModel.confirmSummon() + } + let taskViewModel = DroneShootingTaskViewModel(store: store, orderID: order.id) + let scenarioArgument = arguments.first { $0.hasPrefix("--dock-task-scenario=") } + let scenario = scenarioArgument.flatMap { DroneShootingTaskScenario(rawValue: String($0.dropFirst("--dock-task-scenario=".count))) } ?? .arrived + taskViewModel.applyScenario(scenario) + let task = DroneShootingTaskViewController(viewModel: taskViewModel) + task.delegate = workbench + controllers.append(task) + } + navigation.setViewControllers(controllers, animated: false) + } return navigation } } diff --git a/suixinkan/UI/DroneDock/DroneDockWorkbenchViewController.swift b/suixinkan/UI/DroneDock/DroneDockWorkbenchViewController.swift index 06d1fb6..8c8764f 100644 --- a/suixinkan/UI/DroneDock/DroneDockWorkbenchViewController.swift +++ b/suixinkan/UI/DroneDock/DroneDockWorkbenchViewController.swift @@ -209,7 +209,7 @@ final class DroneDockWorkbenchViewController: BaseViewController { navigationController?.pushViewController(controller, animated: true) } - /// 当前任务、素材和交付将在后续页面实现;本轮点击只展示对应订单入口。 + /// 拍摄进入本地准备/原任务,其他下级业务暂保留入口提示。 private enum OrderEntry { case shooting, materials, delivery } private func showOrderEntry(id: String, action: OrderEntry) { @@ -222,8 +222,8 @@ final class DroneDockWorkbenchViewController: BaseViewController { let detail: String switch action { case .shooting: - title = order.primaryAction.title - detail = order.activeTask.map { "当前任务:\($0.phase.title)" } ?? "剩余 \(order.remainingShootingCount) 次拍摄" + openShootingOrder(id: order.id, from: presenter ?? self) + return case .materials: title = "查看素材" detail = order.materialState.title @@ -236,6 +236,28 @@ final class DroneDockWorkbenchViewController: BaseViewController { (presenter ?? self).present(alert, animated: true) } + /// 始终读取当前范围快照,恢复原任务而不因重新进入重复召唤。 + private func openShootingOrder(id: String, from presenter: UIViewController) { + guard let order = viewModel.store.shootingOrder(id: id) else { return } + if order.activeTask != nil { + openTask(orderID: id, from: presenter) + } else if order.remainingShootingCount > 0 { + let controller = DroneShootingPreparationViewController( + viewModel: DroneShootingPreparationViewModel(store: viewModel.store, orderID: id) + ) + controller.delegate = self + presenter.navigationController?.pushViewController(controller, animated: true) + } + } + + private func openTask(orderID: String, from presenter: UIViewController) { + let controller = DroneShootingTaskViewController( + viewModel: DroneShootingTaskViewModel(store: viewModel.store, orderID: orderID) + ) + controller.delegate = self + presenter.navigationController?.pushViewController(controller, animated: true) + } + @objc private func receiptTapped() { showAlert(title: "收款码", message: "套餐收款页面将在后续搭建,当前不会创建订单或发起收款。") } @@ -268,6 +290,32 @@ extension DroneDockWorkbenchViewController: DroneShootingOrdersViewControllerDel } } +extension DroneDockWorkbenchViewController: DroneShootingPreparationViewControllerDelegate { + func shootingPreparationViewController(_ controller: DroneShootingPreparationViewController, didRequestTaskFor orderID: String) { + openTask(orderID: orderID, from: controller) + } +} + +extension DroneDockWorkbenchViewController: DroneShootingTaskViewControllerDelegate { + func shootingTaskViewControllerDidRequestWorkbench(_ controller: DroneShootingTaskViewController) { + navigationController?.popToViewController(self, animated: true) + } + + func shootingTaskViewController(_ controller: DroneShootingTaskViewController, didRequestPreparationFor order: DroneShootingOrder) { + guard let navigationController, let index = navigationController.viewControllers.firstIndex(where: { $0 === self }) else { return } + let preparation = DroneShootingPreparationViewController( + viewModel: DroneShootingPreparationViewModel(store: viewModel.store, orderID: order.id) + ) + preparation.delegate = self + navigationController.setViewControllers(Array(navigationController.viewControllers.prefix(through: index)) + [preparation], animated: true) + } + + func shootingTaskViewController(_ controller: DroneShootingTaskViewController, didRequestMaterialsFor order: DroneShootingOrder) { + guard let order = viewModel.store.shootingOrder(id: order.id) else { return } + showPreviewEntry(order: order, action: .materials, presenter: controller) + } +} + /// 工作台标题及查看全部入口。 private final class DroneDockSectionHeader: UICollectionReusableView { var onViewAll: (() -> Void)? diff --git a/suixinkan/UI/DroneDock/DronePreparationComponents.swift b/suixinkan/UI/DroneDock/DronePreparationComponents.swift new file mode 100644 index 0000000..aff70b4 --- /dev/null +++ b/suixinkan/UI/DroneDock/DronePreparationComponents.swift @@ -0,0 +1,463 @@ +import SnapKit +import UIKit + +/// 准备页顶部订单额度摘要,成功次数与剩余次数分别展示。 +@MainActor +final class DronePreparationOrderCell: UICollectionViewCell { + private let customerLabel = DroneDockStyle.label(size: 18, weight: .semibold) + private let packageLabel = DroneDockStyle.label(size: 13, color: DroneDockStyle.secondary) + private let completedLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary) + private let remainingLabel = UILabel() + + override init(frame: CGRect) { + super.init(frame: frame) + let separator = UIView() + separator.backgroundColor = DroneDockStyle.border + [customerLabel, packageLabel, completedLabel, remainingLabel, separator].forEach(contentView.addSubview) + customerLabel.adjustsFontSizeToFitWidth = true + customerLabel.minimumScaleFactor = 0.8 + customerLabel.snp.makeConstraints { make in + make.top.equalToSuperview().offset(18) + make.leading.equalToSuperview().offset(4) + make.trailing.lessThanOrEqualTo(separator.snp.leading).offset(-12) + } + packageLabel.snp.makeConstraints { make in + make.top.equalTo(customerLabel.snp.bottom).offset(8) + make.leading.equalTo(customerLabel) + make.bottom.equalToSuperview().inset(14) + } + separator.snp.makeConstraints { make in + make.trailing.equalToSuperview().inset(94) + make.centerY.equalToSuperview() + make.width.equalTo(1 / UIScreen.main.scale) + make.height.equalTo(54) + } + completedLabel.snp.makeConstraints { make in + make.leading.equalTo(separator.snp.trailing).offset(16) + make.top.equalTo(customerLabel) + make.trailing.lessThanOrEqualToSuperview() + } + remainingLabel.snp.makeConstraints { make in + make.leading.equalTo(completedLabel) + make.top.equalTo(completedLabel.snp.bottom).offset(3) + make.trailing.lessThanOrEqualToSuperview() + } + isAccessibilityElement = true + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// 使用订单的权威计数填充摘要,不在视图层扣减额度。 + func apply(order: DroneShootingOrder?) { + guard let order else { + customerLabel.text = "订单信息暂不可用" + packageLabel.text = "请返回订单列表重新进入" + completedLabel.text = "已拍摄 — 次" + remainingLabel.attributedText = remainingText("—") + accessibilityLabel = "订单信息暂不可用" + return + } + customerLabel.text = order.customerName + packageLabel.text = "含 \(order.totalShootingCount) 次拍摄" + completedLabel.text = "已拍摄 \(order.successfulShootingCount) 次" + remainingLabel.attributedText = remainingText(String(order.remainingShootingCount)) + accessibilityLabel = "\(order.customerName),含\(order.totalShootingCount)次拍摄,已拍摄\(order.successfulShootingCount)次,剩余\(order.remainingShootingCount)次" + } + + private func remainingText(_ value: String) -> NSAttributedString { + let text = NSMutableAttributedString(string: "剩余 ", attributes: [.font: UIFont.systemFont(ofSize: 12), .foregroundColor: DroneDockStyle.secondary]) + text.append(NSAttributedString(string: value, attributes: [.font: UIFont.systemFont(ofSize: 26, weight: .medium), .foregroundColor: DroneDockStyle.primary])) + text.append(NSAttributedString(string: " 次", attributes: [.font: UIFont.systemFont(ofSize: 12), .foregroundColor: DroneDockStyle.secondary])) + return text + } +} + +/// 横向点位小卡,使用原型同款本地缩略图展示演示点位。 +@MainActor +final class DronePreparationPointCell: UICollectionViewCell { + private let nameLabel = DroneDockStyle.label(size: 13, weight: .semibold) + private let rangeLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary) + private let countLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary) + private let locationIcon = UIImageView(image: UIImage(systemName: "mappin.circle.fill")) + private let thumbnail = UIImageView() + + override init(frame: CGRect) { + super.init(frame: frame) + contentView.layer.cornerRadius = 7 + contentView.layer.borderWidth = 1 + contentView.layer.cornerCurve = .continuous + thumbnail.contentMode = .scaleAspectFill + thumbnail.backgroundColor = DroneDockStyle.background + thumbnail.layer.cornerRadius = 5 + thumbnail.clipsToBounds = true + locationIcon.contentMode = .scaleAspectFit + [thumbnail, nameLabel, locationIcon, rangeLabel, countLabel].forEach(contentView.addSubview) + thumbnail.snp.makeConstraints { make in + make.leading.equalToSuperview().offset(8) + make.centerY.equalToSuperview() + make.size.equalTo(48) + } + nameLabel.snp.makeConstraints { make in + make.top.equalToSuperview().offset(10) + make.leading.equalTo(thumbnail.snp.trailing).offset(8) + make.trailing.equalToSuperview().inset(6) + } + locationIcon.snp.makeConstraints { make in + make.leading.equalTo(nameLabel) + make.top.equalTo(nameLabel.snp.bottom).offset(5) + make.size.equalTo(10) + } + rangeLabel.snp.makeConstraints { make in + make.leading.equalTo(locationIcon.snp.trailing).offset(3) + make.centerY.equalTo(locationIcon) + make.trailing.equalToSuperview().inset(5) + } + countLabel.snp.makeConstraints { make in + make.top.equalTo(rangeLabel.snp.bottom).offset(4) + make.leading.equalTo(nameLabel) + make.trailing.equalToSuperview().inset(5) + } + isAccessibilityElement = true + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// 仅映射模型提供的范围和次数,已拍摄的点位仍保持可选择。 + func apply(point: DroneShootingPoint, selected: Bool) { + nameLabel.text = point.name + thumbnail.image = UIImage(named: point.id == "point-jinque" ? "drone_demo_pagoda" : "drone_demo_mountain") + rangeLabel.text = point.range.title + switch point.range { + case .inside: rangeLabel.textColor = DroneDockStyle.success + case .outside: rangeLabel.textColor = DroneDockStyle.secondary + case .unknown: rangeLabel.textColor = DroneDockStyle.warning + } + locationIcon.tintColor = rangeLabel.textColor + countLabel.text = point.successfulCountText + contentView.backgroundColor = selected ? DroneDockStyle.primary.withAlphaComponent(0.07) : .white + contentView.layer.borderColor = (selected ? DroneDockStyle.primary : DroneDockStyle.border).cgColor + accessibilityLabel = "\(point.name),\(point.range.title),\(point.successfulCountText)" + accessibilityTraits = selected ? [.button, .selected] : .button + accessibilityIdentifier = "drone.preparation.point.\(point.id)" + } +} + +/// 纵向单选航线行,点击整行后由 ViewModel 保留有效选择。 +@MainActor +final class DronePreparationRouteCell: UICollectionViewCell { + private let nameLabel = DroneDockStyle.label(size: 16, weight: .semibold) + private let routeIcon = DronePreparationRouteIconView() + private let checkmark = UIImageView() + private let separator = UIView() + + override init(frame: CGRect) { + super.init(frame: frame) + contentView.layer.cornerRadius = 8 + contentView.layer.cornerCurve = .continuous + checkmark.contentMode = .scaleAspectFit + separator.backgroundColor = DroneDockStyle.border + [routeIcon, nameLabel, checkmark, separator].forEach(contentView.addSubview) + routeIcon.snp.makeConstraints { make in + make.leading.equalToSuperview().offset(12) + make.centerY.equalToSuperview() + make.size.equalTo(40) + } + nameLabel.snp.makeConstraints { make in + make.leading.equalTo(routeIcon.snp.trailing).offset(14) + make.centerY.equalToSuperview() + make.trailing.lessThanOrEqualTo(checkmark.snp.leading).offset(-12) + } + checkmark.snp.makeConstraints { make in + make.trailing.equalToSuperview().inset(14) + make.centerY.equalToSuperview() + make.size.equalTo(24) + } + separator.snp.makeConstraints { make in + make.leading.trailing.bottom.equalToSuperview() + make.height.equalTo(1 / UIScreen.main.scale) + } + isAccessibilityElement = true + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// 选中样式仅反映现有选择,重复点击不会在视图中取消单选。 + func apply(route: DroneShootingRoute, selected: Bool) { + nameLabel.text = route.name + nameLabel.textColor = selected ? DroneDockStyle.primary : DroneDockStyle.text + routeIcon.apply(selected: selected) + checkmark.image = UIImage(systemName: selected ? "checkmark.circle.fill" : "circle") + checkmark.tintColor = selected ? DroneDockStyle.primary : UIColor(hex: 0xA4ABB8) + contentView.backgroundColor = selected ? DroneDockStyle.primary.withAlphaComponent(0.08) : .white + separator.isHidden = selected + accessibilityLabel = route.name + accessibilityTraits = selected ? [.button, .selected] : .button + accessibilityIdentifier = "drone.preparation.route.\(route.id)" + } +} + +/// 源码绘制的小航线图标,不依赖远程图片和拍摄素材。 +@MainActor +final class DronePreparationRouteIconView: UIView { + private var lineColor = DroneDockStyle.secondary + + override init(frame: CGRect) { + super.init(frame: frame) + layer.cornerRadius = 10 + backgroundColor = UIColor(hex: 0xF0F2F6) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// 图标跟随航线选中态使用统一主色。 + func apply(selected: Bool) { + lineColor = selected ? DroneDockStyle.primary : UIColor(hex: 0x697487) + backgroundColor = selected ? DroneDockStyle.primary.withAlphaComponent(0.07) : UIColor(hex: 0xF0F2F6) + setNeedsDisplay() + } + + override func draw(_ rect: CGRect) { + let scale = min(rect.width, rect.height) / 40 + guard let context = UIGraphicsGetCurrentContext() else { return } + context.saveGState() + context.scaleBy(x: scale, y: scale) + lineColor.setStroke() + let path = UIBezierPath() + path.move(to: CGPoint(x: 22, y: 11)) + path.addLine(to: CGPoint(x: 16, y: 11)) + path.addCurve(to: CGPoint(x: 16, y: 20), controlPoint1: CGPoint(x: 8, y: 11), controlPoint2: CGPoint(x: 8, y: 20)) + path.addLine(to: CGPoint(x: 24, y: 20)) + path.addCurve(to: CGPoint(x: 24, y: 29), controlPoint1: CGPoint(x: 32, y: 20), controlPoint2: CGPoint(x: 32, y: 29)) + path.addLine(to: CGPoint(x: 18, y: 29)) + path.lineWidth = 1.8 + path.lineCapStyle = .round + path.stroke() + UIBezierPath(ovalIn: CGRect(x: 25, y: 8, width: 5, height: 5)).stroke() + UIBezierPath(ovalIn: CGRect(x: 10, y: 26, width: 5, height: 5)).stroke() + context.restoreGState() + } +} + +/// 点位与航线分区标题,数量来自当前点位的实际航线配置。 +@MainActor +final class DronePreparationHeadingView: UICollectionReusableView { + private let titleLabel = DroneDockStyle.label(size: 18, weight: .semibold) + private let detailLabel = DroneDockStyle.label(size: 13, color: DroneDockStyle.secondary) + + override init(frame: CGRect) { + super.init(frame: frame) + let stack = UIStackView(arrangedSubviews: [titleLabel, detailLabel, UIView()]) + stack.axis = .horizontal + stack.alignment = .firstBaseline + stack.spacing = 12 + addSubview(stack) + stack.snp.makeConstraints { make in + make.leading.equalToSuperview().offset(4) + make.trailing.equalToSuperview() + make.centerY.equalToSuperview().offset(3) + } + titleLabel.setContentCompressionResistancePriority(.required, for: .horizontal) + accessibilityTraits = .header + isAccessibilityElement = true + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// 分开展示标题与较浅的航线数量。 + func apply(title: String, detail: String?) { + titleLabel.text = title + detailLabel.text = detail + detailLabel.isHidden = detail == nil + accessibilityLabel = [title, detail].compactMap { $0 }.joined(separator: ",") + } +} + +/// 无点位或无航线时保留就地提示,不增加额外的选择弹窗。 +@MainActor +final class DronePreparationEmptyCell: UICollectionViewCell { + private let titleLabel = DroneDockStyle.label(size: 15, weight: .medium, color: UIColor(hex: 0x697487)) + private let detailLabel = DroneDockStyle.label(size: 13, color: DroneDockStyle.secondary) + + override init(frame: CGRect) { + super.init(frame: frame) + let icon = DronePreparationRouteIconView() + icon.backgroundColor = .clear + let stack = UIStackView(arrangedSubviews: [icon, titleLabel, detailLabel]) + stack.axis = .vertical + stack.alignment = .center + stack.spacing = 14 + detailLabel.numberOfLines = 0 + detailLabel.textAlignment = .center + contentView.addSubview(stack) + icon.snp.makeConstraints { make in make.size.equalTo(36) } + stack.snp.makeConstraints { make in + make.centerY.equalToSuperview().offset(-8) + make.leading.trailing.equalToSuperview().inset(8) + } + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// 明确区分点位未配置与已选点位没有航线。 + func apply(isPointEmpty: Bool) { + titleLabel.text = isPointEmpty ? "暂无可用拍摄点" : "暂无可用航线" + detailLabel.text = isPointEmpty ? "当前景区尚未配置拍摄点" : "请选择其他拍摄点,或稍后重试" + } +} + +/// 固定底部许可栏,独立刷新连接、范围、设备与主按钮。 +@MainActor +final class DronePreparationFooterView: UIView { + /// 工作人员主动点击主操作时通知控制器。 + var onPrimaryTap: (() -> Void)? + /// 结果待确认时由工作人员主动请求同步原召唤状态。 + var onRefreshTap: (() -> Void)? + + private let connectionLabel = DronePreparationIndicatorView() + private let rangeLabel = DronePreparationIndicatorView() + private let selectionLabel = DroneDockStyle.label(size: 13, weight: .semibold) + private let deviceCaption = DroneDockStyle.label("无人机:", size: 11, color: DroneDockStyle.secondary) + private let deviceLabel = DroneDockStatusLabel() + private let primaryButton = UIButton(type: .system) + private let messageLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary) + private let refreshButton = UIButton(type: .system) + + override init(frame: CGRect) { + super.init(frame: frame) + backgroundColor = .white + let statusRow = UIStackView(arrangedSubviews: [connectionLabel, rangeLabel]) + statusRow.axis = .horizontal + statusRow.distribution = .fillEqually + let divider = UIView() + divider.backgroundColor = DroneDockStyle.border + let verticalDivider = UIView() + verticalDivider.backgroundColor = DroneDockStyle.border + let deviceRow = UIStackView(arrangedSubviews: [deviceCaption, deviceLabel, UIView()]) + deviceRow.axis = .horizontal + deviceRow.alignment = .center + deviceRow.spacing = 3 + let summary = UIStackView(arrangedSubviews: [selectionLabel, deviceRow]) + summary.axis = .vertical + summary.spacing = 7 + messageLabel.textAlignment = .center + messageLabel.numberOfLines = 2 + messageLabel.accessibilityIdentifier = "drone.preparation.admission" + refreshButton.setTitle("刷新状态", for: .normal) + refreshButton.setTitleColor(DroneDockStyle.primary, for: .normal) + refreshButton.titleLabel?.font = .systemFont(ofSize: 12, weight: .medium) + refreshButton.accessibilityIdentifier = "drone.preparation.refreshSummon" + refreshButton.addTarget(self, action: #selector(refreshTapped), for: .touchUpInside) + let messageRow = UIStackView(arrangedSubviews: [messageLabel, refreshButton]) + messageRow.axis = .horizontal + messageRow.alignment = .center + messageRow.spacing = 6 + primaryButton.layer.cornerRadius = 8 + primaryButton.layer.cornerCurve = .continuous + primaryButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium) + primaryButton.titleLabel?.adjustsFontSizeToFitWidth = true + primaryButton.titleLabel?.minimumScaleFactor = 0.85 + primaryButton.accessibilityIdentifier = "drone.preparation.summon" + primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside) + [statusRow, divider, summary, primaryButton, messageRow].forEach(addSubview) + statusRow.addSubview(verticalDivider) + statusRow.snp.makeConstraints { make in + make.leading.trailing.top.equalToSuperview() + make.height.equalTo(42) + } + verticalDivider.snp.makeConstraints { make in + make.center.equalToSuperview() + make.width.equalTo(1 / UIScreen.main.scale) + make.height.equalTo(18) + } + divider.snp.makeConstraints { make in + make.top.equalTo(statusRow.snp.bottom) + make.leading.trailing.equalToSuperview() + make.height.equalTo(1 / UIScreen.main.scale) + } + summary.snp.makeConstraints { make in + make.leading.equalToSuperview().offset(20) + make.top.equalTo(divider.snp.bottom).offset(14) + make.trailing.equalTo(primaryButton.snp.leading).offset(-10) + } + primaryButton.snp.makeConstraints { make in + make.top.equalTo(divider.snp.bottom).offset(12) + make.trailing.equalToSuperview().inset(16) + make.width.equalTo(148) + make.height.equalTo(46) + } + refreshButton.snp.makeConstraints { make in + make.width.equalTo(62).priority(999) + make.height.equalTo(26) + } + messageRow.snp.makeConstraints { make in + make.top.equalTo(summary.snp.bottom).offset(10) + make.top.greaterThanOrEqualTo(primaryButton.snp.bottom).offset(9) + make.leading.trailing.equalToSuperview().inset(16) + make.bottom.equalTo(safeAreaLayoutGuide.snp.bottom).inset(10) + } + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// 只绑定 ViewModel 已计算的展示内容和许可,不按电量或连接自行判定可召唤。 + func apply(viewModel: DroneShootingPreparationViewModel) { + connectionLabel.apply(title: viewModel.connectionTitle, tone: viewModel.connectionTone) + rangeLabel.apply(title: viewModel.rangeTitle, tone: viewModel.rangeTone) + selectionLabel.text = viewModel.selectionSummary + deviceLabel.apply(title: viewModel.deviceStatusText, tone: viewModel.deviceState.tone) + primaryButton.setTitle(viewModel.primaryButtonTitle, for: .normal) + primaryButton.isEnabled = viewModel.primaryButtonEnabled + primaryButton.backgroundColor = viewModel.primaryButtonEnabled ? DroneDockStyle.primary : UIColor(hex: 0xE1E7F0) + primaryButton.setTitleColor(.white, for: .normal) + primaryButton.setTitleColor(UIColor(hex: 0x8792A5), for: .disabled) + messageLabel.text = viewModel.admission.message + messageLabel.textColor = DroneDockStyle.color(for: viewModel.admission.tone) + refreshButton.isHidden = !viewModel.shouldShowSummonRefresh + } + + @objc private func primaryTapped() { onPrimaryTap?() } + @objc private func refreshTapped() { onRefreshTap?() } +} + +/// 连接与范围共用的小型状态图标,图标只映射语义色。 +@MainActor +private final class DronePreparationIndicatorView: UIView { + private let icon = UIImageView() + private let label = DroneDockStyle.label(size: 13) + + override init(frame: CGRect) { + super.init(frame: frame) + let stack = UIStackView(arrangedSubviews: [icon, label]) + stack.axis = .horizontal + stack.alignment = .center + stack.spacing = 6 + icon.contentMode = .scaleAspectFit + addSubview(stack) + icon.snp.makeConstraints { make in make.size.equalTo(16) } + stack.snp.makeConstraints { make in + make.center.equalToSuperview() + make.leading.greaterThanOrEqualToSuperview().offset(5) + make.trailing.lessThanOrEqualToSuperview().inset(5) + } + isAccessibilityElement = true + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// 绿色为已满足状态,其他语义色保留各自的提示。 + func apply(title: String, tone: DroneDockStatusTone) { + label.text = title + label.textColor = tone == .green ? DroneDockStyle.text : DroneDockStyle.color(for: tone) + icon.tintColor = DroneDockStyle.color(for: tone) + icon.image = UIImage(systemName: tone == .green ? "checkmark.circle.fill" : "exclamationmark.circle.fill") + accessibilityLabel = title + } +} diff --git a/suixinkan/UI/DroneDock/DroneShootingPreparationViewController.swift b/suixinkan/UI/DroneDock/DroneShootingPreparationViewController.swift new file mode 100644 index 0000000..11d5d93 --- /dev/null +++ b/suixinkan/UI/DroneDock/DroneShootingPreparationViewController.swift @@ -0,0 +1,260 @@ +import SnapKit +import UIKit + +/// 准备页只提出查看任务的导航请求,导航栈由机巢入口统一维护。 +@MainActor +protocol DroneShootingPreparationViewControllerDelegate: AnyObject { + /// 召唤已明确确认,或工作人员主动查看本订单已有任务。 + func shootingPreparationViewController(_ controller: DroneShootingPreparationViewController, didRequestTaskFor orderID: String) +} + +/// 拍摄准备页:选择点位与航线,展示订单额度和设备执行许可。 +@MainActor +final class DroneShootingPreparationViewController: BaseViewController { + /// 由入口注入的共享订单与准备状态。 + let viewModel: DroneShootingPreparationViewModel + /// 将任务导航交回机巢入口,避免页面自行创建任务控制器。 + weak var delegate: DroneShootingPreparationViewControllerDelegate? + + /// 点位使用横向分区,航线使用纵向分区。 + private enum Section: Int, CaseIterable { case order, points, routes } + /// 稳定标识让选择和许可刷新时保留点位的横向滚动位置。 + private enum Item: Hashable { + case order, point(String), route(String), emptyPoints, emptyRoutes + } + + private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: makeLayout()) + private var dataSource: UICollectionViewDiffableDataSource! + private let footerView = DronePreparationFooterView() + private let refreshControl = UIRefreshControl() + + /// 准备页与订单页、任务页读取同一个本地状态源。 + init(viewModel: DroneShootingPreparationViewModel) { + self.viewModel = viewModel + super.init(nibName: nil, bundle: nil) + hidesBottomBarWhenPushed = true + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// 返回页面时刷新配额、选择与设备状态,不提交任何飞行操作。 + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + viewModel.refresh() + if dataSource != nil { applySnapshot(animated: false) } + } + + override func setupNavigationBar() { + title = "拍摄准备" + navigationItem.backButtonDisplayMode = .minimal + #if DEBUG + let scenarios = DroneShootingPreparationScenario.allCases.map { scenario in + UIAction(title: scenario.title) { [weak self] _ in + guard let self else { return } + self.viewModel.applyScenario(scenario) + self.applySnapshot(animated: true) + } + } + let confirmAction = UIAction(title: "模拟召唤确认", image: UIImage(systemName: "checkmark.circle")) { [weak self] _ in + guard let self else { return } + let confirmed = self.viewModel.confirmSummon() + self.applySnapshot(animated: true) + if confirmed { + self.delegate?.shootingPreparationViewController(self, didRequestTaskFor: self.viewModel.orderID) + } + } + let menu = UIMenu(title: "拍摄准备验收状态", children: [ + UIMenu(options: .displayInline, children: scenarios), + UIMenu(options: .displayInline, children: [confirmAction]) + ]) + let item = UIBarButtonItem(image: UIImage(systemName: "slider.horizontal.3"), menu: menu) + item.accessibilityLabel = "拍摄准备验收状态" + item.accessibilityIdentifier = "drone.preparation.scenarios" + navigationItem.rightBarButtonItem = item + #endif + } + + override func setupUI() { + view.backgroundColor = DroneDockStyle.background + collectionView.backgroundColor = .white + collectionView.alwaysBounceVertical = true + collectionView.showsVerticalScrollIndicator = false + collectionView.delegate = self + collectionView.accessibilityIdentifier = "drone.preparation.list" + collectionView.register(DronePreparationOrderCell.self, forCellWithReuseIdentifier: "order") + collectionView.register(DronePreparationPointCell.self, forCellWithReuseIdentifier: "point") + collectionView.register(DronePreparationRouteCell.self, forCellWithReuseIdentifier: "route") + collectionView.register(DronePreparationEmptyCell.self, forCellWithReuseIdentifier: "empty") + collectionView.register(DronePreparationHeadingView.self, + forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, + withReuseIdentifier: "heading") + refreshControl.tintColor = DroneDockStyle.primary + collectionView.refreshControl = refreshControl + view.addSubview(collectionView) + view.addSubview(footerView) + configureDataSource() + applySnapshot(animated: false) + } + + override func setupConstraints() { + collectionView.snp.makeConstraints { make in + make.top.equalTo(view.safeAreaLayoutGuide) + make.leading.trailing.equalToSuperview() + make.bottom.equalTo(footerView.snp.top) + } + footerView.snp.makeConstraints { make in + make.leading.trailing.bottom.equalToSuperview() + } + } + + override func bindActions() { + refreshControl.addTarget(self, action: #selector(refreshTriggered), for: .valueChanged) + footerView.onPrimaryTap = { [weak self] in + guard let self, self.viewModel.primaryButtonEnabled else { return } + let shouldShowTask = self.viewModel.summon() + self.applySnapshot(animated: true) + if shouldShowTask { + self.delegate?.shootingPreparationViewController(self, didRequestTaskFor: self.viewModel.orderID) + } + } + footerView.onRefreshTap = { [weak self] in + guard let self else { return } + self.viewModel.refreshSummonStatus() + self.applySnapshot(animated: true) + } + } + + private func makeLayout() -> UICollectionViewLayout { + UICollectionViewCompositionalLayout { [weak self] sectionIndex, _ in + guard let self, let section = Section(rawValue: sectionIndex) else { return nil } + let height: NSCollectionLayoutDimension + let width: NSCollectionLayoutDimension + switch section { + case .order: + width = .fractionalWidth(1) + height = .estimated(90) + case .points: + width = self.viewModel.points.isEmpty ? .fractionalWidth(1) : .absolute(144) + height = self.viewModel.points.isEmpty ? .absolute(124) : .absolute(80) + case .routes: + width = .fractionalWidth(1) + height = self.viewModel.routes.isEmpty ? .absolute(200) : .absolute(64) + } + let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize( + widthDimension: .fractionalWidth(1), heightDimension: section == .order ? .estimated(90) : .fractionalHeight(1) + )) + let group = NSCollectionLayoutGroup.vertical( + layoutSize: NSCollectionLayoutSize(widthDimension: width, heightDimension: height), subitems: [item] + ) + let layoutSection = NSCollectionLayoutSection(group: group) + layoutSection.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: section == .routes ? 16 : 0, trailing: 16) + if section == .points { + layoutSection.orthogonalScrollingBehavior = self.viewModel.points.isEmpty ? .none : .continuous + layoutSection.interGroupSpacing = 8 + } + if section != .order { + let headerHeight: CGFloat = section == .points ? 46 : 64 + layoutSection.boundarySupplementaryItems = [NSCollectionLayoutBoundarySupplementaryItem( + layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(headerHeight)), + elementKind: UICollectionView.elementKindSectionHeader, alignment: .top + )] + } + return layoutSection + } + } + + private func configureDataSource() { + dataSource = UICollectionViewDiffableDataSource(collectionView: collectionView) { [weak self] list, indexPath, item in + guard let self else { return nil } + switch item { + case .order: + let cell = list.dequeueReusableCell(withReuseIdentifier: "order", for: indexPath) as! DronePreparationOrderCell + cell.apply(order: self.viewModel.order) + return cell + case .point(let id): + let cell = list.dequeueReusableCell(withReuseIdentifier: "point", for: indexPath) as! DronePreparationPointCell + if let point = self.viewModel.points.first(where: { $0.id == id }) { + cell.apply(point: point, selected: self.viewModel.selectedPoint?.id == id) + } + return cell + case .route(let id): + let cell = list.dequeueReusableCell(withReuseIdentifier: "route", for: indexPath) as! DronePreparationRouteCell + if let route = self.viewModel.routes.first(where: { $0.id == id }) { + cell.apply(route: route, selected: self.viewModel.selectedRoute?.id == id) + } + return cell + case .emptyPoints, .emptyRoutes: + let cell = list.dequeueReusableCell(withReuseIdentifier: "empty", for: indexPath) as! DronePreparationEmptyCell + cell.apply(isPointEmpty: item == .emptyPoints) + return cell + } + } + dataSource.supplementaryViewProvider = { [weak self] list, kind, indexPath in + guard let self, kind == UICollectionView.elementKindSectionHeader else { return nil } + let header = list.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "heading", for: indexPath) as! DronePreparationHeadingView + self.applyHeading(header, section: Section(rawValue: indexPath.section)) + return header + } + } + + private func applySnapshot(animated: Bool) { + guard isViewLoaded, dataSource != nil else { return } + let previous = dataSource.snapshot() + let existingItems = Set(previous.itemIdentifiers) + var snapshot = NSDiffableDataSourceSnapshot() + snapshot.appendSections(Section.allCases) + snapshot.appendItems([.order], toSection: .order) + snapshot.appendItems(viewModel.points.isEmpty ? [.emptyPoints] : viewModel.points.map { .point($0.id) }, toSection: .points) + snapshot.appendItems(viewModel.routes.isEmpty ? [.emptyRoutes] : viewModel.routes.map { .route($0.id) }, toSection: .routes) + snapshot.reconfigureItems(snapshot.itemIdentifiers.filter { existingItems.contains($0) }) + footerView.apply(viewModel: viewModel) + dataSource.apply(snapshot, animatingDifferences: animated) { [weak self] in + guard let self else { return } + let kind = UICollectionView.elementKindSectionHeader + for indexPath in self.collectionView.indexPathsForVisibleSupplementaryElements(ofKind: kind) { + guard let header = self.collectionView.supplementaryView(forElementKind: kind, at: indexPath) as? DronePreparationHeadingView else { continue } + self.applyHeading(header, section: Section(rawValue: indexPath.section)) + } + } + let pointEmptinessChanged = previous.itemIdentifiers.contains(.emptyPoints) != snapshot.itemIdentifiers.contains(.emptyPoints) + let routeEmptinessChanged = previous.itemIdentifiers.contains(.emptyRoutes) != snapshot.itemIdentifiers.contains(.emptyRoutes) + if pointEmptinessChanged || routeEmptinessChanged { collectionView.collectionViewLayout.invalidateLayout() } + } + + private func applyHeading(_ header: DronePreparationHeadingView, section: Section?) { + switch section { + case .points: + header.apply(title: "拍摄点", detail: nil) + case .routes: + let title = viewModel.selectedPoint.map { "\($0.name)的航线" } ?? "拍摄航线" + header.apply(title: title, detail: "共 \(viewModel.routes.count) 条") + default: + header.apply(title: "", detail: nil) + } + } + + @objc private func refreshTriggered() { + viewModel.refresh() + applySnapshot(animated: true) + refreshControl.endRefreshing() + } +} + +extension DroneShootingPreparationViewController: UICollectionViewDelegate { + /// 召唤处理中保留滚动浏览,但冻结已提交的点位与航线选择。 + func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { + !viewModel.hasPendingSummon + } + + /// 整卡点位与整行航线均可选择;实际有效性和选择恢复由 ViewModel 处理。 + func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { + guard !viewModel.hasPendingSummon, let item = dataSource.itemIdentifier(for: indexPath) else { return } + switch item { + case .point(let id): viewModel.selectPoint(id: id) + case .route(let id): viewModel.selectRoute(id: id) + default: return + } + applySnapshot(animated: true) + } +} diff --git a/suixinkan/UI/DroneDock/DroneShootingTaskViewController.swift b/suixinkan/UI/DroneDock/DroneShootingTaskViewController.swift new file mode 100644 index 0000000..d4bae5f --- /dev/null +++ b/suixinkan/UI/DroneDock/DroneShootingTaskViewController.swift @@ -0,0 +1,481 @@ +import SnapKit +import UIKit + +/// 当前任务页面的导航意图;返回始终由工作台协调器处理。 +@MainActor +protocol DroneShootingTaskViewControllerDelegate: AnyObject { + /// 直接回工作台,保留原任务,不弹离页确认。 + func shootingTaskViewControllerDidRequestWorkbench(_ controller: DroneShootingTaskViewController) + /// 任务确认结束且仍有余次后,进入准备页恢复有效选择。 + func shootingTaskViewController(_ controller: DroneShootingTaskViewController, didRequestPreparationFor order: DroneShootingOrder) + /// 查看当前订单的素材;首轮由入口协调器提供占位。 + func shootingTaskViewController(_ controller: DroneShootingTaskViewController, didRequestMaterialsFor order: DroneShootingOrder) +} + +/// 原任务控制页:独立展示飞行、拍摄结果、连接及指令确认状态。 +@MainActor +final class DroneShootingTaskViewController: BaseViewController { + /// 协调工作台、重新准备与素材入口,不在页面内创建新任务。 + weak var delegate: (any DroneShootingTaskViewControllerDelegate)? + + private let viewModel: DroneShootingTaskViewModel + private let demoBar = UIView() + private let scrollView = UIScrollView() + private let contentStack = UIStackView() + private let summaryView = UIView() + private let taskTitleLabel = DroneDockStyle.label(size: 17, weight: .semibold) + private let subtitleLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary) + private let feedView = DroneShootingTaskFeedView() + private let telemetryView = DroneShootingTaskTelemetryView() + private let controlPanel = UIView() + private let controlStack = UIStackView() + private let statusIconBackground = UIView() + private let statusIconView = UIImageView() + private let statusTitleLabel = DroneDockStyle.label(size: 21, weight: .semibold) + private let statusMessageLabel = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary) + private let commandView = UIView() + private let commandTitleLabel = DroneDockStyle.label(size: 12, weight: .semibold, color: DroneDockStyle.warning) + private let commandMessageLabel = DroneDockStyle.label(size: 11, color: DroneDockStyle.secondary) + private let refreshTaskButton = UIButton(type: .system) + private let primaryButton = UIButton(type: .system) + private let preparationButton = UIButton(type: .system) + private let materialsButton = UIButton(type: .system) + private let pauseButton = DroneShootingTaskSafetyButton(symbol: "pause.circle", color: UIColor(hex: 0xEC982A), filled: true) + private let returnButton = DroneShootingTaskSafetyButton(symbol: "arrow.uturn.backward", color: UIColor(hex: 0xD85762), filled: false) + private var displayedResultNoticeID: String? + private var interactivePopWasEnabled: Bool? + + /// 注入共享数据源上的原任务 ViewModel;构造及页面出现不会发起召唤。 + init(viewModel: DroneShootingTaskViewModel) { + self.viewModel = viewModel + super.init(nibName: nil, bundle: nil) + hidesBottomBarWhenPushed = true + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// 重进时只读取原任务,等待明确状态,不重发控制指令。 + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + if interactivePopWasEnabled == nil { + interactivePopWasEnabled = navigationController?.interactivePopGestureRecognizer?.isEnabled + } + navigationController?.interactivePopGestureRecognizer?.isEnabled = false + viewModel.refresh() + applySnapshot() + } + + /// 页面完整呈现后才显示本次结果提示,用户可以稍后查看素材。 + override func viewDidAppear(_ animated: Bool) { + super.viewDidAppear(animated) + presentResultNoticeIfNeeded() + } + + /// 恢复其他页面原有返回手势;本页返回统一直接回工作台。 + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + if let interactivePopWasEnabled { + navigationController?.interactivePopGestureRecognizer?.isEnabled = interactivePopWasEnabled + self.interactivePopWasEnabled = nil + } + } + + /// 配置直接返回工作台的导航入口。 + override func setupNavigationBar() { + title = "拍摄任务" + navigationItem.hidesBackButton = true + let back = UIBarButtonItem(image: UIImage(systemName: "chevron.left"), style: .plain, target: self, action: #selector(backTapped)) + back.tintColor = DroneDockStyle.text + back.accessibilityLabel = "返回机巢工作台" + back.accessibilityIdentifier = "drone.task.back" + navigationItem.leftBarButtonItem = back + } + + /// 依原型布局摘要、演示画面、遥测与固定控制区。 + override func setupUI() { + view.backgroundColor = .white + setupDemoBar() + scrollView.showsVerticalScrollIndicator = false + scrollView.alwaysBounceVertical = false + scrollView.accessibilityIdentifier = "drone.task.overview" + view.addSubview(scrollView) + contentStack.axis = .vertical + contentStack.spacing = 0 + scrollView.addSubview(contentStack) + contentStack.addArrangedSubview(summaryView) + summaryView.addSubview(taskTitleLabel) + summaryView.addSubview(subtitleLabel) + taskTitleLabel.numberOfLines = 2 + subtitleLabel.numberOfLines = 1 + subtitleLabel.adjustsFontSizeToFitWidth = true + subtitleLabel.minimumScaleFactor = 0.8 + contentStack.addArrangedSubview(feedView) + contentStack.addArrangedSubview(telemetryView) + setupControlPanel() + } + + /// 上部内容允许在小屏滚动,安全控制始终保持可见。 + override func setupConstraints() { + demoBar.snp.makeConstraints { make in + make.top.equalTo(view.safeAreaLayoutGuide) + make.leading.trailing.equalToSuperview() + make.height.equalTo(29) + } + scrollView.snp.makeConstraints { make in + make.top.equalTo(demoBar.snp.bottom) + make.leading.trailing.equalToSuperview() + make.bottom.equalTo(controlPanel.snp.top) + } + contentStack.snp.makeConstraints { make in + make.edges.equalTo(scrollView.contentLayoutGuide) + make.width.equalTo(scrollView.frameLayoutGuide) + } + taskTitleLabel.snp.makeConstraints { make in + make.top.equalToSuperview().offset(10) + make.leading.trailing.equalToSuperview().inset(16) + } + subtitleLabel.snp.makeConstraints { make in + make.top.equalTo(taskTitleLabel.snp.bottom).offset(5) + make.leading.trailing.equalToSuperview().inset(16) + make.bottom.equalToSuperview().inset(10) + } + feedView.snp.makeConstraints { make in + make.height.equalTo(feedView.snp.width).multipliedBy(9.0 / 16.0) + } + controlPanel.snp.makeConstraints { make in + make.leading.trailing.bottom.equalToSuperview() + } + controlStack.snp.makeConstraints { make in + make.top.equalToSuperview().offset(17) + make.leading.trailing.equalToSuperview().inset(16) + make.bottom.equalTo(view.safeAreaLayoutGuide).inset(12) + } + } + + /// 将按钮操作交给 ViewModel,提交后主动刷新当前快照。 + override func bindActions() { + primaryButton.addTarget(self, action: #selector(primaryTapped), for: .touchUpInside) + preparationButton.addTarget(self, action: #selector(preparationTapped), for: .touchUpInside) + materialsButton.addTarget(self, action: #selector(materialsTapped), for: .touchUpInside) + pauseButton.addTarget(self, action: #selector(pauseTapped), for: .touchUpInside) + returnButton.addTarget(self, action: #selector(returnTapped), for: .touchUpInside) + refreshTaskButton.addTarget(self, action: #selector(refreshTaskTapped), for: .touchUpInside) + feedView.onExpand = { [weak self] in + let expanded = DroneShootingTaskExpandedFeedViewController() + expanded.modalPresentationStyle = .fullScreen + self?.present(expanded, animated: true) + } + feedView.onReconnect = { [weak self] in + guard let self else { return } + if self.viewModel.phoneConnection == .disconnected { + self.viewModel.reconnectPhone() + } else if self.viewModel.phoneConnection == .connected { + self.viewModel.reconnectFeed() + } + self.applySnapshot() + } + } + + private func setupDemoBar() { + demoBar.backgroundColor = UIColor(hex: 0xF3F6FC) + view.addSubview(demoBar) + let label = DroneDockStyle.label("本地界面演示 · 无真实操作", size: 10, color: DroneDockStyle.secondary) + demoBar.addSubview(label) + label.snp.makeConstraints { make in + make.leading.equalToSuperview().offset(16) + make.centerY.equalToSuperview() + } + #if DEBUG + let scenarioButton = UIButton(type: .system) + var configuration = UIButton.Configuration.plain() + configuration.title = "模拟状态" + configuration.image = UIImage(systemName: "slider.horizontal.3") + configuration.imagePadding = 4 + configuration.baseForegroundColor = DroneDockStyle.primary + configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 11) + configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in + var outgoing = incoming + outgoing.font = .systemFont(ofSize: 10) + return outgoing + } + scenarioButton.configuration = configuration + scenarioButton.showsMenuAsPrimaryAction = true + scenarioButton.menu = UIMenu(title: "本地模拟事件 · 不自动推进", children: DroneShootingTaskScenario.allCases.map { scenario in + UIAction(title: scenario.title) { [weak self] _ in + self?.viewModel.applyScenario(scenario) + self?.applySnapshot() + self?.presentResultNoticeIfNeeded() + } + }) + scenarioButton.accessibilityIdentifier = "drone.task.scenarios" + demoBar.addSubview(scenarioButton) + scenarioButton.snp.makeConstraints { make in + make.trailing.equalToSuperview().inset(12) + make.top.bottom.equalToSuperview() + } + #endif + } + + private func setupControlPanel() { + controlPanel.backgroundColor = .white + view.addSubview(controlPanel) + controlStack.axis = .vertical + controlStack.spacing = 11 + controlPanel.addSubview(controlStack) + + let statusRow = UIStackView() + statusRow.axis = .horizontal + statusRow.spacing = 12 + statusRow.alignment = .top + statusIconBackground.layer.cornerRadius = 19 + statusIconBackground.addSubview(statusIconView) + statusIconView.contentMode = .scaleAspectFit + statusIconView.snp.makeConstraints { make in + make.center.equalToSuperview() + make.size.equalTo(22) + } + statusIconBackground.snp.makeConstraints { make in make.size.equalTo(38) } + let statusTexts = UIStackView(arrangedSubviews: [statusTitleLabel, statusMessageLabel]) + statusTexts.axis = .vertical + statusTexts.spacing = 6 + statusTitleLabel.numberOfLines = 2 + statusTitleLabel.accessibilityTraits = .header + statusTitleLabel.accessibilityIdentifier = "drone.task.statusTitle" + statusMessageLabel.numberOfLines = 0 + statusMessageLabel.accessibilityIdentifier = "drone.task.statusMessage" + statusRow.addArrangedSubview(statusIconBackground) + statusRow.addArrangedSubview(statusTexts) + controlStack.addArrangedSubview(statusRow) + setupCommandView() + controlStack.addArrangedSubview(commandView) + controlStack.addArrangedSubview(primaryButton) + primaryButton.accessibilityIdentifier = "drone.task.primary" + primaryButton.snp.makeConstraints { make in make.height.equalTo(49) } + + materialsButton.accessibilityIdentifier = "drone.task.materials" + materialsButton.setTitle("查看素材", for: .normal) + materialsButton.setTitleColor(DroneDockStyle.primary, for: .normal) + materialsButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium) + materialsButton.snp.makeConstraints { make in make.height.equalTo(30).priority(999) } + controlStack.addArrangedSubview(materialsButton) + + preparationButton.accessibilityIdentifier = "drone.task.prepareAgain" + preparationButton.setTitle("继续准备拍摄", for: .normal) + preparationButton.setTitleColor(DroneDockStyle.primary, for: .normal) + preparationButton.titleLabel?.font = .systemFont(ofSize: 13, weight: .medium) + preparationButton.snp.makeConstraints { make in make.height.equalTo(27).priority(999) } + controlStack.addArrangedSubview(preparationButton) + + let safetyHeader = UIView() + let safetyLabel = DroneDockStyle.label("安全控制", size: 10, color: DroneDockStyle.secondary) + let leftLine = UIView() + let rightLine = UIView() + leftLine.backgroundColor = DroneDockStyle.border + rightLine.backgroundColor = DroneDockStyle.border + safetyHeader.addSubview(leftLine) + safetyHeader.addSubview(rightLine) + safetyHeader.addSubview(safetyLabel) + safetyLabel.snp.makeConstraints { make in make.center.equalToSuperview() } + leftLine.snp.makeConstraints { make in + make.leading.centerY.equalToSuperview() + make.trailing.equalTo(safetyLabel.snp.leading).offset(-9) + make.height.equalTo(0.5) + } + rightLine.snp.makeConstraints { make in + make.trailing.centerY.equalToSuperview() + make.leading.equalTo(safetyLabel.snp.trailing).offset(9) + make.height.equalTo(0.5) + } + safetyHeader.snp.makeConstraints { make in make.height.equalTo(13) } + controlStack.addArrangedSubview(safetyHeader) + controlStack.setCustomSpacing(5, after: primaryButton) + controlStack.setCustomSpacing(5, after: safetyHeader) + let safetyButtons = UIStackView(arrangedSubviews: [pauseButton, returnButton]) + safetyButtons.axis = .horizontal + safetyButtons.spacing = 8 + safetyButtons.distribution = .fillEqually + safetyButtons.snp.makeConstraints { make in make.height.equalTo(62) } + pauseButton.accessibilityIdentifier = "drone.task.pause" + returnButton.accessibilityIdentifier = "drone.task.return" + controlStack.addArrangedSubview(safetyButtons) + } + + private func setupCommandView() { + commandView.backgroundColor = UIColor(hex: 0xFFF8EB) + commandView.layer.cornerRadius = 8 + commandView.layer.borderColor = UIColor(hex: 0xF4E5C7).cgColor + commandView.layer.borderWidth = 1 + let commandStack = UIStackView(arrangedSubviews: [commandTitleLabel, commandMessageLabel, refreshTaskButton]) + commandStack.axis = .vertical + commandStack.spacing = 5 + commandTitleLabel.numberOfLines = 0 + commandMessageLabel.numberOfLines = 0 + commandView.addSubview(commandStack) + commandStack.snp.makeConstraints { make in + make.top.leading.trailing.equalToSuperview().inset(10) + make.bottom.equalToSuperview().inset(10).priority(999) + } + var configuration = UIButton.Configuration.bordered() + configuration.title = "刷新任务状态" + configuration.image = UIImage(systemName: "arrow.clockwise") + configuration.imagePadding = 6 + configuration.baseForegroundColor = DroneDockStyle.primary + configuration.background.backgroundColor = .clear + configuration.background.strokeColor = DroneDockStyle.primary.withAlphaComponent(0.5) + configuration.background.strokeWidth = 1 + configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in + var outgoing = incoming + outgoing.font = .systemFont(ofSize: 12) + return outgoing + } + refreshTaskButton.configuration = configuration + refreshTaskButton.accessibilityIdentifier = "drone.task.sync" + refreshTaskButton.snp.makeConstraints { make in make.height.equalTo(34).priority(999) } + } + + private func applySnapshot() { + guard isViewLoaded else { return } + taskTitleLabel.text = viewModel.title + subtitleLabel.text = viewModel.subtitle + feedView.apply(phone: viewModel.phoneConnection, feed: viewModel.feedConnection, isFlightFinished: viewModel.session?.isFlightFinished == true) + telemetryView.apply(telemetry: viewModel.telemetry, isStale: viewModel.phoneConnection != .connected) + statusTitleLabel.text = viewModel.statusTitle + statusMessageLabel.text = viewModel.statusMessage + let statusColor = DroneDockStyle.color(for: viewModel.statusTone) + statusIconBackground.backgroundColor = statusColor.withAlphaComponent(0.1) + statusIconView.tintColor = statusColor + statusIconView.image = UIImage(systemName: statusSymbol) + commandView.isHidden = viewModel.commandTitle == nil + commandTitleLabel.text = viewModel.commandTitle + commandMessageLabel.text = viewModel.commandMessage + refreshTaskButton.isHidden = !viewModel.shouldShowCommandRefresh + configurePrimaryButton() + materialsButton.isHidden = !(viewModel.session?.result == .succeeded && viewModel.primaryAction != .viewMaterials) + preparationButton.isHidden = !(viewModel.session?.isFlightFinished == true && (viewModel.order?.remainingShootingCount ?? 0) > 0 && viewModel.primaryAction == .viewMaterials) + pauseButton.apply(title: viewModel.pauseTitle, subtitle: viewModel.pauseSubtitle, enabled: viewModel.canPause) + returnButton.apply(title: viewModel.returnTitle, subtitle: viewModel.returnSubtitle, enabled: viewModel.canReturn) + } + + private var statusSymbol: String { + if viewModel.phoneConnection != .connected { return "questionmark.circle.fill" } + if viewModel.session?.result == .succeeded { return "checkmark.circle.fill" } + if viewModel.session?.result == .failed { return "exclamationmark.circle.fill" } + switch viewModel.phase { + case .navigating: return "paperplane.fill" + case .arrived: return "checkmark.circle.fill" + case .shooting: return "video.fill" + case .shootingPaused, .returnPaused: return "pause.fill" + case .returning: return "arrow.uturn.backward" + case .unconfirmed, .none: return "questionmark.circle.fill" + } + } + + private func configurePrimaryButton() { + var configuration = UIButton.Configuration.filled() + configuration.title = viewModel.primaryTitle + configuration.image = UIImage(systemName: primarySymbol) + configuration.imagePadding = 9 + configuration.baseBackgroundColor = DroneDockStyle.primary + configuration.baseForegroundColor = .white + configuration.cornerStyle = .medium + let command = viewModel.session?.command + configuration.showsActivityIndicator = command?.status == .processing && ( + (viewModel.primaryAction == .start && command?.kind == .start) + || (viewModel.primaryAction == .resume && command?.kind == .resume) + ) + configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(pointSize: 20) + configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in + var outgoing = incoming + outgoing.font = .systemFont(ofSize: 17, weight: .semibold) + return outgoing + } + primaryButton.configuration = configuration + primaryButton.isEnabled = viewModel.primaryEnabled + primaryButton.alpha = viewModel.primaryEnabled ? 1 : 0.46 + } + + private var primarySymbol: String { + switch viewModel.primaryAction { + case .start: "camera" + case .resume: "play.fill" + case .viewMaterials: "photo.on.rectangle" + case .prepareAgain: "arrow.clockwise" + case .none: "camera" + } + } + + private func presentResultNoticeIfNeeded() { + guard viewIfLoaded?.window != nil, presentedViewController == nil, + let notice = viewModel.resultNotice, displayedResultNoticeID != notice.id else { return } + displayedResultNoticeID = notice.id + let alert = UIAlertController(title: notice.title, message: notice.message, preferredStyle: .alert) + if notice.isSuccess { + alert.addAction(UIAlertAction(title: "稍后再去", style: .cancel) { [weak self] _ in self?.viewModel.dismissResultNotice() }) + alert.addAction(UIAlertAction(title: "去查看", style: .default) { [weak self] _ in + guard let self else { return } + self.viewModel.dismissResultNotice() + self.requestMaterials() + }) + } else { + alert.addAction(UIAlertAction(title: "知道了", style: .default) { [weak self] _ in self?.viewModel.dismissResultNotice() }) + } + present(alert, animated: true) + } + + private func requestMaterials() { + guard let order = viewModel.order else { return } + if let delegate { + delegate.shootingTaskViewController(self, didRequestMaterialsFor: order) + } else { + showAlert(title: "素材库", message: "本地界面预览:素材入口将在后续接入。") + } + } + + @objc private func materialsTapped() { requestMaterials() } + + @objc private func backTapped() { + if let delegate { + delegate.shootingTaskViewControllerDidRequestWorkbench(self) + } else if let workbench = navigationController?.viewControllers.first(where: { $0 is DroneDockWorkbenchViewController }) { + navigationController?.popToViewController(workbench, animated: true) + } else { + navigationController?.popToRootViewController(animated: true) + } + } + + @objc private func primaryTapped() { + guard viewModel.primaryEnabled else { return } + switch viewModel.primaryAction { + case .start: _ = viewModel.startShooting() + case .resume: _ = viewModel.resume() + case .viewMaterials: requestMaterials() + case .prepareAgain: preparationTapped() + case .none: break + } + applySnapshot() + } + + @objc private func preparationTapped() { + guard let order = viewModel.order, order.remainingShootingCount > 0, viewModel.session?.isFlightFinished == true else { return } + delegate?.shootingTaskViewController(self, didRequestPreparationFor: order) + } + + @objc private func pauseTapped() { + guard viewModel.canPause else { return } + _ = viewModel.pause() + applySnapshot() + } + + @objc private func returnTapped() { + guard viewModel.canReturn else { return } + _ = viewModel.requestReturn() + applySnapshot() + } + + @objc private func refreshTaskTapped() { + viewModel.refreshTaskStatus() + applySnapshot() + presentResultNoticeIfNeeded() + } +} diff --git a/suixinkan/UI/DroneDock/DroneShootingTaskViews.swift b/suixinkan/UI/DroneDock/DroneShootingTaskViews.swift new file mode 100644 index 0000000..93a86f5 --- /dev/null +++ b/suixinkan/UI/DroneDock/DroneShootingTaskViews.swift @@ -0,0 +1,349 @@ +import SnapKit +import UIKit + +/// 任务页的本地画面演示组件;连接、断流与任务结果分别展示。 +@MainActor +final class DroneShootingTaskFeedView: UIView { + /// 用户请求查看本地静帧大图。 + var onExpand: (() -> Void)? + /// 用户请求重连手机或画面,具体意图由当前连接状态决定。 + var onReconnect: (() -> Void)? + + private let imageView = UIImageView(image: UIImage(named: "drone_demo_tourists")) + private let captionLabel = DroneDockStyle.label("演示画面 · 本地静帧", size: 11, color: .white) + private let expandButton = UIButton(type: .system) + private let interruptionView = UIView() + private let interruptionIcon = UIImageView() + private let interruptionTitle = DroneDockStyle.label(size: 16, weight: .semibold) + private let interruptionMessage = DroneDockStyle.label(size: 12, color: DroneDockStyle.secondary) + private let reconnectButton = UIButton(type: .system) + + /// 创建 16:9 本地图片画面,不请求网络,也不播放视频。 + override init(frame: CGRect) { + super.init(frame: frame) + setupUI() + setupConstraints() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// 独立应用手机连接与画面连接;完成任务只改变静帧说明。 + func apply(phone: DroneShootingConnectionState, feed: DroneShootingConnectionState, isFlightFinished: Bool) { + let phoneUnavailable = phone != .connected + let feedUnavailable = feed != .connected + interruptionView.isHidden = !phoneUnavailable && !feedUnavailable + expandButton.isHidden = phoneUnavailable || feedUnavailable + captionLabel.text = isFlightFinished ? "上次任务画面 · 本地演示" : "演示画面 · 本地静帧" + + if phoneUnavailable { + interruptionIcon.image = UIImage(systemName: "wifi.slash") + switch phone { + case .disconnected: + interruptionTitle.text = "手机网络连接中断" + interruptionMessage.text = "状态暂未更新,请恢复连接后同步当前任务" + configureReconnect(title: "重新连接", enabled: true) + case .reconnecting: + interruptionTitle.text = "正在重新连接" + interruptionMessage.text = "等待本地模拟连接回执" + configureReconnect(title: "正在连接", enabled: false) + case .synchronizing: + interruptionTitle.text = "正在同步当前任务" + interruptionMessage.text = "同步确认前请勿重复发送指令" + configureReconnect(title: "正在同步", enabled: false) + case .connected: break + } + } else if feedUnavailable { + interruptionIcon.image = UIImage(systemName: "video.slash") + interruptionTitle.text = feed == .disconnected ? "演示画面连接中断" : "正在重新连接画面" + interruptionMessage.text = "仅画面中断,任务与控制状态分别更新" + configureReconnect(title: feed == .disconnected ? "重新连接画面" : "正在连接画面", enabled: feed == .disconnected) + } + } + + private func setupUI() { + backgroundColor = UIColor(hex: 0xE9EEF6) + clipsToBounds = true + imageView.contentMode = .scaleAspectFill + imageView.clipsToBounds = true + imageView.accessibilityLabel = "游客取景示意,本地演示静帧" + addSubview(imageView) + + let captionBackground = UIView() + captionBackground.backgroundColor = UIColor.black.withAlphaComponent(0.38) + captionBackground.layer.cornerRadius = 5 + captionBackground.addSubview(captionLabel) + addSubview(captionBackground) + captionBackground.snp.makeConstraints { make in + make.leading.top.equalToSuperview().inset(12) + } + captionLabel.snp.makeConstraints { make in make.edges.equalToSuperview().inset(UIEdgeInsets(top: 5, left: 7, bottom: 5, right: 7)) } + + expandButton.setImage(UIImage(systemName: "arrow.up.left.and.arrow.down.right"), for: .normal) + expandButton.tintColor = .white + expandButton.backgroundColor = UIColor.black.withAlphaComponent(0.35) + expandButton.layer.cornerRadius = 18 + expandButton.accessibilityLabel = "放大本地演示画面" + expandButton.accessibilityIdentifier = "drone.task.feed.expand" + expandButton.addTarget(self, action: #selector(expandTapped), for: .touchUpInside) + addSubview(expandButton) + + interruptionView.backgroundColor = UIColor(hex: 0xE9EEF6) + addSubview(interruptionView) + interruptionIcon.contentMode = .scaleAspectFit + interruptionIcon.tintColor = UIColor(hex: 0x8992A3) + interruptionTitle.textAlignment = .center + interruptionMessage.textAlignment = .center + interruptionMessage.numberOfLines = 0 + interruptionView.addSubview(interruptionIcon) + interruptionView.addSubview(interruptionTitle) + interruptionView.addSubview(interruptionMessage) + interruptionView.addSubview(reconnectButton) + reconnectButton.accessibilityIdentifier = "drone.task.feed.reconnect" + reconnectButton.addTarget(self, action: #selector(reconnectTapped), for: .touchUpInside) + } + + private func setupConstraints() { + imageView.snp.makeConstraints { make in make.edges.equalToSuperview() } + expandButton.snp.makeConstraints { make in + make.trailing.bottom.equalToSuperview().inset(12) + make.size.equalTo(36) + } + interruptionView.snp.makeConstraints { make in make.edges.equalToSuperview() } + interruptionIcon.snp.makeConstraints { make in + make.centerX.equalToSuperview() + make.centerY.equalToSuperview().offset(-49) + make.size.equalTo(30) + } + interruptionTitle.snp.makeConstraints { make in + make.top.equalTo(interruptionIcon.snp.bottom).offset(11) + make.leading.trailing.equalToSuperview().inset(16) + } + interruptionMessage.snp.makeConstraints { make in + make.top.equalTo(interruptionTitle.snp.bottom).offset(5) + make.leading.trailing.equalToSuperview().inset(18) + } + reconnectButton.snp.makeConstraints { make in + make.top.equalTo(interruptionMessage.snp.bottom).offset(11) + make.centerX.equalToSuperview() + make.height.equalTo(34) + } + } + + private func configureReconnect(title: String, enabled: Bool) { + var configuration = UIButton.Configuration.bordered() + configuration.title = title + configuration.baseForegroundColor = DroneDockStyle.primary + configuration.background.strokeColor = DroneDockStyle.primary.withAlphaComponent(0.5) + configuration.background.strokeWidth = 1 + configuration.background.backgroundColor = .clear + configuration.cornerStyle = .medium + configuration.contentInsets = NSDirectionalEdgeInsets(top: 6, leading: 16, bottom: 6, trailing: 16) + configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in + var outgoing = incoming + outgoing.font = .systemFont(ofSize: 12, weight: .medium) + return outgoing + } + reconnectButton.configuration = configuration + reconnectButton.isEnabled = enabled + } + + @objc private func expandTapped() { onExpand?() } + @objc private func reconnectTapped() { onReconnect?() } +} + +/// 任务页六项遥测格;手机断网或读数缺失时保留未知值。 +@MainActor +final class DroneShootingTaskTelemetryView: UIView { + private let stackView = UIStackView() + private let staleLabel = DroneDockStyle.label("ⓘ 状态暂未更新", size: 11, color: DroneDockStyle.secondary) + private var cells: [DroneShootingTaskTelemetryCell] = [] + + /// 以两行三列固定展示电量、温度、风速、雨量、信号与搜星。 + override init(frame: CGRect) { + super.init(frame: frame) + backgroundColor = DroneDockStyle.background + stackView.axis = .vertical + stackView.spacing = 6 + stackView.alignment = .fill + addSubview(stackView) + stackView.addArrangedSubview(staleLabel) + let definitions = [ + ("电池电量", "battery.75percent"), ("环境温度", "thermometer.medium"), ("风速", "wind"), + ("雨量", "cloud.rain"), ("信号状态", "cellularbars"), ("搜星状态", "location.north.circle") + ] + for rowIndex in 0..<2 { + let row = UIStackView() + row.axis = .horizontal + row.distribution = .fillEqually + row.spacing = 6 + for columnIndex in 0..<3 { + let definition = definitions[rowIndex * 3 + columnIndex] + let cell = DroneShootingTaskTelemetryCell(title: definition.0, symbol: definition.1) + cells.append(cell) + row.addArrangedSubview(cell) + } + stackView.addArrangedSubview(row) + row.snp.makeConstraints { make in make.height.equalTo(55) } + } + stackView.snp.makeConstraints { make in make.edges.equalToSuperview().inset(10) } + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// 新快照覆盖全部读数;不保留断网前的值冒充有效数据。 + func apply(telemetry: DroneDockTelemetry, isStale: Bool) { + staleLabel.isHidden = !isStale + let values = isStale + ? Array(repeating: "—", count: 6) + : [telemetry.batteryText, telemetry.temperatureText, telemetry.windText, telemetry.rainText, telemetry.signalText, telemetry.satelliteText] + for (index, cell) in cells.enumerated() { + cell.apply(value: values[index], isStale: isStale) + } + } +} + +/// 单项遥测读数,标题与图标保持稳定位置。 +@MainActor +private final class DroneShootingTaskTelemetryCell: UIView { + private let valueLabel = DroneDockStyle.label(size: 16, weight: .semibold) + private let iconView: UIImageView + + /// 创建标题、图标与数值的紧凑展示。 + init(title: String, symbol: String) { + iconView = UIImageView(image: UIImage(systemName: symbol)) + super.init(frame: .zero) + backgroundColor = .white + layer.cornerRadius = 7 + let titleLabel = DroneDockStyle.label(title, size: 11, color: DroneDockStyle.secondary) + titleLabel.textAlignment = .center + iconView.contentMode = .scaleAspectFit + let valueRow = UIStackView(arrangedSubviews: [iconView, valueLabel]) + valueRow.axis = .horizontal + valueRow.spacing = 6 + valueRow.alignment = .center + addSubview(titleLabel) + addSubview(valueRow) + iconView.snp.makeConstraints { make in make.size.equalTo(17) } + titleLabel.snp.makeConstraints { make in + make.top.equalToSuperview().offset(7) + make.leading.trailing.equalToSuperview().inset(4) + } + valueRow.snp.makeConstraints { make in + make.centerX.equalToSuperview() + make.top.equalTo(titleLabel.snp.bottom).offset(4) + make.leading.greaterThanOrEqualToSuperview().offset(4) + make.trailing.lessThanOrEqualToSuperview().offset(-4) + } + valueLabel.adjustsFontSizeToFitWidth = true + valueLabel.minimumScaleFactor = 0.8 + isAccessibilityElement = true + accessibilityLabel = title + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// 更新数值和有效性,不根据电量自行推导执行许可。 + func apply(value: String, isStale: Bool) { + valueLabel.text = value + valueLabel.textColor = isStale ? DroneDockStyle.secondary : DroneDockStyle.text + iconView.tintColor = isStale ? DroneDockStyle.secondary : DroneDockStyle.primary + accessibilityValue = value + } +} + +/// 安全控制按钮,双行文案分别表达指令及当前执行状态。 +@MainActor +final class DroneShootingTaskSafetyButton: UIButton { + private let controlTitleLabel = DroneDockStyle.label(size: 15, weight: .semibold) + private let controlSubtitleLabel = DroneDockStyle.label(size: 10) + private let controlIconView: UIImageView + + /// 创建暂停或返航按钮;返回状态只由 ViewModel 决定。 + init(symbol: String, color: UIColor, filled: Bool) { + controlIconView = UIImageView(image: UIImage(systemName: symbol)) + super.init(frame: .zero) + layer.cornerRadius = 9 + layer.borderWidth = filled ? 0 : 1 + layer.borderColor = color.withAlphaComponent(0.6).cgColor + backgroundColor = filled ? color : color.withAlphaComponent(0.05) + controlTitleLabel.textColor = filled ? .white : color + controlSubtitleLabel.textColor = filled ? UIColor.white.withAlphaComponent(0.85) : DroneDockStyle.secondary + controlIconView.tintColor = filled ? .white : color + controlIconView.contentMode = .scaleAspectFit + let titles = UIStackView(arrangedSubviews: [controlTitleLabel, controlSubtitleLabel]) + titles.axis = .vertical + titles.spacing = 3 + titles.alignment = .leading + let content = UIStackView(arrangedSubviews: [controlIconView, titles]) + content.axis = .horizontal + content.spacing = 10 + content.alignment = .center + content.isUserInteractionEnabled = false + addSubview(content) + content.snp.makeConstraints { make in + make.center.equalToSuperview() + make.leading.greaterThanOrEqualToSuperview().offset(9) + make.trailing.lessThanOrEqualToSuperview().offset(-9) + } + controlIconView.snp.makeConstraints { make in make.size.equalTo(27) } + controlTitleLabel.adjustsFontSizeToFitWidth = true + controlTitleLabel.minimumScaleFactor = 0.8 + controlSubtitleLabel.adjustsFontSizeToFitWidth = true + controlSubtitleLabel.minimumScaleFactor = 0.8 + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + /// 应用语义明确的按钮标题、辅助说明及防重复点击状态。 + func apply(title: String, subtitle: String, enabled: Bool) { + controlTitleLabel.text = title + controlSubtitleLabel.text = subtitle + isEnabled = enabled + alpha = enabled ? 1 : 0.42 + accessibilityLabel = title + accessibilityValue = subtitle + } +} + +/// 任务本地静帧的全屏放大页,明确标记画面来源。 +@MainActor +final class DroneShootingTaskExpandedFeedViewController: UIViewController { + /// 显示同一张本地静帧;不建立视频连接。 + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = UIColor(hex: 0x141923) + let imageView = UIImageView(image: UIImage(named: "drone_demo_tourists")) + imageView.contentMode = .scaleAspectFill + imageView.clipsToBounds = true + imageView.accessibilityLabel = "游客取景示意,本地演示静帧" + let caption = DroneDockStyle.label("演示画面 · 本地静帧 · 16:9", size: 12, color: UIColor(hex: 0xA7AFBE)) + caption.textAlignment = .center + let close = UIButton(type: .system) + close.setImage(UIImage(systemName: "xmark"), for: .normal) + close.tintColor = .white + close.accessibilityLabel = "关闭放大画面" + close.accessibilityIdentifier = "drone.task.closeExpandedFeed" + close.addTarget(self, action: #selector(closeTapped), for: .touchUpInside) + view.addSubview(imageView) + view.addSubview(caption) + view.addSubview(close) + imageView.snp.makeConstraints { make in + make.leading.trailing.centerY.equalToSuperview() + make.height.equalTo(imageView.snp.width).multipliedBy(9.0 / 16.0) + } + caption.snp.makeConstraints { make in + make.top.equalTo(imageView.snp.bottom).offset(16) + make.leading.trailing.equalToSuperview().inset(20) + } + close.snp.makeConstraints { make in + make.top.trailing.equalTo(view.safeAreaLayoutGuide).inset(12) + make.size.equalTo(44) + } + } + + @objc private func closeTapped() { dismiss(animated: true) } +} diff --git a/suixinkanTests/DroneShootingFlowViewTests.swift b/suixinkanTests/DroneShootingFlowViewTests.swift new file mode 100644 index 0000000..e10286e --- /dev/null +++ b/suixinkanTests/DroneShootingFlowViewTests.swift @@ -0,0 +1,394 @@ +import UIKit +import XCTest +@testable import suixinkan + +#if DEBUG +/// 使用真机临时窗口验证准备与任务的实际导航、按钮行为和可见布局。 +@MainActor +final class DroneShootingFlowViewTests: XCTestCase { + private weak var previousKeyWindow: UIWindow? + + /// 从工作台按钮进入准备,召唤只提交一次;返回工作台后恢复同一个任务。 + func testWorkbenchPreparationTaskAndBackRestoreOriginalTaskWithoutCharging() async throws { + let store = makeStore() + let order = try XCTUnwrap(store.orders.first) + let originalQuota = order.remainingShootingCount + let workbench = DroneDockWorkbenchViewController(viewModel: DroneDockWorkbenchViewModel(store: store)) + let window = makeWindow(root: workbench) + defer { close(window) } + let navigation = try XCTUnwrap(workbench.navigationController) + let homeList = try collection(in: workbench.view, identifier: "drone.workbench.list") + try await settle(window) { homeList.numberOfSections > 2 && homeList.numberOfItems(inSection: 2) == 1 } + homeList.scrollToItem(at: IndexPath(item: 0, section: 2), at: .centeredVertically, animated: false) + try await settle(window) { self.find(in: workbench.view, identifier: "drone.home.\(order.id).primary") != nil } + + let start = try button(in: workbench.view, identifier: "drone.home.\(order.id).primary") + XCTAssertEqual(start.title(for: .normal), "开始拍摄") + start.sendActions(for: .touchUpInside) + try await settle(window) { navigation.topViewController is DroneShootingPreparationViewController && navigation.transitionCoordinator == nil } + let preparation = try XCTUnwrap(navigation.topViewController as? DroneShootingPreparationViewController) + let list = try collection(in: preparation.view, identifier: "drone.preparation.list") + try await settle(window) { list.numberOfSections == 3 && list.numberOfItems(inSection: 2) > 1 } + + select(list, item: 1, section: 1) + XCTAssertEqual(preparation.viewModel.selectedPoint?.id, preparation.viewModel.points[1].id) + select(list, item: 0, section: 1) + select(list, item: 1, section: 2) + XCTAssertEqual(preparation.viewModel.selectedPoint?.id, preparation.viewModel.points[0].id) + XCTAssertEqual(preparation.viewModel.selectedRoute?.id, preparation.viewModel.routes[1].id) + try await settle(window) { preparation.viewModel.admission == .ready } + let summon = try button(in: preparation.view, identifier: "drone.preparation.summon") + assertVisible(summon, in: window) + XCTAssertTrue(summon.isEnabled) + assertLayout(in: preparation.view) + capture(window, named: "拍摄流程-准备正常") + + summon.sendActions(for: .touchUpInside) + let submitted = try XCTUnwrap(store.shootingSession(orderID: order.id)) + XCTAssertEqual(submitted.commands[.summon]?.status, .processing) + XCTAssertEqual(submitted.phase, .unconfirmed) + XCTAssertFalse(summon.isEnabled) + XCTAssertTrue(navigation.topViewController === preparation) + XCTAssertNil(preparation.presentedViewController) + for _ in 0..<3 { summon.sendActions(for: .touchUpInside) } + XCTAssertEqual(store.shootingSession(orderID: order.id)?.id, submitted.id) + XCTAssertEqual(store.shootingOrder(id: order.id)?.remainingShootingCount, originalQuota) + + XCTAssertTrue(preparation.viewModel.confirmSummon()) + preparation.delegate?.shootingPreparationViewController(preparation, didRequestTaskFor: order.id) + try await settle(window) { navigation.topViewController is DroneShootingTaskViewController && navigation.transitionCoordinator == nil } + let task = try XCTUnwrap(navigation.topViewController as? DroneShootingTaskViewController) + let back = try XCTUnwrap(task.navigationItem.leftBarButtonItem) + let action = try XCTUnwrap(back.action) + XCTAssertTrue(UIApplication.shared.sendAction(action, to: back.target, from: back, for: nil)) + try await settle(window) { navigation.topViewController === workbench && navigation.transitionCoordinator == nil } + XCTAssertEqual(navigation.viewControllers.count, 1) + XCTAssertNil(workbench.presentedViewController) + XCTAssertEqual(store.shootingSession(orderID: order.id)?.id, submitted.id) + XCTAssertEqual(store.shootingOrder(id: order.id)?.remainingShootingCount, originalQuota) + + homeList.scrollToItem(at: IndexPath(item: 0, section: 2), at: .centeredVertically, animated: false) + try await settle(window) { self.find(in: workbench.view, identifier: "drone.home.\(order.id).primary") != nil } + let reopen = try button(in: workbench.view, identifier: "drone.home.\(order.id).primary") + XCTAssertEqual(reopen.title(for: .normal), "查看当前任务") + reopen.sendActions(for: .touchUpInside) + try await settle(window) { navigation.topViewController is DroneShootingTaskViewController && navigation.transitionCoordinator == nil } + XCTAssertEqual(navigation.viewControllers.count, 2) + XCTAssertEqual(store.shootingSession(orderID: order.id)?.id, submitted.id) + XCTAssertEqual(store.shootingOrder(id: order.id)?.remainingShootingCount, originalQuota) + } + + /// 到达后点击开始只进入指令处理中,不提前宣称拍摄、不弹确认、不扣次。 + func testArrivedStartButtonWaitsForExplicitDeviceConfirmation() async throws { + let fixture = try taskFixture(scenario: .arrived) + let controller = DroneShootingTaskViewController(viewModel: fixture.viewModel) + let window = makeWindow(root: controller) + defer { close(window) } + try await settle(window) { self.find(in: controller.view, identifier: "drone.task.primary") != nil } + let primary = try button(in: controller.view, identifier: "drone.task.primary") + XCTAssertTrue(primary.isEnabled) + XCTAssertEqual(primary.configuration?.title, "开始拍摄") + assertVisible(primary, in: window) + assertLayout(in: controller.view) + capture(window, named: "拍摄流程-任务已到达") + + primary.sendActions(for: .touchUpInside) + let pending = try XCTUnwrap(fixture.viewModel.session) + XCTAssertEqual(pending.commands[.start]?.status, .processing) + XCTAssertEqual(pending.phase, .arrived) + XCTAssertEqual(pending.result, .notStarted) + XCTAssertFalse(primary.isEnabled) + XCTAssertNil(controller.presentedViewController) + for _ in 0..<3 { primary.sendActions(for: .touchUpInside) } + XCTAssertEqual(fixture.viewModel.session, pending) + XCTAssertEqual(fixture.viewModel.order?.remainingShootingCount, fixture.originalQuota) + assertLayout(in: controller.view) + } + + /// 紧急暂停直接提交,确认前仍拍摄;收到回执后再显示已暂停与继续按钮。 + func testPauseButtonSubmitsDirectlyAndPausedScreenUsesConfirmedState() async throws { + let fixture = try taskFixture(scenario: .shooting) + let controller = DroneShootingTaskViewController(viewModel: fixture.viewModel) + let window = makeWindow(root: controller) + defer { close(window) } + try await settle(window) { self.find(in: controller.view, identifier: "drone.task.pause") != nil } + let pause = try button(in: controller.view, identifier: "drone.task.pause") + XCTAssertTrue(pause.isEnabled) + pause.sendActions(for: .touchUpInside) + let pending = try XCTUnwrap(fixture.viewModel.session) + XCTAssertEqual(pending.commands[.pause]?.status, .processing) + XCTAssertEqual(pending.phase, .shooting) + XCTAssertFalse(pause.isEnabled) + XCTAssertNil(controller.presentedViewController) + for _ in 0..<3 { pause.sendActions(for: .touchUpInside) } + XCTAssertEqual(fixture.viewModel.session, pending) + XCTAssertEqual(fixture.viewModel.order?.remainingShootingCount, fixture.originalQuota) + + fixture.viewModel.receive(.commandConfirmed(.pause)) + let paused = DroneShootingTaskViewController(viewModel: fixture.viewModel) + controller.navigationController?.setViewControllers([paused], animated: false) + try await settle(window) { paused.viewIfLoaded?.window != nil } + XCTAssertEqual(fixture.viewModel.session?.phase, .shootingPaused) + let primary = try button(in: paused.view, identifier: "drone.task.primary") + XCTAssertEqual(primary.configuration?.title, "继续任务") + XCTAssertTrue(primary.isEnabled) + XCTAssertFalse(try button(in: paused.view, identifier: "drone.task.pause").isEnabled) + assertLayout(in: paused.view) + capture(window, named: "拍摄流程-任务已暂停") + } + + /// 返航直接发送并等待回执;成功扣完次数与返航控制仍分别呈现。 + func testReturnButtonHasNoConfirmationAndZeroQuotaReturningRetainsTask() async throws { + let fixture = try taskFixture(scenario: .arrived) + let controller = DroneShootingTaskViewController(viewModel: fixture.viewModel) + let window = makeWindow(root: controller) + defer { close(window) } + try await settle(window) { self.find(in: controller.view, identifier: "drone.task.return") != nil } + let returnButton = try button(in: controller.view, identifier: "drone.task.return") + XCTAssertTrue(returnButton.isEnabled) + returnButton.sendActions(for: .touchUpInside) + let pending = try XCTUnwrap(fixture.viewModel.session) + XCTAssertEqual(pending.commands[.returnHome]?.status, .processing) + XCTAssertEqual(pending.phase, .arrived) + XCTAssertFalse(returnButton.isEnabled) + XCTAssertNil(controller.presentedViewController) + for _ in 0..<3 { returnButton.sendActions(for: .touchUpInside) } + XCTAssertEqual(fixture.viewModel.session, pending) + XCTAssertEqual(fixture.viewModel.order?.remainingShootingCount, fixture.originalQuota) + + fixture.viewModel.applyScenario(.succeededReturning) + fixture.viewModel.dismissResultNotice() + let returning = DroneShootingTaskViewController(viewModel: fixture.viewModel) + controller.navigationController?.setViewControllers([returning], animated: false) + try await settle(window) { returning.viewIfLoaded?.window != nil } + XCTAssertEqual(fixture.viewModel.order?.remainingShootingCount, 0) + XCTAssertEqual(fixture.viewModel.order?.activeTask?.id, pending.id) + XCTAssertEqual(fixture.viewModel.order?.activeTask?.phase, .returning) + XCTAssertEqual(fixture.viewModel.statusTitle, "拍摄已完成") + XCTAssertEqual(try button(in: returning.view, identifier: "drone.task.primary").configuration?.title, "查看素材") + XCTAssertFalse(try button(in: returning.view, identifier: "drone.task.return").isEnabled) + assertLayout(in: returning.view) + capture(window, named: "拍摄流程-零次仍返航") + + fixture.viewModel.receive(.phaseConfirmed(.returnPaused)) + let returnPaused = DroneShootingTaskViewController(viewModel: fixture.viewModel) + returning.navigationController?.setViewControllers([returnPaused], animated: false) + try await settle(window) { returnPaused.viewIfLoaded?.window != nil } + let resumeReturn = try button(in: returnPaused.view, identifier: "drone.task.primary") + XCTAssertEqual(resumeReturn.configuration?.title, "继续返航") + XCTAssertTrue(resumeReturn.isEnabled) + let materials = try button(in: returnPaused.view, identifier: "drone.task.materials") + assertVisible(materials, in: window) + XCTAssertFalse(materials.isHidden) + XCTAssertEqual(fixture.viewModel.order?.remainingShootingCount, 0) + assertLayout(in: returnPaused.view) + capture(window, named: "拍摄流程-成功后返航暂停仍可查看素材") + } + + /// 占用时可以选择点位航线,但不会召唤;未知设备也保持明确阻断。 + func testOccupiedPreparationAllowsSelectionButBlocksSummonAndUnknownRemainsBlocked() async throws { + let store = makeStore() + let order = try XCTUnwrap(store.orders.first) + let viewModel = DroneShootingPreparationViewModel(store: store, orderID: order.id) + viewModel.applyScenario(.occupied) + let controller = DroneShootingPreparationViewController(viewModel: viewModel) + let window = makeWindow(root: controller) + defer { close(window) } + let list = try collection(in: controller.view, identifier: "drone.preparation.list") + try await settle(window) { list.numberOfSections == 3 && list.numberOfItems(inSection: 2) > 1 } + select(list, item: 1, section: 1) + XCTAssertEqual(viewModel.selectedPoint?.id, viewModel.points[1].id) + select(list, item: 0, section: 1) + select(list, item: 1, section: 2) + XCTAssertEqual(viewModel.selectedRoute?.id, viewModel.routes[1].id) + XCTAssertEqual(viewModel.admission, .occupied) + let summon = try button(in: controller.view, identifier: "drone.preparation.summon") + XCTAssertFalse(summon.isEnabled) + summon.sendActions(for: .touchUpInside) + XCTAssertNil(store.shootingSession(orderID: order.id)) + XCTAssertEqual(store.shootingOrder(id: order.id)?.remainingShootingCount, order.remainingShootingCount) + try await settle(window) { !list.visibleCells.isEmpty } + assertLayout(in: controller.view) + capture(window, named: "拍摄流程-准备占用仍可选线") + + viewModel.applyScenario(.unknown) + let unknown = DroneShootingPreparationViewController(viewModel: viewModel) + controller.navigationController?.setViewControllers([unknown], animated: false) + try await settle(window) { unknown.viewIfLoaded?.window != nil } + XCTAssertEqual(viewModel.admission, .unknownDevice) + XCTAssertFalse(try button(in: unknown.view, identifier: "drone.preparation.summon").isEnabled) + XCTAssertTrue(labels(in: unknown.view).contains { $0.text?.contains("待确认") == true }) + assertLayout(in: unknown.view) + capture(window, named: "拍摄流程-设备未知") + } + + /// 手机断网、仅图传断流、指令结果未知分别显示,重连不会自动重发或扣次。 + func testPhoneOfflineStreamLossAndUnconfirmedCommandHaveIndependentControlsAndLayout() async throws { + let fixture = try taskFixture(scenario: .phoneOffline) + let placeholder = UIViewController() + let window = makeWindow(root: placeholder) + defer { close(window) } + let navigation = try XCTUnwrap(placeholder.navigationController) + for scenario in [DroneShootingTaskScenario.phoneOffline, .streamLost, .commandUnconfirmed] { + fixture.viewModel.applyScenario(scenario) + let controller = DroneShootingTaskViewController(viewModel: fixture.viewModel) + navigation.setViewControllers([controller], animated: false) + try await settle(window) { controller.viewIfLoaded?.window != nil } + let pause = try button(in: controller.view, identifier: "drone.task.pause") + let primary = try button(in: controller.view, identifier: "drone.task.primary") + switch scenario { + case .phoneOffline: + XCTAssertEqual(fixture.viewModel.phoneConnection, .disconnected) + XCTAssertFalse(pause.isEnabled) + XCTAssertFalse(primary.isEnabled) + XCTAssertFalse(try button(in: controller.view, identifier: "drone.task.return").isEnabled) + XCTAssertGreaterThanOrEqual(labels(in: controller.view).filter { $0.text == "—" }.count, 6) + assertLayout(in: controller.view) + capture(window, named: "拍摄流程-手机离线") + let reconnect = try button(in: controller.view, identifier: "drone.task.feed.reconnect") + XCTAssertTrue(reconnect.isEnabled) + reconnect.sendActions(for: .touchUpInside) + XCTAssertEqual(fixture.viewModel.phoneConnection, .reconnecting) + XCTAssertFalse(reconnect.isEnabled) + case .streamLost: + XCTAssertEqual(fixture.viewModel.phoneConnection, .connected) + XCTAssertEqual(fixture.viewModel.feedConnection, .disconnected) + XCTAssertTrue(pause.isEnabled) + XCTAssertFalse(primary.isEnabled) + XCTAssertFalse(labels(in: controller.view).contains { $0.text == "—" }) + assertLayout(in: controller.view) + capture(window, named: "拍摄流程-仅图传断流") + let reconnect = try button(in: controller.view, identifier: "drone.task.feed.reconnect") + reconnect.sendActions(for: .touchUpInside) + XCTAssertEqual(fixture.viewModel.feedConnection, .reconnecting) + XCTAssertEqual(fixture.viewModel.session?.phase, .shooting) + XCTAssertEqual(fixture.viewModel.phoneConnection, .connected) + case .commandUnconfirmed: + XCTAssertEqual(fixture.viewModel.session?.commands[.start]?.status, .unconfirmed) + XCTAssertFalse(primary.isEnabled) + let sync = try button(in: controller.view, identifier: "drone.task.sync") + assertVisible(sync, in: window) + assertLayout(in: controller.view) + capture(window, named: "拍摄流程-指令结果待确认") + sync.sendActions(for: .touchUpInside) + XCTAssertEqual(fixture.viewModel.phoneConnection, .synchronizing) + XCTAssertEqual(fixture.viewModel.session?.commands[.start]?.status, .unconfirmed) + default: XCTFail("未覆盖的连接演示场景") + } + XCTAssertEqual(fixture.viewModel.order?.remainingShootingCount, fixture.originalQuota) + XCTAssertNil(controller.presentedViewController) + } + } + + /// 仅保留演示订单 2 和一台设备,使工作台入口在真机窗口中稳定可见。 + private func makeStore() -> DroneDockDemoStore { + let demo = DroneDockDemoStore() + return DroneDockDemoStore(context: .demo, orders: [demo.orders[1]], devices: Array(demo.devices.prefix(1))) + } + + /// 所有任务先从准备模型提交并明确确认,再显式应用待验收的设备事件。 + private func taskFixture(scenario: DroneShootingTaskScenario) throws -> (viewModel: DroneShootingTaskViewModel, originalQuota: Int) { + let store = makeStore() + let order = try XCTUnwrap(store.orders.first) + let preparation = DroneShootingPreparationViewModel(store: store, orderID: order.id) + XCTAssertEqual(preparation.admission, .ready) + XCTAssertFalse(preparation.summon()) + XCTAssertTrue(preparation.confirmSummon()) + let viewModel = DroneShootingTaskViewModel(store: store, orderID: order.id) + viewModel.applyScenario(scenario) + return (viewModel, order.remainingShootingCount) + } + + /// 点位卡和航线行通过真实 collection delegate 传递选择意图。 + private func select(_ list: UICollectionView, item: Int, section: Int) { + let indexPath = IndexPath(item: item, section: section) + guard item < list.numberOfItems(inSection: section), + list.delegate?.collectionView?(list, shouldSelectItemAt: indexPath) != false else { + XCTFail("预期可以选择点位或航线") + return + } + list.delegate?.collectionView?(list, didSelectItemAt: indexPath) + } + + /// 在已连接真机的应用场景里创建测试窗口,不启动模拟器。 + private func makeWindow(root controller: UIViewController) -> UIWindow { + let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } + let scene = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first + previousKeyWindow = scene?.windows.first { $0.isKeyWindow } + let window = scene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: UIScreen.main.bounds) + window.frame = scene?.coordinateSpace.bounds ?? UIScreen.main.bounds + window.overrideUserInterfaceStyle = .light + window.rootViewController = UINavigationController(rootViewController: controller) + window.makeKeyAndVisible() + window.layoutIfNeeded() + return window + } + + /// 结束窗口测试,恢复应用原有主窗口。 + private func close(_ window: UIWindow) { + window.endEditing(true) + window.rootViewController?.dismiss(animated: false) + window.isHidden = true + window.rootViewController = nil + previousKeyWindow?.makeKeyAndVisible() + } + + /// 等待导航与 Diffable 完成,再为截图与布局断言提供稳定帧。 + private func settle(_ window: UIWindow, until condition: () -> Bool) async throws { + for _ in 0..<150 { + window.layoutIfNeeded() + window.rootViewController?.view.layoutIfNeeded() + if condition() { + try await Task.sleep(nanoseconds: 350_000_000) + window.layoutIfNeeded() + return + } + try await Task.sleep(nanoseconds: 20_000_000) + } + XCTFail("拍摄页面未在预期时间内完成布局或导航") + throw NSError(domain: "DroneShootingFlowViewTests", code: 1) + } + + private func allViews(in view: UIView) -> [UIView] { [view] + view.subviews.flatMap { allViews(in: $0) } } + private func find(in view: UIView, identifier: String) -> UIView? { allViews(in: view).first { $0.accessibilityIdentifier == identifier } } + private func button(in view: UIView, identifier: String) throws -> UIButton { + try XCTUnwrap(find(in: view, identifier: identifier) as? UIButton, "缺少按钮:\(identifier)") + } + private func collection(in view: UIView, identifier: String) throws -> UICollectionView { + try XCTUnwrap(find(in: view, identifier: identifier) as? UICollectionView, "缺少列表:\(identifier)") + } + private func labels(in view: UIView) -> [UILabel] { allViews(in: view).compactMap { $0 as? UILabel } } + private func isHiddenByAncestor(_ view: UIView) -> Bool { + view.isHidden || view.alpha < 0.01 || (view.superview.map { isHiddenByAncestor($0) } ?? false) + } + + /// 只检查可见、参与 Auto Layout 的应用视图,排除 UIKit 内部视图。 + private func assertLayout(in root: UIView, file: StaticString = #filePath, line: UInt = #line) { + let ambiguous = allViews(in: root).filter { + !$0.translatesAutoresizingMaskIntoConstraints && !isHiddenByAncestor($0) && !$0.bounds.isEmpty + && !String(describing: type(of: $0)).hasPrefix("_") && $0.hasAmbiguousLayout + } + XCTAssertTrue(ambiguous.isEmpty, "布局歧义:\(ambiguous.map { String(describing: type(of: $0)) + " " + ($0.accessibilityIdentifier ?? "") })", file: file, line: line) + } + + /// 确认可见控件留在窗口内,包含固定底部操作区。 + private func assertVisible(_ control: UIView, in window: UIWindow, file: StaticString = #filePath, line: UInt = #line) { + XCTAssertFalse(isHiddenByAncestor(control), file: file, line: line) + let frame = control.convert(control.bounds, to: window) + XCTAssertGreaterThan(frame.width, 0, file: file, line: line) + XCTAssertGreaterThanOrEqual(frame.height, 30, file: file, line: line) + XCTAssertTrue(window.bounds.contains(frame), "操作区超出窗口:\(frame)", file: file, line: line) + } + + /// 将关键状态截图始终保留在真机 xcresult 中。 + private func capture(_ window: UIWindow, named name: String) { + let image = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + } + let attachment = XCTAttachment(image: image) + attachment.name = name + attachment.lifetime = .keepAlways + add(attachment) + } +} +#endif diff --git a/suixinkanTests/DroneShootingSessionViewModelTests.swift b/suixinkanTests/DroneShootingSessionViewModelTests.swift new file mode 100644 index 0000000..07bf5a2 --- /dev/null +++ b/suixinkanTests/DroneShootingSessionViewModelTests.swift @@ -0,0 +1,466 @@ +import XCTest +@testable import suixinkan + +/// 验证本地准备及任务页共享状态、明确回执和成功扣次规则。 +final class DroneShootingSessionViewModelTests: XCTestCase { + func testPointSwitchRestoresItsOwnRouteAndRepeatedSelectionDoesNotClearIt() throws { + let store = makeStore() + let preparation = DroneShootingPreparationViewModel(store: store, orderID: "order-a") + let firstPoint = try XCTUnwrap(preparation.selectedPoint) + let secondRoute = try XCTUnwrap(preparation.routes.dropFirst().first) + preparation.selectRoute(id: secondRoute.id) + preparation.selectRoute(id: secondRoute.id) + XCTAssertEqual(preparation.selectedRoute?.id, secondRoute.id) + + let secondPoint = try XCTUnwrap(preparation.points.dropFirst().first) + preparation.selectPoint(id: secondPoint.id) + XCTAssertNotEqual(preparation.selectedRoute?.id, secondRoute.id) + XCTAssertTrue(preparation.routes.allSatisfy { $0.id.hasPrefix(secondPoint.id) }) + preparation.selectPoint(id: firstPoint.id) + XCTAssertEqual(preparation.selectedRoute?.id, secondRoute.id) + + let reopened = DroneShootingPreparationViewModel(store: store, orderID: "order-a") + XCTAssertEqual(reopened.selectedPoint?.id, firstPoint.id) + XCTAssertEqual(reopened.selectedRoute?.id, secondRoute.id) + } + + func testInvalidRouteIsClearedWithoutSelectingSameNamedReplacement() throws { + let store = makeStore() + let preparation = DroneShootingPreparationViewModel(store: store, orderID: "order-a") + let point = try XCTUnwrap(preparation.selectedPoint) + let oldRoute = try XCTUnwrap(preparation.selectedRoute) + let replacement = DroneShootingRoute(id: "different-route-id", name: oldRoute.name) + store.updateShootingPoints(preparation.points, routesByPointID: [point.id: [replacement]], orderID: "order-a") + preparation.refresh() + + XCTAssertNil(preparation.selectedRoute) + XCTAssertEqual(preparation.admission, .noRoute) + preparation.selectRoute(id: oldRoute.id) + XCTAssertNil(preparation.selectedRoute) + preparation.selectRoute(id: replacement.id) + XCTAssertEqual(preparation.selectedRoute, replacement) + } + + func testRangeUpdatePreservesPointOrderAndSelectionButBlocksSummon() throws { + let store = makeStore() + let preparation = DroneShootingPreparationViewModel(store: store, orderID: "order-a") + let originalIDs = preparation.points.map(\.id) + let selected = try XCTUnwrap(preparation.selectedPoint) + let selectedRoute = try XCTUnwrap(preparation.selectedRoute) + let updated = preparation.points.map { + DroneShootingPoint(id: $0.id, name: $0.name, range: .unknown, successfulCount: $0.successfulCount) + } + store.updateShootingPoints(updated, routesByPointID: [selected.id: preparation.routes], orderID: "order-a") + preparation.refresh() + + XCTAssertEqual(preparation.points.map(\.id), originalIDs) + XCTAssertEqual(preparation.selectedPoint?.id, selected.id) + XCTAssertEqual(preparation.selectedRoute, selectedRoute) + XCTAssertEqual(preparation.admission, .unknownRange) + XCTAssertFalse(preparation.summon()) + XCTAssertNil(store.shootingOrder(id: "order-a")?.activeTask) + } + + func testOutOfRangePointAndRoutesRemainSelectable() throws { + let preparation = DroneShootingPreparationViewModel(store: makeStore(), orderID: "order-a") + let point = try XCTUnwrap(preparation.points.dropFirst().first) + preparation.selectPoint(id: point.id) + let route = try XCTUnwrap(preparation.routes.last) + preparation.selectRoute(id: route.id) + + XCTAssertEqual(preparation.selectedPoint?.id, point.id) + XCTAssertEqual(preparation.selectedRoute, route) + XCTAssertEqual(preparation.admission, .outOfRange) + XCTAssertFalse(preparation.primaryButtonEnabled) + XCTAssertFalse(preparation.summon()) + } + + func testEveryExplicitDeviceBlockPreventsSummonWithoutUsingBatteryThreshold() { + let cases: [(DroneDockDeviceState, DroneShootingAdmission)] = [ + (.occupied, .occupied), (.disconnected, .disconnected), (.noSignal, .noSignal), + (.lowBattery, .lowBattery), (.unknown, .unknownDevice) + ] + for (state, expected) in cases { + let store = makeStore(deviceState: state) + let preparation = DroneShootingPreparationViewModel(store: store, orderID: "order-a") + XCTAssertEqual(preparation.admission, expected) + XCTAssertFalse(preparation.summon()) + XCTAssertNil(store.shootingOrder(id: "order-a")?.activeTask) + } + let explicitReady = DroneShootingPreparationViewModel(store: makeStore(deviceState: .ready, battery: 18), orderID: "order-a") + XCTAssertTrue(explicitReady.admission.canSummon) + } + + func testMissingDeviceNoRoutesNoQuotaAndUnknownOrderAreDistinctBlocks() throws { + let noDevice = DroneShootingPreparationViewModel(store: DroneDockDemoStore(context: context, orders: [order()], devices: []), orderID: "order-a") + XCTAssertEqual(noDevice.admission, .unknownDevice) + let zeroQuota = DroneShootingPreparationViewModel(store: makeStore(orders: [order(total: 1, successful: 1)]), orderID: "order-a") + XCTAssertEqual(zeroQuota.admission, .noQuota) + let unavailable = DroneShootingPreparationViewModel(store: makeStore(), orderID: "missing") + XCTAssertEqual(unavailable.admission, .orderUnavailable) + + let store = makeStore() + let noRoute = DroneShootingPreparationViewModel(store: store, orderID: "order-a") + store.updateShootingPoints(noRoute.points, routesByPointID: [:], orderID: "order-a") + noRoute.refresh() + XCTAssertEqual(noRoute.admission, .noRoutes) + XCTAssertNil(noRoute.selectedRoute) + XCTAssertFalse(noRoute.summon()) + } + + func testSummonStaysPendingCreatesOneSharedTaskAndFreezesSubmittedSelection() throws { + let store = makeStore() + let preparation = DroneShootingPreparationViewModel(store: store, orderID: "order-a") + let selectedPoint = try XCTUnwrap(preparation.selectedPoint) + let selectedRoute = try XCTUnwrap(preparation.selectedRoute) + XCTAssertFalse(preparation.summon()) + let pending = try XCTUnwrap(store.shootingSession(orderID: "order-a")) + XCTAssertEqual(pending.phase, .unconfirmed) + XCTAssertEqual(pending.commands[.summon]?.status, .processing) + XCTAssertTrue(preparation.hasPendingSummon) + XCTAssertEqual(preparation.primaryButtonTitle, "召唤处理中") + XCTAssertFalse(preparation.primaryButtonEnabled) + + preparation.selectPoint(id: preparation.points[1].id) + preparation.selectRoute(id: preparation.routes[1].id) + XCTAssertEqual(preparation.selectedPoint, selectedPoint) + XCTAssertEqual(preparation.selectedRoute, selectedRoute) + XCTAssertFalse(preparation.summon()) + XCTAssertEqual(store.shootingSession(orderID: "order-a")?.id, pending.id) + XCTAssertEqual(store.shootingOrder(id: "order-a")?.successfulShootingCount, 0) + XCTAssertEqual(DroneDockWorkbenchViewModel(store: store).orders.first?.activeTask?.id, pending.id) + + store.receiveShootingEvent(.commandConfirmed(.summon), orderID: "order-a", taskID: pending.id) + XCTAssertEqual(preparation.admission, .currentTask) + XCTAssertTrue(preparation.summon()) + XCTAssertEqual(store.shootingSession(orderID: "order-a")?.id, pending.id) + } + + func testOtherOrdersCanPrepareButCannotSummonWhenOriginalTaskOccupiesDevice() throws { + let store = makeStore(orders: [order(), order(id: "order-b")]) + let first = DroneShootingPreparationViewModel(store: store, orderID: "order-a") + first.summon() + let second = DroneShootingPreparationViewModel(store: store, orderID: "order-b") + let nextPoint = try XCTUnwrap(second.points.dropFirst().first) + second.selectPoint(id: nextPoint.id) + XCTAssertEqual(second.selectedPoint?.id, nextPoint.id) + XCTAssertNotNil(second.selectedRoute) + second.selectPoint(id: second.points[0].id) + XCTAssertEqual(second.deviceState, .occupied) + XCTAssertEqual(second.admission, .occupied) + XCTAssertFalse(second.summon()) + XCTAssertNil(store.shootingOrder(id: "order-b")?.activeTask) + } + + func testStartPauseAndResumeRequireExplicitAcknowledgments() throws { + let (store, task) = try arrivedTask() + let id = try XCTUnwrap(task.session?.id) + XCTAssertTrue(task.startShooting()) + XCTAssertFalse(task.startShooting()) + XCTAssertEqual(task.session?.phase, .arrived) + XCTAssertEqual(task.session?.result, .notStarted) + XCTAssertEqual(task.commandTitle, "开始拍摄处理中") + task.receive(.commandConfirmed(.start)) + XCTAssertEqual(task.session?.phase, .shooting) + XCTAssertEqual(task.session?.result, .inProgress) + + XCTAssertTrue(task.pause()) + XCTAssertEqual(task.session?.phase, .shooting) + XCTAssertEqual(task.pauseTitle, "暂停处理中") + XCTAssertFalse(task.pause()) + task.receive(.commandConfirmed(.pause)) + XCTAssertEqual(task.session?.phase, .shootingPaused) + XCTAssertTrue(task.resume()) + XCTAssertEqual(task.session?.phase, .shootingPaused) + XCTAssertFalse(task.resume()) + task.receive(.commandConfirmed(.resume)) + XCTAssertEqual(task.session?.phase, .shooting) + XCTAssertEqual(store.shootingOrder(id: "order-a")?.successfulShootingCount, 0) + XCTAssertEqual(store.shootingOrder(id: "order-a")?.activeTask?.id, id) + } + + func testReturnDirectlySubmitsAndReturningPauseRestoresReturnInsteadOfShooting() throws { + let (_, task) = try arrivedTask() + XCTAssertTrue(task.requestReturn()) + XCTAssertEqual(task.session?.phase, .arrived) + XCTAssertEqual(task.returnTitle, "正在发送返航指令") + XCTAssertEqual(task.returnSubtitle, "尚未确认返航") + XCTAssertFalse(task.requestReturn()) + task.receive(.commandConfirmed(.returnHome)) + XCTAssertEqual(task.session?.phase, .returning) + XCTAssertTrue(task.pause()) + task.receive(.commandConfirmed(.pause)) + XCTAssertEqual(task.session?.phase, .returnPaused) + XCTAssertTrue(task.resume()) + XCTAssertEqual(task.session?.phase, .returnPaused) + task.receive(.commandConfirmed(.resume)) + XCTAssertEqual(task.session?.phase, .returning) + XCTAssertEqual(task.order?.successfulShootingCount, 0) + } + + func testCommandTimeoutAndRejectionDoNotBecomeShootingFailureOrDeductQuota() throws { + let (_, task) = try arrivedTask() + task.startShooting() + task.receive(.commandResultUnknown(.start)) + XCTAssertEqual(task.session?.result, .notStarted) + XCTAssertEqual(task.session?.phase, .arrived) + XCTAssertEqual(task.phase, .unconfirmed) + XCTAssertTrue(task.shouldShowCommandRefresh) + XCTAssertFalse(task.startShooting()) + XCTAssertFalse(task.primaryEnabled) + XCTAssertNil(task.resultNotice) + task.refreshTaskStatus() + XCTAssertEqual(task.phoneConnection, .synchronizing) + XCTAssertEqual(task.session?.commands[.start]?.status, .unconfirmed) + task.receive(.synchronized(phase: .arrived, result: .notStarted, flightFinished: false, deviceReady: false)) + XCTAssertTrue(task.primaryEnabled) + + task.startShooting() + task.receive(.commandRejected(.start, message: "设备拒绝开始")) + XCTAssertEqual(task.session?.result, .notStarted) + XCTAssertEqual(task.commandTitle, "指令未执行") + XCTAssertNil(task.resultNotice) + XCTAssertEqual(task.order?.successfulShootingCount, 0) + } + + func testSuccessConsumesExactlyOneQuotaAndDoesNotChangeFlightPhase() throws { + let (store, task) = try arrivedTask(total: 1) + task.startShooting() + task.receive(.commandConfirmed(.start)) + task.receive(.shootingSucceeded) + task.receive(.shootingSucceeded) + XCTAssertEqual(task.session?.phase, .shooting) + XCTAssertEqual(task.session?.result, .succeeded) + XCTAssertEqual(task.order?.remainingShootingCount, 0) + XCTAssertEqual(task.order?.materialState, .uploading) + XCTAssertEqual(task.order?.activeTask?.shootingResult, .succeeded) + XCTAssertEqual(task.primaryAction, .viewMaterials) + XCTAssertTrue(DroneDockWorkbenchViewModel(store: store).orders.isEmpty) + + task.receive(.phaseConfirmed(.returning)) + let completed = DroneShootingOrdersViewModel(store: store, initialFilter: .completed) + XCTAssertEqual(completed.orders.first?.primaryAction, .viewCurrentTask) + XCTAssertEqual(completed.orders.first?.activeTask?.phase, .returning) + task.receive(.flightFinished(deviceReady: true)) + completed.refresh() + XCTAssertNil(completed.orders.first?.activeTask) + XCTAssertEqual(completed.orders.first?.primaryAction, DroneShootingPrimaryAction.none) + XCTAssertEqual(task.order?.successfulShootingCount, 1) + } + + func testSuccessSnapshotCannotBeOverwrittenByLateFailureOrNonterminalSync() throws { + let (_, task) = try arrivedTask(total: 3) + task.receive(.shootingSucceeded) + task.receive(.shootingFailed(reason: "迟到失败")) + task.receive(.synchronized(phase: .returning, result: .inProgress, flightFinished: false, deviceReady: false)) + XCTAssertEqual(task.session?.result, .succeeded) + XCTAssertEqual(task.order?.successfulShootingCount, 1) + XCTAssertEqual(task.session?.phase, .returning) + } + + func testFailureCannotPrepareAgainUntilFlightEndsAndDeviceIsReady() throws { + let (store, task) = try arrivedTask(total: 3) + let preparationBefore = DroneShootingPreparationViewModel(store: store, orderID: "order-a") + let point = preparationBefore.selectedPoint + let route = preparationBefore.selectedRoute + task.receive(.shootingFailed(reason: "拍摄执行失败")) + task.receive(.phaseConfirmed(.returning)) + XCTAssertEqual(task.primaryAction, .prepareAgain) + XCTAssertFalse(task.primaryEnabled) + XCTAssertNotNil(task.order?.activeTask) + XCTAssertEqual(task.order?.successfulShootingCount, 0) + + task.receive(.flightFinished(deviceReady: false)) + XCTAssertNil(task.order?.activeTask) + XCTAssertFalse(task.primaryEnabled) + task.receive(.flightFinished(deviceReady: true)) + XCTAssertTrue(task.primaryEnabled) + XCTAssertEqual(task.order?.primaryAction, .prepareAgain) + + let preparationAfter = DroneShootingPreparationViewModel(store: store, orderID: "order-a") + XCTAssertEqual(preparationAfter.selectedPoint, point) + XCTAssertEqual(preparationAfter.selectedRoute, route) + XCTAssertEqual(preparationAfter.admission, .ready) + XCTAssertNil(task.order?.activeTask) + } + + func testUnknownResultAfterFlightEndStillRetainsOriginalTaskAndBlocksNewSummon() throws { + let (store, task) = try arrivedTask() + task.receive(.protectiveReturn(reason: "设备保护")) + task.receive(.flightFinished(deviceReady: true)) + XCTAssertTrue(task.session?.isFlightFinished == true) + XCTAssertEqual(task.session?.result, .unknown) + XCTAssertNotNil(task.order?.activeTask) + let preparation = DroneShootingPreparationViewModel(store: store, orderID: "order-a") + XCTAssertEqual(preparation.admission, .currentTask) + XCTAssertTrue(preparation.summon()) + XCTAssertEqual(store.shootingSession(orderID: "order-a")?.id, task.session?.id) + XCTAssertEqual(task.order?.successfulShootingCount, 0) + } + + func testStreamLossDoesNotChangePhoneNetworkTelemetryOrSafetyPermissions() throws { + let (_, task) = try arrivedTask() + task.receive(.phaseConfirmed(.shooting)) + let telemetry = task.telemetry + task.receive(.feedConnectionChanged(.disconnected)) + XCTAssertEqual(task.phoneConnection, .connected) + XCTAssertEqual(task.feedConnection, .disconnected) + XCTAssertEqual(task.telemetry, telemetry) + XCTAssertEqual(task.session?.phase, .shooting) + XCTAssertTrue(task.canPause) + XCTAssertTrue(task.canReturn) + task.reconnectFeed() + XCTAssertEqual(task.feedConnection, .reconnecting) + XCTAssertEqual(task.phoneConnection, .connected) + } + + func testPhoneReconnectWaitsForExplicitTaskSyncAndDoesNotRestoreLostFeed() throws { + let (_, task) = try arrivedTask() + task.receive(.feedConnectionChanged(.disconnected)) + task.receive(.phoneConnectionChanged(.disconnected)) + XCTAssertEqual(task.phase, .unconfirmed) + XCTAssertEqual(task.telemetry, .unknown) + XCTAssertFalse(task.canPause) + XCTAssertFalse(task.canReturn) + XCTAssertEqual(task.session?.result, .notStarted) + task.reconnectPhone() + XCTAssertEqual(task.phoneConnection, .reconnecting) + XCTAssertFalse(task.primaryEnabled) + task.receive(.synchronized(phase: .arrived, result: .notStarted, flightFinished: false, deviceReady: false)) + XCTAssertEqual(task.phoneConnection, .connected) + XCTAssertEqual(task.feedConnection, .disconnected) + XCTAssertEqual(task.phase, .arrived) + XCTAssertTrue(task.primaryEnabled) + } + + func testProtectiveReturnDoesNotAssumeFailureSuccessOrQuotaConsumption() throws { + let (_, task) = try arrivedTask() + task.receive(.protectiveReturn(reason: "电量不足")) + XCTAssertEqual(task.session?.phase, .returning) + XCTAssertEqual(task.session?.result, .unknown) + XCTAssertEqual(task.statusTitle, "无人机自动返航") + XCTAssertEqual(task.primaryTitle, "结果待确认") + XCTAssertEqual(task.order?.successfulShootingCount, 0) + XCTAssertNil(task.resultNotice) + } + + func testResultDialogDismissalAndPageRefreshDoNotCreateTaskOrDeductAgain() throws { + let (store, task) = try arrivedTask(total: 3) + let id = try XCTUnwrap(task.session?.id) + task.receive(.shootingSucceeded) + XCTAssertNotNil(task.resultNotice) + task.dismissResultNotice() + for _ in 0..<5 { task.refresh() } + let reopened = DroneShootingTaskViewModel(store: store, orderID: "order-a") + XCTAssertEqual(reopened.session?.id, id) + XCTAssertEqual(reopened.order?.successfulShootingCount, 1) + XCTAssertNil(reopened.resultNotice) + } + + func testNewSessionIgnoresLateEventsFromFinishedTask() throws { + let (store, task) = try arrivedTask(total: 3) + let oldID = try XCTUnwrap(task.session?.id) + task.receive(.shootingFailed(reason: "本次失败")) + task.receive(.flightFinished(deviceReady: true)) + let preparation = DroneShootingPreparationViewModel(store: store, orderID: "order-a") + XCTAssertFalse(preparation.summon()) + let newID = try XCTUnwrap(store.shootingSession(orderID: "order-a")?.id) + XCTAssertNotEqual(newID, oldID) + store.receiveShootingEvent(.shootingSucceeded, orderID: "order-a", taskID: oldID) + XCTAssertEqual(store.shootingOrder(id: "order-a")?.successfulShootingCount, 0) + XCTAssertEqual(store.shootingSession(orderID: "order-a")?.result, .notStarted) + } + + func testScenicSwitchHidesStaleControllersAndPreservesOriginalTaskForReturn() throws { + let (store, task) = try arrivedTask(total: 3) + let originalID = try XCTUnwrap(task.session?.id) + let preparation = DroneShootingPreparationViewModel(store: store, orderID: "order-a") + let other = DroneDockContext(scenicID: "other", scenicName: "另一景区", userID: context.userID, photographerName: context.photographerName) + store.switchContext(to: other) + XCTAssertNil(task.order) + XCTAssertNil(task.session) + XCTAssertEqual(preparation.admission, .orderUnavailable) + XCTAssertFalse(task.pause()) + XCTAssertFalse(preparation.summon()) + store.switchContext(to: context) + task.refresh() + XCTAssertEqual(task.session?.id, originalID) + XCTAssertEqual(task.session?.phase, .arrived) + XCTAssertEqual(task.order?.successfulShootingCount, 0) + } + + func testExistingTaskReferenceIsRestoredWithoutCreatingNewTaskOrChargingSuccessAgain() throws { + let active = DroneShootingTask(id: "existing-task", phase: .returning, shootingResult: .succeeded) + let store = makeStore(orders: [order(total: 3, successful: 1, task: active)]) + let task = DroneShootingTaskViewModel(store: store, orderID: "order-a") + XCTAssertEqual(task.session?.id, active.id) + XCTAssertEqual(task.session?.result, .succeeded) + task.receive(.shootingSucceeded) + XCTAssertEqual(task.order?.successfulShootingCount, 1) + let preparation = DroneShootingPreparationViewModel(store: store, orderID: "order-a") + XCTAssertEqual(preparation.primaryButtonTitle, "查看当前任务") + XCTAssertTrue(preparation.summon()) + XCTAssertEqual(store.shootingSession(orderID: "order-a")?.id, active.id) + } + + #if DEBUG + func testWorkbenchScenarioResetDiscardsOldSessionAndRestoresNewReferencedTask() throws { + let store = DroneDockDemoStore(context: context) + let pendingOrder = try XCTUnwrap(store.orders.first { $0.fulfillmentState == .pending }) + let preparation = DroneShootingPreparationViewModel(store: store, orderID: pendingOrder.id) + preparation.summon() + let oldID = try XCTUnwrap(store.shootingSession(orderID: pendingOrder.id)?.id) + store.applyScenario(.standard) + XCTAssertNil(store.shootingSession(orderID: pendingOrder.id)) + store.applyScenario(.shootingPaused) + let activeOrder = try XCTUnwrap(store.orders.first { $0.activeTask != nil }) + let restored = try XCTUnwrap(store.shootingSession(orderID: activeOrder.id)) + XCTAssertEqual(restored.id, activeOrder.activeTask?.id) + XCTAssertNotEqual(restored.id, oldID) + XCTAssertEqual(restored.phase, .shootingPaused) + } + + func testPreparationPreviewRestoresOriginalQuotaAndTaskPreviewNeverDoubleChargesSameSession() throws { + let store = makeStore(orders: [order(total: 3, successful: 1)]) + let preparation = DroneShootingPreparationViewModel(store: store, orderID: "order-a") + preparation.applyScenario(.noQuota) + XCTAssertEqual(preparation.order?.remainingShootingCount, 0) + preparation.applyScenario(.ready) + XCTAssertEqual(preparation.order?.remainingShootingCount, 2) + preparation.summon() + XCTAssertTrue(preparation.confirmSummon()) + let task = DroneShootingTaskViewModel(store: store, orderID: "order-a") + task.applyScenario(.succeededReturning) + task.applyScenario(.succeededReturning) + task.applyScenario(.succeededFinished) + XCTAssertEqual(task.order?.successfulShootingCount, 2) + } + #endif + + private var context: DroneDockContext { + DroneDockContext(scenicID: "scenic", scenicName: "测试景区", userID: "user", photographerName: "工作人员") + } + + private func order(id: String = "order-a", total: Int = 3, successful: Int = 0, task: DroneShootingTask? = nil) -> DroneShootingOrder { + DroneShootingOrder(id: id, scenicID: context.scenicID, assignedUserID: context.userID, + customerName: "游客136****2806", orderNumber: "TEST-\(id)", createdAtText: "10-23 09:00", + packageName: "航拍套餐", totalShootingCount: total, successfulShootingCount: successful, + activeTask: task, needsRepreparation: false, materialState: .none, + deliveredVideoCount: 0, visitorConfirmationState: .none) + } + + private func makeStore(orders: [DroneShootingOrder]? = nil, deviceState: DroneDockDeviceState = .ready, battery: Int? = 95) -> DroneDockDemoStore { + let telemetry = DroneDockTelemetry(batteryPercent: battery, temperatureCelsius: 20.3, windSpeed: 0, rainDescription: "无雨", signalDescription: "良好", satelliteCount: 36) + return DroneDockDemoStore(context: context, orders: orders ?? [order()], devices: [DroneDockDevice(id: "device", name: "01号无人机", state: deviceState, telemetry: telemetry)]) + } + + private func arrivedTask(total: Int = 3) throws -> (DroneDockDemoStore, DroneShootingTaskViewModel) { + let store = makeStore(orders: [order(total: total)]) + let preparation = DroneShootingPreparationViewModel(store: store, orderID: "order-a") + preparation.summon() + let id = try XCTUnwrap(store.shootingSession(orderID: "order-a")?.id) + store.receiveShootingEvent(.commandConfirmed(.summon), orderID: "order-a", taskID: id) + store.receiveShootingEvent(.phaseConfirmed(.arrived), orderID: "order-a", taskID: id) + return (store, DroneShootingTaskViewModel(store: store, orderID: "order-a")) + } +}