优化已采集页面数据统计、更新初始化页面加载动画资源、替换新识别模型

This commit is contained in:
2026-04-28 15:29:53 +08:00
parent 13f893cd0c
commit c995daf48d
20 changed files with 597 additions and 325 deletions
@@ -50,6 +50,7 @@ import com.sw.inbound.utils.ext.toJsonString
import com.sw.inbound.utils.ext.toast
import com.sw.inbound.utils.ext.visible
import com.sw.inbound.viewmodel.ReceiptViewModel
import com.sw.inbound.viewmodel.UserViewModel
import dagger.hilt.android.AndroidEntryPoint
import io.objectbox.exception.DbException
import io.objectbox.exception.FileCorruptException
@@ -78,8 +79,8 @@ class FoodCollectionActivity : BaseActivity() {
private lateinit var binding: ActivityFoodCollectionBinding
private lateinit var previewView: PreviewView
private val viewModel: ReceiptViewModel by viewModels()
private val receiptViewModel: ReceiptViewModel by viewModels()
val userViewModel: UserViewModel by viewModels()
private val cameraUtils: CameraUtils by lazy {
CameraUtils(this)
}
@@ -517,7 +518,7 @@ class FoodCollectionActivity : BaseActivity() {
// 取消上一次未完成的搜索,避免并发竞争导致结果乱序
searchJob?.cancel()
searchJob = lifecycleScope.launch {
val records = viewModel.searchGoodsInfoList2(
val records = receiptViewModel.searchGoodsInfoList2(
goodsName = searchName,
pageNo = pageNo,
pageSize = pageSize
@@ -549,7 +550,7 @@ class FoodCollectionActivity : BaseActivity() {
totalList = collectList,
uploadImage = { batch ->
val files = batch.map { it.imageFile }
viewModel.uploadMultipleImages(files = files, params)
receiptViewModel.uploadMultipleImages(files = files, params)
},
onProgress = { count, batch ->
// lifecycleScope 默认在主线程执行,无需 runOnUiThread
@@ -585,7 +586,7 @@ class FoodCollectionActivity : BaseActivity() {
pageSize: Int = 10
): List<SearchGoodsInfo.Record> {
// 统一使用类顶部声明的 viewModel,避免重复创建 ViewModel 实例
return viewModel.searchGoodsInfoList2(goodsName, pageNo, pageSize)
return receiptViewModel.searchGoodsInfoList2(goodsName, pageNo, pageSize)
}
private var mDialogWaiting: CustomDialog? = null
@@ -146,7 +146,7 @@ class InitActivity : BaseActivity() {
GlobalData.appBaseUrl = savedUrl
} else {
// 未保存过则使用默认逻辑:特定设备走测试环境,其余走 UAT
GlobalData.appBaseUrl = GlobalData.UAT_BASE_URL
GlobalData.appBaseUrl = GlobalData.PROD_BASE_URL
val list = listOf(
//"5a41a2cf-3cee-3731-911d-a28b10164f7a",
"f0bcabbb-0d58-3b14-8bed-9863b7ec61ef"
@@ -1,5 +1,6 @@
package com.sw.inbound.activity
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.graphics.Color
@@ -9,11 +10,11 @@ import android.view.ViewGroup
import android.view.WindowManager
import androidx.core.graphics.drawable.toDrawable
import androidx.lifecycle.lifecycleScope
import com.sw.inbound.base.BaseActivity
import androidx.recyclerview.widget.GridLayoutManager
import coil.load
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.sw.inbound.base.BaseActivity
import com.sw.inbound.databinding.ActivityLocalImagePreviewBinding
import com.sw.inbound.databinding.DialogImageFullPreviewBinding
import com.sw.inbound.databinding.ListItemImagePreviewBinding
@@ -23,6 +24,8 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
class LocalImagePreviewActivity : BaseActivity() {
@@ -57,7 +60,7 @@ class LocalImagePreviewActivity : BaseActivity() {
val nameWithoutExt = it.nameWithoutExtension
// 兼容 IMG_CROP_{时间戳} 和其他命名格式
val displayName = if (nameWithoutExt.startsWith("IMG_CROP_")) {
nameWithoutExt.removePrefix("IMG_CROP_")
df.format(Date(nameWithoutExt.removePrefix("IMG_CROP_").toLong()))
} else {
nameWithoutExt
}
@@ -74,6 +77,9 @@ class LocalImagePreviewActivity : BaseActivity() {
}
}
@SuppressLint("SimpleDateFormat")
private val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/** 弹出全屏大图预览 Dialog,支持左右切换 */
private fun showFullImagePreview(startPosition: Int) {
var currentIndex = startPosition
@@ -8,12 +8,13 @@ import androidx.core.graphics.toColorInt
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.sw.inbound.databinding.ListItemCollectSearchBinding
import com.sw.inbound.model.response.CollectedFoodInfo
import com.sw.inbound.model.response.SearchGoodsInfo
import com.sw.inbound.utils.ext.dp
import com.sw.inbound.utils.ext.setShapeDrawable
class CollectSearchAdapter(var list: MutableList<SearchGoodsInfo.Record>) :
BaseQuickAdapter<SearchGoodsInfo.Record, CollectSearchAdapter.VH>(list) {
class CollectSearchAdapter(var list: MutableList<CollectedFoodInfo>) :
BaseQuickAdapter<CollectedFoodInfo, CollectSearchAdapter.VH>(list) {
inner class VH(var binding: ListItemCollectSearchBinding) : QuickViewHolder(binding.root)
@@ -23,19 +24,20 @@ class CollectSearchAdapter(var list: MutableList<SearchGoodsInfo.Record>) :
return VH(binding)
}
override fun onBindViewHolder(holder: VH, position: Int, item: SearchGoodsInfo.Record?) {
override fun onBindViewHolder(holder: VH, position: Int, item: CollectedFoodInfo?) {
holder.binding.let {
var goodsName = item!!.goodsName?.split("WP")?.get(0)
val goodsName = item!!.foodName.split("WP")[0]
// if (goodsName?.contains("\n") == true) {
// goodsName = goodsName?.split("\n")?.get(0)
// }
it.tvGoodsName.run {
text = Html.fromHtml(goodsName)
setTextColor(if (item!!.isSelected) "#FF0032C8".toColorInt() else "#FF666666".toColorInt())
setTextColor(if (item.isSelected) "#FF0032C8".toColorInt() else "#FF666666".toColorInt())
//setTextColor("#FF666666".toColorInt())
}
it.tvGoodsNum.text = "已采集${item.foodNum}"
it.root.run {
if (item!!.isSelected) {
if (item.isSelected) {
setShapeDrawable(
solidColor = "#FFEAF0FF",
strokeColor = "#FF0033CC",
@@ -5,7 +5,9 @@ import android.content.Context
import android.view.LayoutInflater
import android.view.View
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.sw.inbound.R
@@ -13,6 +15,7 @@ import com.sw.inbound.activity.FoodCollectionActivity
import com.sw.inbound.adapter.CollectSearchAdapter
import com.sw.inbound.databinding.DialogCollectSearchBinding
import com.sw.inbound.databinding.LayoutEmptySearchBinding
import com.sw.inbound.model.response.CollectedFoodInfo
import com.sw.inbound.model.response.SearchGoodsInfo
import com.sw.inbound.objbox.ObjectBox
import com.sw.inbound.utils.ext.addOnActionSearchListener
@@ -28,6 +31,32 @@ class CollectSearchDialog(
private lateinit var inflater: LayoutInflater
private var emptyBinding: LayoutEmptySearchBinding? = null
private lateinit var binding: DialogCollectSearchBinding
/**
* 收集 searchFoodState
*/
@SuppressLint("NotifyDataSetChanged")
private fun initObserver() {
activity?.run {
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
userViewModel.collectedFoodListState.collect { items ->
binding.rvSearch.layoutManager =
GridLayoutManager(activity, 2, LinearLayoutManager.VERTICAL, false)
list.clear()
list.addAll(items)
searchAdapter.notifyDataSetChanged()
finishRefresh()
binding.root.hideKeyboard()
if (items.isEmpty()) {
loadEmptyView()
}
}
}
}
}
}
override fun getRootView(): View {
inflater = LayoutInflater.from(context)
binding = DialogCollectSearchBinding.inflate(inflater)
@@ -82,23 +111,14 @@ class CollectSearchDialog(
this@CollectSearchDialog.clickIndex = -1
val searchName = binding.etInputGoods.text.toString().trim()
getCollectGoods(searchName)
}
//it.setOnLoadMoreListener {
// searchGoods()
//}
}
getCollectGoods()
//binding.root.clickWithDebounce {
// Thread {
// FoodModule.initDefFoodData(activity!!) {
// activity?.runOnUiThread {
// activity?.toast("添加完成")
// getCollectGoods()
// }
// }
// }.start()
//}
binding.root.postDelayed({
finishRefresh()
}, 1000)
}
}
initObserver()
getCollectGoods()
}
private var pageNo = 1
@@ -118,17 +138,17 @@ class CollectSearchDialog(
private var clickIndex = -1
private val list: MutableList<SearchGoodsInfo.Record> = mutableListOf()
private val list: MutableList<CollectedFoodInfo> = mutableListOf()
private val searchAdapter by lazy {
CollectSearchAdapter(list).apply {
isStateViewEnable = true
setOnItemClickListener { _, _, position ->
activity?.lifecycleScope?.launch {
val goodsName = list[position].goodsName?:""
val count = ObjectBox.countNameField(goodsName)
activity?.toast("已采集数据${count}")
}
}
// setOnItemClickListener { _, _, position ->
// activity?.lifecycleScope?.launch {
// val goodsName = list[position].goodsName?:""
// val count = ObjectBox.countNameField(goodsName)
// activity?.toast("已采集数据${count}条")
// }
// }
addOnItemChildClickListener(R.id.ivDelete) { _, _, position ->
this@CollectSearchDialog.clickIndex = position
list.forEach { item ->
@@ -144,46 +164,24 @@ class CollectSearchDialog(
}
private fun showDeleteDialog(position: Int, deleteAction: () -> Unit = {}) {
val foodName = list[position].foodName
WarnDialog(
context = context,
content = "请确认是否删除物品:${list[position].goodsName?.split("WP")?.get(0)}",
content = "请确认是否删除物品:${foodName.split("WP").first()}",
cancelBlock = {
this@CollectSearchDialog.clickIndex = -1
list[position].isSelected = false
searchAdapter.notifyItemChanged(position)
},
confirmBlock = {
// Thread {
// }.start()
activity?.lifecycleScope?.launch {
deleteGoods(position, deleteAction)
}
activity?.userViewModel?.removeCollectedFood(
foodName = foodName,
nameFilter = binding.etInputGoods.text.toString().trim()
)
deleteAction()
}).show()
}
private suspend fun deleteGoods(position: Int, deleteAction: () -> Unit = {}) {
activity?.runOnUiThread {
Loading.show(activity!!)
}
val name = list[position].goodsName ?: ""
// val filterIdList = box?.all?.filter { it.name == name }?.map { it.id }
// ObjectBox.boxStore.runInTx {
// box?.removeByIds(filterIdList)
// }
ObjectBox.remove(name)
activity?.runOnUiThread {
Loading.dismiss()
//list.remove(list[position])
//searchAdapter.notifyDataSetChanged()
searchAdapter.removeAt(position)
activity?.toast("删除成功")
if (list.isEmpty()) {
loadEmptyView()
}
deleteAction()
}
}
private fun finishRefresh() {
binding.refreshLayout.let {
if (pageNo == 1) {
@@ -197,27 +195,8 @@ class CollectSearchDialog(
// private var box: Box<Food>? = null
@SuppressLint("NotifyDataSetChanged")
private fun getCollectGoods(searchName: String? = null) = activity?.lifecycleScope?.launch {
// if (box == null) {
// box = ObjectBox.boxStore.boxFor(Food::class)
// }
list.clear()
// var queryList = box?.all?.distinctBy { it.name }
// if (searchName.isNullOrBlank().not()) {
// queryList = queryList?.filter { it.name?.contains(searchName!!) == true }
// }
val queryList = ObjectBox.filter(searchName)
queryList?.forEach {
list.add((SearchGoodsInfo.Record(goodsName = it.name)))
}
binding.rvSearch.layoutManager =
GridLayoutManager(activity, 2, LinearLayoutManager.VERTICAL, false)
searchAdapter.notifyDataSetChanged()
if (list.isEmpty()) {
loadEmptyView()
}
finishRefresh()
binding.root.hideKeyboard()
private fun getCollectGoods(name: String? = null) {
activity?.userViewModel?.loadCollectedFoodList(nameFilter = name)
}
// fun test() {
@@ -1,7 +1,6 @@
package com.sw.inbound.model.request
import android.os.Parcelable
import com.sw.inbound.model.response.BaseBean
import com.sw.inbound.model.response.GoodsInfo
import kotlinx.parcelize.Parcelize
import java.math.BigDecimal
@@ -90,6 +89,6 @@ private data class UploadGoodsInfo(
// 已调整
var isAdjusted: Boolean = false
) : Parcelable, BaseBean() {
) : Parcelable {
}
@@ -1,5 +0,0 @@
package com.sw.inbound.model.response
open class BaseBean() {
}
@@ -0,0 +1,7 @@
package com.sw.inbound.model.response
data class CollectedFoodInfo(
var foodName: String,
var foodNum: Int,
var isSelected: Boolean = false
)
@@ -117,7 +117,7 @@ data class GoodsInfo(
var buyToInventoryValue:String?="",
//--------------------------------------------------------
) : Parcelable, BaseBean() {
) : Parcelable {
val goodNameStr: String
get() {
@@ -31,6 +31,6 @@ data class PurchaseInfo(
var receiveGoodsInfoList: List<GoodsInfo> = emptyList<GoodsInfo>(),
// 自用
var warehouseName: String = "选择仓库"
) : BaseBean() {
) {
}
@@ -209,6 +209,31 @@ object ObjectBox {
} ?: emptyList()
}
/**
* 按名称分组统计采集数量
* 使用属性查询只加载 name 字段,不加载 foodVector,节省大量内存
* @param nameFilter 名称过滤关键词,为空时查询全部
* @return 按名称分组后的 (名称, 数量) 列表,按名称排序
*/
suspend fun queryFoodNameCounts(nameFilter: String? = null) = safeDbOp {
val box = getBox<Food>() ?: return@safeDbOp emptyList<Pair<String, Int>>()
val query = if (!nameFilter.isNullOrBlank()) {
box.query(Food_.name.contains(nameFilter)).build()
} else {
box.query().build()
}
try {
// 只查 name 字段,完全不加载 foodVector
query.property(Food_.name).findStrings()
.groupingBy { it }
.eachCount()
.map { (name, count) -> Pair(name, count) }
.sortedBy { it.first }
} finally {
query.close()
}
} ?: emptyList()
// 使用 QueryBuilder 在数据库层删除,避免全量加载到内存
suspend fun remove(name: String) = safeDbOp {
getBox<Food>()?.query(Food_.name.equal(name))?.build()?.remove()
@@ -14,6 +14,7 @@ import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.TypedValue
import android.view.TouchDelegate
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
@@ -270,3 +271,24 @@ fun String.copyText(context: Context, showToast: Boolean = true) {
Toast.makeText(context, "文本已复制到剪贴板", Toast.LENGTH_SHORT).show()
}
}
/**
* 扩大 View 的点击区域
* @param horizontal 水平方向扩大距离(dp)→ 左右各扩大一半
* @param vertical 垂直方向扩大距离(dp)→ 上下各扩大一半
*/
fun View.expandClickArea(horizontal: Int, vertical: Int) {
val density = resources.displayMetrics.density
val hPx = (horizontal * density).toInt()
val vPx = (vertical * density).toInt()
post {
val rect = android.graphics.Rect()
getHitRect(rect)
// 扩大区域:负值 = 向外扩大
rect.inset(-hPx, -vPx)
//rect.bottom += downPx // 只往下扩大
(parent as View).touchDelegate = TouchDelegate(rect, this)
}
}
@@ -1,17 +1,23 @@
package com.sw.inbound.viewmodel
import androidx.lifecycle.viewModelScope
import com.sw.inbound.GlobalData
import com.sw.inbound.GlobalKey
import com.sw.inbound.model.request.LoginParam
import com.sw.inbound.model.response.CollectedFoodInfo
import com.sw.inbound.model.response.User
import com.sw.inbound.objbox.ObjectBox
import com.sw.inbound.repository.RemoteRepository
import com.sw.inbound.utils.GsonUtils
import com.sw.inbound.utils.SPUtil
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import timber.log.Timber
import javax.inject.Inject
import kotlin.collections.remove
@HiltViewModel
class UserViewModel @Inject constructor(
@@ -64,6 +70,39 @@ class UserViewModel @Inject constructor(
SPUtil.getInstance().remove(GlobalKey.KEY_TOKEN)
}
/**
* 已采集食材列表 UI 状态流
* 元素为按名称分组后的(名称,数量)数据
*/
private val _collectedFoodListState = MutableStateFlow<List<CollectedFoodInfo>>(emptyList())
val collectedFoodListState: StateFlow<List<CollectedFoodInfo>> = _collectedFoodListState.asStateFlow()
/**
* 加载已采集食材列表,按名称分组统计数量
* 使用属性查询只读 name 字段,不加载 foodVector,节省内存
* @param nameFilter 名称过滤关键词,为空时加载全部
*/
fun loadCollectedFoodList(nameFilter: String? = null) {
viewModelScope.launch {
val result = ObjectBox.queryFoodNameCounts(nameFilter)
_collectedFoodListState.value = result.map { (name, count) ->
CollectedFoodInfo(foodName = name, foodNum = count)
}
}
}
/**
* 删除指定名称的所有采集记录,删除完成后刷新列表
* @param foodName 食材名称
* @param nameFilter 当前搜索关键词,用于删除后刷新列表
*/
fun removeCollectedFood(foodName: String, nameFilter: String? = null) {
viewModelScope.launch {
ObjectBox.remove(foodName)
loadCollectedFoodList(nameFilter)
}
}
override fun handleSensorScale(weight: Double) {
}