feat: update wallet punch point and report success

This commit is contained in:
2026-07-09 14:27:18 +08:00
parent 2970f1514b
commit 43e6133c21
34 changed files with 6671 additions and 71 deletions

View File

@ -0,0 +1,84 @@
//
// PunchPointAPI.swift
// suixinkan
//
import Foundation
/// API 便 ViewModel
@MainActor
protocol PunchPointAPIProtocol {
///
func list(scenicAreaId: String, status: Int, page: Int, pageSize: Int) async throws -> PunchPointListResponse
///
func info(id: Int64) async throws -> PunchPointDetail
///
func add(_ request: PunchPointSaveRequest) async throws
///
func edit(_ request: PunchPointSaveRequest) async throws
///
func delete(id: Int64) async throws
}
/// API Android `NetworkApi` `photog/scenic-spot`
@MainActor
final class PunchPointAPI: PunchPointAPIProtocol {
private let client: APIClient
/// API
init(client: APIClient) {
self.client = client
}
///
func list(scenicAreaId: String, status: Int, page: Int, pageSize: Int) async throws -> PunchPointListResponse {
try await client.send(
APIRequest(
method: .get,
path: "/api/yf-handset-app/photog/scenic-spot/list",
queryItems: [
URLQueryItem(name: "scenic_area_id", value: scenicAreaId),
URLQueryItem(name: "status", value: String(status)),
URLQueryItem(name: "page", value: String(max(page, 1))),
URLQueryItem(name: "page_size", value: String(max(pageSize, 1))),
]
)
)
}
///
func info(id: Int64) async throws -> PunchPointDetail {
try await client.send(
APIRequest(
method: .get,
path: "/api/yf-handset-app/photog/scenic-spot/info",
queryItems: [URLQueryItem(name: "id", value: String(id))]
)
)
}
///
func add(_ request: PunchPointSaveRequest) async throws {
let _: EmptyPayload = try await client.send(
APIRequest(method: .post, path: "/api/yf-handset-app/photog/scenic-spot/add", body: request)
)
}
///
func edit(_ request: PunchPointSaveRequest) async throws {
let _: EmptyPayload = try await client.send(
APIRequest(method: .post, path: "/api/yf-handset-app/photog/scenic-spot/edit", body: request)
)
}
///
func delete(id: Int64) async throws {
let _: EmptyPayload = try await client.send(
APIRequest(
method: .post,
path: "/api/yf-handset-app/photog/scenic-spot/delete",
body: PunchPointIDRequest(id: id)
)
)
}
}

View File

@ -0,0 +1,441 @@
//
// PunchPointModels.swift
// suixinkan
//
import CoreLocation
import Foundation
/// Android `PunchPointFilterType`
enum PunchPointFilterType: Int, CaseIterable, Sendable, Equatable, Hashable {
case all = 0
case inOperation = 1
case paused = 2
case pendingReview = 3
case rejected = 4
///
var title: String {
switch self {
case .all: "全部"
case .inOperation: "运营中"
case .paused: "已暂停"
case .pendingReview: "未审核"
case .rejected: "审核未通过"
}
}
/// `status`
var apiStatus: Int { rawValue }
}
///
struct PunchPointListResponse: Decodable, Sendable, Equatable {
let total: Int
let list: [PunchPointItem]
init(total: Int = 0, list: [PunchPointItem] = []) {
self.total = total
self.list = list
}
}
///
struct PunchPointRegion: Codable, Sendable, Equatable, Hashable {
let lat: Double
let lot: Double
let address: String
let scenicSpotString: String?
enum CodingKeys: String, CodingKey {
case lat
case lot
case address
case scenicSpotString = "scenic_spot_str"
}
init(lat: Double = 0, lot: Double = 0, address: String = "", scenicSpotString: String? = nil) {
self.lat = lat
self.lot = lot
self.address = address
self.scenicSpotString = scenicSpotString
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
lat = try container.decodeIfPresent(Double.self, forKey: .lat) ?? 0
lot = try container.decodeIfPresent(Double.self, forKey: .lot) ?? 0
address = try container.decodeIfPresent(String.self, forKey: .address) ?? ""
scenicSpotString = try container.decodeIfPresent(String.self, forKey: .scenicSpotString)
}
}
/// Android `ScenicSpotItem`
struct PunchPointItem: Decodable, Sendable, Equatable, Hashable, Identifiable {
let id: Int64
let name: String
let status: Int
let statusLabel: String
let region: PunchPointRegion?
let scenicSpotString: String
let guideImages: [String]
let mpQrcode: String?
let createdAt: String
let creatorId: Int64?
let creator: String?
let creatorPhone: String?
let auditor: String?
let auditTime: String?
let auditRemark: String?
enum CodingKeys: String, CodingKey {
case id
case name
case status
case statusLabel = "status_label"
case region
case scenicSpotString = "scenic_spot_str"
case guideImages = "guide_imgs"
case mpQrcode = "mp_qrcode"
case createdAt = "created_at"
case creatorId = "creator_id"
case creator
case creatorPhone = "creator_phone"
case auditor
case auditTime = "audit_time"
case auditRemark = "audit_remark"
}
init(
id: Int64 = 0,
name: String = "",
status: Int = 0,
statusLabel: String = "",
region: PunchPointRegion? = nil,
scenicSpotString: String = "",
guideImages: [String] = [],
mpQrcode: String? = nil,
createdAt: String = "",
creatorId: Int64? = nil,
creator: String? = nil,
creatorPhone: String? = nil,
auditor: String? = nil,
auditTime: String? = nil,
auditRemark: String? = nil
) {
self.id = id
self.name = name
self.status = status
self.statusLabel = statusLabel
self.region = region
self.scenicSpotString = scenicSpotString
self.guideImages = guideImages
self.mpQrcode = mpQrcode
self.createdAt = createdAt
self.creatorId = creatorId
self.creator = creator
self.creatorPhone = creatorPhone
self.auditor = auditor
self.auditTime = auditTime
self.auditRemark = auditRemark
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decodeFlexibleInt64(forKey: .id) ?? 0
name = try container.decodeIfPresent(String.self, forKey: .name) ?? ""
status = try container.decodeIfPresent(Int.self, forKey: .status) ?? 0
statusLabel = try container.decodeIfPresent(String.self, forKey: .statusLabel) ?? ""
region = try container.decodeIfPresent(PunchPointRegion.self, forKey: .region)
scenicSpotString = try container.decodeIfPresent(String.self, forKey: .scenicSpotString) ?? ""
guideImages = try container.decodeIfPresent([String].self, forKey: .guideImages) ?? []
mpQrcode = try container.decodeIfPresent(String.self, forKey: .mpQrcode)
createdAt = try container.decodeIfPresent(String.self, forKey: .createdAt) ?? ""
creatorId = try container.decodeFlexibleInt64(forKey: .creatorId)
creator = try container.decodeIfPresent(String.self, forKey: .creator)
creatorPhone = try container.decodeIfPresent(String.self, forKey: .creatorPhone)
auditor = try container.decodeIfPresent(String.self, forKey: .auditor)
auditTime = try container.decodeIfPresent(String.self, forKey: .auditTime)
auditRemark = try container.decodeIfPresent(String.self, forKey: .auditRemark)
}
///
var displayAddress: String {
let address = region?.address.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
if !address.isEmpty { return address }
return scenicSpotString.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
/// Android `ScenicSpotDetailResponse`
struct PunchPointDetail: Decodable, Sendable, Equatable {
let id: Int64
let name: String
let status: Int
let statusLabel: String
let region: PunchPointRegion?
let scenicSpotString: String
let description: String?
let guideImages: [String]
let mpQrcode: String?
let createdAt: String
let creatorId: Int64?
let creator: String?
let creatorPhone: String?
let auditor: String?
let auditTime: String?
let auditRemark: String?
enum CodingKeys: String, CodingKey {
case id
case name
case status
case statusLabel = "status_label"
case region
case scenicSpotString = "scenic_spot_str"
case description
case guideImages = "guide_imgs"
case mpQrcode = "mp_qrcode"
case createdAt = "created_at"
case creatorId = "creator_id"
case creator
case creatorPhone = "creator_phone"
case auditor
case auditTime = "audit_time"
case auditRemark = "audit_remark"
}
init(
id: Int64 = 0,
name: String = "",
status: Int = 0,
statusLabel: String = "",
region: PunchPointRegion? = nil,
scenicSpotString: String = "",
description: String? = nil,
guideImages: [String] = [],
mpQrcode: String? = nil,
createdAt: String = "",
creatorId: Int64? = nil,
creator: String? = nil,
creatorPhone: String? = nil,
auditor: String? = nil,
auditTime: String? = nil,
auditRemark: String? = nil
) {
self.id = id
self.name = name
self.status = status
self.statusLabel = statusLabel
self.region = region
self.scenicSpotString = scenicSpotString
self.description = description
self.guideImages = guideImages
self.mpQrcode = mpQrcode
self.createdAt = createdAt
self.creatorId = creatorId
self.creator = creator
self.creatorPhone = creatorPhone
self.auditor = auditor
self.auditTime = auditTime
self.auditRemark = auditRemark
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decodeFlexibleInt64(forKey: .id) ?? 0
name = try container.decodeIfPresent(String.self, forKey: .name) ?? ""
status = try container.decodeIfPresent(Int.self, forKey: .status) ?? 0
statusLabel = try container.decodeIfPresent(String.self, forKey: .statusLabel) ?? ""
region = try container.decodeIfPresent(PunchPointRegion.self, forKey: .region)
scenicSpotString = try container.decodeIfPresent(String.self, forKey: .scenicSpotString) ?? ""
description = try container.decodeIfPresent(String.self, forKey: .description)
guideImages = try container.decodeIfPresent([String].self, forKey: .guideImages) ?? []
mpQrcode = try container.decodeIfPresent(String.self, forKey: .mpQrcode)
createdAt = try container.decodeIfPresent(String.self, forKey: .createdAt) ?? ""
creatorId = try container.decodeFlexibleInt64(forKey: .creatorId)
creator = try container.decodeIfPresent(String.self, forKey: .creator)
creatorPhone = try container.decodeIfPresent(String.self, forKey: .creatorPhone)
auditor = try container.decodeIfPresent(String.self, forKey: .auditor)
auditTime = try container.decodeIfPresent(String.self, forKey: .auditTime)
auditRemark = try container.decodeIfPresent(String.self, forKey: .auditRemark)
}
///
var displayAddress: String {
let address = region?.address.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
if !address.isEmpty { return address }
return scenicSpotString.trimmingCharacters(in: .whitespacesAndNewlines)
}
///
var coordinate: CLLocationCoordinate2D? {
guard let region else { return nil }
return CLLocationCoordinate2D(latitude: region.lat, longitude: region.lot)
}
}
///
struct PunchPointSaveRequest: Encodable, Sendable, Equatable {
let id: Int64?
let scenicAreaId: String
let name: String
let description: String?
let region: PunchPointSaveRegion
let scenicSpotString: String
let guideImages: [String]
enum CodingKeys: String, CodingKey {
case id
case scenicAreaId = "scenic_area_id"
case name
case description
case region
case scenicSpotString = "scenic_spot_str"
case guideImages = "guide_imgs"
}
init(
id: Int64? = nil,
scenicAreaId: String,
name: String,
description: String?,
region: PunchPointSaveRegion,
scenicSpotString: String,
guideImages: [String]
) {
self.id = id
self.scenicAreaId = scenicAreaId
self.name = name
self.description = description
self.region = region
self.scenicSpotString = scenicSpotString
self.guideImages = guideImages
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(id, forKey: .id)
try container.encode(scenicAreaId, forKey: .scenicAreaId)
try container.encode(name, forKey: .name)
try container.encodeIfPresent(description, forKey: .description)
try container.encode(region, forKey: .region)
try container.encode(scenicSpotString, forKey: .scenicSpotString)
try container.encode(guideImages, forKey: .guideImages)
}
}
///
struct PunchPointSaveRegion: Encodable, Sendable, Equatable {
let lot: Double
let lat: Double
let address: String
}
///
struct PunchPointIDRequest: Encodable, Sendable, Equatable {
let id: Int64
}
///
struct PunchPointImageState: Sendable, Equatable, Hashable, Identifiable {
let id: UUID
var data: Data
var previewURL: String?
var fileName: String
var uploadedURL: String
var isUploading: Bool
var uploadProgress: Int
var errorMessage: String?
init(
id: UUID = UUID(),
data: Data,
previewURL: String? = nil,
fileName: String,
uploadedURL: String = "",
isUploading: Bool = false,
uploadProgress: Int = 0,
errorMessage: String? = nil
) {
self.id = id
self.data = data
self.previewURL = previewURL
self.fileName = fileName
self.uploadedURL = uploadedURL
self.isUploading = isUploading
self.uploadProgress = uploadProgress
self.errorMessage = errorMessage
}
///
static func remote(url: String) -> PunchPointImageState {
PunchPointImageState(
data: Data(),
previewURL: url,
fileName: URL(string: url)?.lastPathComponent.nonEmptyTrimmed ?? "punch_point.jpg",
uploadedURL: url,
isUploading: false,
uploadProgress: 100
)
}
///
var isUploaded: Bool { !uploadedURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
}
///
struct PunchPointUploadDialogState: Sendable, Equatable {
let title: String
let progress: Int
}
/// UI
enum PunchPointDisplayFormatter {
///
static func maskedPhone(_ phone: String?) -> String {
guard let phone = phone?.trimmingCharacters(in: .whitespacesAndNewlines), !phone.isEmpty else { return "--" }
guard phone.count >= 11 else { return phone }
let prefix = phone.prefix(3)
let suffix = phone.suffix(phone.count - 7)
return "\(prefix)****\(suffix)"
}
/// /
static func statusColors(_ status: Int) -> (background: UInt, text: UInt) {
switch status {
case 1:
return (0xF0FDF4, 0x09BE4F)
case 2:
return (0xFFF0E2, 0xFF7B00)
case 3:
return (0xEFF6FF, 0x0073FF)
case 4:
return (0xFFE7E7, 0xEF4444)
default:
return (0xF4F4F4, 0x666666)
}
}
}
private extension KeyedDecodingContainer {
func decodeFlexibleInt64(forKey key: Key) throws -> Int64? {
if let value = try decodeIfPresent(Int64.self, forKey: key) {
return value
}
if let value = try decodeIfPresent(Int.self, forKey: key) {
return Int64(value)
}
if let value = try decodeIfPresent(String.self, forKey: key) {
return Int64(value)
}
return nil
}
}
private extension String {
var nonEmptyTrimmed: String? {
let text = trimmingCharacters(in: .whitespacesAndNewlines)
return text.isEmpty ? nil : text
}
}

View File

@ -0,0 +1,481 @@
//
// PunchPointViewModels.swift
// suixinkan
//
import CoreLocation
import Foundation
/// 便 ViewModel
@MainActor
protocol PunchPointImageUploading {
/// OSS URL
func uploadPunchPointImage(
data: Data,
fileName: String,
scenicId: Int,
onProgress: @escaping (Int) -> Void
) async throws -> String
}
/// ViewModel
final class PunchPointListViewModel {
private(set) var items: [PunchPointItem] = []
private(set) var filterType: PunchPointFilterType = .all
private(set) var isLoading = false
private(set) var isRefreshing = false
private(set) var canLoadMore = false
var onStateChange: (() -> Void)?
var onShowMessage: ((String) -> Void)?
var onShowQRCode: ((String) -> Void)?
private var currentPage = 1
private var totalCount = 0
private let pageSize = 10
private let currentScenicIdProvider: () -> Int
/// ViewModel
init(currentScenicIdProvider: @escaping () -> Int = { AppStore.shared.currentScenicId }) {
self.currentScenicIdProvider = currentScenicIdProvider
}
///
func loadInitial(api: any PunchPointAPIProtocol) async {
await load(reset: true, showLoading: true, api: api)
}
///
func refresh(api: any PunchPointAPIProtocol) async {
isRefreshing = true
notifyStateChange()
await load(reset: true, showLoading: false, api: api)
}
///
func selectFilter(_ type: PunchPointFilterType, api: any PunchPointAPIProtocol) async {
guard filterType != type else { return }
filterType = type
notifyStateChange()
await load(reset: true, showLoading: false, api: api)
}
///
func loadMoreIfNeeded(lastVisibleIndex: Int, api: any PunchPointAPIProtocol) async {
guard lastVisibleIndex >= items.count - 3 else { return }
await load(reset: false, showLoading: false, api: api)
}
///
func showQRCode(for item: PunchPointItem) {
guard item.status == 1 || item.status == 2 else {
onShowMessage?("未审核通过不可查看二维码")
return
}
guard let url = item.mpQrcode?.trimmingCharacters(in: .whitespacesAndNewlines), !url.isEmpty else {
onShowMessage?("暂无二维码")
return
}
onShowQRCode?(url)
}
///
func delete(item: PunchPointItem, api: any PunchPointAPIProtocol) async {
do {
try await api.delete(id: item.id)
items.removeAll { $0.id == item.id }
totalCount = max(0, totalCount - 1)
canLoadMore = items.count < totalCount
notifyStateChange()
} catch is CancellationError {
return
} catch {
onShowMessage?(error.localizedDescription.isEmpty ? "删除失败" : "删除失败:\(error.localizedDescription)")
}
}
private func load(reset: Bool, showLoading: Bool, api: any PunchPointAPIProtocol) async {
if reset {
currentPage = 1
canLoadMore = false
} else {
guard canLoadMore, !isLoading, !isRefreshing else { return }
currentPage += 1
}
let scenicId = currentScenicIdProvider()
guard scenicId > 0 else {
onShowMessage?("请先选择景区")
if reset {
items = []
canLoadMore = false
totalCount = 0
}
notifyStateChange()
return
}
isLoading = showLoading
notifyStateChange()
defer {
isLoading = false
isRefreshing = false
notifyStateChange()
}
do {
let response = try await api.list(
scenicAreaId: String(scenicId),
status: filterType.apiStatus,
page: currentPage,
pageSize: pageSize
)
totalCount = response.total
items = reset ? response.list : items + response.list
canLoadMore = response.list.count >= pageSize && items.count < totalCount
} catch is CancellationError {
return
} catch {
if !reset, currentPage > 1 {
currentPage -= 1
}
if reset {
items = []
totalCount = 0
canLoadMore = false
}
onShowMessage?(error.localizedDescription.isEmpty ? "获取打卡点列表失败" : "获取打卡点列表失败:\(error.localizedDescription)")
}
}
private func notifyStateChange() {
onStateChange?()
}
}
/// ViewModel
final class PunchPointDetailViewModel {
private(set) var detail: PunchPointDetail?
private(set) var isLoading = false
var onStateChange: (() -> Void)?
var onShowMessage: ((String) -> Void)?
let punchPointId: Int64
/// ViewModel
init(punchPointId: Int64) {
self.punchPointId = punchPointId
}
///
func load(api: any PunchPointAPIProtocol) async {
guard punchPointId > 0 else {
onShowMessage?("打卡点信息异常")
return
}
isLoading = true
notifyStateChange()
defer {
isLoading = false
notifyStateChange()
}
do {
detail = try await api.info(id: punchPointId)
} catch is CancellationError {
return
} catch {
onShowMessage?(error.localizedDescription.isEmpty ? "获取打卡点详情失败" : error.localizedDescription)
}
}
private func notifyStateChange() {
onStateChange?()
}
}
/// ViewModel
final class PunchPointFormViewModel {
///
enum Mode: Equatable {
case create
case edit(id: Int64)
}
private(set) var name = ""
private(set) var address = ""
private(set) var description = ""
private(set) var coordinate: CLLocationCoordinate2D?
private(set) var images: [PunchPointImageState] = []
private(set) var uploadDialogState: PunchPointUploadDialogState?
private(set) var isSubmitting = false
private(set) var isLocating = false
var onStateChange: (() -> Void)?
var onShowMessage: ((String) -> Void)?
var onSubmitSuccess: (() -> Void)?
var onCoordinateChange: ((CLLocationCoordinate2D) -> Void)?
let mode: Mode
private let currentScenicIdProvider: () -> Int
private let locationProvider: any LocationProviding
/// ViewModel
init(
mode: Mode = .create,
currentScenicIdProvider: @escaping () -> Int = { AppStore.shared.currentScenicId },
locationProvider: any LocationProviding = LocationProvider.shared
) {
self.mode = mode
self.currentScenicIdProvider = currentScenicIdProvider
self.locationProvider = locationProvider
}
///
var coordinatesText: String {
guard let coordinate else { return "" }
return "\(coordinate.latitude),\(coordinate.longitude)"
}
/// 使
func initialize(with detail: PunchPointDetail) {
name = detail.name
address = detail.displayAddress
description = detail.description ?? ""
coordinate = detail.coordinate
images = detail.guideImages.map(PunchPointImageState.remote(url:))
if let coordinate {
onCoordinateChange?(coordinate)
}
notifyStateChange()
}
///
func updateName(_ text: String) {
name = text
notifyStateChange()
}
///
func updateAddress(_ text: String) {
address = text
notifyStateChange()
}
/// 50
func updateDescription(_ text: String) {
description = String(text.prefix(50))
notifyStateChange()
}
///
func autoLocation() async {
await locate(updateMap: true, missingPermissionMessage: "定位权限未授予,无法自动定位")
}
///
func locateToCurrent() async {
await locate(updateMap: true, missingPermissionMessage: "定位权限未授予,请在设置中开启")
}
///
func selectCoordinate(_ coordinate: CLLocationCoordinate2D) async {
self.coordinate = coordinate
notifyStateChange()
onCoordinateChange?(coordinate)
let resolved = await locationProvider.reverseGeocode(
latitude: coordinate.latitude,
longitude: coordinate.longitude
)
if !resolved.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
address = resolved
notifyStateChange()
}
}
///
func addLocalImages(_ newImages: [PunchPointImageState], uploader: any PunchPointImageUploading) async {
let remaining = 9 - images.count
guard remaining > 0 else {
onShowMessage?("最多只能选择9张图片")
return
}
let accepted = Array(newImages.prefix(remaining))
guard !accepted.isEmpty else { return }
let start = images.count
images.append(contentsOf: accepted)
notifyStateChange()
for offset in accepted.indices {
await uploadImage(at: start + offset, title: "正在上传(\(offset + 1)/\(accepted.count))", uploader: uploader)
}
uploadDialogState = nil
notifyStateChange()
}
///
func deleteImage(at index: Int) {
guard images.indices.contains(index), !images[index].isUploading else { return }
images.remove(at: index)
notifyStateChange()
}
///
func retryUpload(at index: Int, uploader: any PunchPointImageUploading) async {
guard images.indices.contains(index) else { return }
images[index].errorMessage = nil
notifyStateChange()
await uploadImage(at: index, title: "正在上传(1/1)", uploader: uploader)
uploadDialogState = nil
notifyStateChange()
}
///
func submit(api: any PunchPointAPIProtocol) async {
guard !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
onShowMessage?("请输入打卡点名称")
return
}
guard let coordinate else {
onShowMessage?("请选择打卡点坐标")
return
}
guard !address.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
onShowMessage?("请输入打卡点地址")
return
}
guard !images.isEmpty else {
onShowMessage?("请上传至少一张图片")
return
}
guard !images.contains(where: { $0.isUploading }) else {
onShowMessage?("图片正在上传,请稍后提交")
return
}
guard !images.contains(where: { !$0.isUploaded }) else {
onShowMessage?("请先完成图片上传")
return
}
let scenicId = currentScenicIdProvider()
guard scenicId > 0 else {
onShowMessage?("请先选择景区")
return
}
let request = PunchPointSaveRequest(
id: editId,
scenicAreaId: String(scenicId),
name: name,
description: description.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : description,
region: PunchPointSaveRegion(
lot: coordinate.longitude,
lat: coordinate.latitude,
address: address
),
scenicSpotString: address,
guideImages: images.map(\.uploadedURL)
)
isSubmitting = true
notifyStateChange()
defer {
isSubmitting = false
notifyStateChange()
}
do {
switch mode {
case .create:
try await api.add(request)
case .edit:
try await api.edit(request)
}
onShowMessage?("提交成功")
onSubmitSuccess?()
} catch is CancellationError {
return
} catch {
onShowMessage?(error.localizedDescription.isEmpty ? "提交失败" : "提交失败\(error.localizedDescription)")
}
}
private var editId: Int64? {
if case .edit(let id) = mode { return id }
return nil
}
private func locate(updateMap: Bool, missingPermissionMessage: String) async {
isLocating = true
notifyStateChange()
defer {
isLocating = false
notifyStateChange()
}
do {
let snapshot = try await locationProvider.requestSnapshot()
let coordinate = CLLocationCoordinate2D(latitude: snapshot.latitude, longitude: snapshot.longitude)
self.coordinate = coordinate
if !snapshot.address.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
address = snapshot.address
}
if updateMap {
onCoordinateChange?(coordinate)
}
} catch LocationProviderError.permissionDenied {
onShowMessage?(missingPermissionMessage)
} catch is CancellationError {
return
} catch {
onShowMessage?(error.localizedDescription.isEmpty ? "定位失败" : error.localizedDescription)
}
}
private func uploadImage(at index: Int, title: String, uploader: any PunchPointImageUploading) async {
guard images.indices.contains(index) else { return }
let scenicId = currentScenicIdProvider()
guard scenicId > 0 else {
onShowMessage?("请先选择景区")
return
}
guard !images[index].isUploaded else { return }
images[index].isUploading = true
images[index].uploadProgress = 0
images[index].errorMessage = nil
uploadDialogState = PunchPointUploadDialogState(title: title, progress: 0)
notifyStateChange()
do {
let item = images[index]
let url = try await uploader.uploadPunchPointImage(
data: item.data,
fileName: item.fileName,
scenicId: scenicId,
onProgress: { [weak self] progress in
guard let self else { return }
Task { @MainActor in
guard self.images.indices.contains(index) else { return }
self.images[index].uploadProgress = progress
self.images[index].isUploading = progress < 100
self.uploadDialogState = PunchPointUploadDialogState(title: title, progress: progress)
self.notifyStateChange()
}
}
)
guard images.indices.contains(index) else { return }
images[index].uploadedURL = url
images[index].previewURL = url
images[index].isUploading = false
images[index].uploadProgress = 100
} catch is CancellationError {
return
} catch {
guard images.indices.contains(index) else { return }
images[index].isUploading = false
images[index].uploadProgress = 0
images[index].errorMessage = error.localizedDescription.isEmpty ? "上传失败" : error.localizedDescription
onShowMessage?(error.localizedDescription.isEmpty ? "图片上传失败,请重试" : error.localizedDescription)
}
}
private func notifyStateChange() {
onStateChange?()
}
}