Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f16ac79d68 |
@@ -29,6 +29,8 @@ import com.yzx.kiosk.ui.face.resource.FaceCaptureFileStore
|
||||
import com.yzx.kiosk.ui.face.resource.FaceThumbnailDecoder
|
||||
import com.yzx.kiosk.ui.face.view.*
|
||||
import com.yzx.kiosk.ui.face.viewmodel.*
|
||||
import com.yzx.kiosk.ui.upload.view.PhotoSelectScreen
|
||||
import com.yzx.kiosk.ui.upload.viewmodel.PhotoSelectViewModel
|
||||
import com.yzx.kiosk.websocket.WebSocketService
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -57,6 +59,7 @@ class RecentPhotosFlowTest {
|
||||
private val requests = CopyOnWriteArrayList<Request>()
|
||||
private lateinit var testRepository: NetWorkRepository
|
||||
private var completionVm: ElectronicCompletionViewModel? = null
|
||||
private var uploadVm: PhotoSelectViewModel? = null
|
||||
@Volatile private var electronicAmount: String? = null
|
||||
@Volatile private var completionStatus = 30
|
||||
@Volatile private var payFails = false
|
||||
@@ -140,6 +143,7 @@ class RecentPhotosFlowTest {
|
||||
if (::resultVm.isInitialized) resultVm.viewModelScope.cancel()
|
||||
if (::faceVm.isInitialized) faceVm.viewModelScope.cancel()
|
||||
completionVm?.viewModelScope?.cancel()
|
||||
uploadVm?.viewModelScope?.cancel()
|
||||
scopedResultVms.forEach { it.viewModelScope.cancel() }
|
||||
restoreConfig?.invoke()
|
||||
}
|
||||
@@ -320,6 +324,221 @@ class RecentPhotosFlowTest {
|
||||
job.cancel()
|
||||
}
|
||||
|
||||
@Test fun facePreviewUpdatesSelectionAndBothPurchaseAmounts() {
|
||||
verifyPreviewSelectionPricing(AppRoutes.FACE_RESULT_SOURCE)
|
||||
}
|
||||
|
||||
@Test fun recentPreviewUpdatesSelectionAndBothPurchaseAmounts() {
|
||||
verifyPreviewSelectionPricing(AppRoutes.RECENT_RESULT_SOURCE)
|
||||
}
|
||||
|
||||
@Test fun capturePhotoPreviewSelectedAndUnselectedScreenshots() {
|
||||
val externalDir = checkNotNull(context.getExternalFilesDir(null))
|
||||
val demo = File(externalDir, "demo-photo.jpg")
|
||||
Assume.assumeTrue("Screenshot capture requires demo-photo.jpg in the app's external files directory.", demo.isFile)
|
||||
electronicAmount = "1.00"
|
||||
val files = (1..3).map { id ->
|
||||
File.createTempFile("preview-demo-$id-", ".jpg", context.cacheDir).also { demo.copyTo(it, overwrite = true) }
|
||||
}
|
||||
val photos = files.mapIndexed { index, file ->
|
||||
val url = file.toURI().toString()
|
||||
FaceSearchResult(index + 1, url, url, url, url)
|
||||
}
|
||||
compose.setContent { FaceRecognitionResultScreen(results = photos, viewModel = resultVm) }
|
||||
compose.waitUntil(10_000) { resultVm.photoList.value.size == 3 }
|
||||
compose.onNodeWithText("全选").performClick()
|
||||
waitForPreviewQuote(selectedCount = 3, printAmount = "6.00", electronicAmount = "3.00")
|
||||
compose.onAllNodesWithText("点击预览")[1].performClick()
|
||||
compose.onNodeWithText("2/3").assertIsDisplayed()
|
||||
compose.onNodeWithText("上一张").assertIsEnabled()
|
||||
compose.onNodeWithText("下一张").assertIsEnabled()
|
||||
compose.onNode(isToggleable()).assertIsOn()
|
||||
compose.waitUntil(10_000) {
|
||||
compose.onAllNodes(SemanticsMatcher.keyIsDefined(SemanticsProperties.ProgressBarRangeInfo))
|
||||
.fetchSemanticsNodes().isEmpty()
|
||||
}
|
||||
saveFullScreenScreenshot(File(externalDir, "photo-preview-selected.png"))
|
||||
|
||||
compose.onNode(isToggleable()).performClick()
|
||||
waitForPreviewQuote(selectedCount = 2, printAmount = "4.00", electronicAmount = "2.00")
|
||||
compose.onNodeWithText("2/3").assertIsDisplayed()
|
||||
compose.onNode(isToggleable()).assertIsOff()
|
||||
saveFullScreenScreenshot(File(externalDir, "photo-preview-unselected.png"))
|
||||
files.forEach { it.delete() }
|
||||
}
|
||||
|
||||
private fun saveFullScreenScreenshot(file: File) {
|
||||
compose.waitForIdle()
|
||||
val automation = InstrumentationRegistry.getInstrumentation().uiAutomation
|
||||
automation.waitForIdle(500, 5_000)
|
||||
val bitmap = checkNotNull(automation.takeScreenshot())
|
||||
try {
|
||||
file.outputStream().use { output ->
|
||||
check(bitmap.compress(Bitmap.CompressFormat.PNG, 100, output))
|
||||
}
|
||||
} finally {
|
||||
bitmap.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun uploadPreviewUpdatesSelectionAmountAndTypeOneQuoteIds() {
|
||||
val app = context.applicationContext as com.yzx.kiosk.App
|
||||
lateinit var vm: PhotoSelectViewModel
|
||||
compose.runOnUiThread {
|
||||
vm = PhotoSelectViewModel(nav, app.appState, testRepository, app.appStoreDataSource, testSocket)
|
||||
uploadVm = vm
|
||||
}
|
||||
val fixtures = previewPriceFixtures()
|
||||
val ids = listOf(41, 42)
|
||||
val urls = fixtures.mapIndexed { index, file -> "${ids[index]}:${file.toURI()}" }
|
||||
compose.setContent { PhotoSelectScreen(photoUrls = urls, viewModel = vm) }
|
||||
if (compose.onAllNodesWithText("我知道了").fetchSemanticsNodes().isNotEmpty()) {
|
||||
compose.onNodeWithText("我知道了").performClick()
|
||||
}
|
||||
compose.waitUntil(10_000) {
|
||||
vm.photoList.value.size == 2 && !vm.quoteLoading.value && vm.pricePerPhoto.value == "2.00"
|
||||
}
|
||||
assertLatestUploadQuoteIds(emptySet())
|
||||
compose.onNodeWithText("全选").performClick()
|
||||
waitForUploadQuote(vm, ids.toSet(), "4.00")
|
||||
assertLatestUploadQuoteIds(ids.toSet())
|
||||
compose.onNodeWithText("支付4元").assertIsEnabled()
|
||||
compose.onAllNodesWithText("点击预览")[0].performClick()
|
||||
|
||||
compose.onNodeWithText("1/2").assertIsDisplayed()
|
||||
compose.onNode(isToggleable()).assertIsOn().performClick()
|
||||
waitForUploadQuote(vm, setOf(ids[1]), "2.00")
|
||||
assertLatestUploadQuoteIds(setOf(ids[1]))
|
||||
compose.onNodeWithText("1/2").assertIsDisplayed()
|
||||
compose.onNode(isToggleable()).assertIsOff().performClick()
|
||||
waitForUploadQuote(vm, ids.toSet(), "4.00")
|
||||
assertLatestUploadQuoteIds(ids.toSet())
|
||||
|
||||
compose.onNode(isToggleable()).performClick()
|
||||
waitForUploadQuote(vm, setOf(ids[1]), "2.00")
|
||||
compose.onNodeWithText("下一张").performClick()
|
||||
compose.onNodeWithText("2/2").assertIsDisplayed()
|
||||
compose.onNode(isToggleable()).assertIsOn().performClick()
|
||||
waitForUploadQuote(vm, emptySet(), "0.00")
|
||||
assertLatestUploadQuoteIds(emptySet())
|
||||
compose.onNodeWithText("2/2").assertIsDisplayed()
|
||||
compose.onNodeWithText("上一张").performClick()
|
||||
compose.onNodeWithText("1/2").assertIsDisplayed()
|
||||
compose.onNode(isToggleable()).assertIsOff().performClick()
|
||||
waitForUploadQuote(vm, setOf(ids[0]), "2.00")
|
||||
compose.onNodeWithContentDescription("关闭").performClick()
|
||||
compose.onNodeWithText("已选择").assertIsDisplayed()
|
||||
compose.onNodeWithText("1").assertIsDisplayed()
|
||||
compose.onNodeWithText("支付2元").assertIsEnabled()
|
||||
|
||||
compose.onAllNodesWithText("点击预览")[0].performClick()
|
||||
compose.onNodeWithText("1/1").assertIsDisplayed()
|
||||
compose.onNode(isToggleable()).assertIsOn().performClick()
|
||||
waitForUploadQuote(vm, emptySet(), "0.00")
|
||||
assertLatestUploadQuoteIds(emptySet())
|
||||
compose.onNodeWithText("1/1").assertIsDisplayed()
|
||||
compose.onNodeWithContentDescription("关闭").performClick()
|
||||
compose.onNodeWithText("0").assertIsDisplayed()
|
||||
compose.onNodeWithText("支付0元").assertIsNotEnabled()
|
||||
assertTrue(requests.none { it.url.encodedPath.endsWith("get-pay-url") })
|
||||
fixtures.forEach { it.delete() }
|
||||
}
|
||||
|
||||
private fun waitForUploadQuote(vm: PhotoSelectViewModel, selectedIds: Set<Int>, amount: String) {
|
||||
compose.waitUntil(10_000) {
|
||||
vm.selectedPhotoIds.value == selectedIds && !vm.quoteLoading.value && vm.totalPrice.value == amount
|
||||
}
|
||||
}
|
||||
|
||||
private fun assertLatestUploadQuoteIds(expectedIds: Set<Int>) {
|
||||
val quote = requests.filter { it.url.encodedPath.endsWith("verify-result") }.map { request ->
|
||||
val body = okio.Buffer().also { request.body!!.writeTo(it) }.readUtf8()
|
||||
Gson().fromJson(body, com.google.gson.JsonObject::class.java)
|
||||
}.last { it.get("type").asInt == 1 }
|
||||
assertEquals(expectedIds, quote.getAsJsonArray("image_id").map { it.asInt }.toSet())
|
||||
assertFalse(quote.has("video_id"))
|
||||
}
|
||||
|
||||
private fun previewPriceFixtures(): List<File> =
|
||||
(1..2).map { id ->
|
||||
val file = File.createTempFile("preview-price-$id-", ".png", context.cacheDir)
|
||||
val image = Bitmap.createBitmap(160, 100, Bitmap.Config.ARGB_8888).apply {
|
||||
eraseColor(if (id == 1) Color.GREEN else Color.BLUE)
|
||||
}
|
||||
file.outputStream().use { image.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||
image.recycle()
|
||||
file
|
||||
}
|
||||
|
||||
private fun verifyPreviewSelectionPricing(source: String) {
|
||||
electronicAmount = "1.00"
|
||||
val fixtures = previewPriceFixtures()
|
||||
val photos = fixtures.mapIndexed { index, file ->
|
||||
val url = file.toURI().toString()
|
||||
FaceSearchResult(index + 1, url, url, url, url)
|
||||
}
|
||||
recentBody = Gson().toJson(mapOf("count" to photos.size, "results" to photos))
|
||||
compose.setContent {
|
||||
FaceRecognitionResultScreen(
|
||||
results = if (source == AppRoutes.FACE_RESULT_SOURCE) photos else emptyList(),
|
||||
source = source,
|
||||
viewModel = resultVm
|
||||
)
|
||||
}
|
||||
compose.waitUntil(10_000) { resultVm.photoList.value.size == 2 }
|
||||
compose.onNodeWithText("全选").performClick()
|
||||
waitForPreviewQuote(selectedCount = 2, printAmount = "4.00", electronicAmount = "2.00")
|
||||
compose.onNodeWithText("已选择 2 张").assertIsDisplayed()
|
||||
compose.onNodeWithText("购买打印照片\n4元").assertIsEnabled()
|
||||
compose.onNodeWithText("购买电子照片\n2元").assertIsEnabled()
|
||||
|
||||
compose.onAllNodesWithText("点击预览")[0].performClick()
|
||||
compose.onNodeWithText("1/2").assertIsDisplayed()
|
||||
compose.onNode(isToggleable()).assertIsOn().performClick()
|
||||
waitForPreviewQuote(selectedCount = 1, printAmount = "2.00", electronicAmount = "1.00")
|
||||
compose.onNodeWithText("1/2").assertIsDisplayed()
|
||||
compose.onNode(isToggleable()).assertIsOff()
|
||||
compose.runOnIdle { assertEquals(setOf(fixtures[1].toURI().toString()), resultVm.selectedPhotos.value) }
|
||||
|
||||
compose.onNodeWithText("下一张").performClick()
|
||||
compose.onNodeWithText("2/2").assertIsDisplayed()
|
||||
compose.onNode(isToggleable()).assertIsOn().performClick()
|
||||
waitForPreviewQuote(selectedCount = 0, printAmount = "0.00", electronicAmount = "0.00")
|
||||
compose.onNodeWithText("2/2").assertIsDisplayed()
|
||||
compose.onNodeWithContentDescription("关闭").assertIsDisplayed()
|
||||
|
||||
compose.onNodeWithText("上一张").performClick()
|
||||
compose.onNodeWithText("1/2").assertIsDisplayed()
|
||||
compose.onNode(isToggleable()).assertIsOff().performClick()
|
||||
waitForPreviewQuote(selectedCount = 1, printAmount = "2.00", electronicAmount = "1.00")
|
||||
compose.runOnIdle { assertEquals(setOf(fixtures[0].toURI().toString()), resultVm.selectedPhotos.value) }
|
||||
compose.onNodeWithContentDescription("关闭").performClick()
|
||||
compose.onNodeWithText("已选择 1 张").assertIsDisplayed()
|
||||
compose.onNodeWithText("购买打印照片\n2元").assertIsEnabled()
|
||||
compose.onNodeWithText("购买电子照片\n1元").assertIsEnabled()
|
||||
|
||||
// Reopening takes the current selection, rather than retaining the previous session's two photos.
|
||||
compose.onAllNodesWithText("点击预览")[0].performClick()
|
||||
compose.onNodeWithText("1/1").assertIsDisplayed()
|
||||
compose.onNode(isToggleable()).assertIsOn().performClick()
|
||||
waitForPreviewQuote(selectedCount = 0, printAmount = "0.00", electronicAmount = "0.00")
|
||||
compose.onNodeWithText("1/1").assertIsDisplayed()
|
||||
compose.onNodeWithContentDescription("关闭").performClick()
|
||||
compose.onNodeWithText("已选择 0 张").assertIsDisplayed()
|
||||
compose.onNodeWithText("购买打印照片\n0元").assertIsNotEnabled()
|
||||
compose.onNodeWithText("购买电子照片\n0元").assertIsNotEnabled()
|
||||
assertTrue(requests.none { it.url.encodedPath.endsWith("get-pay-url") })
|
||||
fixtures.forEach { it.delete() }
|
||||
}
|
||||
|
||||
private fun waitForPreviewQuote(selectedCount: Int, printAmount: String, electronicAmount: String) {
|
||||
compose.waitUntil(10_000) {
|
||||
resultVm.selectedPhotos.value.size == selectedCount &&
|
||||
!resultVm.quoteLoading.value && resultVm.totalPrice.value == printAmount &&
|
||||
resultVm.electronicTotal.value == electronicAmount
|
||||
}
|
||||
}
|
||||
|
||||
private fun showElectronicSelection(amount: String?) {
|
||||
electronicAmount = amount
|
||||
val image = Bitmap.createBitmap(160, 100, Bitmap.Config.ARGB_8888).apply { eraseColor(Color.BLUE) }
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
package com.yzx.kiosk.ui.upload.view
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Color
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.assertIsNotEnabled
|
||||
import androidx.compose.ui.test.assertIsOff
|
||||
import androidx.compose.ui.test.assertIsOn
|
||||
import androidx.compose.ui.test.isToggleable
|
||||
import androidx.compose.ui.test.junit4.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.yzx.kiosk.theme.AppTheme
|
||||
import java.io.File
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
|
||||
class PhotoPreviewDialogTest {
|
||||
@get:Rule val compose = createComposeRule()
|
||||
private val fixtures = mutableListOf<File>()
|
||||
|
||||
@After fun deleteFixtures() {
|
||||
fixtures.forEach { it.delete() }
|
||||
}
|
||||
|
||||
@Test fun cancellingCurrentPhotoKeepsItsPageAndEachPhotoRemembersSelection() {
|
||||
val photos = photoFixtures(3)
|
||||
var selectedIds by mutableStateOf(photos.map { it.id }.toSet())
|
||||
val toggledIds = mutableListOf<Int>()
|
||||
compose.setContent {
|
||||
AppTheme {
|
||||
PhotoPreviewDialog(
|
||||
photoList = photos,
|
||||
initialIndex = 1,
|
||||
selectedPhotoIds = selectedIds,
|
||||
onToggleSelection = { photo ->
|
||||
toggledIds.add(photo.id)
|
||||
selectedIds = if (photo.id in selectedIds) selectedIds - photo.id else selectedIds + photo.id
|
||||
},
|
||||
onDismiss = {}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
compose.onNodeWithText("2/3").assertIsDisplayed()
|
||||
val previousBounds = compose.onNodeWithText("上一张").fetchSemanticsNode().boundsInRoot
|
||||
val selectionBounds = compose.onNode(isToggleable()).fetchSemanticsNode().boundsInRoot
|
||||
val nextBounds = compose.onNodeWithText("下一张").fetchSemanticsNode().boundsInRoot
|
||||
assertTrue(previousBounds.center.x < selectionBounds.center.x)
|
||||
assertTrue(selectionBounds.center.x < nextBounds.center.x)
|
||||
assertEquals(previousBounds.center.y, selectionBounds.center.y, 1f)
|
||||
assertEquals(nextBounds.center.y, selectionBounds.center.y, 1f)
|
||||
|
||||
compose.onNode(isToggleable()).assertIsOn().performClick()
|
||||
compose.onNodeWithText("2/3").assertIsDisplayed()
|
||||
compose.onNode(isToggleable()).assertIsOff()
|
||||
compose.runOnIdle {
|
||||
assertEquals(listOf(photos[1].id), toggledIds)
|
||||
assertEquals(setOf(photos[0].id, photos[2].id), selectedIds)
|
||||
}
|
||||
|
||||
compose.onNodeWithText("下一张").performClick()
|
||||
compose.onNodeWithText("3/3").assertIsDisplayed()
|
||||
compose.onNode(isToggleable()).assertIsOn()
|
||||
compose.onNodeWithText("上一张").performClick()
|
||||
compose.onNodeWithText("2/3").assertIsDisplayed()
|
||||
compose.onNode(isToggleable()).assertIsOff().performClick()
|
||||
compose.onNodeWithText("2/3").assertIsDisplayed()
|
||||
compose.onNode(isToggleable()).assertIsOn()
|
||||
compose.runOnIdle { assertEquals(photos.map { it.id }.toSet(), selectedIds) }
|
||||
}
|
||||
|
||||
@Test fun cancellingEveryPhotoLeavesPreviewOpenAndAllowsReselection() {
|
||||
val photos = photoFixtures(2)
|
||||
var selectedIds by mutableStateOf(photos.map { it.id }.toSet())
|
||||
var dismissed = false
|
||||
compose.setContent {
|
||||
AppTheme {
|
||||
PhotoPreviewDialog(
|
||||
photoList = photos,
|
||||
initialIndex = 0,
|
||||
selectedPhotoIds = selectedIds,
|
||||
onToggleSelection = { photo ->
|
||||
selectedIds = if (photo.id in selectedIds) selectedIds - photo.id else selectedIds + photo.id
|
||||
},
|
||||
onDismiss = { dismissed = true }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
compose.onNodeWithText("上一张").assertIsNotEnabled()
|
||||
compose.onNode(isToggleable()).performClick()
|
||||
compose.onNodeWithText("下一张").performClick()
|
||||
compose.onNode(isToggleable()).performClick()
|
||||
compose.onNodeWithText("2/2").assertIsDisplayed()
|
||||
compose.onNodeWithText("下一张").assertIsNotEnabled()
|
||||
compose.onNodeWithContentDescription("关闭").assertIsDisplayed()
|
||||
compose.runOnIdle {
|
||||
assertTrue(selectedIds.isEmpty())
|
||||
assertTrue(!dismissed)
|
||||
}
|
||||
|
||||
compose.onNodeWithText("上一张").performClick()
|
||||
compose.onNodeWithText("1/2").assertIsDisplayed()
|
||||
compose.onNode(isToggleable()).assertIsOff().performClick()
|
||||
compose.onNode(isToggleable()).assertIsOn()
|
||||
compose.runOnIdle { assertEquals(setOf(photos[0].id), selectedIds) }
|
||||
}
|
||||
|
||||
@Test fun reopeningUsesTheNewPhotoListAndInitialPage() {
|
||||
val photos = photoFixtures(3)
|
||||
var previewPhotos by mutableStateOf(photos)
|
||||
var selectedIds by mutableStateOf(photos.map { it.id }.toSet())
|
||||
var initialIndex by mutableStateOf(1)
|
||||
var visible by mutableStateOf(true)
|
||||
compose.setContent {
|
||||
AppTheme {
|
||||
if (visible) {
|
||||
PhotoPreviewDialog(
|
||||
photoList = previewPhotos,
|
||||
initialIndex = initialIndex,
|
||||
selectedPhotoIds = selectedIds,
|
||||
onToggleSelection = { photo ->
|
||||
selectedIds = if (photo.id in selectedIds) selectedIds - photo.id else selectedIds + photo.id
|
||||
},
|
||||
onDismiss = { visible = false }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
compose.onNodeWithText("2/3").assertIsDisplayed()
|
||||
compose.onNodeWithContentDescription("关闭").performClick()
|
||||
compose.onNodeWithContentDescription("关闭").assertDoesNotExist()
|
||||
compose.runOnIdle {
|
||||
previewPhotos = listOf(photos[2])
|
||||
selectedIds = setOf(photos[2].id)
|
||||
initialIndex = 0
|
||||
visible = true
|
||||
}
|
||||
compose.onNodeWithText("1/1").assertIsDisplayed()
|
||||
compose.onNodeWithText("上一张").assertIsNotEnabled()
|
||||
compose.onNodeWithText("下一张").assertIsNotEnabled()
|
||||
compose.onNode(isToggleable()).assertIsOn().performClick()
|
||||
compose.onNodeWithText("1/1").assertIsDisplayed()
|
||||
compose.onNode(isToggleable()).assertIsOff()
|
||||
compose.runOnIdle { assertTrue(selectedIds.isEmpty()) }
|
||||
}
|
||||
|
||||
@Test fun disabledSelectionDoesNotChangeCurrentPhoto() {
|
||||
val photos = photoFixtures(1)
|
||||
var toggleCount = 0
|
||||
compose.setContent {
|
||||
AppTheme {
|
||||
PhotoPreviewDialog(
|
||||
photoList = photos,
|
||||
initialIndex = 0,
|
||||
selectedPhotoIds = setOf(photos[0].id),
|
||||
onToggleSelection = { toggleCount++ },
|
||||
selectionEnabled = false,
|
||||
onDismiss = {}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
compose.onNode(isToggleable()).assertIsOn().assertIsNotEnabled().performClick()
|
||||
compose.onNodeWithText("1/1").assertIsDisplayed()
|
||||
compose.runOnIdle { assertEquals(0, toggleCount) }
|
||||
}
|
||||
|
||||
private fun photoFixtures(count: Int): List<PhotoPreviewItem> {
|
||||
val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
return (1..count).map { id ->
|
||||
val file = File.createTempFile("preview-$id-", ".png", context.cacheDir).also { fixtures.add(it) }
|
||||
val bitmap = Bitmap.createBitmap(160, 100, Bitmap.Config.ARGB_8888).apply {
|
||||
eraseColor(if (id % 2 == 0) Color.BLUE else Color.GREEN)
|
||||
}
|
||||
file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||
bitmap.recycle()
|
||||
PhotoPreviewItem(id = id, url = file.toURI().toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,7 @@ import com.yzx.kiosk.network.model.response.FaceSearchResult
|
||||
import com.yzx.kiosk.ui.common.view.FullScreenMode
|
||||
import com.yzx.kiosk.ui.face.viewmodel.FaceRecognitionResultViewModel
|
||||
import com.yzx.kiosk.ui.upload.view.PhotoPreviewDialog
|
||||
import com.yzx.kiosk.ui.upload.view.PhotoPreviewItem
|
||||
import com.yzx.kiosk.ui.upload.view.RetryableAsyncImage
|
||||
import com.yzx.kiosk.utils.QrCodeUtils
|
||||
import kotlinx.coroutines.flow.collect
|
||||
@@ -104,6 +105,7 @@ fun FaceRecognitionResultScreen(
|
||||
// 预览弹框状态
|
||||
var showPreviewDialog by remember { mutableStateOf(false) }
|
||||
var previewInitialIndex by remember { mutableIntStateOf(0) }
|
||||
var previewPhotos by remember { mutableStateOf<List<PhotoPreviewItem>>(emptyList()) }
|
||||
|
||||
// 支付弹框状态
|
||||
var showPayDialog by remember { mutableStateOf(false) }
|
||||
@@ -315,10 +317,13 @@ fun FaceRecognitionResultScreen(
|
||||
loadState = loadState,
|
||||
onToggleSelection = { viewModel.togglePhotoSelection(photo.url) },
|
||||
onPreviewClick = {
|
||||
// 计算在已选列表中的索引
|
||||
val selectedList = photoList.filter { selectedPhotos.contains(it.url) }
|
||||
val selectedIndex = selectedList.indexOfFirst { it.url == photo.url }
|
||||
// 固定本次预览列表,取消选择后仍可查看和重新勾选。
|
||||
val selectedList = photoList
|
||||
.filter { selectedPhotos.contains(it.url) }
|
||||
.map { PhotoPreviewItem(id = it.id, url = it.url) }
|
||||
val selectedIndex = selectedList.indexOfFirst { it.id == photo.id }
|
||||
if (selectedIndex >= 0) {
|
||||
previewPhotos = selectedList
|
||||
previewInitialIndex = selectedIndex
|
||||
showPreviewDialog = true
|
||||
}
|
||||
@@ -335,13 +340,19 @@ fun FaceRecognitionResultScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// 预览弹框 - 仅预览已选择的图片
|
||||
val selectedPhotoUrls = photoList.filter { selectedPhotos.contains(it.url) }.map { it.url }
|
||||
if (showPreviewDialog && selectedPhotoUrls.isNotEmpty()) {
|
||||
// 预览列表在打开时固定,选择状态与网格实时同步。
|
||||
val selectedPhotoIds = previewPhotos.filter { selectedPhotos.contains(it.url) }.map { it.id }.toSet()
|
||||
if (showPreviewDialog && previewPhotos.isNotEmpty()) {
|
||||
PhotoPreviewDialog(
|
||||
photoList = selectedPhotoUrls,
|
||||
photoList = previewPhotos,
|
||||
initialIndex = previewInitialIndex,
|
||||
onDismiss = { showPreviewDialog = false }
|
||||
selectedPhotoIds = selectedPhotoIds,
|
||||
onToggleSelection = { viewModel.togglePhotoSelection(it.url) },
|
||||
selectionEnabled = !creatingOrder,
|
||||
onDismiss = {
|
||||
showPreviewDialog = false
|
||||
previewPhotos = emptyList()
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -309,9 +309,9 @@ class FaceRecognitionResultViewModel @Inject constructor(
|
||||
val revision = quoteRevision.next()
|
||||
quoteJob?.cancel()
|
||||
_pricePerPhoto.value = "--"
|
||||
_totalPrice.value = "--"
|
||||
_totalPrice.value = if (imageIds.isEmpty()) "0.00" else "--"
|
||||
_electronicPrice.value = "--"
|
||||
_electronicTotal.value = "--"
|
||||
_electronicTotal.value = if (imageIds.isEmpty()) "0.00" else "--"
|
||||
quoteJob = viewModelScope.launch {
|
||||
try {
|
||||
val response = netWorkRepository.verifyResult(VerifyResultRequest(2, imageIds.distinct(), videoId = emptyList())).first()
|
||||
@@ -329,13 +329,13 @@ class FaceRecognitionResultViewModel @Inject constructor(
|
||||
val printTotal = money(data.amount)
|
||||
if (printUnit != null && printTotal != null) {
|
||||
_pricePerPhoto.value = printUnit
|
||||
_totalPrice.value = printTotal
|
||||
_totalPrice.value = if (imageIds.isEmpty()) "0.00" else printTotal
|
||||
}
|
||||
val electronicUnit = money(data.priceElectronic)
|
||||
val electronicTotal = money(data.amountElectronic)
|
||||
if (electronicQuoteAvailable(electronicUnit, electronicTotal, imageIds.isNotEmpty())) {
|
||||
_electronicPrice.value = checkNotNull(electronicUnit)
|
||||
_electronicTotal.value = checkNotNull(electronicTotal)
|
||||
_electronicTotal.value = if (imageIds.isEmpty()) "0.00" else checkNotNull(electronicTotal)
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
|
||||
@@ -2,10 +2,13 @@ package com.yzx.kiosk.ui.upload.view
|
||||
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
@@ -18,8 +21,10 @@ import androidx.compose.foundation.pager.HorizontalPager
|
||||
import androidx.compose.foundation.pager.rememberPagerState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.selection.toggleable
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
@@ -35,9 +40,11 @@ import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
@@ -49,22 +56,33 @@ import com.yzx.kiosk.utils.LogUtils
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** 本次预览中的稳定照片标识,不随勾选状态变化。 */
|
||||
data class PhotoPreviewItem(val id: Int, val url: String)
|
||||
|
||||
/**
|
||||
* 图片预览弹框 - 全屏展示,仅预览已选择的图片
|
||||
* 全屏预览本次打开时选中的照片,购买选择由调用页面实时维护。
|
||||
*/
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun PhotoPreviewDialog(
|
||||
photoList: List<String>,
|
||||
photoList: List<PhotoPreviewItem>,
|
||||
initialIndex: Int,
|
||||
selectedPhotoIds: Set<Int>,
|
||||
onToggleSelection: (PhotoPreviewItem) -> Unit,
|
||||
selectionEnabled: Boolean = true,
|
||||
onDismiss: () -> Unit
|
||||
) {
|
||||
if (photoList.isEmpty()) return
|
||||
|
||||
val pagerState = rememberPagerState(
|
||||
initialPage = initialIndex,
|
||||
initialPage = initialIndex.coerceIn(0, photoList.lastIndex),
|
||||
pageCount = { photoList.size }
|
||||
)
|
||||
val coroutineScope = rememberCoroutineScope()
|
||||
val currentIndex = pagerState.currentPage
|
||||
val currentPhoto = photoList[currentIndex]
|
||||
val isSelected = currentPhoto.id in selectedPhotoIds
|
||||
val canToggleSelection = selectionEnabled && !pagerState.isScrollInProgress
|
||||
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
@@ -127,60 +145,128 @@ fun PhotoPreviewDialog(
|
||||
) {
|
||||
Spacer(modifier = Modifier.height(36.dp))
|
||||
|
||||
// 上一张/下一张按钮
|
||||
Row(
|
||||
// 翻页与当前照片的勾选集中在同一操作行。
|
||||
BoxWithConstraints(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 48.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
.padding(horizontal = 24.dp)
|
||||
) {
|
||||
// 上一张按钮
|
||||
Button(
|
||||
onClick = {
|
||||
if (currentIndex > 0) {
|
||||
coroutineScope.launch {
|
||||
pagerState.animateScrollToPage(currentIndex - 1)
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled = currentIndex > 0,
|
||||
shape = RoundedCornerShape(18.dp),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = Color(0xFF2196F3),
|
||||
disabledContainerColor = Color(0xFFF4F4F4)
|
||||
),
|
||||
modifier = Modifier.width(111.dp).height(56.dp)
|
||||
) {
|
||||
Text(
|
||||
text = "上一张",
|
||||
fontSize = 21.sp,
|
||||
color = if (currentIndex > 0) Color.White else Color(0xFF999999),
|
||||
fontWeight = FontWeight.Bold)
|
||||
val narrow = maxWidth < 250.dp
|
||||
val controlFontSize = when {
|
||||
narrow -> 14.sp
|
||||
maxWidth < 360.dp -> 17.sp
|
||||
else -> 21.sp
|
||||
}
|
||||
val selectionIndicatorSize = when {
|
||||
narrow -> 20.dp
|
||||
maxWidth < 360.dp -> 24.dp
|
||||
else -> 28.dp
|
||||
}
|
||||
val selectionCheckSize = when {
|
||||
narrow -> 16.dp
|
||||
maxWidth < 360.dp -> 18.dp
|
||||
else -> 22.dp
|
||||
}
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Button(
|
||||
onClick = {
|
||||
if (currentIndex > 0) {
|
||||
coroutineScope.launch {
|
||||
pagerState.animateScrollToPage(currentIndex - 1)
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled = currentIndex > 0,
|
||||
shape = RoundedCornerShape(18.dp),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = Color(0xFF2196F3),
|
||||
disabledContainerColor = Color(0xFFF4F4F4)
|
||||
),
|
||||
contentPadding = PaddingValues(horizontal = 8.dp),
|
||||
modifier = Modifier.weight(1f).height(56.dp)
|
||||
) {
|
||||
Text(
|
||||
text = "上一张",
|
||||
fontSize = controlFontSize,
|
||||
maxLines = 1,
|
||||
color = if (currentIndex > 0) Color.White else Color(0xFF999999),
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
}
|
||||
|
||||
// 下一张按钮
|
||||
Button(
|
||||
onClick = {
|
||||
if (currentIndex < photoList.size - 1) {
|
||||
coroutineScope.launch {
|
||||
pagerState.animateScrollToPage(currentIndex + 1)
|
||||
val selectionColor = if (isSelected) Color(0xFF0073FF) else Color(0xFF757575)
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.weight(1.4f)
|
||||
.height(56.dp)
|
||||
.clip(RoundedCornerShape(18.dp))
|
||||
.alpha(if (canToggleSelection) 1f else 0.5f)
|
||||
.toggleable(
|
||||
value = isSelected,
|
||||
enabled = canToggleSelection,
|
||||
role = Role.Checkbox,
|
||||
onValueChange = { onToggleSelection(currentPhoto) }
|
||||
)
|
||||
.padding(horizontal = 8.dp),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(selectionIndicatorSize)
|
||||
.clip(CircleShape)
|
||||
.background(if (isSelected) Color(0xFF0073FF) else Color.Transparent)
|
||||
.border(1.5.dp, selectionColor, CircleShape),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
if (isSelected) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Check,
|
||||
contentDescription = null,
|
||||
tint = Color.White,
|
||||
modifier = Modifier.size(selectionCheckSize)
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled = currentIndex < photoList.size - 1,
|
||||
shape = RoundedCornerShape(18.dp),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = Color(0xFF2196F3),
|
||||
disabledContainerColor = Color(0xFFF4F4F4)
|
||||
),
|
||||
modifier = Modifier.width(111.dp).height(56.dp)
|
||||
) {
|
||||
Text(
|
||||
text = "下一张",
|
||||
fontSize = 21.sp,
|
||||
color = if (currentIndex < photoList.size - 1) Color.White else Color(0xFF999999),
|
||||
fontWeight = FontWeight.Bold)
|
||||
Spacer(Modifier.width(if (narrow) 6.dp else 8.dp))
|
||||
Text(
|
||||
text = if (isSelected) "已选择" else "未选择",
|
||||
fontSize = controlFontSize,
|
||||
maxLines = 1,
|
||||
color = if (isSelected) Color(0xFF0073FF) else Color(0xFF616161),
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
}
|
||||
|
||||
Button(
|
||||
onClick = {
|
||||
if (currentIndex < photoList.size - 1) {
|
||||
coroutineScope.launch {
|
||||
pagerState.animateScrollToPage(currentIndex + 1)
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled = currentIndex < photoList.size - 1,
|
||||
shape = RoundedCornerShape(18.dp),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = Color(0xFF2196F3),
|
||||
disabledContainerColor = Color(0xFFF4F4F4)
|
||||
),
|
||||
contentPadding = PaddingValues(horizontal = 8.dp),
|
||||
modifier = Modifier.weight(1f).height(56.dp)
|
||||
) {
|
||||
Text(
|
||||
text = "下一张",
|
||||
fontSize = controlFontSize,
|
||||
maxLines = 1,
|
||||
color = if (currentIndex < photoList.size - 1) Color.White else Color(0xFF999999),
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -189,6 +275,7 @@ fun PhotoPreviewDialog(
|
||||
// 图片轮播
|
||||
HorizontalPager(
|
||||
state = pagerState,
|
||||
key = { photoList[it].id },
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 48.dp)
|
||||
@@ -200,7 +287,7 @@ fun PhotoPreviewDialog(
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
RetryableAsyncImage(
|
||||
imageUrl = photoList[page],
|
||||
imageUrl = photoList[page].url,
|
||||
modifier = Modifier.fillMaxWidth().background(color = Color.White, shape = RoundedCornerShape(18.dp)),
|
||||
contentScale = ContentScale.Fit,
|
||||
maxRetries = 10
|
||||
@@ -208,7 +295,14 @@ fun PhotoPreviewDialog(
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(36.dp))
|
||||
Spacer(modifier = Modifier.height(24.dp))
|
||||
Text(
|
||||
text = "已选择 ${selectedPhotoIds.size} 张",
|
||||
modifier = Modifier.align(Alignment.CenterHorizontally),
|
||||
fontSize = 18.sp,
|
||||
color = Color(0xFF666666)
|
||||
)
|
||||
Spacer(modifier = Modifier.height(24.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,6 +66,7 @@ fun PhotoSelectScreen(
|
||||
val selectedPhotoIds by viewModel.selectedPhotoIds.collectAsState()
|
||||
val pricePerPhoto by viewModel.pricePerPhoto.collectAsState() // 从接口获取的单价(字符串)
|
||||
val totalPrice by viewModel.totalPrice.collectAsState() // 从接口获取的总价(字符串)
|
||||
val quoteLoading by viewModel.quoteLoading.collectAsState()
|
||||
|
||||
val selectedCount = selectedPhotoIds.size
|
||||
val isAllSelected = photoList.isNotEmpty() && selectedPhotoIds.size == photoList.size
|
||||
@@ -73,6 +74,7 @@ fun PhotoSelectScreen(
|
||||
// 预览弹框状态
|
||||
var showPreviewDialog by remember { mutableStateOf(false) }
|
||||
var previewInitialIndex by remember { mutableIntStateOf(0) }
|
||||
var previewPhotos by remember { mutableStateOf<List<PhotoPreviewItem>>(emptyList()) }
|
||||
|
||||
// 支付弹框状态
|
||||
var showPayDialog by remember { mutableStateOf(false) }
|
||||
@@ -168,10 +170,15 @@ fun PhotoSelectScreen(
|
||||
.widthIn(min = 180.dp),
|
||||
shape = RoundedCornerShape(18.dp),
|
||||
colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF0073FF)),
|
||||
enabled = selectedCount > 0
|
||||
enabled = selectedCount > 0 && totalPrice != "--" && !quoteLoading
|
||||
) {
|
||||
Text(
|
||||
text = if (selectedCount > 0) "支付${formatPriceDisplay(totalPrice)}元" else "支付0元",
|
||||
text = when {
|
||||
selectedCount == 0 -> "支付0元"
|
||||
quoteLoading -> "正在更新价格…"
|
||||
totalPrice == "--" -> "价格暂不可用"
|
||||
else -> "支付${formatPriceDisplay(totalPrice)}元"
|
||||
},
|
||||
fontSize = 24.sp,
|
||||
color = Color.White,
|
||||
fontWeight = FontWeight.Bold
|
||||
@@ -242,10 +249,13 @@ fun PhotoSelectScreen(
|
||||
isSelected = isSelected,
|
||||
onToggleSelection = { viewModel.togglePhotoSelection(photo.id) },
|
||||
onPreviewClick = {
|
||||
// 计算在已选列表中的索引
|
||||
val selectedList = photoList.filter { selectedPhotoIds.contains(it.id) }
|
||||
// 固定本次预览列表,取消选择后仍可查看和重新勾选。
|
||||
val selectedList = photoList
|
||||
.filter { selectedPhotoIds.contains(it.id) }
|
||||
.map { PhotoPreviewItem(id = it.id, url = it.url) }
|
||||
val selectedIndex = selectedList.indexOfFirst { it.id == photo.id }
|
||||
if (selectedIndex >= 0) {
|
||||
previewPhotos = selectedList
|
||||
previewInitialIndex = selectedIndex
|
||||
showPreviewDialog = true
|
||||
}
|
||||
@@ -264,13 +274,17 @@ fun PhotoSelectScreen(
|
||||
)
|
||||
}
|
||||
|
||||
// 预览弹框 - 仅预览已选择的图片
|
||||
val selectedPhotoUrls = photoList.filter { selectedPhotoIds.contains(it.id) }.map { it.url }
|
||||
if (showPreviewDialog && selectedPhotoUrls.isNotEmpty()) {
|
||||
// 预览列表在打开时固定,选择状态与网格实时同步。
|
||||
if (showPreviewDialog && previewPhotos.isNotEmpty()) {
|
||||
PhotoPreviewDialog(
|
||||
photoList = selectedPhotoUrls,
|
||||
photoList = previewPhotos,
|
||||
initialIndex = previewInitialIndex,
|
||||
onDismiss = { showPreviewDialog = false }
|
||||
selectedPhotoIds = selectedPhotoIds,
|
||||
onToggleSelection = { viewModel.togglePhotoSelection(it.id) },
|
||||
onDismiss = {
|
||||
showPreviewDialog = false
|
||||
previewPhotos = emptyList()
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import coil.request.ImageRequest
|
||||
import coil.size.Size
|
||||
import com.yzx.kiosk.App
|
||||
import com.yzx.kiosk.base.BaseViewModel
|
||||
import com.yzx.kiosk.component.auth.GlobalAuthDialogManager
|
||||
import com.yzx.kiosk.datastore.AppState
|
||||
import com.yzx.kiosk.navigation.AppNavigator
|
||||
import com.yzx.kiosk.navigation.routes.AppRoutes
|
||||
@@ -13,6 +14,8 @@ import com.yzx.kiosk.network.model.request.GetPayUrlRequest
|
||||
import com.yzx.kiosk.network.model.request.VerifyResultRequest
|
||||
import com.yzx.kiosk.network.repository.NetWorkRepository
|
||||
import com.yzx.kiosk.network.result.asResult
|
||||
import com.yzx.kiosk.ui.face.viewmodel.QuoteRevision
|
||||
import com.yzx.kiosk.ui.face.viewmodel.money
|
||||
import com.yzx.kiosk.utils.ToastUtils
|
||||
import com.yzx.kiosk.websocket.WebSocketService
|
||||
import com.yzx.kiosk.websocket.UploadPhotoEvent
|
||||
@@ -23,13 +26,16 @@ import com.yzx.kiosk.datastore.AppStoreDataSource
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.flow.onEach
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.awaitAll
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import com.yzx.kiosk.utils.LogUtils
|
||||
@@ -97,9 +103,14 @@ class PhotoSelectViewModel @Inject constructor(
|
||||
val pricePerPhoto: StateFlow<String> = _pricePerPhoto.asStateFlow()
|
||||
|
||||
// 总价(从接口获取)
|
||||
private val _totalPrice = MutableStateFlow("--")
|
||||
private val _totalPrice = MutableStateFlow("0.00")
|
||||
val totalPrice: StateFlow<String> = _totalPrice.asStateFlow()
|
||||
|
||||
private val _quoteLoading = MutableStateFlow(false)
|
||||
val quoteLoading: StateFlow<Boolean> = _quoteLoading.asStateFlow()
|
||||
private val quoteRevision = QuoteRevision()
|
||||
private var quoteJob: Job? = null
|
||||
|
||||
// 支付二维码URL
|
||||
private val _payQrCodeUrl = MutableStateFlow<String?>(null)
|
||||
val payQrCodeUrl: StateFlow<String?> = _payQrCodeUrl.asStateFlow()
|
||||
@@ -155,6 +166,7 @@ class PhotoSelectViewModel @Inject constructor(
|
||||
// 如果没有传入数据,清空列表
|
||||
_photoList.value = emptyList()
|
||||
_selectedPhotoIds.value = emptySet()
|
||||
verifyResult(emptyList())
|
||||
return
|
||||
}
|
||||
|
||||
@@ -226,6 +238,7 @@ class PhotoSelectViewModel @Inject constructor(
|
||||
if (initialPhotos.isEmpty()) {
|
||||
_photoList.value = emptyList()
|
||||
_selectedPhotoIds.value = emptySet()
|
||||
verifyResult(emptyList())
|
||||
return@launch
|
||||
}
|
||||
|
||||
@@ -403,50 +416,39 @@ class PhotoSelectViewModel @Inject constructor(
|
||||
* @param imageIds 选中的图片ID数组
|
||||
*/
|
||||
private fun verifyResult(imageIds: List<Int>) {
|
||||
viewModelScope.launch {
|
||||
val revision = quoteRevision.next()
|
||||
quoteJob?.cancel()
|
||||
// 选择变化后,旧金额立即失效;空选择始终显示 0。
|
||||
_totalPrice.value = if (imageIds.isEmpty()) "0.00" else "--"
|
||||
_quoteLoading.value = true
|
||||
quoteJob = viewModelScope.launch {
|
||||
try {
|
||||
val request = VerifyResultRequest(
|
||||
type = 1,
|
||||
imageId = imageIds
|
||||
)
|
||||
// 直接在当前 Job 收集,取消时同时取消实际报价请求。
|
||||
val response = netWorkRepository.verifyResult(
|
||||
VerifyResultRequest(type = 1, imageId = imageIds)
|
||||
).first()
|
||||
if (!quoteRevision.isCurrent(revision)) return@launch
|
||||
if (response.isTokenFailed) {
|
||||
GlobalAuthDialogManager.show()
|
||||
return@launch
|
||||
}
|
||||
if (!response.isSucceeded || response.data == null) {
|
||||
LogUtils.e("PhotoSelectViewModel", "验证结果失败: ${response.message}")
|
||||
return@launch
|
||||
}
|
||||
|
||||
handleResultWithData(
|
||||
flow = netWorkRepository.verifyResult(request).asResult(),
|
||||
showToast = false,
|
||||
onData = { response ->
|
||||
// 更新单价(使用接口返回的 price_image)
|
||||
val priceImage = response.priceImage
|
||||
if (!priceImage.isNullOrEmpty()) {
|
||||
_pricePerPhoto.value = priceImage
|
||||
} else {
|
||||
_pricePerPhoto.value = "--"
|
||||
}
|
||||
|
||||
// 更新总价(使用接口返回的 amount)
|
||||
val amount = response.amount
|
||||
if (!amount.isNullOrEmpty()) {
|
||||
_totalPrice.value = amount
|
||||
} else {
|
||||
_totalPrice.value = "--"
|
||||
}
|
||||
|
||||
LogUtils.d("PhotoSelectViewModel", "验证结果成功 - 单价: $priceImage, 总价: $amount")
|
||||
},
|
||||
onError = { msg, _ ->
|
||||
LogUtils.e("PhotoSelectViewModel", "验证结果失败: $msg")
|
||||
// 接口失败时,保持当前值或设置为默认值
|
||||
if (_selectedPhotoIds.value.isEmpty()) {
|
||||
_pricePerPhoto.value = "--"
|
||||
_totalPrice.value = "--"
|
||||
}
|
||||
}
|
||||
)
|
||||
val data = response.data
|
||||
// 初始化的空列表请求仍用于取得单价,不让服务端金额覆盖空选择的 0。
|
||||
_pricePerPhoto.value = money(data.priceImage) ?: "--"
|
||||
_totalPrice.value = if (imageIds.isEmpty()) "0.00" else money(data.amount) ?: "--"
|
||||
LogUtils.d("PhotoSelectViewModel", "验证结果成功 - 单价: ${data.priceImage}, 总价: ${data.amount}")
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
LogUtils.e("PhotoSelectViewModel", "验证结果异常: ${e.message}")
|
||||
if (_selectedPhotoIds.value.isEmpty()) {
|
||||
_pricePerPhoto.value = "--"
|
||||
_totalPrice.value = "--"
|
||||
}
|
||||
} finally {
|
||||
// 旧请求的完成/取消不能结束当前请求的加载状态。
|
||||
if (quoteRevision.isCurrent(revision)) _quoteLoading.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -461,6 +463,10 @@ class PhotoSelectViewModel @Inject constructor(
|
||||
ToastUtils.show("请选择要打印的照片")
|
||||
return@launch
|
||||
}
|
||||
if (_quoteLoading.value || money(_totalPrice.value) == null) {
|
||||
ToastUtils.show(if (_quoteLoading.value) "正在更新价格,请稍候" else "价格获取失败,请重新选择照片")
|
||||
return@launch
|
||||
}
|
||||
|
||||
try {
|
||||
val request = GetPayUrlRequest(
|
||||
|
||||
Reference in New Issue
Block a user