AppleHealthTestView.swift 9.26 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 authorization = try await checkHealthAuthorization()
      appendLog("checkHealthAppAuthorization status=\(authorization.status), hasData=\(authorization.hasData)")

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

      if authorization.status == 0 {
        appendLog("当前需要请求授权,开始 requestHealthClientAuthorization")
        let granted = try await requestHealthClientAuthorization()
        appendLog("requestHealthClientAuthorization = \(granted)")
      } else {
        appendLog("当前不需要再次请求授权,跳过 requestHealthClientAuthorization")
      }

      let cancelResult = try api.cancelHealthAppAuthorization()
      appendLog("cancelHealthAppAuthorization = \(cancelResult) (iOS 不支持应用内撤销)")
    } catch {
      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)
    appendLog("数据范围: \(formatTimestamp(startTime)) -> \(formatTimestamp(endTime))")

    do {
      let uploadResult = try api.performHealthUpload()
      appendLog(
        "performHealthUpload common=\(uploadResult.commonUploadSuccess), sleep=\(uploadResult.sleepUploadSuccess), error=\(uploadResult.errorMessage ?? "nil")"
      )
    } catch {
      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)
        }
      }
      appendLog("\(title): \(points.count) 条")
      appendSample(points)
    } catch {
      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)
        }
      }
      appendLog("睡眠: \(points.count) 条")
      for point in points.prefix(3) {
        appendLog("  sample dataType=\(point.dataType), from=\(formatTimestamp(point.fromTime)), to=\(formatTimestamp(point.toTime))")
      }
    } catch {
      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 {
        appendLog("活动目标: move=\(target.move.map(String.init) ?? "nil"), stand=\(target.stand.map(String.init) ?? "nil")")
      } else {
        appendLog("活动目标: nil")
      }
    } catch {
      appendError("活动目标获取失败", error)
    }
  }

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

  private func requestHealthClientAuthorization() async throws -> Bool {
    try await withCheckedThrowingContinuation { continuation in
      api.requestHealthClientAuthorization { 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()
}