AppleHealthTestView.swift 9.02 KB
//
//  AppleHealthTestView.swift
//  Runner
//
//  Created by 权海 on 2026/6/15.
//

import SwiftUI

struct AppleHealthTestView: View {
  @State private var logs: [String] = []
  @State private var isRunning = false
  @State private var runningTitle: String?

  private let api = HealthKitHostApiImpl()
  private let logTimeFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateFormat = "HH:mm:ss.SSS"
    return formatter
  }()

  var body: some View {
    NavigationStack {
      VStack(spacing: 0) {
        logPanel

        Divider()

        HStack(spacing: 12) {
          actionButton(title: "AppleHealth 权限检查", systemImage: "checkmark.shield") {
            await runPermissionCheck()
          }

          actionButton(title: "获取数据接口", systemImage: "waveform.path.ecg") {
            await runDataFetch()
          }
        }
        .padding(16)
        .background(.regularMaterial)
      }
      .navigationTitle("Apple Health Test")
      .navigationBarTitleDisplayMode(.inline)
      .toolbar {
        ToolbarItem(placement: .topBarTrailing) {
          Button("清空") {
            logs.removeAll()
          }
          .disabled(isRunning || logs.isEmpty)
        }
      }
    }
  }

  private var logPanel: some View {
    ScrollViewReader { proxy in
      ScrollView {
        LazyVStack(alignment: .leading, spacing: 8) {
          if logs.isEmpty {
            ContentUnavailableView(
              "暂无日志",
              systemImage: "list.bullet.rectangle",
              description: Text("点击底部按钮开始测试 HealthKitHostApiImpl。")
            )
            .frame(maxWidth: .infinity, minHeight: 280)
          } else {
            ForEach(Array(logs.enumerated()), id: \.offset) { index, line in
              Text(line)
                .font(.system(.footnote, design: .monospaced))
                .foregroundStyle(line.contains("❌") ? .red : .primary)
                .textSelection(.enabled)
                .frame(maxWidth: .infinity, alignment: .leading)
                .id(index)
            }
          }
        }
        .padding(16)
      }
      .background(Color(.systemGroupedBackground))
      .onChange(of: logs.count) { _, newValue in
        guard newValue > 0 else { return }
        withAnimation(.easeOut(duration: 0.2)) {
          proxy.scrollTo(newValue - 1, anchor: .bottom)
        }
      }
    }
  }

  private func actionButton(
    title: String,
    systemImage: String,
    action: @escaping () async -> Void
  ) -> some View {
    Button {
      guard !isRunning else { return }
      Task {
        await runAction(title, action: action)
      }
    } label: {
      Label(isRunning && runningTitle == title ? "执行中..." : title, systemImage: systemImage)
        .font(.system(size: 15, weight: .semibold))
        .frame(maxWidth: .infinity)
        .frame(height: 48)
    }
    .buttonStyle(.borderedProminent)
    .disabled(isRunning)
  }

  @MainActor
  private func runAction(_ title: String, action: @escaping () async -> Void) async {
    isRunning = true
    runningTitle = title
    appendLog("▶️ \(title) 开始")
    await action()
    appendLog("✅ \(title) 完成")
    isRunning = false
    runningTitle = nil
  }

  private func runPermissionCheck() async {
    do {
      let isAuthorized = try await checkHealthAuthorization()
      await appendLog("checkHealthAppAuthorization = \(isAuthorized)")

      let authUrl = try await getHealthServerAuthUrl()
      await appendLog("getHealthServerAuthUrl = \(authUrl.isEmpty ? "<empty, iOS system managed>" : authUrl)")

      if !isAuthorized {
        await appendLog("当前未授权,开始 requestHealthClientAuthorization")
        let granted = try api.requestHealthClientAuthorization()
        await appendLog("requestHealthClientAuthorization = \(granted)")
      } else {
        await appendLog("当前已授权,跳过 requestHealthClientAuthorization")
      }

      let cancelResult = try api.cancelHealthAppAuthorization()
      await appendLog("cancelHealthAppAuthorization = \(cancelResult) (iOS 不支持应用内撤销)")
    } catch {
      await appendError("权限检查失败", error)
    }
  }

  private func runDataFetch() async {
    let endTime = Int64(Date().timeIntervalSince1970)
    let startTime = Int64(Calendar.current.date(byAdding: .day, value: -7, to: Date())?.timeIntervalSince1970 ?? Date().timeIntervalSince1970)
    await appendLog("数据范围: \(formatTimestamp(startTime)) -> \(formatTimestamp(endTime))")

    do {
      let uploadResult = try api.performHealthUpload()
      await appendLog(
        "performHealthUpload common=\(uploadResult.commonUploadSuccess), sleep=\(uploadResult.sleepUploadSuccess), error=\(uploadResult.errorMessage ?? "nil")"
      )
    } catch {
      await appendError("performHealthUpload 失败", error)
    }

    await fetchCommon("HRV", startTime, endTime, api.fetchHrvData)
    await fetchCommon("心率", startTime, endTime, api.fetchHeartRateData)
    await fetchCommon("步行心率", startTime, endTime, api.fetchWalkingHeartRateData)
    await fetchCommon("静息心率", startTime, endTime, api.fetchRestingHeartRateData)
    await fetchCommon("睡眠心率", startTime, endTime, api.fetchSleepingHeartRateData)
    await fetchCommon("血氧", startTime, endTime, api.fetchOxygenSaturationData)
    await fetchCommon("活动能量", startTime, endTime, api.fetchActiveEnergyData)
    await fetchCommon("锻炼", startTime, endTime, api.fetchExerciseData)
    await fetchCommon("站立", startTime, endTime, api.fetchStandData)
    await fetchCommon("步数", startTime, endTime, api.fetchStepCountData)
    await fetchCommon("睡眠腕温", startTime, endTime, api.fetchSleepingWristTemperatureData)
    await fetchCommon("呼吸频率", startTime, endTime, api.fetchRespiratoryRateData)
    await fetchCommon("不规则心律", startTime, endTime, api.fetchIrregularHeartRhythmData)
    await fetchSleep(startTime: startTime, endTime: endTime)
    await fetchActivityTarget(startTime: startTime, endTime: endTime)
  }

  private func fetchCommon(
    _ title: String,
    _ startTime: Int64,
    _ endTime: Int64,
    _ fetch: @escaping (Int64, Int64, @escaping (Result<[HealthUploadDataPoint], Error>) -> Void) -> Void
  ) async {
    do {
      let points = try await withCheckedThrowingContinuation { continuation in
        fetch(startTime, endTime) { result in
          continuation.resume(with: result)
        }
      }
      await appendLog("\(title): \(points.count) 条")
      await appendSample(points)
    } catch {
      await appendError("\(title) 获取失败", error)
    }
  }

  private func fetchSleep(startTime: Int64, endTime: Int64) async {
    do {
      let points = try await withCheckedThrowingContinuation { continuation in
        api.fetchSleepData(startTime: startTime, endTime: endTime) { result in
          continuation.resume(with: result)
        }
      }
      await appendLog("睡眠: \(points.count) 条")
      for point in points.prefix(3) {
        await appendLog("  sample dataType=\(point.dataType), from=\(formatTimestamp(point.fromTime)), to=\(formatTimestamp(point.toTime))")
      }
    } catch {
      await appendError("睡眠获取失败", error)
    }
  }

  private func fetchActivityTarget(startTime: Int64, endTime: Int64) async {
    do {
      let target = try await withCheckedThrowingContinuation { continuation in
        api.fetchActivityTargetData(startTime: startTime, endTime: endTime) { result in
          continuation.resume(with: result)
        }
      }
      if let target {
        await appendLog("活动目标: move=\(target.move.map(String.init) ?? "nil"), stand=\(target.stand.map(String.init) ?? "nil")")
      } else {
        await appendLog("活动目标: nil")
      }
    } catch {
      await appendError("活动目标获取失败", error)
    }
  }

  private func checkHealthAuthorization() async throws -> Bool {
    try await withCheckedThrowingContinuation { continuation in
      api.checkHealthAppAuthorization { result in
        continuation.resume(with: result)
      }
    }
  }

  private func getHealthServerAuthUrl() async throws -> String {
    try await withCheckedThrowingContinuation { continuation in
      api.getHealthServerAuthUrl { result in
        continuation.resume(with: result)
      }
    }
  }

  @MainActor
  private func appendLog(_ message: String) {
    logs.append("[\(logTimeFormatter.string(from: Date()))] \(message)")
  }

  @MainActor
  private func appendError(_ prefix: String, _ error: Error) {
    appendLog("❌ \(prefix): \(error.localizedDescription)")
  }

  @MainActor
  private func appendSample(_ points: [HealthUploadDataPoint]) {
    for point in points.prefix(3) {
      appendLog("  sample dataType=\(point.dataType), time=\(formatTimestamp(point.time)), value=\(point.value)")
    }
  }

  private func formatTimestamp(_ timestamp: Int64) -> String {
    let date = Date(timeIntervalSince1970: TimeInterval(timestamp))
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    return formatter.string(from: date)
  }
}

#Preview {
  AppleHealthTestView()
}