Compare commits
93
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7b66652c0b | ||
|
|
9e4b2bd009 | ||
|
|
6d3c5490a4 | ||
|
|
45543295e3 | ||
|
|
049c724303 | ||
|
|
acd1dd4605 | ||
|
|
17470bf12c | ||
|
|
0a3185fc9e | ||
|
|
9e41841086 | ||
|
|
80d80e7e63 | ||
|
|
2d88ce1479 | ||
|
|
d580040c55 | ||
|
|
00bf478185 | ||
|
|
ea79e584f3 | ||
|
|
1140d6bf91 | ||
|
|
f3dbb3fe68 | ||
|
|
dc91cdfa2e | ||
|
|
a6ce3a1ed3 | ||
|
|
292fdade81 | ||
|
|
aa539d87d0 | ||
|
|
e570707216 | ||
|
|
87ca6abe1b | ||
|
|
28784fa7c1 | ||
|
|
df01312577 | ||
|
|
7d3cb27b6e | ||
|
|
ef6a29ffb0 | ||
|
|
d7f9fb05fb | ||
|
|
d9cfd3007d | ||
|
|
c1f52c6337 | ||
|
|
5723209614 | ||
|
|
d080ca0690 | ||
|
|
1024d82958 | ||
|
|
8b19da2710 | ||
|
|
25167829cc | ||
|
|
e38f19ac1b | ||
|
|
ada83b64e6 | ||
|
|
d3f02620af | ||
|
|
deb03a0c37 | ||
|
|
b562694665 | ||
|
|
64586175ff | ||
|
|
e8431de53d | ||
|
|
4ccd4eaad0 | ||
|
|
b44f4aae5a | ||
|
|
fee9598689 | ||
|
|
b24435744c | ||
|
|
a257b03b9d | ||
|
|
89fff7c2b0 | ||
|
|
6392b76ac2 | ||
|
|
8398bd4fd3 | ||
|
|
535da33aab | ||
|
|
120f5432de | ||
|
|
61d11c6a78 | ||
|
|
301f470274 | ||
|
|
67d64848de | ||
|
|
ce7d2da6d8 | ||
|
|
65958bf637 | ||
|
|
7e72ce413b | ||
|
|
5745791041 | ||
|
|
d412e03c6e | ||
|
|
b6389be898 | ||
|
|
919e43afba | ||
|
|
0b9b3e8988 | ||
|
|
803ae75e40 | ||
|
|
ec4c3f1232 | ||
|
|
63911fe432 | ||
|
|
8f15c0efb7 | ||
|
|
879af8426f | ||
|
|
dc947df6e3 | ||
|
|
ef13aa8307 | ||
|
|
a9663a21f0 | ||
|
|
d060305417 | ||
|
|
bb319ee4ee | ||
|
|
bb1ecbde43 | ||
|
|
7a03ab8108 | ||
|
|
3b1dc0a03f | ||
|
|
f4d383dfe1 | ||
|
|
a14072af00 | ||
|
|
436de88d73 | ||
|
|
a0137d6979 | ||
|
|
c46264a4cf | ||
|
|
979b93c53d | ||
|
|
9880f2a5a8 | ||
|
|
19b5d721a7 | ||
|
|
0648f458a7 | ||
|
|
c17402c3c2 | ||
|
|
a64a00e099 | ||
|
|
6595c4bde0 | ||
|
|
2de5ec39b5 | ||
|
|
e5fc0c265d | ||
|
|
05063ee9de | ||
|
|
af737b910c | ||
|
|
12c6b5cf94 | ||
|
|
e990652981 |
@@ -1,4 +1,3 @@
|
||||
|
||||
plugins {
|
||||
// alias(libs.plugins.android.application)
|
||||
// alias(libs.plugins.kotlin.android)
|
||||
@@ -24,9 +23,8 @@ android {
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
ndk {
|
||||
//设置支持的SO库架构
|
||||
//设置支持的SO库架构;x86_64 仅用于在 Windows 模拟器上调试(秤功能不可用)
|
||||
abiFilters.addAll(listOf("armeabi-v7a"))
|
||||
//, 'x86', 'armeabi-v7a', 'x86_64', 'arm64-v8a'
|
||||
}
|
||||
|
||||
// 设置输出APK文件名格式
|
||||
@@ -48,12 +46,13 @@ android {
|
||||
"proguard-rules.pro"
|
||||
)
|
||||
signingConfig = signingConfigs.getByName("debug_507")
|
||||
// buildConfigField("boolean", "DEBUG", "false")
|
||||
buildConfigField("Boolean", "IS_TEST_DEVICE", "false")
|
||||
}
|
||||
debug {
|
||||
//507扫码秤主板在android.buildTypes{}内增加
|
||||
signingConfig = signingConfigs.getByName("debug_507")
|
||||
// buildConfigField("boolean", "DEBUG", "true")
|
||||
// 调试构建视为测试设备,使用固定的 DEVICE_ID_1 代替真实 UDID
|
||||
buildConfigField("Boolean", "IS_TEST_DEVICE", "false")
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
@@ -98,6 +97,7 @@ dependencies {
|
||||
androidTestImplementation(libs.androidx.junit)
|
||||
androidTestImplementation(libs.androidx.espresso.core)
|
||||
implementation(libs.androidx.activity.ktx)
|
||||
implementation(libs.androidx.fragment.ktx)
|
||||
implementation(libs.androidx.lifecycle.runtime.ktx)
|
||||
implementation(libs.androidx.lifecycle.viewmodel.ktx)
|
||||
|
||||
@@ -138,8 +138,8 @@ dependencies {
|
||||
implementation(libs.androidx.camera.extensions)
|
||||
|
||||
//pytorch
|
||||
implementation (libs.pytorch.android)
|
||||
implementation (libs.pytorch.android.torchvision)
|
||||
implementation(libs.pytorch.android)
|
||||
implementation(libs.pytorch.android.torchvision)
|
||||
|
||||
// objectbox
|
||||
if (isDebug) {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"entities": [
|
||||
{
|
||||
"id": "1:6465153867413579585",
|
||||
"lastPropertyId": "4:3660727688686055762",
|
||||
"lastPropertyId": "5:7592685238899911344",
|
||||
"name": "Food",
|
||||
"properties": [
|
||||
{
|
||||
@@ -30,6 +30,11 @@
|
||||
"indexId": "1:5497952887792054610",
|
||||
"type": 28,
|
||||
"flags": 8
|
||||
},
|
||||
{
|
||||
"id": "5:7592685238899911344",
|
||||
"name": "version",
|
||||
"type": 9
|
||||
}
|
||||
],
|
||||
"relations": []
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -45,6 +45,8 @@
|
||||
<activity
|
||||
android:name=".ui.InitActivity"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTask"
|
||||
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboardHidden|keyboard|navigation|uiMode|locale|layoutDirection|fontScale|density"
|
||||
tools:ignore="DiscouragedApi,LockedOrientationActivity">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
|
||||
@@ -6,7 +6,7 @@ import android.view.ViewGroup
|
||||
import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.databinding.ListItemCollectedFoodBinding
|
||||
import com.shuwei.dish.match.entity.CollectedFoodItem
|
||||
import com.shuwei.dish.match.model.CollectedFoodItem
|
||||
|
||||
/**
|
||||
* 已采集食材列表适配器
|
||||
|
||||
+9
-6
@@ -5,13 +5,16 @@ import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.databinding.ListItemDishRecordBinding
|
||||
import com.shuwei.dish.match.entity.FoodRecord
|
||||
import com.shuwei.dish.match.databinding.ListItemFood2Binding
|
||||
import com.shuwei.dish.match.model.FoodRecord
|
||||
|
||||
class FoodRecordAdapter(list: MutableList<FoodRecord>) :
|
||||
BaseQuickAdapter<FoodRecord, FoodRecordAdapter.VH>(list) {
|
||||
/**
|
||||
* 菜品搜索页面的适配器
|
||||
*/
|
||||
class Food2Adapter(list: MutableList<FoodRecord>) :
|
||||
BaseQuickAdapter<FoodRecord, Food2Adapter.VH>(list) {
|
||||
|
||||
inner class VH(var binding: ListItemDishRecordBinding) : QuickViewHolder(binding.root)
|
||||
inner class VH(var binding: ListItemFood2Binding) : QuickViewHolder(binding.root)
|
||||
|
||||
override fun onBindViewHolder(
|
||||
holder: VH,
|
||||
@@ -27,7 +30,7 @@ class FoodRecordAdapter(list: MutableList<FoodRecord>) :
|
||||
viewType: Int
|
||||
): VH {
|
||||
val inflater = LayoutInflater.from(context)
|
||||
val binding = ListItemDishRecordBinding.inflate(inflater, parent, false)
|
||||
val binding = ListItemFood2Binding.inflate(inflater, parent, false)
|
||||
return VH(binding)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.shuwei.dish.match.adapter
|
||||
|
||||
import android.content.Context
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.databinding.ListItemFood3Binding
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
|
||||
/**
|
||||
* 向量采集页面的适配器
|
||||
*/
|
||||
class Food3Adapter(list: MutableList<GoodsItem>) :
|
||||
BaseQuickAdapter<GoodsItem, Food3Adapter.VH>(list) {
|
||||
|
||||
override fun onBindViewHolder(
|
||||
holder: VH,
|
||||
position: Int,
|
||||
item: GoodsItem?
|
||||
) {
|
||||
item ?: return
|
||||
holder.binding.tvFoodName.run {
|
||||
text = item.goodsName
|
||||
isChecked = item.isClicked
|
||||
}
|
||||
// 显示当前选中的净材种类,无数据时隐藏
|
||||
holder.binding.tvRawMaterialsType.run {
|
||||
if (item.rawMaterialsType.isNullOrEmpty()) {
|
||||
visibility = View.GONE
|
||||
} else {
|
||||
visibility = View.VISIBLE
|
||||
text = item.rawMaterialsType
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreateViewHolder(
|
||||
context: Context,
|
||||
parent: ViewGroup,
|
||||
viewType: Int
|
||||
): VH {
|
||||
val binding = ListItemFood3Binding.inflate(LayoutInflater.from(context), parent, false)
|
||||
return VH(binding)
|
||||
}
|
||||
|
||||
inner class VH(var binding: ListItemFood3Binding) : QuickViewHolder(binding.root)
|
||||
|
||||
}
|
||||
+28
-14
@@ -7,41 +7,56 @@ import androidx.core.content.ContextCompat
|
||||
import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.databinding.ListItemSearchGoodsInfoBinding
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.databinding.ListItemFoodBinding
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.roundedDecimalPlace
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
|
||||
class GoodsInfoSearchAdapter(private var list: MutableList<CookFoodGoodsEntity>) :
|
||||
BaseQuickAdapter<CookFoodGoodsEntity, GoodsInfoSearchAdapter.VH>(list) {
|
||||
/**
|
||||
* 识别页面和搜索弹窗的适配器
|
||||
*/
|
||||
class FoodAdapter(list: MutableList<GoodsItem>) :
|
||||
BaseQuickAdapter<GoodsItem, FoodAdapter.VH>(list) {
|
||||
|
||||
override fun onBindViewHolder(
|
||||
holder: VH,
|
||||
position: Int,
|
||||
item: CookFoodGoodsEntity?
|
||||
item: GoodsItem?
|
||||
) {
|
||||
item ?: return
|
||||
holder.binding.tvGoodsInfo.run {
|
||||
text = item.goodsName
|
||||
holder.binding.root.run {
|
||||
setBackgroundResource(
|
||||
if (item.isClicked == true) R.drawable.shape_green_stroke
|
||||
if (item.isClicked) R.drawable.shape_green_stroke
|
||||
else R.drawable.shape_white_12_corners
|
||||
)
|
||||
}
|
||||
holder.binding.tvGoodsInfo.run {
|
||||
text = item.goodsName
|
||||
setTextColor(
|
||||
ContextCompat.getColor(
|
||||
context,
|
||||
if (item.isClicked == true) R.color.dish_green
|
||||
if (item.isClicked) R.color.dish_green
|
||||
else R.color.black666
|
||||
)
|
||||
)
|
||||
}
|
||||
if (item.foodScore == -1){
|
||||
if (item.foodScore == -1) {
|
||||
holder.binding.tvFoodScore.gone()
|
||||
} else {
|
||||
holder.binding.tvFoodScore.let {
|
||||
it.visible()
|
||||
it.text = "${(item.foodScore / 100.0).roundedDecimalPlace(2)}%"
|
||||
val foodScoreText = "${(item.foodScore / 100.0).roundedDecimalPlace(2)}%"
|
||||
it.text = foodScoreText
|
||||
|
||||
}
|
||||
}
|
||||
if (item.rawMaterialsType.isNullOrBlank()) {
|
||||
holder.binding.tvRawMaterialsType.gone()
|
||||
} else {
|
||||
holder.binding.tvRawMaterialsType.let {
|
||||
it.visible()
|
||||
it.text = item.rawMaterialsType
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,11 +67,10 @@ class GoodsInfoSearchAdapter(private var list: MutableList<CookFoodGoodsEntity>)
|
||||
viewType: Int
|
||||
): VH {
|
||||
val binding =
|
||||
ListItemSearchGoodsInfoBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||
|
||||
ListItemFoodBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||
return VH(binding)
|
||||
}
|
||||
|
||||
inner class VH(var binding: ListItemSearchGoodsInfoBinding) : QuickViewHolder(binding.root)
|
||||
inner class VH(var binding: ListItemFoodBinding) : QuickViewHolder(binding.root)
|
||||
|
||||
}
|
||||
@@ -8,7 +8,8 @@ import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.databinding.ListItemFoodListBinding
|
||||
import com.shuwei.dish.match.entity.FoodRecord
|
||||
import com.shuwei.dish.match.model.FoodRecord
|
||||
import com.shuwei.dish.match.model.SampleStatus
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
import java.text.DecimalFormat
|
||||
@@ -86,6 +87,16 @@ class FoodListAdapter(
|
||||
return@run
|
||||
}
|
||||
// 非烹饪中,采样模式
|
||||
tvDishName.setTextColor(ContextCompat.getColor(holder.itemView.context, R.color.dish_green))
|
||||
clBlock.setBackgroundResource(R.drawable.shape_white_fb_15_corners)
|
||||
// 已提交采样列表(sample-list):展示实验状态 + 熟重(g)
|
||||
val statusName = item.statusName
|
||||
if (!statusName.isNullOrBlank()) {
|
||||
tvDishCount.text = "熟重:${formatGram(foodWeight)}"
|
||||
tvShowState.text = statusName
|
||||
tvShowState.setTextColor(statusColor(holder, item.status))
|
||||
return@run
|
||||
}
|
||||
val realTotalWeight = if (totalWeight > 0.0) totalWeight else foodWeight
|
||||
val showTotalWeight = if (realTotalWeight == 0.0) "-" else df.format(realTotalWeight / 1000.0F)
|
||||
tvDishCount.text = "累计统计:${showTotalWeight}kg(${item.count ?: "-"}次)"
|
||||
@@ -94,5 +105,21 @@ class FoodListAdapter(
|
||||
}
|
||||
}
|
||||
|
||||
/** 熟重(g)格式化,整数不带小数,小数保留 2 位 */
|
||||
private fun formatGram(weight: Double): String {
|
||||
val gramDf = DecimalFormat("0.##")
|
||||
return "${gramDf.format(weight)}g"
|
||||
}
|
||||
|
||||
/** 实验状态着色:1=实验中(灰) / 2=已评测(绿) / 9=已转化(绿) */
|
||||
private fun statusColor(holder: VH, status: Int?): Int {
|
||||
val context = holder.itemView.context
|
||||
return when (status) {
|
||||
SampleStatus.EVALUATED, SampleStatus.CONVERTED ->
|
||||
ContextCompat.getColor(context, R.color.dish_green)
|
||||
else -> ContextCompat.getColor(context, R.color.black999)
|
||||
}
|
||||
}
|
||||
|
||||
private val df = DecimalFormat("0.000")
|
||||
}
|
||||
|
||||
+23
-9
@@ -1,41 +1,47 @@
|
||||
package com.shuwei.dish.match.adapter
|
||||
|
||||
import android.content.Context
|
||||
import android.content.res.ColorStateList
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.databinding.ListItemDishCookBinding
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.databinding.ListItemFoodMaterialBinding
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.roundedOneDecimalPlace
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
import androidx.core.graphics.toColorInt
|
||||
|
||||
class DishPartAdapter(list: MutableList<CookFoodGoodsEntity>) :
|
||||
BaseQuickAdapter<CookFoodGoodsEntity, DishPartAdapter.VH>(list) {
|
||||
class FoodMaterialAdapter(list: MutableList<GoodsItem>) :
|
||||
BaseQuickAdapter<GoodsItem, FoodMaterialAdapter.VH>(list) {
|
||||
|
||||
/** item 主体点击回调 */
|
||||
var onItemClick: ((position: Int) -> Unit)? = null
|
||||
|
||||
inner class VH(var binding: ListItemDishCookBinding) : QuickViewHolder(binding.root)
|
||||
inner class VH(var binding: ListItemFoodMaterialBinding) : QuickViewHolder(binding.root)
|
||||
|
||||
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
||||
val inflater = LayoutInflater.from(context)
|
||||
val binding = ListItemDishCookBinding.inflate(inflater, parent, false)
|
||||
val binding = ListItemFoodMaterialBinding.inflate(inflater, parent, false)
|
||||
return VH(binding)
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: VH, position: Int, item: CookFoodGoodsEntity?) {
|
||||
override fun onBindViewHolder(holder: VH, position: Int, item: GoodsItem?) {
|
||||
holder.binding.run {
|
||||
val data = item ?: return
|
||||
|
||||
clBlock.setOnClickListener {
|
||||
onItemClick?.invoke(holder.bindingAdapterPosition)
|
||||
}
|
||||
|
||||
tvDishName.text = data.goodsName
|
||||
//if (data.isOriginalData) {
|
||||
// tvDishName.text = data.goodsName
|
||||
//} else {
|
||||
// tvDishName.text = data.goodsName + "-${data.rawMaterialsType}"
|
||||
//}
|
||||
tvDishType.text = if (data.materialType == 1) "主辅材:主材" else if (data.materialType == 2) "主辅材:辅材" else ""
|
||||
tvDishWeight.text =
|
||||
if (data.useWeight == null || data.useWeight == 0.toDouble()) "" else "${data.useWeight!!.roundedOneDecimalPlace()}克"
|
||||
@@ -54,12 +60,20 @@ class DishPartAdapter(list: MutableList<CookFoodGoodsEntity>) :
|
||||
if (data.isOriginalData) R.drawable.ic_dish_clear
|
||||
else R.drawable.ic_delete
|
||||
)
|
||||
// isOriginalData 时根据是否有重量信息控制图标颜色:无重量染灰色,有重量恢复原色
|
||||
if (data.isOriginalData) {
|
||||
val hasWeight = data.useWeight != null && data.useWeight != 0.0
|
||||
ivClearIcon.imageTintList = if (hasWeight) null
|
||||
else ColorStateList.valueOf("#BFBFBF".toColorInt())
|
||||
} else {
|
||||
ivClearIcon.imageTintList = null
|
||||
}
|
||||
ivOperateIcon.setImageResource(
|
||||
if (data.isSetFinished) R.drawable.ic_dish_selected
|
||||
else R.drawable.ic_dish_unselected
|
||||
)
|
||||
clBlock.setBackgroundResource(
|
||||
if (data.isItemClicked) R.drawable.shape_item_cook_dish
|
||||
if (data.isClicked) R.drawable.shape_item_cook_dish
|
||||
else R.drawable.shape_white_fb_15_corners
|
||||
)
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package com.shuwei.dish.match.adapter
|
||||
|
||||
import android.content.Context
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.databinding.ListItemSearchFoodBinding
|
||||
import com.shuwei.dish.match.databinding.ListItemSearchGoodsInfoBinding
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.roundedDecimalPlace
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
|
||||
class FoodSearchAdapter(private var list: MutableList<CookFoodGoodsEntity>) :
|
||||
BaseQuickAdapter<CookFoodGoodsEntity, FoodSearchAdapter.VH>(list) {
|
||||
|
||||
override fun onBindViewHolder(
|
||||
holder: VH,
|
||||
position: Int,
|
||||
item: CookFoodGoodsEntity?
|
||||
) {
|
||||
item ?: return
|
||||
holder.binding.tvFoodName.run {
|
||||
text = item.goodsName
|
||||
isChecked = item.isClicked
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreateViewHolder(
|
||||
context: Context,
|
||||
parent: ViewGroup,
|
||||
viewType: Int
|
||||
): VH {
|
||||
val binding = ListItemSearchFoodBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||
return VH(binding)
|
||||
}
|
||||
|
||||
inner class VH(var binding: ListItemSearchFoodBinding) : QuickViewHolder(binding.root)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.shuwei.dish.match.adapter
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.shuwei.dish.match.databinding.ItemGoodsPreviewBinding
|
||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||
|
||||
/**
|
||||
* 用料明细预览列表适配器
|
||||
* 显示字段:foodId、goodsId、goodsCode、goodsName、materialType、useWeight
|
||||
*/
|
||||
class GoodsPreviewAdapter(
|
||||
private val list: List<CookFoodGoodsEntity>
|
||||
) : RecyclerView.Adapter<GoodsPreviewAdapter.VH>() {
|
||||
|
||||
inner class VH(val binding: ItemGoodsPreviewBinding) : RecyclerView.ViewHolder(binding.root)
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
|
||||
val binding = ItemGoodsPreviewBinding.inflate(
|
||||
LayoutInflater.from(parent.context), parent, false
|
||||
)
|
||||
return VH(binding)
|
||||
}
|
||||
|
||||
@SuppressLint("SetTextI18n")
|
||||
override fun onBindViewHolder(holder: VH, position: Int) {
|
||||
val item = list[position]
|
||||
holder.binding.run {
|
||||
tvGoodsId.text = item.goodsId
|
||||
tvGoodsCode.text = item.goodsCode.orEmpty()
|
||||
tvGoodsName.text = item.goodsName.orEmpty()
|
||||
// materialType:1主料 2辅料 3调料
|
||||
tvMaterialType.text = when (item.materialType) {
|
||||
1 -> "主料"
|
||||
2 -> "辅料"
|
||||
3 -> "调料"
|
||||
else -> "${item.materialType}"
|
||||
}
|
||||
tvUseWeight.text = "${item.useWeight ?: 0.0}g"
|
||||
}
|
||||
}
|
||||
|
||||
override fun getItemCount() = list.size
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.databinding.ListItemHomeModeBinding
|
||||
import com.shuwei.dish.match.entity.HomeModeBean
|
||||
import com.shuwei.dish.match.model.HomeModeBean
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
|
||||
|
||||
@@ -3,14 +3,19 @@ package com.shuwei.dish.match.adapter
|
||||
import android.content.Context
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.databinding.ListItemScaleRowBinding
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
|
||||
/**
|
||||
* 线性列表秤数据 Adapter
|
||||
* 用于 SlaveActivity 非22/18格子设备的秤列表展示
|
||||
* 通过 updateItem / updateName / removeByAddress 同步更新,避免 submitList 的
|
||||
* AsyncListDiffer 异步窗口期导致点击事件丢失
|
||||
*/
|
||||
class ScaleRowAdapter : BaseQuickAdapter<ScaleRowAdapter.ScaleItem, ScaleRowAdapter.VH>() {
|
||||
|
||||
@@ -23,6 +28,9 @@ class ScaleRowAdapter : BaseQuickAdapter<ScaleRowAdapter.ScaleItem, ScaleRowAdap
|
||||
*/
|
||||
data class ScaleItem(val address: Int, val weight: Double, val state: Int, val name: String = "")
|
||||
|
||||
/** item 点击回调 */
|
||||
var onItemClick: ((ScaleItem) -> Unit)? = null
|
||||
|
||||
inner class VH(val b: ListItemScaleRowBinding) : QuickViewHolder(b.root)
|
||||
|
||||
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
||||
@@ -34,11 +42,63 @@ class ScaleRowAdapter : BaseQuickAdapter<ScaleRowAdapter.ScaleItem, ScaleRowAdap
|
||||
holder.b.tvScaleLabel.text = "秤 ${item.address}"
|
||||
holder.b.tvName.text = item.name.ifEmpty { "-" }
|
||||
holder.b.tvWeight.text = "${item.weight} g"
|
||||
holder.b.tvState.text = when (item.state) {
|
||||
WeightUtil.STATE_STABLE -> "稳定"
|
||||
WeightUtil.STATE_UNSTABLE -> "不稳定"
|
||||
WeightUtil.STATE_OVER_WEIGHT -> "超量"
|
||||
else -> "${item.state}"
|
||||
holder.b.tvState.text = WeightUtil.getStateStr(item.state)
|
||||
if (item.state == WeightUtil.STATE_OVER_WEIGHT) {
|
||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell_over_weight)
|
||||
val white = ContextCompat.getColor(holder.b.root.context, R.color.white)
|
||||
holder.b.tvScaleLabel.setTextColor(white)
|
||||
holder.b.tvName.setTextColor(white)
|
||||
holder.b.tvWeight.setTextColor(white)
|
||||
holder.b.tvState.setTextColor(white)
|
||||
} else {
|
||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell)
|
||||
holder.b.tvScaleLabel.setTextColor(ContextCompat.getColor(holder.b.root.context, R.color.black))
|
||||
holder.b.tvName.setTextColor(ContextCompat.getColor(holder.b.root.context, R.color.black))
|
||||
holder.b.tvWeight.setTextColor(ContextCompat.getColor(holder.b.root.context, R.color.home_title))
|
||||
holder.b.tvState.setTextColor(ContextCompat.getColor(holder.b.root.context, R.color.home_sub_title))
|
||||
}
|
||||
// 点击时通过 bindingAdapterPosition 取最新数据,避免闭包捕获过期 item
|
||||
holder.b.root.setOnClickListener {
|
||||
val pos = holder.bindingAdapterPosition
|
||||
if (pos != RecyclerView.NO_POSITION) {
|
||||
items.getOrNull(pos)?.let { onItemClick?.invoke(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步更新单条秤数据:存在则定点刷新,不存在则按 address 升序插入
|
||||
* 使用 set/add 替代 submitList,消除 AsyncListDiffer 异步窗口期
|
||||
* @param item 最新秤数据
|
||||
*/
|
||||
fun updateItem(item: ScaleItem) {
|
||||
val idx = items.indexOfFirst { it.address == item.address }
|
||||
if (idx >= 0) {
|
||||
set(idx, item)
|
||||
} else {
|
||||
// 找到按 address 升序的插入位置
|
||||
val insertPos = items.indexOfFirst { it.address > item.address }
|
||||
.let { if (it < 0) items.size else it }
|
||||
add(insertPos, item)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步更新指定地址的调料名称
|
||||
* @param address 秤地址
|
||||
* @param name 新名称
|
||||
*/
|
||||
fun updateName(address: Int, name: String) {
|
||||
val idx = items.indexOfFirst { it.address == address }
|
||||
if (idx >= 0) set(idx, items[idx].copy(name = name))
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步移除指定地址的条目
|
||||
* @param address 秤地址
|
||||
*/
|
||||
fun removeByAddress(address: Int) {
|
||||
val idx = items.indexOfFirst { it.address == address }
|
||||
if (idx >= 0) removeAt(idx)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,24 +90,34 @@ class Seasoning18GridAdapter(
|
||||
holder.b.tvAddress.text = "秤${item!!.address}"
|
||||
holder.b.tvName.text = if (!item.name.isNullOrBlank()) item.name else "-"
|
||||
holder.b.tvWeight.text = "${item.weight}g"
|
||||
holder.b.tvState.text = stateStr(item.state)
|
||||
holder.b.tvState.text = WeightUtil.getStateStr(item.state)
|
||||
}
|
||||
if (position == highlightedPosition) {
|
||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell_highlight)
|
||||
val white = ContextCompat.getColor(holder.b.root.context, R.color.white)
|
||||
holder.b.tvAddress.setTextColor(white)
|
||||
holder.b.tvName.setTextColor(white)
|
||||
holder.b.tvWeight.setTextColor(white)
|
||||
holder.b.tvState.setTextColor(white)
|
||||
} else {
|
||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell)
|
||||
val normal = ContextCompat.getColor(holder.b.root.context, R.color.home_title)
|
||||
val sub = ContextCompat.getColor(holder.b.root.context, R.color.home_sub_title)
|
||||
val black = ContextCompat.getColor(holder.b.root.context, R.color.black)
|
||||
holder.b.tvAddress.setTextColor(sub)
|
||||
holder.b.tvName.setTextColor(black)
|
||||
holder.b.tvWeight.setTextColor(normal)
|
||||
holder.b.tvState.setTextColor(sub)
|
||||
val white = ContextCompat.getColor(holder.b.root.context, R.color.white)
|
||||
when {
|
||||
valid && item!!.state == WeightUtil.STATE_OVER_WEIGHT -> {
|
||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell_over_weight)
|
||||
holder.b.tvAddress.setTextColor(white)
|
||||
holder.b.tvName.setTextColor(white)
|
||||
holder.b.tvWeight.setTextColor(white)
|
||||
holder.b.tvState.setTextColor(white)
|
||||
}
|
||||
position == highlightedPosition -> {
|
||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell_highlight)
|
||||
holder.b.tvAddress.setTextColor(white)
|
||||
holder.b.tvName.setTextColor(white)
|
||||
holder.b.tvWeight.setTextColor(white)
|
||||
holder.b.tvState.setTextColor(white)
|
||||
}
|
||||
else -> {
|
||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell)
|
||||
val normal = ContextCompat.getColor(holder.b.root.context, R.color.home_title)
|
||||
val sub = ContextCompat.getColor(holder.b.root.context, R.color.home_sub_title)
|
||||
val black = ContextCompat.getColor(holder.b.root.context, R.color.black)
|
||||
holder.b.tvAddress.setTextColor(sub)
|
||||
holder.b.tvName.setTextColor(black)
|
||||
holder.b.tvWeight.setTextColor(normal)
|
||||
holder.b.tvState.setTextColor(sub)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,11 +174,4 @@ class Seasoning18GridAdapter(
|
||||
fun updateByAddress(scales: List<ScaleData>) {
|
||||
update(scales)
|
||||
}
|
||||
|
||||
private fun stateStr(state: Int) = when (state) {
|
||||
WeightUtil.STATE_STABLE -> "稳定"
|
||||
WeightUtil.STATE_UNSTABLE -> "不稳定"
|
||||
WeightUtil.STATE_OVER_WEIGHT -> "超量"
|
||||
else -> ""
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,25 +95,34 @@ class Seasoning22GridAdapter(
|
||||
holder.b.tvAddress.text = "秤${item!!.address}"
|
||||
holder.b.tvName.text = if (!item.name.isNullOrBlank()) item.name else "-"
|
||||
holder.b.tvWeight.text = "${item.weight}g"
|
||||
holder.b.tvState.text = stateStr(item.state)
|
||||
holder.b.tvState.text = WeightUtil.getStateStr(item.state)
|
||||
}
|
||||
// 高亮格子:红底白字;其余恢复默认
|
||||
if (position == highlightedPosition) {
|
||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell_highlight)
|
||||
val white = ContextCompat.getColor(holder.b.root.context, R.color.white)
|
||||
holder.b.tvAddress.setTextColor(white)
|
||||
holder.b.tvName.setTextColor(white)
|
||||
holder.b.tvWeight.setTextColor(white)
|
||||
holder.b.tvState.setTextColor(white)
|
||||
} else {
|
||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell)
|
||||
val normal = ContextCompat.getColor(holder.b.root.context, R.color.home_title)
|
||||
val sub = ContextCompat.getColor(holder.b.root.context, R.color.home_sub_title)
|
||||
val black = ContextCompat.getColor(holder.b.root.context, R.color.black)
|
||||
holder.b.tvAddress.setTextColor(sub)
|
||||
holder.b.tvName.setTextColor(black)
|
||||
holder.b.tvWeight.setTextColor(normal)
|
||||
holder.b.tvState.setTextColor(sub)
|
||||
val white = ContextCompat.getColor(holder.b.root.context, R.color.white)
|
||||
when {
|
||||
valid && item!!.state == WeightUtil.STATE_OVER_WEIGHT -> {
|
||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell_over_weight)
|
||||
holder.b.tvAddress.setTextColor(white)
|
||||
holder.b.tvName.setTextColor(white)
|
||||
holder.b.tvWeight.setTextColor(white)
|
||||
holder.b.tvState.setTextColor(white)
|
||||
}
|
||||
position == highlightedPosition -> {
|
||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell_highlight)
|
||||
holder.b.tvAddress.setTextColor(white)
|
||||
holder.b.tvName.setTextColor(white)
|
||||
holder.b.tvWeight.setTextColor(white)
|
||||
holder.b.tvState.setTextColor(white)
|
||||
}
|
||||
else -> {
|
||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell)
|
||||
val normal = ContextCompat.getColor(holder.b.root.context, R.color.home_title)
|
||||
val sub = ContextCompat.getColor(holder.b.root.context, R.color.home_sub_title)
|
||||
val black = ContextCompat.getColor(holder.b.root.context, R.color.black)
|
||||
holder.b.tvAddress.setTextColor(sub)
|
||||
holder.b.tvName.setTextColor(black)
|
||||
holder.b.tvWeight.setTextColor(normal)
|
||||
holder.b.tvState.setTextColor(sub)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,11 +179,4 @@ class Seasoning22GridAdapter(
|
||||
fun updateByAddress(scales: List<ScaleData>) {
|
||||
update(scales)
|
||||
}
|
||||
|
||||
private fun stateStr(state: Int) = when (state) {
|
||||
WeightUtil.STATE_STABLE -> "稳定"
|
||||
WeightUtil.STATE_UNSTABLE -> "不稳定"
|
||||
WeightUtil.STATE_OVER_WEIGHT -> "超量"
|
||||
else -> ""
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,23 +7,22 @@ import androidx.core.content.ContextCompat
|
||||
import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.databinding.ListItemSearchGoodsInfoBinding
|
||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.databinding.ListItemSeasoningBinding
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
|
||||
class SeasoningSearchAdapter(private var list: MutableList<SeasoningEntity>) :
|
||||
BaseQuickAdapter<SeasoningEntity, SeasoningSearchAdapter.VH>(list) {
|
||||
/**
|
||||
* 调料搜索弹窗适配器
|
||||
*/
|
||||
class SeasoningSearchAdapter(private var list: MutableList<GoodsItem>) :
|
||||
BaseQuickAdapter<GoodsItem, SeasoningSearchAdapter.VH>(list) {
|
||||
|
||||
override fun onBindViewHolder(
|
||||
holder: VH,
|
||||
position: Int,
|
||||
item: SeasoningEntity?
|
||||
item: GoodsItem?
|
||||
) {
|
||||
holder.binding.tvGoodsInfo.run {
|
||||
text = item?.goodsName
|
||||
setBackgroundResource(
|
||||
if (item?.isClicked == true) R.drawable.shape_green_stroke
|
||||
else R.drawable.shape_white_12_corners
|
||||
)
|
||||
setTextColor(
|
||||
ContextCompat.getColor(
|
||||
context,
|
||||
@@ -32,6 +31,10 @@ class SeasoningSearchAdapter(private var list: MutableList<SeasoningEntity>) :
|
||||
)
|
||||
)
|
||||
}
|
||||
holder.binding.root.setBackgroundResource(
|
||||
if (item?.isClicked == true) R.drawable.shape_green_stroke
|
||||
else R.drawable.shape_white_12_corners
|
||||
)
|
||||
}
|
||||
|
||||
override fun onCreateViewHolder(
|
||||
@@ -40,10 +43,10 @@ class SeasoningSearchAdapter(private var list: MutableList<SeasoningEntity>) :
|
||||
viewType: Int
|
||||
): VH {
|
||||
val binding =
|
||||
ListItemSearchGoodsInfoBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||
ListItemSeasoningBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||
return VH(binding)
|
||||
}
|
||||
|
||||
inner class VH(var binding: ListItemSearchGoodsInfoBinding) : QuickViewHolder(binding.root)
|
||||
inner class VH(var binding: ListItemSeasoningBinding) : QuickViewHolder(binding.root)
|
||||
|
||||
}
|
||||
@@ -6,14 +6,25 @@ import android.view.ViewGroup
|
||||
import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.databinding.ItemSeasoningWeightBinding
|
||||
import com.shuwei.dish.match.databinding.ItemSeasoningWeightListBinding
|
||||
import com.shuwei.dish.match.utils.ext.roundedDecimalPlace
|
||||
|
||||
/**
|
||||
* 调料使用重量列表 Adapter
|
||||
* 用于 SubmitFoodActivity 展示各调料槽位的实时用量
|
||||
* 同名调料已在外部聚合,adapter 按 goodsName 作为唯一标识
|
||||
* 支持两种布局模式:
|
||||
* - VIEW_TYPE_GRID(默认):4 列卡片,名称与重量垂直排列
|
||||
* - VIEW_TYPE_LIST:2 列,名称与重量水平排列,名称占剩余空间
|
||||
*/
|
||||
class SeasoningWeightAdapter : BaseQuickAdapter<SeasoningWeightAdapter.Item, SeasoningWeightAdapter.VH>() {
|
||||
class SeasoningWeightAdapter : BaseQuickAdapter<SeasoningWeightAdapter.Item, QuickViewHolder>() {
|
||||
|
||||
companion object {
|
||||
/** 4 列卡片模式 */
|
||||
const val VIEW_TYPE_GRID = 0
|
||||
/** 2 列水平模式 */
|
||||
const val VIEW_TYPE_LIST = 1
|
||||
}
|
||||
|
||||
/** 调料展示数据项,key = goodsName(同名调料已聚合) */
|
||||
data class Item(
|
||||
@@ -23,6 +34,13 @@ class SeasoningWeightAdapter : BaseQuickAdapter<SeasoningWeightAdapter.Item, Sea
|
||||
val useWeight: Double
|
||||
)
|
||||
|
||||
/** 当前布局模式,由外部切换后调用 notifyDataSetChanged 生效 */
|
||||
var isListMode: Boolean = false
|
||||
|
||||
override fun getItemViewType(position: Int, list: List<Item>): Int {
|
||||
return if (isListMode) VIEW_TYPE_LIST else VIEW_TYPE_GRID
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新单个 item,按 goodsName 匹配;不存在则追加
|
||||
*/
|
||||
@@ -43,18 +61,21 @@ class SeasoningWeightAdapter : BaseQuickAdapter<SeasoningWeightAdapter.Item, Sea
|
||||
if (idx >= 0) removeAt(idx)
|
||||
}
|
||||
|
||||
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
||||
val binding = ItemSeasoningWeightBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||
return VH(binding)
|
||||
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): QuickViewHolder {
|
||||
return if (viewType == VIEW_TYPE_LIST) {
|
||||
val binding = ItemSeasoningWeightListBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||
QuickViewHolder(binding.root)
|
||||
} else {
|
||||
val binding = ItemSeasoningWeightBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||
QuickViewHolder(binding.root)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: VH, position: Int, item: Item?) {
|
||||
override fun onBindViewHolder(holder: QuickViewHolder, position: Int, item: Item?) {
|
||||
item ?: return
|
||||
holder.binding.tvSeasoningName.text = item.goodsName
|
||||
val showWeight = "${item.useWeight.roundedDecimalPlace(1)}g"
|
||||
holder.binding.tvSeasoningWeight.text = showWeight
|
||||
holder.setText(com.shuwei.dish.match.R.id.tvSeasoningName, item.goodsName)
|
||||
holder.setText(com.shuwei.dish.match.R.id.tvSeasoningWeight, showWeight)
|
||||
}
|
||||
|
||||
inner class VH(var binding: ItemSeasoningWeightBinding) : QuickViewHolder(binding.root)
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.shuwei.dish.match.adapter
|
||||
|
||||
import android.content.Context
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.databinding.ListItemSettingBinding
|
||||
import com.shuwei.dish.match.model.SettingItem
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
|
||||
/**
|
||||
* 设置页面列表适配器
|
||||
* 点击事件直接调用 item.onClick(),无需在 Adapter 中分发业务逻辑
|
||||
*/
|
||||
class SettingAdapter : BaseQuickAdapter<SettingItem, SettingAdapter.VH>() {
|
||||
|
||||
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
||||
val binding = ListItemSettingBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||
return VH(binding)
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: VH, position: Int, item: SettingItem?) {
|
||||
item ?: return
|
||||
holder.binding.tvTitle.text = item.title
|
||||
|
||||
// 有副标题则显示,否则隐藏
|
||||
val subtitle = item.subtitle
|
||||
if (subtitle != null) {
|
||||
holder.binding.tvSubtitle.visible()
|
||||
holder.binding.tvSubtitle.text = subtitle
|
||||
} else {
|
||||
holder.binding.tvSubtitle.gone()
|
||||
}
|
||||
}
|
||||
|
||||
inner class VH(val binding: ListItemSettingBinding) : QuickViewHolder(binding.root)
|
||||
}
|
||||
@@ -1,136 +1,136 @@
|
||||
package com.shuwei.dish.match.adapter
|
||||
|
||||
import android.graphics.Typeface
|
||||
import android.icu.text.DecimalFormat
|
||||
import android.text.SpannableStringBuilder
|
||||
import android.text.style.AbsoluteSizeSpan
|
||||
import android.text.style.ForegroundColorSpan
|
||||
import android.text.style.LineHeightSpan
|
||||
import android.text.style.StyleSpan
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import android.widget.FrameLayout
|
||||
import android.widget.TextView
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.graphics.toColorInt
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.databinding.ListItemCellBinding
|
||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.utils.ext.appendText
|
||||
import com.shuwei.dish.match.utils.ext.buildSpannableString
|
||||
import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import com.shuwei.dish.match.utils.ext.invisible
|
||||
import com.shuwei.dish.match.utils.ext.roundedOneDecimalPlace
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
|
||||
class TextCellAdapter(var list: MutableList<SeasoningEntity>) :
|
||||
RecyclerView.Adapter<TextCellAdapter.VH>() {
|
||||
|
||||
inner class VH(var binding: ListItemCellBinding) : QuickViewHolder(binding.root)
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
|
||||
val inflater = LayoutInflater.from(parent.context)
|
||||
val binding = ListItemCellBinding.inflate(inflater, parent, false)
|
||||
return VH(binding)
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: VH, position: Int) {
|
||||
val item = list[position]
|
||||
holder.binding.run {
|
||||
if (position == 10 || position == 11 || position == 13 || position == 14) {
|
||||
root.invisible()
|
||||
} else {
|
||||
root.visible()
|
||||
}
|
||||
loadCell(tvCell, item)
|
||||
//root.setBackgroundResource(R.color.dish_green)
|
||||
(root.layoutParams as RecyclerView.LayoutParams).let {
|
||||
// it.bottomMargin = 15.dp
|
||||
it.width = 226.dp
|
||||
it.height = 120.dp
|
||||
// it.rightMargin = 0
|
||||
// it.leftMargin = if (position % 3 == 0) 0 else 15.dp
|
||||
|
||||
it.leftMargin = 7.dp
|
||||
it.rightMargin = 8.dp
|
||||
it.topMargin = 7.dp
|
||||
it.bottomMargin = 8.dp
|
||||
}
|
||||
if (item.pageType == 1) {
|
||||
root.clickWithDebounce { onCellClick?.invoke(position) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun getItemCount() = list.size
|
||||
|
||||
var onCellClick: ((positon: Int) -> Unit)? = null
|
||||
|
||||
companion object {
|
||||
fun loadLayout(frameLayout: FrameLayout, item: SeasoningEntity) {
|
||||
val child: TextView = frameLayout.getChildAt(0) as TextView
|
||||
child.text = getTextSpan(item)
|
||||
}
|
||||
fun loadCell(tvCell: TextView, item: SeasoningEntity) {
|
||||
tvCell.text = getTextSpan(item)
|
||||
}
|
||||
// fun loadCell2(tvCell: TextView, item: SeasoningEntity) {
|
||||
// if (item.goodsName.isNullOrBlank()) {
|
||||
// tvCell.run {
|
||||
// text = buildSpannableString {
|
||||
// appendText(
|
||||
// "未配置",
|
||||
// ForegroundColorSpan("#999999".toColorInt()),
|
||||
// StyleSpan(Typeface.BOLD),
|
||||
// AbsoluteSizeSpan(28, true),
|
||||
// LineHeightSpan { text, start, end, spanstartv, v, fm ->
|
||||
// fm.descent += 10.dp // 增加行间距
|
||||
// }
|
||||
// )}
|
||||
// //setTextColor(ContextCompat.getColor(context, R.color.black999))
|
||||
// }
|
||||
//package com.shuwei.dish.match.adapter
|
||||
//
|
||||
//import android.graphics.Typeface
|
||||
//import android.icu.text.DecimalFormat
|
||||
//import android.text.SpannableStringBuilder
|
||||
//import android.text.style.AbsoluteSizeSpan
|
||||
//import android.text.style.ForegroundColorSpan
|
||||
//import android.text.style.LineHeightSpan
|
||||
//import android.text.style.StyleSpan
|
||||
//import android.view.LayoutInflater
|
||||
//import android.view.ViewGroup
|
||||
//import android.widget.FrameLayout
|
||||
//import android.widget.TextView
|
||||
//import androidx.core.content.ContextCompat
|
||||
//import androidx.core.graphics.toColorInt
|
||||
//import androidx.recyclerview.widget.RecyclerView
|
||||
//import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
//import com.shuwei.dish.match.R
|
||||
//import com.shuwei.dish.match.databinding.ListItemCellBinding
|
||||
//import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
//import com.shuwei.dish.match.utils.ext.appendText
|
||||
//import com.shuwei.dish.match.utils.ext.buildSpannableString
|
||||
//import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
||||
//import com.shuwei.dish.match.utils.ext.dp
|
||||
//import com.shuwei.dish.match.utils.ext.invisible
|
||||
//import com.shuwei.dish.match.utils.ext.roundedOneDecimalPlace
|
||||
//import com.shuwei.dish.match.utils.ext.visible
|
||||
//
|
||||
//class TextCellAdapter(var list: MutableList<SeasoningEntity>) :
|
||||
// RecyclerView.Adapter<TextCellAdapter.VH>() {
|
||||
//
|
||||
// inner class VH(var binding: ListItemCellBinding) : QuickViewHolder(binding.root)
|
||||
//
|
||||
// override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
|
||||
// val inflater = LayoutInflater.from(parent.context)
|
||||
// val binding = ListItemCellBinding.inflate(inflater, parent, false)
|
||||
// return VH(binding)
|
||||
// }
|
||||
//
|
||||
// override fun onBindViewHolder(holder: VH, position: Int) {
|
||||
// val item = list[position]
|
||||
// holder.binding.run {
|
||||
// if (position == 10 || position == 11 || position == 13 || position == 14) {
|
||||
// root.invisible()
|
||||
// } else {
|
||||
//// if (item.pageType == 1) {
|
||||
//// tvCell.run {
|
||||
//// text = item.goodsName
|
||||
//// setTextColor(ContextCompat.getColor(context, R.color.black))
|
||||
//// }
|
||||
//// } else {
|
||||
// tvCell.text = getTextSpan(item)
|
||||
//// }
|
||||
// root.visible()
|
||||
// }
|
||||
// loadCell(tvCell, item)
|
||||
// //root.setBackgroundResource(R.color.dish_green)
|
||||
// (root.layoutParams as RecyclerView.LayoutParams).let {
|
||||
//// it.bottomMargin = 15.dp
|
||||
// it.width = 226.dp
|
||||
// it.height = 120.dp
|
||||
//// it.rightMargin = 0
|
||||
//// it.leftMargin = if (position % 3 == 0) 0 else 15.dp
|
||||
//
|
||||
// it.leftMargin = 7.dp
|
||||
// it.rightMargin = 8.dp
|
||||
// it.topMargin = 7.dp
|
||||
// it.bottomMargin = 8.dp
|
||||
// }
|
||||
// if (item.pageType == 1) {
|
||||
// root.clickWithDebounce { onCellClick?.invoke(position) }
|
||||
// }
|
||||
// }
|
||||
|
||||
fun getTextSpan(item: SeasoningEntity): SpannableStringBuilder {
|
||||
val endIndex = if (item.sort == 9) 10 else 6
|
||||
var name = if (item.goodsName.isNullOrBlank()) "未配置" else item.goodsName!!
|
||||
if (name.length > endIndex) {
|
||||
name = "${name.substring(0, endIndex)}…"
|
||||
}
|
||||
return buildSpannableString {
|
||||
appendText(
|
||||
name,
|
||||
ForegroundColorSpan(if (item.goodsName.isNullOrBlank()) "#999999".toColorInt() else "#000000".toColorInt()),
|
||||
StyleSpan(Typeface.BOLD),
|
||||
AbsoluteSizeSpan(28, true),
|
||||
LineHeightSpan { text, start, end, spanstartv, v, fm ->
|
||||
fm.descent += 10.dp // 增加行间距
|
||||
}
|
||||
)
|
||||
append("\n")
|
||||
val weight = item.useWeight ?: 0.toDouble()
|
||||
val weightColor = if (weight == 0.toDouble()) "#999999" else "#00BC71"
|
||||
appendText(
|
||||
// "${DecimalFormat("#").format(weight)}g",
|
||||
"${weight.roundedOneDecimalPlace()}g",
|
||||
ForegroundColorSpan(weightColor.toColorInt()),
|
||||
AbsoluteSizeSpan(30, true)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
// }
|
||||
//
|
||||
// override fun getItemCount() = list.size
|
||||
//
|
||||
// var onCellClick: ((positon: Int) -> Unit)? = null
|
||||
//
|
||||
// companion object {
|
||||
// fun loadLayout(frameLayout: FrameLayout, item: SeasoningEntity) {
|
||||
// val child: TextView = frameLayout.getChildAt(0) as TextView
|
||||
// child.text = getTextSpan(item)
|
||||
// }
|
||||
// fun loadCell(tvCell: TextView, item: SeasoningEntity) {
|
||||
// tvCell.text = getTextSpan(item)
|
||||
// }
|
||||
//// fun loadCell2(tvCell: TextView, item: SeasoningEntity) {
|
||||
//// if (item.goodsName.isNullOrBlank()) {
|
||||
//// tvCell.run {
|
||||
//// text = buildSpannableString {
|
||||
//// appendText(
|
||||
//// "未配置",
|
||||
//// ForegroundColorSpan("#999999".toColorInt()),
|
||||
//// StyleSpan(Typeface.BOLD),
|
||||
//// AbsoluteSizeSpan(28, true),
|
||||
//// LineHeightSpan { text, start, end, spanstartv, v, fm ->
|
||||
//// fm.descent += 10.dp // 增加行间距
|
||||
//// }
|
||||
//// )}
|
||||
//// //setTextColor(ContextCompat.getColor(context, R.color.black999))
|
||||
//// }
|
||||
//// } else {
|
||||
////// if (item.pageType == 1) {
|
||||
////// tvCell.run {
|
||||
////// text = item.goodsName
|
||||
////// setTextColor(ContextCompat.getColor(context, R.color.black))
|
||||
////// }
|
||||
////// } else {
|
||||
//// tvCell.text = getTextSpan(item)
|
||||
////// }
|
||||
//// }
|
||||
//// }
|
||||
//
|
||||
// fun getTextSpan(item: SeasoningEntity): SpannableStringBuilder {
|
||||
// val endIndex = if (item.sort == 9) 10 else 6
|
||||
// var name = if (item.goodsName.isNullOrBlank()) "未配置" else item.goodsName!!
|
||||
// if (name.length > endIndex) {
|
||||
// name = "${name.substring(0, endIndex)}…"
|
||||
// }
|
||||
// return buildSpannableString {
|
||||
// appendText(
|
||||
// name,
|
||||
// ForegroundColorSpan(if (item.goodsName.isNullOrBlank()) "#999999".toColorInt() else "#000000".toColorInt()),
|
||||
// StyleSpan(Typeface.BOLD),
|
||||
// AbsoluteSizeSpan(28, true),
|
||||
// LineHeightSpan { text, start, end, spanstartv, v, fm ->
|
||||
// fm.descent += 10.dp // 增加行间距
|
||||
// }
|
||||
// )
|
||||
// append("\n")
|
||||
// val weight = item.useWeight ?: 0.toDouble()
|
||||
// val weightColor = if (weight == 0.toDouble()) "#999999" else "#00BC71"
|
||||
// appendText(
|
||||
//// "${DecimalFormat("#").format(weight)}g",
|
||||
// "${weight.roundedOneDecimalPlace()}g",
|
||||
// ForegroundColorSpan(weightColor.toColorInt()),
|
||||
// AbsoluteSizeSpan(30, true)
|
||||
// )
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
//}
|
||||
@@ -9,7 +9,7 @@ import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.databinding.ListItemVectorCollectionBinding
|
||||
import com.shuwei.dish.match.entity.FoodCollectionBean
|
||||
import com.shuwei.dish.match.model.FoodCollectionBean
|
||||
import com.shuwei.dish.match.utils.ext.load
|
||||
|
||||
class VectorCollectionAdapter (var list: MutableList<FoodCollectionBean>) :
|
||||
|
||||
@@ -5,6 +5,7 @@ import android.content.pm.ActivityInfo
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import android.view.View
|
||||
import android.widget.FrameLayout
|
||||
import android.widget.ImageView
|
||||
@@ -23,6 +24,7 @@ import com.shuwei.dish.match.net.NetViewModel
|
||||
import com.shuwei.dish.match.db.DbViewModel
|
||||
import com.shuwei.dish.match.ui.InitActivity
|
||||
import com.shuwei.dish.match.utils.ActivityManager
|
||||
import com.shuwei.dish.match.utils.KeyboardUtil
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.invisible
|
||||
@@ -36,6 +38,7 @@ import kotlin.getValue
|
||||
open class BaseActivity : AppCompatActivity() {
|
||||
|
||||
companion object {
|
||||
const val TAG = "BaseActivity"
|
||||
/** 日期时间格式化器,复用避免每秒重复创建 */
|
||||
private val DATE_FORMATTER =
|
||||
DateTimeFormatter.ofPattern("yyyy年MM月dd日 EEEE***HH:mm:ss", Locale.CHINA)
|
||||
@@ -65,11 +68,13 @@ open class BaseActivity : AppCompatActivity() {
|
||||
binding.tvRightTime.setPadding(0, verticalPadding, 0, verticalPadding)
|
||||
binding.llTitleBar.gone()
|
||||
binding.ivBack.setOnClickListener { finish() }
|
||||
binding.root.setOnClickListener { hideKeyboard() }
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
handler.removeCallbacksAndMessages(null)
|
||||
dismissLoading()
|
||||
// 只关闭自己弹出的 Loading,防止误关其他 Activity 的 Loading
|
||||
Loading.dismissIfOwnedBy(this)
|
||||
super.onDestroy()
|
||||
ActivityManager.removeActivity(this)
|
||||
}
|
||||
@@ -90,13 +95,13 @@ open class BaseActivity : AppCompatActivity() {
|
||||
titleBarAction: ((FrameLayout) -> Unit)? = null,
|
||||
backAction: ((ImageView) -> Unit)? = null,
|
||||
titleAction: ((TextView) -> Unit)? = null,
|
||||
rightIconActon: ((ImageView) -> Unit)? = null
|
||||
rightIconAction: ((ImageView) -> Unit)? = null
|
||||
) {
|
||||
binding.llTitleBar.visible()
|
||||
titleBarAction?.invoke(binding.llTitleBar)
|
||||
backAction?.invoke(binding.ivBack)
|
||||
titleAction?.invoke(binding.tvTitle)
|
||||
rightIconActon?.invoke(binding.ivRightIcon)
|
||||
rightIconAction?.invoke(binding.ivRightIcon)
|
||||
}
|
||||
|
||||
fun setHeaderBgVisible(show: Boolean) {
|
||||
@@ -148,22 +153,25 @@ open class BaseActivity : AppCompatActivity() {
|
||||
handler.removeCallbacks(updateTask)
|
||||
}
|
||||
|
||||
fun showLoading(msg: String = "加载中……") {
|
||||
fun showLoading(msg: String = "加载中……", timeoutMs: Long = Loading.DEFAULT_TIMEOUT_MS) {
|
||||
handler.post {
|
||||
Loading.show(
|
||||
context = this,
|
||||
message = msg
|
||||
message = msg,
|
||||
timeoutMs = timeoutMs
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun dismissLoading() {
|
||||
Log.d(TAG, "dismissLoading, ${this.javaClass.simpleName}")
|
||||
handler.post {
|
||||
Loading.dismiss()
|
||||
}
|
||||
}
|
||||
|
||||
fun delayDismissLoading() {
|
||||
Log.d(TAG, "delayDismissLoading, ${this.javaClass.simpleName}")
|
||||
handler.postDelayed({
|
||||
Loading.dismiss()
|
||||
}, 500)
|
||||
@@ -180,7 +188,7 @@ open class BaseActivity : AppCompatActivity() {
|
||||
|
||||
|
||||
val netViewModel: NetViewModel by viewModels()
|
||||
val appViewModel: DbViewModel by viewModels()
|
||||
val dbViewModel: DbViewModel by viewModels()
|
||||
|
||||
private var singlePermissionCallback: ((isGranted: Boolean) -> Unit)? = null
|
||||
private var multiplePermissionsCallback: ((isGranted: Boolean) -> Unit)? = null
|
||||
@@ -264,4 +272,8 @@ open class BaseActivity : AppCompatActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
fun hideKeyboard() {
|
||||
KeyboardUtil.hideKeyboard(binding.root)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,41 +1,41 @@
|
||||
package com.shuwei.dish.match.base
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.content.SharedPreferences
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import com.shuwei.dish.match.BuildConfig
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.db.DatabaseProvider
|
||||
import com.shuwei.dish.match.objbox.ObjectBox
|
||||
import com.shuwei.dish.match.scale.ScaleDeviceConfig
|
||||
import com.shuwei.dish.match.scale.ScaleServiceManager
|
||||
import com.shuwei.dish.match.utils.AppUtil
|
||||
import com.shuwei.dish.match.utils.SpTool
|
||||
import com.shuwei.dish.match.utils.BootReceiver
|
||||
import com.shuwei.dish.match.utils.CrashHandler
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
import com.shuwei.dish.match.utils.Weigher2
|
||||
|
||||
|
||||
/**
|
||||
* BaseApp is the main application class that extends Android's Application class.
|
||||
* It handles initialization of core components, device role determination,
|
||||
* and service management for the weighing system.
|
||||
*/
|
||||
class BaseApp : Application() {
|
||||
|
||||
// Lazy initialization of the database instance
|
||||
val database by lazy { DatabaseProvider(this).instance }
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
// Set the application instance
|
||||
instance = this
|
||||
// Initialize crash handler for error tracking
|
||||
// 读取本地保存的环境地址,覆盖默认值
|
||||
val savedBaseUrl = SpTool.baseUrl
|
||||
if (savedBaseUrl.isNotEmpty()) {
|
||||
GlobalData.appBaseUrl = savedBaseUrl
|
||||
}
|
||||
CrashHandler.init(this)
|
||||
// Get and store the unique device ID
|
||||
val deviceId = AppUtil.getUDID(this)
|
||||
Log.d(TAG, "onCreate: deviceId=$deviceId")
|
||||
val deviceId = if (BuildConfig.IS_TEST_DEVICE) ScaleDeviceConfig.DEVICE_ID_2 else AppUtil.getUDID(this)
|
||||
Log.d(TAG, "onCreate: deviceId=$deviceId, isTestDevice=${BuildConfig.IS_TEST_DEVICE}")
|
||||
GlobalData.deviceId = deviceId
|
||||
|
||||
// 根据设备 ID 判断角色:指定 ID 为主设备,其余为子设备
|
||||
@@ -51,6 +51,26 @@ class BaseApp : Application() {
|
||||
|
||||
// 启动秤服务(主设备多启动发现+聚合,子设备只启动服务端+注册)
|
||||
ScaleServiceManager.start(this)
|
||||
|
||||
// 初始化秤,进程级生命周期管理:最后一个 Activity 销毁时才停止读取
|
||||
WeightUtil.init()
|
||||
WeightUtil.getWeight()
|
||||
WeightUtil.startContinuousRead()
|
||||
registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
|
||||
private var activityCount = 0
|
||||
override fun onActivityCreated(a: Activity, b: Bundle?) { activityCount++ }
|
||||
override fun onActivityDestroyed(a: Activity) {
|
||||
if (--activityCount <= 0) {
|
||||
WeightUtil.stopContinuousRead()
|
||||
}
|
||||
}
|
||||
override fun onActivityStarted(a: Activity) {}
|
||||
override fun onActivityResumed(a: Activity) {}
|
||||
override fun onActivityPaused(a: Activity) {}
|
||||
override fun onActivityStopped(a: Activity) {}
|
||||
override fun onActivitySaveInstanceState(a: Activity, b: Bundle) {}
|
||||
})
|
||||
|
||||
// GlobalData.deviceId = "39a7abdd06b3c7ab"
|
||||
val filter = IntentFilter(Intent.ACTION_BOOT_COMPLETED)
|
||||
registerReceiver(BootReceiver(), filter)
|
||||
@@ -59,24 +79,21 @@ class BaseApp : Application() {
|
||||
|
||||
companion object {
|
||||
private val TAG = "BaseApp"
|
||||
// const val canteenId = "1678234139391512577"
|
||||
var canteenId = "0"
|
||||
// var configUrl = ""
|
||||
|
||||
// var token: String? = null
|
||||
// var deviceId: String? = null
|
||||
var appVersion: String = "1"
|
||||
@Volatile
|
||||
private var sharedPref: SharedPreferences? = null
|
||||
|
||||
public var instance: BaseApp? = null
|
||||
fun getSharedPref(): SharedPreferences? {
|
||||
if (sharedPref != null) {
|
||||
return sharedPref
|
||||
lateinit var instance: BaseApp
|
||||
|
||||
/** 双重检查锁,保证多线程下只初始化一次 */
|
||||
fun getSharedPref(): SharedPreferences {
|
||||
return sharedPref ?: synchronized(this) {
|
||||
sharedPref ?: instance.getSharedPreferences(
|
||||
instance.getString(R.string.sp_save_name),
|
||||
Context.MODE_PRIVATE
|
||||
).also { sharedPref = it }
|
||||
}
|
||||
val saveName = instance?.getString(R.string.sp_save_name)
|
||||
sharedPref = instance?.getSharedPreferences(saveName, Context.MODE_PRIVATE)
|
||||
return sharedPref
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,14 +8,14 @@ package com.shuwei.dish.match.base
|
||||
enum class DeviceRole { MASTER, SLAVE }
|
||||
|
||||
object GlobalData {
|
||||
var appBaseUrl: String = TEST_BASE_URL
|
||||
var appBaseUrl: String = PROD_BASE_URL
|
||||
|
||||
/**
|
||||
* 具体业务 BaseUrl
|
||||
*/
|
||||
const val TEST_BASE_URL = "http://192.168.1.201:14801"
|
||||
const val TEST_BASE_URL = "http://192.168.10.101:24801"
|
||||
const val UAT_BASE_URL = "https://dev.yixiong-tech.com:8081"
|
||||
const val PROD_BASE_URL = "https://api.dm.yixiong-tech.com:8443"
|
||||
const val PROD_BASE_URL = "https://platform-api.uat.shuziweidao.com"
|
||||
/**
|
||||
* 设备id
|
||||
*/
|
||||
@@ -25,8 +25,6 @@ object GlobalData {
|
||||
* 当前设备角色,启动时从 SpTool 读取,默认为 SLAVE
|
||||
*/
|
||||
var deviceRole: DeviceRole = DeviceRole.SLAVE
|
||||
var appId = "Hkz1rBk6PZXbS8KwKr67K2eZtsz8bRoMHLg64bUdgCZj"
|
||||
var sdkKey = "AabXs3sHM8UhhE7oCGf4LVMLrdkGb1nJNksbjjTdVt7k"
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -37,4 +35,5 @@ object GlobalKey {
|
||||
const val KEY_TOKEN = "tokenKey"
|
||||
const val KEY_USER_INFO = "userInfoKey"
|
||||
const val KEY_USER_NAME = "userNameKey"
|
||||
const val KEY_BASE_URL = "baseUrl"
|
||||
}
|
||||
@@ -10,10 +10,10 @@ import com.shuwei.dish.match.db.dao.CookFoodDao
|
||||
import com.shuwei.dish.match.db.dao.CookFoodGoodsDao
|
||||
import com.shuwei.dish.match.db.dao.SeasoningDao
|
||||
import com.shuwei.dish.match.db.dao.SeasoningSlotDao
|
||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.entity.SeasoningSlotEntity
|
||||
import com.shuwei.dish.match.db.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.db.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.db.entity.SeasoningSlotEntity
|
||||
|
||||
|
||||
// 步骤1:更新版本号
|
||||
@@ -25,7 +25,7 @@ import com.shuwei.dish.match.entity.SeasoningSlotEntity
|
||||
CookFoodGoodsEntity::class,
|
||||
SeasoningSlotEntity::class,
|
||||
],
|
||||
version = 8,
|
||||
version = 13,
|
||||
exportSchema = true
|
||||
)
|
||||
abstract class AppDatabase : RoomDatabase() {
|
||||
@@ -214,6 +214,48 @@ val MIGRATION_6_7 = MigrationImpl(6, 7) {db ->
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 版本8→9:为 dm_cook_food_goods 和 dm_seasoning 表新增 zjmCode、materId 字段
|
||||
*/
|
||||
val MIGRATION_8_9 = MigrationImpl(8, 9) { db ->
|
||||
db.execSQL("ALTER TABLE dm_cook_food_goods ADD COLUMN zjmCode TEXT DEFAULT ''")
|
||||
db.execSQL("ALTER TABLE dm_cook_food_goods ADD COLUMN materId TEXT DEFAULT ''")
|
||||
db.execSQL("ALTER TABLE dm_seasoning ADD COLUMN zjmCode TEXT DEFAULT ''")
|
||||
db.execSQL("ALTER TABLE dm_seasoning ADD COLUMN materId TEXT DEFAULT ''")
|
||||
}
|
||||
|
||||
/**
|
||||
* 版本9→10:删除 dm_cook_food 表 foodId 唯一索引
|
||||
* 改为由应用层保证同一 foodId 且 isDel=0 只有一条记录,以支持逻辑删除
|
||||
*/
|
||||
val MIGRATION_9_10 = MigrationImpl(9, 10) { db ->
|
||||
db.execSQL("DROP INDEX IF EXISTS dm_cook_food_foodId_IDX")
|
||||
}
|
||||
|
||||
/**
|
||||
* 版本10→11:为 dm_cook_food_goods 和 dm_seasoning 表新增 goodsCode(物料编码)字段
|
||||
*/
|
||||
val MIGRATION_10_11 = MigrationImpl(10, 11) { db ->
|
||||
db.execSQL("ALTER TABLE dm_cook_food_goods ADD COLUMN goodsCode TEXT DEFAULT ''")
|
||||
db.execSQL("ALTER TABLE dm_seasoning ADD COLUMN goodsCode TEXT DEFAULT ''")
|
||||
}
|
||||
|
||||
/**
|
||||
* 版本11→12:为 dm_cook_food_goods 和 dm_seasoning 表新增 rawMaterialsType(净材种类)字段
|
||||
*/
|
||||
val MIGRATION_11_12 = MigrationImpl(11, 12) { db ->
|
||||
db.execSQL("ALTER TABLE dm_cook_food_goods ADD COLUMN rawMaterialsType TEXT DEFAULT NULL")
|
||||
db.execSQL("ALTER TABLE dm_seasoning ADD COLUMN rawMaterialsType TEXT DEFAULT NULL")
|
||||
}
|
||||
|
||||
/**
|
||||
* 版本12→13:为 dm_cook_food 表新增 submitState(接口提交状态)字段
|
||||
* 0-未提交(本地草稿/手动删除),1-接口提交成功后删除
|
||||
*/
|
||||
val MIGRATION_12_13 = MigrationImpl(12, 13) { db ->
|
||||
db.execSQL("ALTER TABLE dm_cook_food ADD COLUMN submitState INTEGER NOT NULL DEFAULT 0")
|
||||
}
|
||||
|
||||
class DatabaseProvider(private val context: Context) {
|
||||
// 单例模式确保全局唯一实例
|
||||
val instance: AppDatabase by lazy {
|
||||
@@ -233,6 +275,11 @@ class DatabaseProvider(private val context: Context) {
|
||||
// .addMigrations(MIGRATION_5_6)
|
||||
// .addMigrations(MIGRATION_6_7)
|
||||
.addMigrations(MIGRATION_7_8)
|
||||
.addMigrations(MIGRATION_8_9)
|
||||
.addMigrations(MIGRATION_9_10)
|
||||
.addMigrations(MIGRATION_10_11)
|
||||
.addMigrations(MIGRATION_11_12)
|
||||
.addMigrations(MIGRATION_12_13)
|
||||
.build()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
package com.shuwei.dish.match.db
|
||||
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.entity.SeasoningSlotEntity
|
||||
import com.shuwei.dish.match.db.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.db.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.db.entity.SeasoningSlotEntity
|
||||
import androidx.sqlite.db.SupportSQLiteQuery
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
@@ -21,8 +22,8 @@ class DbRepository {
|
||||
db.cookFoodDao().updateCookFood(item)
|
||||
}
|
||||
|
||||
suspend fun getCookFoodById(foodId: String, cookMode: Int) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().getCookFoodById(BaseApp.canteenId, foodId, cookMode)
|
||||
suspend fun getCookFoodById(foodId: String, cookMode: Int, dinnerType: String) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().getCookFoodById(BaseApp.canteenId, foodId, cookMode, dinnerType)
|
||||
}
|
||||
|
||||
suspend fun getCookFoodList(cookMode: Int, dinnerType: String) = withContext(Dispatchers.IO) {
|
||||
@@ -33,13 +34,23 @@ class DbRepository {
|
||||
db.cookFoodDao().countCookFood(BaseApp.canteenId, cookMode)
|
||||
}
|
||||
|
||||
suspend fun deleteCookFood(foodId: String, cookMode: Int) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().deleteCookFood(BaseApp.canteenId, foodId, cookMode)
|
||||
suspend fun deleteCookFood(foodId: String, cookMode: Int, dinnerType: String) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().deleteCookFood(BaseApp.canteenId, foodId, cookMode, dinnerType)
|
||||
}
|
||||
|
||||
/** 接口提交成功后逻辑删除菜品,同时把 submitState 置 1 */
|
||||
suspend fun markSubmittedAndDelete(foodId: String, cookMode: Int, dinnerType: String) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().markSubmittedAndDelete(BaseApp.canteenId, foodId, cookMode, dinnerType)
|
||||
}
|
||||
|
||||
suspend fun deleteCookFoodGoodsList(pid: Long, foodId: String) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodGoodsDao().deleteCookFoodGoodsList(pid, foodId)
|
||||
}
|
||||
|
||||
/** 仅逻辑删除调料行(materialType = 3),主辅材不动 */
|
||||
suspend fun deleteSeasoningOnly(pid: Long, foodId: String) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodGoodsDao().deleteSeasoningOnly(pid, foodId)
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------
|
||||
|
||||
suspend fun insertGoodsList(items: MutableList<CookFoodGoodsEntity>) =
|
||||
@@ -67,7 +78,7 @@ class DbRepository {
|
||||
db.seasoningDao().getSeasoningBySort(sort)
|
||||
}
|
||||
|
||||
suspend fun getSeasoningByGoodsId(goodsId: Int) = withContext(Dispatchers.IO) {
|
||||
suspend fun getSeasoningByGoodsId(goodsId: String) = withContext(Dispatchers.IO) {
|
||||
db.seasoningDao().getSeasoningByGoodsId(goodsId)
|
||||
}
|
||||
|
||||
@@ -100,6 +111,20 @@ class DbRepository {
|
||||
db.seasoningDao().insertSeasoning(item)
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 goodsId 查重后 upsert:存在则更新,不存在则插入
|
||||
* 确保同一个 goodsId 在 dm_seasoning 中只有一条记录
|
||||
*/
|
||||
suspend fun upsertSeasoningByGoodsId(item: SeasoningEntity) = withContext(Dispatchers.IO) {
|
||||
val existing = db.seasoningDao().getSeasoningByGoodsId(item.goodsId)
|
||||
if (existing != null) {
|
||||
db.seasoningDao().updateSeasoning(item.also { it.id = existing.id })
|
||||
} else {
|
||||
item.id = 0
|
||||
db.seasoningDao().insertSeasoning(item)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询指定设备是否已配置调料槽位
|
||||
* @param deviceId 目标设备 ID
|
||||
@@ -154,6 +179,105 @@ class DbRepository {
|
||||
suspend fun deleteAllSlotsByDeviceId(deviceId: String) = withContext(Dispatchers.IO) {
|
||||
db.seasoningSlotDao().deleteAllByDeviceId(deviceId)
|
||||
}
|
||||
|
||||
// ---- 调试用:查询各表全量数据(含已删除记录)----
|
||||
|
||||
/** 查询 dm_cook_food 全部记录 */
|
||||
suspend fun getAllCookFood() = withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().getAllCookFood()
|
||||
}
|
||||
|
||||
/** 查询 dm_cook_food_goods 全部记录 */
|
||||
suspend fun getAllCookFoodGoods() = withContext(Dispatchers.IO) {
|
||||
db.cookFoodGoodsDao().getAllCookFoodGoods()
|
||||
}
|
||||
|
||||
/** 查询 dm_seasoning 全部记录 */
|
||||
suspend fun getAllSeasoning() = withContext(Dispatchers.IO) {
|
||||
db.seasoningDao().getAllSeasoning()
|
||||
}
|
||||
|
||||
// ---- 调试用:分页查询(含 isDel 过滤)----
|
||||
|
||||
suspend fun getCookFoodPaged(showDel: Boolean, limit: Int, offset: Int) =
|
||||
withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().getCookFoodPaged(if (showDel) 1 else 0, limit, offset)
|
||||
}
|
||||
|
||||
suspend fun countCookFoodAll(showDel: Boolean) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().countCookFoodAll(if (showDel) 1 else 0)
|
||||
}
|
||||
|
||||
suspend fun getCookFoodGoodsPaged(showDel: Boolean, limit: Int, offset: Int) =
|
||||
withContext(Dispatchers.IO) {
|
||||
db.cookFoodGoodsDao().getCookFoodGoodsPaged(if (showDel) 1 else 0, limit, offset)
|
||||
}
|
||||
|
||||
suspend fun countCookFoodGoodsAll(showDel: Boolean) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodGoodsDao().countCookFoodGoodsAll(if (showDel) 1 else 0)
|
||||
}
|
||||
|
||||
suspend fun getSeasoningPaged(showDel: Boolean, limit: Int, offset: Int) =
|
||||
withContext(Dispatchers.IO) {
|
||||
db.seasoningDao().getSeasoningPaged(if (showDel) 1 else 0, limit, offset)
|
||||
}
|
||||
|
||||
suspend fun countSeasoningAll(showDel: Boolean) = withContext(Dispatchers.IO) {
|
||||
db.seasoningDao().countSeasoningAll(if (showDel) 1 else 0)
|
||||
}
|
||||
|
||||
suspend fun getSlotPaged(limit: Int, offset: Int) = withContext(Dispatchers.IO) {
|
||||
db.seasoningSlotDao().getSlotPaged(limit, offset)
|
||||
}
|
||||
|
||||
suspend fun countSlotAll() = withContext(Dispatchers.IO) {
|
||||
db.seasoningSlotDao().countSlotAll()
|
||||
}
|
||||
|
||||
// ---- 调试用:动态条件过滤分页查询 ----
|
||||
|
||||
suspend fun getCookFoodPagedFiltered(query: SupportSQLiteQuery) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().queryPagedFiltered(query)
|
||||
}
|
||||
|
||||
suspend fun countCookFoodFiltered(query: SupportSQLiteQuery) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().countFiltered(query)
|
||||
}
|
||||
|
||||
suspend fun getCookFoodGoodsPagedFiltered(query: SupportSQLiteQuery) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodGoodsDao().queryPagedFiltered(query)
|
||||
}
|
||||
|
||||
suspend fun countCookFoodGoodsFiltered(query: SupportSQLiteQuery) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodGoodsDao().countFiltered(query)
|
||||
}
|
||||
|
||||
suspend fun getSeasoningPagedFiltered(query: SupportSQLiteQuery) = withContext(Dispatchers.IO) {
|
||||
db.seasoningDao().queryPagedFiltered(query)
|
||||
}
|
||||
|
||||
suspend fun countSeasoningFiltered(query: SupportSQLiteQuery) = withContext(Dispatchers.IO) {
|
||||
db.seasoningDao().countFiltered(query)
|
||||
}
|
||||
|
||||
suspend fun getSlotPagedFiltered(query: SupportSQLiteQuery) = withContext(Dispatchers.IO) {
|
||||
db.seasoningSlotDao().queryPagedFiltered(query)
|
||||
}
|
||||
|
||||
suspend fun countSlotFiltered(query: SupportSQLiteQuery) = withContext(Dispatchers.IO) {
|
||||
db.seasoningSlotDao().countFiltered(query)
|
||||
}
|
||||
|
||||
/**
|
||||
* 物理清空全部 4 张表的测试数据
|
||||
* 清除顺序:先删子表(食材),再删主表(菜品),最后删配置表(调料、槽位)
|
||||
*/
|
||||
suspend fun clearAllData() = withContext(Dispatchers.IO) {
|
||||
db.cookFoodGoodsDao().deleteAll()
|
||||
db.cookFoodDao().deleteAll()
|
||||
db.seasoningDao().deleteAll()
|
||||
db.seasoningSlotDao().deleteAll()
|
||||
}
|
||||
}
|
||||
//
|
||||
//class SeasoningRepository(val seasoningDao: SeasoningDao) {
|
||||
|
||||
@@ -2,12 +2,13 @@ package com.shuwei.dish.match.db
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.shuwei.dish.match.entity.CollectedFoodItem
|
||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
||||
import androidx.sqlite.db.SimpleSQLiteQuery
|
||||
import com.shuwei.dish.match.model.CollectedFoodItem
|
||||
import com.shuwei.dish.match.db.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.objbox.ObjectBox
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.entity.SeasoningSlotEntity
|
||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.db.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.db.entity.SeasoningSlotEntity
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
@@ -28,9 +29,9 @@ class DbViewModel : ViewModel() {
|
||||
private val _cookFoodDetailState = MutableStateFlow<CookFoodEntity?>(null)
|
||||
val cookFoodDetailState: StateFlow<CookFoodEntity?> = _cookFoodDetailState.asStateFlow()
|
||||
|
||||
fun getCookFoodById(foodId: String, cookMode: Int) {
|
||||
fun getCookFoodById(foodId: String, cookMode: Int, dinnerType: String) {
|
||||
viewModelScope.launch {
|
||||
_cookFoodDetailState.value = rep.getCookFoodById(foodId, cookMode)
|
||||
_cookFoodDetailState.value = rep.getCookFoodById(foodId, cookMode, dinnerType)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,6 +49,30 @@ class DbViewModel : ViewModel() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询本地烹饪中数据(回调版本),结果通过 onResult 直接回调,不经过 StateFlow
|
||||
* 适合不需要跨生命周期持续监听的一次性查询场景
|
||||
*/
|
||||
fun getCookFoodListWithCallback(
|
||||
cookMode: Int,
|
||||
dinnerType: String = "0",
|
||||
onResult: (MutableList<CookFoodEntity>?) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onResult(rep.getCookFoodList(cookMode, dinnerType))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接返回本地烹饪中数据,供需要串行等待结果的场景使用(如先查库再发网络请求)
|
||||
*/
|
||||
suspend fun getCookFoodListDirect(
|
||||
cookMode: Int,
|
||||
dinnerType: String = "0"
|
||||
): MutableList<CookFoodEntity>? {
|
||||
return rep.getCookFoodList(cookMode, dinnerType)
|
||||
}
|
||||
|
||||
suspend fun countCookFood(cookMode: Int): Int {
|
||||
return rep.countCookFood(cookMode)
|
||||
}
|
||||
@@ -68,28 +93,62 @@ class DbViewModel : ViewModel() {
|
||||
entity: CookFoodEntity,
|
||||
list: MutableList<CookFoodGoodsEntity>?
|
||||
) {
|
||||
val data = rep.getCookFoodById(entity.foodId, cookMode)
|
||||
if (data != null) {
|
||||
// 存在数据先删除
|
||||
rep.deleteCookFood(entity.foodId, cookMode)
|
||||
rep.deleteCookFoodGoodsList(data.id, entity.foodId)
|
||||
}
|
||||
// 重新保存数据
|
||||
rep.insertCookFood(entity)
|
||||
val newData = rep.getCookFoodById(entity.foodId, cookMode)
|
||||
list?.let { it ->
|
||||
it.forEach { goods ->
|
||||
goods.id = 0
|
||||
goods.pid = newData?.id ?: 0
|
||||
val data = rep.getCookFoodById(entity.foodId, cookMode, entity.dinnerType ?: "0")
|
||||
if (data == null) {
|
||||
// 首次保存:主表 + 主辅材 + 调料 全量 insert
|
||||
rep.insertCookFood(entity)
|
||||
val newData = rep.getCookFoodById(entity.foodId, cookMode, entity.dinnerType ?: "0")
|
||||
// 回填 id,防止下次调用时 getCookFoodById 查不到而重复插入主辅材
|
||||
newData?.let { entity.id = it.id }
|
||||
list?.let {
|
||||
it.forEach { goods ->
|
||||
goods.id = 0
|
||||
goods.pid = newData?.id ?: 0
|
||||
}
|
||||
rep.insertGoodsList(it)
|
||||
}
|
||||
} else {
|
||||
// 已存在:主表与主辅材保持不变,仅重建调料部分,避免主表/主辅材累积逻辑删除脏数据
|
||||
rep.deleteSeasoningOnly(data.id, entity.foodId)
|
||||
val seasoningList = list?.filter { it.materialType == 3 }?.toMutableList()
|
||||
if (!seasoningList.isNullOrEmpty()) {
|
||||
seasoningList.forEach { goods ->
|
||||
goods.id = 0
|
||||
goods.pid = data.id
|
||||
goods.foodId = entity.foodId
|
||||
}
|
||||
rep.insertGoodsList(seasoningList)
|
||||
}
|
||||
rep.insertGoodsList(it)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun deleteCookFoodAndGoods(cookMode: Int, foodId: String) {
|
||||
val data = rep.getCookFoodById(foodId, cookMode)
|
||||
suspend fun deleteCookFoodAndGoods(cookMode: Int, foodId: String, dinnerType: String) {
|
||||
val data = rep.getCookFoodById(foodId, cookMode, dinnerType)
|
||||
if (data != null) {
|
||||
rep.deleteCookFood(foodId = foodId, cookMode = cookMode)
|
||||
rep.deleteCookFood(foodId = foodId, cookMode = cookMode, dinnerType = dinnerType)
|
||||
rep.deleteCookFoodGoodsList(pid = data.id, foodId = foodId)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 接口提交成功后删除本地菜品草稿(异步版本,绑定 viewModelScope)
|
||||
* 与 [markSubmittedAndDelete] 的区别:不是 suspend,内部用 viewModelScope 启动协程,
|
||||
* 不受调用方 Activity 生命周期影响,适合 singleTask 跳转前触发删除的场景
|
||||
*/
|
||||
fun markSubmittedAndDeleteAsync(cookMode: Int, foodId: String, dinnerType: String) {
|
||||
viewModelScope.launch {
|
||||
markSubmittedAndDelete(cookMode, foodId, dinnerType)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 接口提交成功后删除本地菜品草稿
|
||||
* 与 [deleteCookFoodAndGoods] 的区别:主表 submitState 会被置 1,便于审计区分手动删除与接口删除
|
||||
*/
|
||||
suspend fun markSubmittedAndDelete(cookMode: Int, foodId: String, dinnerType: String) {
|
||||
val data = rep.getCookFoodById(foodId, cookMode, dinnerType)
|
||||
if (data != null) {
|
||||
rep.markSubmittedAndDelete(foodId = foodId, cookMode = cookMode, dinnerType = dinnerType)
|
||||
rep.deleteCookFoodGoodsList(pid = data.id, foodId = foodId)
|
||||
}
|
||||
}
|
||||
@@ -98,9 +157,10 @@ class DbViewModel : ViewModel() {
|
||||
|
||||
suspend fun getCookFoodGoodsList(
|
||||
foodId: String,
|
||||
cookMode: Int
|
||||
cookMode: Int,
|
||||
dinnerType: String
|
||||
): MutableList<CookFoodGoodsEntity> {
|
||||
val cookFood = rep.getCookFoodById(foodId, cookMode)
|
||||
val cookFood = rep.getCookFoodById(foodId, cookMode, dinnerType)
|
||||
return if (cookFood != null) rep.getCookFoodGoodsList(pid = cookFood.id, foodId = cookFood.foodId)
|
||||
else mutableListOf()
|
||||
}
|
||||
@@ -237,7 +297,240 @@ class DbViewModel : ViewModel() {
|
||||
suspend fun deleteAllSlotsByDeviceId(deviceId: String) =
|
||||
rep.deleteAllSlotsByDeviceId(deviceId)
|
||||
|
||||
// fun updateAll(list: MutableList<SeasoningEntity>) {
|
||||
// ---- 数据库调试查看 ----
|
||||
|
||||
/**
|
||||
* 物理清空全部 4 张表的测试数据,完成后通过回调通知 UI
|
||||
* @param onDone 清除完成后在主线程执行的回调
|
||||
*/
|
||||
fun clearAllData(onDone: () -> Unit) {
|
||||
viewModelScope.launch {
|
||||
rep.clearAllData()
|
||||
onDone()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** 每页加载条数 */
|
||||
const val DB_INSPECT_PAGE_SIZE = 50
|
||||
}
|
||||
|
||||
/**
|
||||
* 单条数据库记录的展示模型
|
||||
* @param isDel 是否已逻辑删除
|
||||
* @param fields 字段名-值对列表,按顺序排列
|
||||
* @param columnsPerRow 每行显示的列数,默认 3;槽位表传 1 保持单列
|
||||
*/
|
||||
data class DbRecord(
|
||||
val isDel: Boolean,
|
||||
val fields: List<Pair<String, String>>,
|
||||
val columnsPerRow: Int = 3
|
||||
)
|
||||
|
||||
/**
|
||||
* 数据库调试页面 UI 状态
|
||||
* @param items 当前已加载的记录列表
|
||||
* @param totalCount 当前过滤条件下的总记录数
|
||||
* @param hasMore 是否还有更多数据可加载
|
||||
* @param isLoading 是否正在加载(首次加载或加载更多)
|
||||
* @param filter 当前生效的筛选条件,供"加载更多"复用
|
||||
*/
|
||||
data class DbInspectUiState(
|
||||
val items: List<DbRecord> = emptyList(),
|
||||
val totalCount: Int = 0,
|
||||
val hasMore: Boolean = false,
|
||||
val isLoading: Boolean = false,
|
||||
val filter: DbInspectFilter = DbInspectFilter()
|
||||
)
|
||||
|
||||
/**
|
||||
* 数据库调试页面筛选条件
|
||||
* @param showDel 是否包含已删除记录
|
||||
* @param exactFields 精确匹配字段:列名 → 值
|
||||
* @param likeFields 模糊匹配字段:列名 → 值(自动加 %value%)
|
||||
*/
|
||||
data class DbInspectFilter(
|
||||
val showDel: Boolean = true,
|
||||
val exactFields: Map<String, String> = emptyMap(),
|
||||
val likeFields: Map<String, String> = emptyMap()
|
||||
)
|
||||
|
||||
private val _dbInspectState = MutableStateFlow(DbInspectUiState())
|
||||
val dbInspectState: StateFlow<DbInspectUiState> = _dbInspectState.asStateFlow()
|
||||
|
||||
/**
|
||||
* 加载指定表的第一页数据(切换 Tab / 修改筛选条件时调用)
|
||||
* @param tableIndex 0=菜品 1=食材 2=调料 3=槽位
|
||||
* @param filter 筛选条件,包含 showDel 和各字段过滤值
|
||||
*/
|
||||
fun loadDbInspect(tableIndex: Int, filter: DbInspectFilter) {
|
||||
viewModelScope.launch {
|
||||
// 立即清空旧数据并显示加载状态,避免切换 Tab 时旧数据闪现
|
||||
_dbInspectState.value = DbInspectUiState(isLoading = true, filter = filter)
|
||||
val (items, total) = queryPage(tableIndex, filter, offset = 0)
|
||||
_dbInspectState.value = DbInspectUiState(
|
||||
items = items,
|
||||
totalCount = total,
|
||||
hasMore = items.size < total,
|
||||
isLoading = false,
|
||||
filter = filter
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 追加加载下一页数据(点击"加载更多"时调用)
|
||||
* 筛选条件从当前 state 中复用,无需重新传入
|
||||
* @param tableIndex 0=菜品 1=食材 2=调料 3=槽位
|
||||
*/
|
||||
fun loadMoreDbInspect(tableIndex: Int) {
|
||||
viewModelScope.launch {
|
||||
val current = _dbInspectState.value
|
||||
// 已在加载中或无更多数据时直接返回,防止重复请求
|
||||
if (!current.hasMore || current.isLoading) return@launch
|
||||
_dbInspectState.value = current.copy(isLoading = true)
|
||||
val (newItems, total) = queryPage(tableIndex, current.filter, offset = current.items.size)
|
||||
val merged = current.items + newItems
|
||||
_dbInspectState.value = DbInspectUiState(
|
||||
items = merged,
|
||||
totalCount = total,
|
||||
hasMore = merged.size < total,
|
||||
isLoading = false,
|
||||
filter = current.filter
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行分页查询,返回 DbRecord 列表和总记录数
|
||||
* 通过 buildQueries 将 filter 转换为动态 SQL
|
||||
*/
|
||||
private suspend fun queryPage(
|
||||
tableIndex: Int,
|
||||
filter: DbInspectFilter,
|
||||
offset: Int
|
||||
): Pair<List<DbRecord>, Int> {
|
||||
val limit = DB_INSPECT_PAGE_SIZE
|
||||
return when (tableIndex) {
|
||||
0 -> {
|
||||
val (pageQ, countQ) = buildQueries("dm_cook_food", "createTime DESC", true, filter, limit, offset)
|
||||
val total = rep.countCookFoodFiltered(countQ)
|
||||
val rows = rep.getCookFoodPagedFiltered(pageQ).map { e ->
|
||||
DbRecord(
|
||||
isDel = e.isDel == 1,
|
||||
fields = listOf(
|
||||
"id" to "${e.id}", "foodId" to "${e.foodId}", "foodName" to "${e.foodName}",
|
||||
"canteenId" to "${e.canteenId}", "foodWeight" to "${e.foodWeight}", "cookMode" to "${e.cookMode}",
|
||||
"dinnerType" to "${e.dinnerType}", "isDel" to "${e.isDel}", "submitState" to "${e.submitState}",
|
||||
"createTime" to "${e.createTime}"
|
||||
)
|
||||
)
|
||||
}
|
||||
rows to total
|
||||
}
|
||||
1 -> {
|
||||
val (pageQ, countQ) = buildQueries("dm_cook_food_goods", "createTime DESC", true, filter, limit, offset)
|
||||
val total = rep.countCookFoodGoodsFiltered(countQ)
|
||||
val rows = rep.getCookFoodGoodsPagedFiltered(pageQ).map { e ->
|
||||
DbRecord(
|
||||
isDel = e.isDel == 1,
|
||||
fields = listOf(
|
||||
"id" to "${e.id}", "pid" to "${e.pid}", "goodsId" to "${e.goodsId}",
|
||||
"goodsName" to "${e.goodsName}", "foodId" to "${e.foodId}", "materialType" to "${e.materialType}",
|
||||
"relateionType" to "${e.relateionType}", "allEdible" to "${e.allEdible}", "useWeight" to "${e.useWeight}",
|
||||
"sort" to "${e.sort}", "zjmCode" to "${e.zjmCode}", "materId" to "${e.materId}",
|
||||
"isDel" to "${e.isDel}", "createTime" to "${e.createTime}"
|
||||
)
|
||||
)
|
||||
}
|
||||
rows to total
|
||||
}
|
||||
2 -> {
|
||||
val (pageQ, countQ) = buildQueries("dm_seasoning", "sort ASC", true, filter, limit, offset)
|
||||
val total = rep.countSeasoningFiltered(countQ)
|
||||
val rows = rep.getSeasoningPagedFiltered(pageQ).map { e ->
|
||||
DbRecord(
|
||||
isDel = e.isDel == 1,
|
||||
fields = listOf(
|
||||
"id" to "${e.id}", "goodsId" to "${e.goodsId}", "goodsName" to "${e.goodsName}",
|
||||
"sort" to "${e.sort}", "materialType" to "${e.materialType}", "useWeight" to "${e.useWeight}",
|
||||
"zjmCode" to "${e.zjmCode}", "materId" to "${e.materId}", "isDel" to "${e.isDel}",
|
||||
"createTime" to "${e.createTime}"
|
||||
)
|
||||
)
|
||||
}
|
||||
rows to total
|
||||
}
|
||||
3 -> {
|
||||
val (pageQ, countQ) = buildQueries("dm_seasoning_slot", "deviceId ASC, address ASC", false, filter, limit, offset)
|
||||
val total = rep.countSlotFiltered(countQ)
|
||||
val rows = rep.getSlotPagedFiltered(pageQ).map { e ->
|
||||
DbRecord(
|
||||
isDel = false,
|
||||
fields = listOf(
|
||||
"deviceId" to e.deviceId, "address" to "${e.address}",
|
||||
"goodsId" to e.goodsId, "goodsName" to e.goodsName
|
||||
),
|
||||
columnsPerRow = 1
|
||||
)
|
||||
}
|
||||
rows to total
|
||||
}
|
||||
else -> emptyList<DbRecord>() to 0
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据筛选条件动态构建分页查询和计数查询的 SQL
|
||||
* @param tableName 表名
|
||||
* @param orderBy ORDER BY 子句(不含关键字)
|
||||
* @param hasIsDel 是否有 isDel 字段,无则忽略 showDel 参数
|
||||
* @param filter 筛选条件
|
||||
* @param limit 分页大小
|
||||
* @param offset 偏移量
|
||||
* @return Pair<分页查询, 计数查询>
|
||||
*/
|
||||
private fun buildQueries(
|
||||
tableName: String,
|
||||
orderBy: String,
|
||||
hasIsDel: Boolean,
|
||||
filter: DbInspectFilter,
|
||||
limit: Int,
|
||||
offset: Int
|
||||
): Pair<SimpleSQLiteQuery, SimpleSQLiteQuery> {
|
||||
val conditions = mutableListOf<String>()
|
||||
val args = mutableListOf<Any>()
|
||||
|
||||
if (hasIsDel && !filter.showDel) {
|
||||
conditions.add("isDel = 0")
|
||||
}
|
||||
filter.exactFields.forEach { (col, value) ->
|
||||
if (value.isNotBlank()) {
|
||||
conditions.add("$col = ?")
|
||||
args.add(value)
|
||||
}
|
||||
}
|
||||
filter.likeFields.forEach { (col, value) ->
|
||||
if (value.isNotBlank()) {
|
||||
conditions.add("$col LIKE ?")
|
||||
args.add("%$value%")
|
||||
}
|
||||
}
|
||||
|
||||
val where = if (conditions.isEmpty()) "" else "WHERE ${conditions.joinToString(" AND ")}"
|
||||
val pageQuery = SimpleSQLiteQuery(
|
||||
"SELECT * FROM $tableName $where ORDER BY $orderBy LIMIT ? OFFSET ?",
|
||||
(args + limit + offset).toTypedArray()
|
||||
)
|
||||
val countQuery = SimpleSQLiteQuery(
|
||||
"SELECT COUNT(*) FROM $tableName $where",
|
||||
args.toTypedArray()
|
||||
)
|
||||
return pageQuery to countQuery
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------------------------------------
|
||||
|
||||
// viewModelScope.launch {
|
||||
// list.forEach {
|
||||
// rep.updateSeasoning(it)
|
||||
@@ -266,6 +559,20 @@ class DbViewModel : ViewModel() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 goodsId 查重后 upsert 调料数据,确保同一 goodsId 只有一条记录
|
||||
*/
|
||||
suspend fun upsertSeasoningByGoodsId(entity: SeasoningEntity) {
|
||||
rep.upsertSeasoningByGoodsId(entity)
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 goodsId 查询调料详情
|
||||
*/
|
||||
suspend fun getSeasoningByGoodsId(goodsId: String): SeasoningEntity? {
|
||||
return rep.getSeasoningByGoodsId(goodsId)
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
@@ -301,5 +608,17 @@ class DbViewModel : ViewModel() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除所有向量采集数据,完成后刷新列表
|
||||
* @param onDone 清除完成后在主线程执行的回调
|
||||
*/
|
||||
fun clearAllCollectedFood(onDone: (() -> Unit)? = null) {
|
||||
viewModelScope.launch {
|
||||
ObjectBox.removeAll()
|
||||
loadCollectedFoodList()
|
||||
onDone?.invoke()
|
||||
}
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------------------------------------
|
||||
}
|
||||
@@ -4,8 +4,10 @@ import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.RawQuery
|
||||
import androidx.room.Update
|
||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
||||
import androidx.sqlite.db.SupportSQLiteQuery
|
||||
import com.shuwei.dish.match.db.entity.CookFoodEntity
|
||||
|
||||
@Dao
|
||||
interface CookFoodDao {
|
||||
@@ -16,8 +18,8 @@ interface CookFoodDao {
|
||||
@Update
|
||||
suspend fun updateCookFood(item: CookFoodEntity)
|
||||
|
||||
@Query("SELECT * FROM dm_cook_food WHERE isDel = 0 AND canteenId = :canteenId AND foodId = :foodId AND cookMode = :cookMode")
|
||||
suspend fun getCookFoodById(canteenId: String, foodId: String, cookMode: Int): CookFoodEntity?
|
||||
@Query("SELECT * FROM dm_cook_food WHERE isDel = 0 AND canteenId = :canteenId AND foodId = :foodId AND cookMode = :cookMode AND dinnerType = :dinnerType")
|
||||
suspend fun getCookFoodById(canteenId: String, foodId: String, cookMode: Int, dinnerType: String): CookFoodEntity?
|
||||
|
||||
@Query("SELECT * FROM dm_cook_food WHERE isDel = 0 AND canteenId = :canteenId AND cookMode = :cookMode AND dinnerType = :dinnerType ORDER BY createTime DESC")
|
||||
suspend fun getCookFoodList(canteenId: String, cookMode: Int, dinnerType: String): MutableList<CookFoodEntity>?
|
||||
@@ -25,6 +27,35 @@ interface CookFoodDao {
|
||||
@Query("SELECT count(1) FROM dm_cook_food WHERE isDel = 0 AND canteenId = :canteenId AND cookMode = :cookMode")
|
||||
suspend fun countCookFood(canteenId: String, cookMode: Int): Int
|
||||
|
||||
@Query("DELETE FROM dm_cook_food WHERE canteenId = :canteenId AND foodId = :foodId AND cookMode = :cookMode")
|
||||
suspend fun deleteCookFood(canteenId: String, foodId: String, cookMode: Int)
|
||||
// @Query("DELETE FROM dm_cook_food WHERE canteenId = :canteenId AND foodId = :foodId AND cookMode = :cookMode")
|
||||
@Query("UPDATE dm_cook_food SET isDel = 1 WHERE isDel = 0 AND canteenId = :canteenId AND foodId = :foodId AND cookMode = :cookMode AND dinnerType = :dinnerType")
|
||||
suspend fun deleteCookFood(canteenId: String, foodId: String, cookMode: Int, dinnerType: String)
|
||||
|
||||
/** 接口提交成功后逻辑删除菜品,同时把 submitState 置 1 以便在数据库审计中区分手动删除 */
|
||||
@Query("UPDATE dm_cook_food SET isDel = 1, submitState = 1 WHERE isDel = 0 AND canteenId = :canteenId AND foodId = :foodId AND cookMode = :cookMode AND dinnerType = :dinnerType")
|
||||
suspend fun markSubmittedAndDelete(canteenId: String, foodId: String, cookMode: Int, dinnerType: String)
|
||||
|
||||
/** 查询全部菜品记录(含已删除),用于数据库调试查看 */
|
||||
@Query("SELECT * FROM dm_cook_food ORDER BY createTime DESC")
|
||||
suspend fun getAllCookFood(): MutableList<CookFoodEntity>
|
||||
|
||||
/** 分页查询菜品记录,showDel=true 时包含已删除记录 */
|
||||
@Query("SELECT * FROM dm_cook_food WHERE (:showDel = 1 OR isDel = 0) ORDER BY createTime DESC LIMIT :limit OFFSET :offset")
|
||||
suspend fun getCookFoodPaged(showDel: Int, limit: Int, offset: Int): List<CookFoodEntity>
|
||||
|
||||
/** 统计菜品记录总数,showDel=true 时包含已删除记录 */
|
||||
@Query("SELECT COUNT(*) FROM dm_cook_food WHERE (:showDel = 1 OR isDel = 0)")
|
||||
suspend fun countCookFoodAll(showDel: Int): Int
|
||||
|
||||
/** 物理清空全表,用于清除测试数据 */
|
||||
@Query("DELETE FROM dm_cook_food")
|
||||
suspend fun deleteAll()
|
||||
|
||||
/** 动态条件分页查询菜品记录,由 ViewModel 构建 SQL */
|
||||
@RawQuery
|
||||
suspend fun queryPagedFiltered(query: SupportSQLiteQuery): List<CookFoodEntity>
|
||||
|
||||
/** 动态条件统计菜品记录总数,由 ViewModel 构建 SQL */
|
||||
@RawQuery
|
||||
suspend fun countFiltered(query: SupportSQLiteQuery): Int
|
||||
}
|
||||
|
||||
@@ -4,8 +4,10 @@ import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.RawQuery
|
||||
import androidx.room.Update
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import androidx.sqlite.db.SupportSQLiteQuery
|
||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||
|
||||
@Dao
|
||||
interface CookFoodGoodsDao {
|
||||
@@ -25,6 +27,35 @@ interface CookFoodGoodsDao {
|
||||
@Query("SELECT * FROM dm_cook_food_goods WHERE isDel = 0 AND foodId = :foodId AND materialType = :materialType")
|
||||
suspend fun getCookFoodGoodsListByType(foodId: String, materialType: Int): MutableList<CookFoodGoodsEntity>
|
||||
|
||||
@Query("DELETE FROM dm_cook_food_goods WHERE pid = :pid AND foodId = :foodId")
|
||||
// @Query("DELETE FROM dm_cook_food_goods WHERE pid = :pid AND foodId = :foodId")
|
||||
@Query("UPDATE dm_cook_food_goods SET isDel = 1 WHERE isDel = 0 AND pid = :pid AND foodId = :foodId")
|
||||
suspend fun deleteCookFoodGoodsList(pid: Long, foodId: String)
|
||||
|
||||
/** 仅逻辑删除调料行(materialType = 3),主辅材不动,用于 cook 时只重建调料部分 */
|
||||
@Query("UPDATE dm_cook_food_goods SET isDel = 1 WHERE isDel = 0 AND pid = :pid AND foodId = :foodId AND materialType = 3")
|
||||
suspend fun deleteSeasoningOnly(pid: Long, foodId: String)
|
||||
|
||||
/** 查询全部食材记录(含已删除),用于数据库调试查看 */
|
||||
@Query("SELECT * FROM dm_cook_food_goods ORDER BY createTime DESC")
|
||||
suspend fun getAllCookFoodGoods(): MutableList<CookFoodGoodsEntity>
|
||||
|
||||
/** 分页查询食材记录,showDel=true 时包含已删除记录 */
|
||||
@Query("SELECT * FROM dm_cook_food_goods WHERE (:showDel = 1 OR isDel = 0) ORDER BY createTime DESC LIMIT :limit OFFSET :offset")
|
||||
suspend fun getCookFoodGoodsPaged(showDel: Int, limit: Int, offset: Int): List<CookFoodGoodsEntity>
|
||||
|
||||
/** 统计食材记录总数,showDel=true 时包含已删除记录 */
|
||||
@Query("SELECT COUNT(*) FROM dm_cook_food_goods WHERE (:showDel = 1 OR isDel = 0)")
|
||||
suspend fun countCookFoodGoodsAll(showDel: Int): Int
|
||||
|
||||
/** 物理清空全表,用于清除测试数据 */
|
||||
@Query("DELETE FROM dm_cook_food_goods")
|
||||
suspend fun deleteAll()
|
||||
|
||||
/** 动态条件分页查询食材记录,由 ViewModel 构建 SQL */
|
||||
@RawQuery
|
||||
suspend fun queryPagedFiltered(query: SupportSQLiteQuery): List<CookFoodGoodsEntity>
|
||||
|
||||
/** 动态条件统计食材记录总数,由 ViewModel 构建 SQL */
|
||||
@RawQuery
|
||||
suspend fun countFiltered(query: SupportSQLiteQuery): Int
|
||||
}
|
||||
|
||||
@@ -4,8 +4,10 @@ import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.RawQuery
|
||||
import androidx.room.Update
|
||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
import androidx.sqlite.db.SupportSQLiteQuery
|
||||
import com.shuwei.dish.match.db.entity.SeasoningEntity
|
||||
|
||||
@Dao
|
||||
interface SeasoningDao {
|
||||
@@ -26,7 +28,7 @@ interface SeasoningDao {
|
||||
suspend fun getSeasoningBySort(sort: Int): MutableList<SeasoningEntity>?
|
||||
|
||||
@Query("SELECT * FROM dm_seasoning WHERE isDel = 0 AND goodsId = :goodsId")
|
||||
suspend fun getSeasoningByGoodsId(goodsId: Int): SeasoningEntity?
|
||||
suspend fun getSeasoningByGoodsId(goodsId: String): SeasoningEntity?
|
||||
|
||||
@Query("SELECT * FROM dm_seasoning WHERE isDel = 0 AND goodsId != -1 AND goodsName != '' ORDER BY sort ASC")
|
||||
fun getAllStream(): MutableList<SeasoningEntity>
|
||||
@@ -34,9 +36,35 @@ interface SeasoningDao {
|
||||
@Query("SELECT * FROM dm_seasoning WHERE isDel = 0 AND goodsName LIKE '%' || :query || '%'")
|
||||
suspend fun search(query: String): MutableList<SeasoningEntity>
|
||||
|
||||
@Query("DELETE FROM dm_seasoning WHERE isDel = 0 AND sort = :sort")
|
||||
// @Query("DELETE FROM dm_seasoning WHERE isDel = 0 AND sort = :sort")
|
||||
@Query("UPDATE dm_seasoning SET isDel = 1 WHERE isDel = 0 AND sort = :sort")
|
||||
suspend fun deleteSeasoningBySort(sort: Int): Int
|
||||
|
||||
@Query("DELETE FROM dm_seasoning WHERE isDel = 0")
|
||||
// @Query("DELETE FROM dm_seasoning WHERE isDel = 0")
|
||||
@Query("UPDATE dm_seasoning SET isDel = 1 WHERE isDel = 0")
|
||||
suspend fun clearAllSeasoning(): Int
|
||||
|
||||
/** 查询全部调料记录(含已删除),用于数据库调试查看 */
|
||||
@Query("SELECT * FROM dm_seasoning ORDER BY sort ASC")
|
||||
suspend fun getAllSeasoning(): MutableList<SeasoningEntity>
|
||||
|
||||
/** 分页查询调料记录,showDel=true 时包含已删除记录 */
|
||||
@Query("SELECT * FROM dm_seasoning WHERE (:showDel = 1 OR isDel = 0) ORDER BY sort ASC LIMIT :limit OFFSET :offset")
|
||||
suspend fun getSeasoningPaged(showDel: Int, limit: Int, offset: Int): List<SeasoningEntity>
|
||||
|
||||
/** 统计调料记录总数,showDel=true 时包含已删除记录 */
|
||||
@Query("SELECT COUNT(*) FROM dm_seasoning WHERE (:showDel = 1 OR isDel = 0)")
|
||||
suspend fun countSeasoningAll(showDel: Int): Int
|
||||
|
||||
/** 物理清空全表,用于清除测试数据(比 clearAllSeasoning 的逻辑删除更彻底) */
|
||||
@Query("DELETE FROM dm_seasoning")
|
||||
suspend fun deleteAll()
|
||||
|
||||
/** 动态条件分页查询调料记录,由 ViewModel 构建 SQL */
|
||||
@RawQuery
|
||||
suspend fun queryPagedFiltered(query: SupportSQLiteQuery): List<SeasoningEntity>
|
||||
|
||||
/** 动态条件统计调料记录总数,由 ViewModel 构建 SQL */
|
||||
@RawQuery
|
||||
suspend fun countFiltered(query: SupportSQLiteQuery): Int
|
||||
}
|
||||
|
||||
@@ -4,7 +4,9 @@ import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import com.shuwei.dish.match.entity.SeasoningSlotEntity
|
||||
import androidx.room.RawQuery
|
||||
import androidx.sqlite.db.SupportSQLiteQuery
|
||||
import com.shuwei.dish.match.db.entity.SeasoningSlotEntity
|
||||
|
||||
/**
|
||||
* 调料槽位配置 DAO
|
||||
@@ -38,6 +40,14 @@ interface SeasoningSlotDao {
|
||||
@Query("SELECT * FROM dm_seasoning_slot")
|
||||
suspend fun queryAll(): List<SeasoningSlotEntity>
|
||||
|
||||
/** 分页查询槽位记录(槽位表无 isDel,showDel 参数忽略) */
|
||||
@Query("SELECT * FROM dm_seasoning_slot ORDER BY deviceId ASC, address ASC LIMIT :limit OFFSET :offset")
|
||||
suspend fun getSlotPaged(limit: Int, offset: Int): List<SeasoningSlotEntity>
|
||||
|
||||
/** 统计槽位记录总数 */
|
||||
@Query("SELECT COUNT(*) FROM dm_seasoning_slot")
|
||||
suspend fun countSlotAll(): Int
|
||||
|
||||
/**
|
||||
* 删除指定设备的指定槽位配置
|
||||
* @param deviceId 目标设备 ID
|
||||
@@ -52,4 +62,16 @@ interface SeasoningSlotDao {
|
||||
*/
|
||||
@Query("DELETE FROM dm_seasoning_slot WHERE deviceId = :deviceId")
|
||||
suspend fun deleteAllByDeviceId(deviceId: String)
|
||||
|
||||
/** 物理清空全表,用于清除测试数据 */
|
||||
@Query("DELETE FROM dm_seasoning_slot")
|
||||
suspend fun deleteAll()
|
||||
|
||||
/** 动态条件分页查询槽位记录,由 ViewModel 构建 SQL */
|
||||
@RawQuery
|
||||
suspend fun queryPagedFiltered(query: SupportSQLiteQuery): List<SeasoningSlotEntity>
|
||||
|
||||
/** 动态条件统计槽位记录总数,由 ViewModel 构建 SQL */
|
||||
@RawQuery
|
||||
suspend fun countFiltered(query: SupportSQLiteQuery): Int
|
||||
}
|
||||
|
||||
+5
-3
@@ -1,4 +1,4 @@
|
||||
package com.shuwei.dish.match.entity
|
||||
package com.shuwei.dish.match.db.entity
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Ignore
|
||||
@@ -18,11 +18,13 @@ data class CookFoodEntity(
|
||||
//0-制作模式,1-采样模式,2-品控模式
|
||||
var cookMode:Int = 0,
|
||||
var isDel: Int = 0,
|
||||
/** 接口提交状态:0-未提交(本地草稿或手动删除),1-接口提交成功后删除 */
|
||||
var submitState: Int = 0,
|
||||
var createTime: String = DateTimeUtil.formatDateTime(LocalDateTime.now()),
|
||||
var dinnerType: String? = "0",
|
||||
) : BaseEntity {
|
||||
@Ignore
|
||||
var stFoodInfoConstituteList: MutableList<CookFoodGoodsEntity>? = null
|
||||
// @Ignore
|
||||
// var stFoodInfoConstituteList: MutableList<CookFoodGoodsEntity>? = null
|
||||
@Ignore
|
||||
var matchingConstituteInfoList: MutableList<CookFoodGoodsEntity>? = null
|
||||
@Ignore
|
||||
+30
-24
@@ -1,9 +1,9 @@
|
||||
package com.shuwei.dish.match.entity
|
||||
package com.shuwei.dish.match.db.entity
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Ignore
|
||||
import androidx.room.PrimaryKey
|
||||
import com.shuwei.dish.match.db.BaseEntity
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
import com.shuwei.dish.match.utils.DateTimeUtil
|
||||
import java.io.Serializable
|
||||
import java.time.LocalDateTime
|
||||
@@ -63,30 +63,36 @@ class CookFoodGoodsEntity(
|
||||
|
||||
var relateionType_dictText: String? = "",
|
||||
|
||||
var zjmCode: String? = "",
|
||||
|
||||
var materId: String? = "",
|
||||
|
||||
/** 物料编码 */
|
||||
var goodsCode: String? = "",
|
||||
|
||||
/** 净材种类 */
|
||||
var rawMaterialsType: String? = null,
|
||||
|
||||
var isDel: Int = 0,
|
||||
var createTime: String = DateTimeUtil.formatDateTime(LocalDateTime.now())
|
||||
) : BaseEntity, Serializable {
|
||||
constructor() : this(goodsId = "") // 必需的空构造,
|
||||
constructor() : this(goodsId = "") // 必需的空构造
|
||||
|
||||
@Ignore
|
||||
var isSetFinished: Boolean = false
|
||||
|
||||
@Ignore
|
||||
var isItemClicked: Boolean = false
|
||||
|
||||
@Ignore
|
||||
var isSamplingPage: Boolean = false
|
||||
|
||||
@Ignore
|
||||
var isNewDishType: Boolean = false
|
||||
|
||||
@Ignore
|
||||
var isClicked: Boolean = false
|
||||
|
||||
//true-原始数据,false-非原始数据
|
||||
@Ignore
|
||||
var isOriginalData: Boolean = true
|
||||
|
||||
@Ignore
|
||||
var foodScore: Int = -1
|
||||
/**
|
||||
* 转换为 GoodsItem,用于 UI 层(DishPartAdapter、PrepareFoodActivity 等)
|
||||
*/
|
||||
fun toGoodsItem(): GoodsItem = GoodsItem(
|
||||
goodsId = goodsId,
|
||||
goodsName = goodsName,
|
||||
popularName = popularName,
|
||||
zjmCode = zjmCode,
|
||||
materId = materId,
|
||||
materCode = goodsCode,
|
||||
materialType = materialType,
|
||||
useWeight = useWeight,
|
||||
relateionType = relateionType,
|
||||
allEdible = allEdible,
|
||||
goodsOrRelationCode = goodsOrRelationCode,
|
||||
rawMaterialsType = rawMaterialsType
|
||||
)
|
||||
}
|
||||
+11
-8
@@ -1,7 +1,6 @@
|
||||
package com.shuwei.dish.match.entity
|
||||
package com.shuwei.dish.match.db.entity
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Ignore
|
||||
import androidx.room.PrimaryKey
|
||||
import com.shuwei.dish.match.db.BaseEntity
|
||||
import com.shuwei.dish.match.utils.DateTimeUtil
|
||||
@@ -55,6 +54,16 @@ data class SeasoningEntity(
|
||||
|
||||
var relateionType_dictText: String? = "",
|
||||
|
||||
var zjmCode: String? = "",
|
||||
|
||||
var materId: String? = "",
|
||||
|
||||
/** 物料编码 */
|
||||
var goodsCode: String? = "",
|
||||
|
||||
/** 净材种类 */
|
||||
var rawMaterialsType: String? = null,
|
||||
|
||||
var sort: Int = 9999,
|
||||
/**
|
||||
* isDel表示数据是否已删除,1-已删除,为无效数据,0-正常使用,有效数据
|
||||
@@ -62,11 +71,5 @@ data class SeasoningEntity(
|
||||
var isDel: Int = 0,
|
||||
var createTime: String = DateTimeUtil.formatDateTime(LocalDateTime.now())
|
||||
) : BaseEntity {
|
||||
@Ignore
|
||||
var pageType: Int = 0
|
||||
|
||||
@Ignore
|
||||
var isClicked: Boolean = false
|
||||
|
||||
constructor() : this(goodsId = "") // 必需的空构造
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.shuwei.dish.match.entity
|
||||
package com.shuwei.dish.match.db.entity
|
||||
|
||||
import androidx.room.Entity
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.shuwei.dish.match.dialog
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Dialog
|
||||
import android.content.Context
|
||||
import android.graphics.drawable.ColorDrawable
|
||||
@@ -8,13 +7,13 @@ import android.os.Bundle
|
||||
import android.view.View
|
||||
import android.view.Window
|
||||
import android.widget.LinearLayout
|
||||
import androidx.annotation.StyleRes
|
||||
import android.widget.TextView
|
||||
import androidx.core.view.updateLayoutParams
|
||||
import com.shuwei.dish.match.base.DeviceRole
|
||||
import com.shuwei.dish.match.base.GlobalData
|
||||
import com.shuwei.dish.match.databinding.DialogCommonBinding
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import java.lang.ref.WeakReference
|
||||
import com.shuwei.dish.match.R
|
||||
|
||||
open class CommonDialog(
|
||||
context: Context
|
||||
@@ -27,10 +26,17 @@ open class CommonDialog(
|
||||
private var negativeText = "取消"
|
||||
private var positiveText = "确认"
|
||||
private var neutralText: String? = null
|
||||
private var singleText: String? = null
|
||||
private var negativeClick: (() -> Unit)? = null
|
||||
private var positiveClick: (() -> Unit)? = null
|
||||
// 返回 true 时关闭弹窗,返回 false 时保持弹窗显示(用于校验不通过的场景)
|
||||
private var positiveClick: (() -> Boolean)? = null
|
||||
private var neutralClick: (() -> Unit)? = null
|
||||
private var singleClick: (() -> Unit)? = null
|
||||
private var dismissCallback: (() -> Unit)? = null
|
||||
// 待添加到 llContent 的自定义 View,在 onCreate 后挂载
|
||||
private var pendingContentView: View? = null
|
||||
// pendingContentView 非空时对 tvContent 的灵活控制回调(可调整可见性、间距等)
|
||||
private var tvContentConfigurator: ((TextView) -> Unit)? = null
|
||||
|
||||
/** 设置标题,为空时隐藏 */
|
||||
fun setTitle(text: String): CommonDialog = apply { titleText = text }
|
||||
@@ -44,8 +50,17 @@ open class CommonDialog(
|
||||
negativeClick = onClick
|
||||
}
|
||||
|
||||
/** 设置右侧确认按钮文字及点击回调(3按钮模式下对应底部按钮) */
|
||||
/** 设置右侧确认按钮文字及点击回调(3按钮模式下对应底部按钮),点击后自动关闭弹窗 */
|
||||
fun setPositiveButton(text: String, onClick: (() -> Unit)? = null): CommonDialog = apply {
|
||||
positiveText = text
|
||||
positiveClick = onClick?.let { cb -> { cb(); true } }
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置右侧确认按钮文字及可拦截的点击回调
|
||||
* 回调返回 true 时关闭弹窗,返回 false 时保持弹窗显示(用于校验不通过的场景)
|
||||
*/
|
||||
fun setPositiveButtonInterceptable(text: String, onClick: () -> Boolean): CommonDialog = apply {
|
||||
positiveText = text
|
||||
positiveClick = onClick
|
||||
}
|
||||
@@ -56,11 +71,27 @@ open class CommonDialog(
|
||||
neutralClick = onClick
|
||||
}
|
||||
|
||||
/** 设置单按钮文字及点击回调,调用后自动切换为单按钮布局(优先级最高) */
|
||||
fun setSingleButton(text: String, onClick: (() -> Unit)? = null): CommonDialog = apply {
|
||||
singleText = text
|
||||
singleClick = onClick
|
||||
}
|
||||
|
||||
/** 设置弹窗消失回调 */
|
||||
fun setOnDismissCallback(callback: () -> Unit): CommonDialog = apply {
|
||||
dismissCallback = callback
|
||||
}
|
||||
|
||||
/**
|
||||
* 向弹窗自定义内容区域添加 View,调用后 llContent 自动显示
|
||||
* @param view 要嵌入的自定义布局(如单选列表)
|
||||
* @param tvContentConfig 可选回调,用于在 pendingContentView 非空时灵活控制 tvContent 的可见性及间距等属性
|
||||
*/
|
||||
fun addContentView(view: View, tvContentConfig: ((TextView) -> Unit)? = null): CommonDialog = apply {
|
||||
pendingContentView = view
|
||||
tvContentConfigurator = tvContentConfig
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
requestWindowFeature(Window.FEATURE_NO_TITLE)
|
||||
@@ -68,19 +99,19 @@ open class CommonDialog(
|
||||
setContentView(binding.root)
|
||||
// 弹窗不允许点击外部关闭
|
||||
setCancelable(false)
|
||||
val isMaster = GlobalData.deviceRole == DeviceRole.MASTER
|
||||
window?.run {
|
||||
val screenWidth = context.resources.displayMetrics.widthPixels
|
||||
val isMaster = GlobalData.deviceRole == DeviceRole.MASTER
|
||||
attributes = attributes.apply {
|
||||
width = if (isMaster) (screenWidth * 0.72f).toInt() else (screenWidth * 0.60f).toInt()
|
||||
}
|
||||
// 透明背景,让 shape_dialog_bg 的阴影层正常显示
|
||||
setBackgroundDrawable(ColorDrawable())
|
||||
// 应用缩放+淡入淡出动画
|
||||
setWindowAnimations(com.shuwei.dish.match.R.style.CommonDialogAnimation)
|
||||
setWindowAnimations(R.style.CommonDialogAnimation)
|
||||
}
|
||||
// 主/从设备边距微调:主设备内容区域更大,适当增加上下留白
|
||||
val verticalMargin = if (GlobalData.deviceRole == DeviceRole.MASTER) 48.dp else 36.dp
|
||||
val verticalMargin = if (isMaster) 48.dp else 36.dp
|
||||
binding.tvTitle.updateLayoutParams<LinearLayout.LayoutParams> { topMargin = verticalMargin }
|
||||
binding.tvContent.updateLayoutParams<LinearLayout.LayoutParams> { bottomMargin = verticalMargin }
|
||||
|
||||
@@ -90,8 +121,8 @@ open class CommonDialog(
|
||||
dismiss()
|
||||
}
|
||||
binding.btnRight.setOnClickListener {
|
||||
positiveClick?.invoke()
|
||||
dismiss()
|
||||
// 回调返回 false 时阻止关闭,null 或 true 时正常关闭
|
||||
if (positiveClick?.invoke() != false) dismiss()
|
||||
}
|
||||
|
||||
// 3按钮点击事件(negativeClick/positiveClick 与2按钮模式共用)
|
||||
@@ -104,11 +135,24 @@ open class CommonDialog(
|
||||
dismiss()
|
||||
}
|
||||
binding.btnBottom.setOnClickListener {
|
||||
positiveClick?.invoke()
|
||||
if (positiveClick?.invoke() != false) dismiss()
|
||||
}
|
||||
|
||||
// 单按钮点击事件
|
||||
binding.btnSingle.setOnClickListener {
|
||||
singleClick?.invoke()
|
||||
dismiss()
|
||||
}
|
||||
|
||||
setOnDismissListener { dismissCallback?.invoke() }
|
||||
|
||||
// 挂载自定义内容 View,并执行 tvContent 的灵活控制回调
|
||||
pendingContentView?.let {
|
||||
binding.llContent.removeAllViews()
|
||||
binding.llContent.addView(it)
|
||||
binding.llContent.visibility = View.VISIBLE
|
||||
tvContentConfigurator?.invoke(binding.tvContent)
|
||||
}
|
||||
}
|
||||
|
||||
override fun show() {
|
||||
@@ -119,10 +163,15 @@ open class CommonDialog(
|
||||
binding.tvContent.visibility = if (contentText.isNullOrEmpty()) View.GONE else View.VISIBLE
|
||||
|
||||
val hasThreeButtons = !neutralText.isNullOrEmpty()
|
||||
binding.layoutButtonsHorizontal.visibility = if (hasThreeButtons) View.GONE else View.VISIBLE
|
||||
val hasSingleButton = !singleText.isNullOrEmpty()
|
||||
binding.btnSingle.visibility = if (hasSingleButton) View.VISIBLE else View.GONE
|
||||
binding.layoutButtonsHorizontal.visibility = if (!hasSingleButton && !hasThreeButtons) View.VISIBLE else View.GONE
|
||||
binding.layoutButtonsVertical.visibility = if (hasThreeButtons) View.VISIBLE else View.GONE
|
||||
|
||||
if (hasThreeButtons) {
|
||||
if (hasSingleButton) {
|
||||
// 单按钮模式
|
||||
binding.btnSingle.text = singleText
|
||||
} else if (hasThreeButtons) {
|
||||
// 3按钮模式:顶部=取消,中间=中立,底部=确认
|
||||
binding.btnTop.text = negativeText
|
||||
binding.btnMiddle.text = neutralText
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.shuwei.dish.match.dialog
|
||||
|
||||
import android.content.Context
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import com.shuwei.dish.match.base.GlobalData
|
||||
import com.shuwei.dish.match.databinding.DialogEnvSwitchContentBinding
|
||||
import com.shuwei.dish.match.utils.SpTool
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
|
||||
/**
|
||||
* 环境切换弹窗
|
||||
*
|
||||
* 基于 [CommonDialog] 实现,通过 addContentView 注入 RadioGroup 内容区。
|
||||
* 提供 TEST / UAT / PROD 三套环境的切换功能,初始化时自动根据
|
||||
* [GlobalData.appBaseUrl] 选中当前环境,确认后更新 [GlobalData.appBaseUrl]
|
||||
* 并通过 [onEnvChanged] 回调通知外部。
|
||||
*
|
||||
* @param context 上下文
|
||||
* @param onEnvChanged 确认切换后的回调,参数为新的 baseUrl
|
||||
*/
|
||||
class EnvSwitchDialog(
|
||||
context: Context,
|
||||
private val onEnvChanged: (newBaseUrl: String) -> Unit = {}
|
||||
) {
|
||||
|
||||
private val contentBinding = DialogEnvSwitchContentBinding.inflate(LayoutInflater.from(context))
|
||||
|
||||
private val dialog = CommonDialog(context)
|
||||
.setTitle("切换环境")
|
||||
.addContentView(contentBinding.root) { tvContent ->
|
||||
// 内容区已由 RadioGroup 承载,隐藏默认文本
|
||||
tvContent.visibility = View.GONE
|
||||
}
|
||||
.setNegativeButton("取消")
|
||||
.setPositiveButtonInterceptable("确认") {
|
||||
// 未选中任何选项时提示并阻止关闭
|
||||
if (contentBinding.rgEnv.checkedRadioButtonId == -1) {
|
||||
context.toast("请选择环境")
|
||||
return@setPositiveButtonInterceptable false
|
||||
}
|
||||
val newUrl = when (contentBinding.rgEnv.checkedRadioButtonId) {
|
||||
contentBinding.rbTest.id -> GlobalData.TEST_BASE_URL
|
||||
contentBinding.rbUat.id -> GlobalData.UAT_BASE_URL
|
||||
contentBinding.rbProd.id -> GlobalData.PROD_BASE_URL
|
||||
else -> return@setPositiveButtonInterceptable false
|
||||
}
|
||||
GlobalData.appBaseUrl = newUrl
|
||||
SpTool.baseUrl = newUrl
|
||||
onEnvChanged(newUrl)
|
||||
true
|
||||
}
|
||||
|
||||
init {
|
||||
// 根据当前 appBaseUrl 预选对应 RadioButton
|
||||
when (GlobalData.appBaseUrl) {
|
||||
GlobalData.TEST_BASE_URL -> contentBinding.rbTest.isChecked = true
|
||||
GlobalData.UAT_BASE_URL -> contentBinding.rbUat.isChecked = true
|
||||
GlobalData.PROD_BASE_URL -> contentBinding.rbProd.isChecked = true
|
||||
}
|
||||
}
|
||||
|
||||
/** 显示弹窗 */
|
||||
fun show() = dialog.show()
|
||||
|
||||
/** 关闭弹窗 */
|
||||
fun dismiss() = dialog.dismiss()
|
||||
}
|
||||
@@ -1,62 +1,62 @@
|
||||
package com.shuwei.dish.match.dialog
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.LayoutInflater
|
||||
import androidx.recyclerview.widget.GridLayoutManager
|
||||
import com.google.android.material.bottomsheet.BottomSheetDialog
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.GoodsInfoSearchAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.databinding.DialogFoodRecognizeBinding
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
|
||||
/**
|
||||
* 菜品识别结果弹窗,继承 BottomSheetDialog 确保只初始化一次
|
||||
* @param activity 宿主 Activity
|
||||
* @param onDismiss 弹窗关闭时的额外回调(可选)
|
||||
* @param onItemSelected 用户点击某一菜品时的回调
|
||||
*/
|
||||
class FoodRecognizeDialog(
|
||||
private val activity: BaseActivity,
|
||||
private val onDismiss: (() -> Unit)? = null,
|
||||
private val onItemSelected: (item: CookFoodGoodsEntity) -> Unit
|
||||
) : BottomSheetDialog(activity, R.style.BottomSheet) {
|
||||
|
||||
private val binding = DialogFoodRecognizeBinding.inflate(LayoutInflater.from(activity))
|
||||
private val list = mutableListOf<CookFoodGoodsEntity>()
|
||||
private val adapter = GoodsInfoSearchAdapter(list).apply {
|
||||
setOnItemClickListener { _, _, position ->
|
||||
list[position].isClicked = true
|
||||
notifyItemChanged(position)
|
||||
Handler(Looper.getMainLooper()).postDelayed({
|
||||
onItemSelected(list[position])
|
||||
dismiss()
|
||||
}, 300)
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
setContentView(binding.root)
|
||||
setCancelable(true)
|
||||
behavior.skipCollapsed = false
|
||||
setOnDismissListener { activity.hideStatusBar(); onDismiss?.invoke() }
|
||||
binding.recyclerView.run {
|
||||
layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
||||
adapter = this@FoodRecognizeDialog.adapter
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载识别结果数据并显示弹窗
|
||||
* @param items 识别到的菜品列表
|
||||
*/
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
fun loadData(items: List<CookFoodGoodsEntity>) {
|
||||
list.clear()
|
||||
list.addAll(items)
|
||||
adapter.notifyDataSetChanged()
|
||||
if (!isShowing) show()
|
||||
}
|
||||
}
|
||||
//package com.shuwei.dish.match.dialog
|
||||
//
|
||||
//import android.annotation.SuppressLint
|
||||
//import android.os.Handler
|
||||
//import android.os.Looper
|
||||
//import android.view.LayoutInflater
|
||||
//import androidx.recyclerview.widget.GridLayoutManager
|
||||
//import com.google.android.material.bottomsheet.BottomSheetDialog
|
||||
//import com.shuwei.dish.match.R
|
||||
//import com.shuwei.dish.match.adapter.FoodAdapter
|
||||
//import com.shuwei.dish.match.base.BaseActivity
|
||||
//import com.shuwei.dish.match.databinding.DialogFoodRecognizeBinding
|
||||
//import com.shuwei.dish.match.entity.GoodsItem
|
||||
//
|
||||
///**
|
||||
// * 菜品识别结果弹窗,继承 BottomSheetDialog 确保只初始化一次
|
||||
// * @param activity 宿主 Activity
|
||||
// * @param onDismiss 弹窗关闭时的额外回调(可选)
|
||||
// * @param onItemSelected 用户点击某一菜品时的回调
|
||||
// */
|
||||
//class FoodRecognizeDialog(
|
||||
// private val activity: BaseActivity,
|
||||
// private val onDismiss: (() -> Unit)? = null,
|
||||
// private val onItemSelected: (item: GoodsItem) -> Unit
|
||||
//) : BottomSheetDialog(activity, R.style.BottomSheet) {
|
||||
//
|
||||
// private val binding = DialogFoodRecognizeBinding.inflate(LayoutInflater.from(activity))
|
||||
// private val list = mutableListOf<GoodsItem>()
|
||||
// private val adapter = FoodAdapter(list).apply {
|
||||
// setOnItemClickListener { _, _, position ->
|
||||
// list[position].isClicked = true
|
||||
// notifyItemChanged(position)
|
||||
// Handler(Looper.getMainLooper()).postDelayed({
|
||||
// onItemSelected(list[position])
|
||||
// dismiss()
|
||||
// }, 300)
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// init {
|
||||
// setContentView(binding.root)
|
||||
// setCancelable(true)
|
||||
// behavior.skipCollapsed = false
|
||||
// setOnDismissListener { activity.hideStatusBar(); onDismiss?.invoke() }
|
||||
// binding.recyclerView.run {
|
||||
// layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
||||
// adapter = this@FoodRecognizeDialog.adapter
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 加载识别结果数据并显示弹窗
|
||||
// * @param items 识别到的菜品列表
|
||||
// */
|
||||
// @SuppressLint("NotifyDataSetChanged")
|
||||
// fun loadData(items: List<GoodsItem>) {
|
||||
// list.clear()
|
||||
// list.addAll(items)
|
||||
// adapter.notifyDataSetChanged()
|
||||
// if (!isShowing) show()
|
||||
// }
|
||||
//}
|
||||
|
||||
@@ -1,30 +1,32 @@
|
||||
package com.shuwei.dish.match.dialog
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.graphics.Rect
|
||||
import android.text.Editable
|
||||
import android.view.KeyboardShortcutGroup
|
||||
import android.view.LayoutInflater
|
||||
import android.view.Menu
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import androidx.core.view.isEmpty
|
||||
import android.view.Window
|
||||
import android.widget.FrameLayout
|
||||
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.RecyclerView
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import com.chad.library.adapter4.util.setOnDebouncedItemClick
|
||||
import com.google.android.material.bottomsheet.BottomSheetDialog
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.GoodsInfoSearchAdapter
|
||||
import com.shuwei.dish.match.adapter.FoodAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.databinding.DialogFoodSearchBinding
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
import com.shuwei.dish.match.model.MaterSearchItem
|
||||
import com.shuwei.dish.match.net.UiState
|
||||
import com.shuwei.dish.match.utils.KeyboardUtil
|
||||
import com.shuwei.dish.match.utils.showRawMaterialsDialog
|
||||
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import kotlinx.coroutines.flow.collect
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
@@ -36,37 +38,47 @@ import kotlinx.coroutines.launch
|
||||
class FoodSearchDialog(
|
||||
private val activity: BaseActivity,
|
||||
private val defGoodsName: String? = null,
|
||||
private val onItemSelected: (item: CookFoodGoodsEntity) -> Unit
|
||||
private val onItemSelected: (item: GoodsItem) -> Unit
|
||||
) : BottomSheetDialog(activity, R.style.BottomSheet) {
|
||||
|
||||
private val binding = DialogFoodSearchBinding.inflate(LayoutInflater.from(activity))
|
||||
private val list = mutableListOf<CookFoodGoodsEntity>().apply {
|
||||
add(CookFoodGoodsEntity(goodsId = "200001", goodsName = "土豆丝"))
|
||||
add(CookFoodGoodsEntity(goodsId = "200002", goodsName = "土豆片"))
|
||||
add(CookFoodGoodsEntity(goodsId = "200003", goodsName = "土豆丁"))
|
||||
add(CookFoodGoodsEntity(goodsId = "200004", goodsName = "胡萝卜丝"))
|
||||
add(CookFoodGoodsEntity(goodsId = "200005", goodsName = "胡萝卜片"))
|
||||
add(CookFoodGoodsEntity(goodsId = "200006", goodsName = "胡萝卜丁"))
|
||||
add(CookFoodGoodsEntity(goodsId = "200007", goodsName = "黄瓜丝"))
|
||||
add(CookFoodGoodsEntity(goodsId = "200008", goodsName = "黄瓜片"))
|
||||
add(CookFoodGoodsEntity(goodsId = "200009", goodsName = "黄瓜丁"))
|
||||
add(CookFoodGoodsEntity(goodsId = "200010", goodsName = "洋葱丝"))
|
||||
add(CookFoodGoodsEntity(goodsId = "200011", goodsName = "洋葱丁"))
|
||||
companion object {
|
||||
const val PAGE_SIZE = 50
|
||||
}
|
||||
private val adapter = GoodsInfoSearchAdapter(list).apply {
|
||||
setOnItemClickListener { _, _, position ->
|
||||
list[position].isClicked = true
|
||||
|
||||
private val binding = DialogFoodSearchBinding.inflate(LayoutInflater.from(activity))
|
||||
private val list = mutableListOf<GoodsItem>()
|
||||
|
||||
private val adapter = FoodAdapter(list).apply {
|
||||
isStateViewEnable = true
|
||||
setOnDebouncedItemClick { _, _, position ->
|
||||
val item = list.getOrNull(position) ?: return@setOnDebouncedItemClick
|
||||
item.isClicked = true
|
||||
notifyItemChanged(position)
|
||||
binding.root.postDelayed({
|
||||
onItemSelected(list[position])
|
||||
dismiss()
|
||||
}, 300)
|
||||
// mater-search 不返回净材种类,rawMaterialsTypes 为空时直接选中返回,避免卡在净材弹窗
|
||||
if (item.rawMaterialsTypes.isNullOrBlank()) {
|
||||
binding.root.postDelayed({
|
||||
onItemSelected(item)
|
||||
dismiss()
|
||||
}, 300)
|
||||
return@setOnDebouncedItemClick
|
||||
}
|
||||
// 有净材种类时弹出单选弹窗,确认后再回调并关闭弹窗
|
||||
showRawMaterialsDialog(
|
||||
context = activity,
|
||||
types = item.rawMaterialsTypes,
|
||||
checkedType = item.rawMaterialsType
|
||||
) { selectedType ->
|
||||
item.rawMaterialsType = selectedType
|
||||
binding.root.postDelayed({
|
||||
onItemSelected(item)
|
||||
dismiss()
|
||||
}, 300)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var goodsName: String? = null
|
||||
private var pageNo = 1
|
||||
private val pageSize = 50
|
||||
|
||||
init {
|
||||
setContentView(binding.root)
|
||||
@@ -91,22 +103,22 @@ class FoodSearchDialog(
|
||||
addOnActionSearchListener { searchGoods(this) }
|
||||
}
|
||||
|
||||
// RecyclerView 初始化及滑动冲突处理
|
||||
// RecyclerView 初始化
|
||||
binding.recyclerView.run {
|
||||
layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
||||
adapter = this@FoodSearchDialog.adapter
|
||||
addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
||||
override fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) {
|
||||
super.onScrolled(rv, dx, dy)
|
||||
// 解决 RecyclerView 与 SmartRefreshLayout 滑动冲突
|
||||
val topRowVerticalPosition = if (rv.isEmpty()) 0 else rv.getChildAt(0).top
|
||||
binding.refreshLayout.setNestedScrollingEnabled(topRowVerticalPosition >= 0)
|
||||
}
|
||||
})
|
||||
// addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
||||
// override fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) {
|
||||
// super.onScrolled(rv, dx, dy)
|
||||
// // 解决 RecyclerView 与 SmartRefreshLayout 滑动冲突
|
||||
// val topRowVerticalPosition = if (rv.isEmpty()) 0 else rv.getChildAt(0).top
|
||||
// binding.refreshLayout.setNestedScrollingEnabled(topRowVerticalPosition >= 0)
|
||||
// }
|
||||
// })
|
||||
}
|
||||
|
||||
binding.refreshLayout.run {
|
||||
setEnableRefresh(false)
|
||||
setEnableRefresh(true)
|
||||
setEnableLoadMore(false)
|
||||
setOnRefreshListener { pageNo = 1; getGoodsList() }
|
||||
setOnLoadMoreListener { getGoodsList() }
|
||||
@@ -115,31 +127,49 @@ class FoodSearchDialog(
|
||||
binding.ivSearch.setOnClickListener { searchGoods(it) }
|
||||
binding.root.setOnClickListener { KeyboardUtil.hideKeyboard(it) }
|
||||
|
||||
initObserver()
|
||||
|
||||
// 若有默认食材名称,自动填充并触发搜索
|
||||
if (!defGoodsName.isNullOrBlank()) {
|
||||
binding.etSheetInput.setText(defGoodsName)
|
||||
searchGoods(binding.etSheetInput)
|
||||
}
|
||||
//if (!defGoodsName.isNullOrBlank()) {
|
||||
//binding.etSheetInput.setText(defGoodsName)
|
||||
pageNo = 1
|
||||
getGoodsList()
|
||||
KeyboardUtil.hideKeyboard(binding.root)
|
||||
//}
|
||||
}
|
||||
|
||||
/**
|
||||
* 收集 goodsListState,统一处理 Loading / Success / Error 状态
|
||||
*/
|
||||
private fun initObserver() {
|
||||
activity.lifecycleScope.launch {
|
||||
activity.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
activity.netViewModel.goodsListState.collect { state ->
|
||||
when (state) {
|
||||
is UiState.Success -> loadGoodsList(state.data)
|
||||
is UiState.Error -> {
|
||||
activity.toast(state.msg)
|
||||
finishRefresh()
|
||||
}
|
||||
else -> {}
|
||||
/** 弹窗显示时在 Window.Callback 层提前拦截触摸,解决 BottomSheet 拖拽与列表滑动的手势冲突 */
|
||||
override fun show() {
|
||||
super.show()
|
||||
// Window.Callback.dispatchTouchEvent 在整个 View 树的 onInterceptTouchEvent 之前执行,
|
||||
// 是最早能感知触摸的时机。在此处判断触摸点位置来控制 behavior.isDraggable,
|
||||
// 从而确保 BottomSheetBehavior 在 CoordinatorLayout.onInterceptTouchEvent 时
|
||||
// 已经是禁用状态,不会拦截列表区域的滑动手势。
|
||||
val originalCallback = window?.callback ?: return
|
||||
window?.callback = object : Window.Callback by originalCallback {
|
||||
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
val rect = Rect()
|
||||
binding.refreshLayout.getGlobalVisibleRect(rect)
|
||||
// 触摸点落在列表区域内则禁止 BottomSheet 拖拽
|
||||
behavior.isDraggable = !rect.contains(event.rawX.toInt(), event.rawY.toInt())
|
||||
}
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
behavior.isDraggable = true
|
||||
}
|
||||
}
|
||||
return originalCallback.dispatchTouchEvent(event)
|
||||
}
|
||||
|
||||
override fun onPointerCaptureChanged(hasCapture: Boolean) {
|
||||
originalCallback.onPointerCaptureChanged(hasCapture)
|
||||
}
|
||||
|
||||
override fun onProvideKeyboardShortcuts(
|
||||
data: List<KeyboardShortcutGroup?>?,
|
||||
menu: Menu?,
|
||||
deviceId: Int
|
||||
) {
|
||||
originalCallback.onProvideKeyboardShortcuts(data, menu, deviceId)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -158,41 +188,104 @@ class FoodSearchDialog(
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求食材列表
|
||||
* 请求食材列表(采样模式新配比秤接口 mater-search,回调版本)
|
||||
*/
|
||||
private fun getGoodsList() {
|
||||
val param = mutableMapOf<String, Any>(
|
||||
"goodsType" to "0",
|
||||
"placeId" to BaseApp.canteenId,
|
||||
"pageNum" to pageNo,
|
||||
"pageSize" to pageSize
|
||||
activity.netViewModel.materSearch(
|
||||
keyword = goodsName.takeUnless { it.isNullOrBlank() },
|
||||
pageNum = pageNo,
|
||||
pageSize = PAGE_SIZE,
|
||||
onResult = { state ->
|
||||
when (state) {
|
||||
is UiState.Success -> loadGoodsList(state.data)
|
||||
is UiState.Error -> {
|
||||
activity.toast(state.msg)
|
||||
finishRefresh()
|
||||
if (pageNo == 1) loadEmptyView()
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
)
|
||||
if (!goodsName.isNullOrBlank()) {
|
||||
param["goodsName"] = goodsName!!
|
||||
}
|
||||
activity.netViewModel.queryGoodsList(param)
|
||||
}
|
||||
|
||||
/**
|
||||
* 将返回数据填充到列表
|
||||
*/
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun loadGoodsList(records: MutableList<CookFoodGoodsEntity>?) {
|
||||
private fun loadGoodsList(records: List<MaterSearchItem>?) {
|
||||
finishRefresh()
|
||||
if (records.isNullOrEmpty()) {
|
||||
activity.toast("暂未搜索到食材信息")
|
||||
if (pageNo == 1) {
|
||||
loadEmptyView()
|
||||
}
|
||||
return
|
||||
}
|
||||
// 仅当当前不是 GridLayoutManager 时才重新赋值(空态切回网格时)
|
||||
binding.recyclerView.run {
|
||||
if (layoutManager !is GridLayoutManager) {
|
||||
layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
||||
}
|
||||
}
|
||||
if (pageNo == 1) list.clear()
|
||||
list.addAll(records)
|
||||
// mater-search 不返回净材种类,rawMaterialsTypes 保持 null,点击时直接选中返回
|
||||
val goodsItems = records.map { it.toGoodsItem() }
|
||||
list.addAll(goodsItems)
|
||||
adapter.notifyDataSetChanged()
|
||||
val isLoadMoreEnable = records.size >= pageSize
|
||||
val isLoadMoreEnable = records.size >= PAGE_SIZE
|
||||
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
|
||||
if (isLoadMoreEnable) pageNo++
|
||||
}
|
||||
|
||||
/**
|
||||
* MaterSearchItem → GoodsItem 映射
|
||||
* id 即食材id,同时作为 goodsId 和 materId(提交 sample/save 时使用)
|
||||
*/
|
||||
private fun MaterSearchItem.toGoodsItem() = GoodsItem(
|
||||
goodsId = id,
|
||||
materId = id,
|
||||
goodsName = materName,
|
||||
materCode = materCode,
|
||||
popularName = alias
|
||||
)
|
||||
|
||||
private fun finishRefresh() {
|
||||
if (pageNo == 1) binding.refreshLayout.finishRefresh()
|
||||
else binding.refreshLayout.finishLoadMore()
|
||||
}
|
||||
|
||||
private var emptyViewBinding: LayoutEmptyViewBinding? = null
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun loadEmptyView() {
|
||||
try {
|
||||
binding.refreshLayout.setEnableRefresh(true)
|
||||
binding.refreshLayout.setEnableLoadMore(false)
|
||||
list.clear()
|
||||
adapter.notifyDataSetChanged()
|
||||
if (emptyViewBinding == null) {
|
||||
emptyViewBinding = LayoutEmptyViewBinding.inflate(
|
||||
LayoutInflater.from(activity),
|
||||
binding.recyclerView,
|
||||
false
|
||||
)
|
||||
}
|
||||
emptyViewBinding?.let {
|
||||
it.tvContent.text = "暂无数据"
|
||||
it.tvSubContent.text = "未查询到食材信息,请联系管理员添加"
|
||||
// it.root.setOnClickListener { loadGoodsList(buildMockGoodsList().toMutableList()) }
|
||||
it.root.layoutParams = FrameLayout.LayoutParams(
|
||||
FrameLayout.LayoutParams.MATCH_PARENT,
|
||||
FrameLayout.LayoutParams.MATCH_PARENT
|
||||
)
|
||||
binding.recyclerView.layoutManager = LinearLayoutManager(activity)
|
||||
binding.recyclerView.post {
|
||||
it.root.minimumHeight = binding.recyclerView.height
|
||||
adapter.stateView = it.root
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.shuwei.dish.match.dialog
|
||||
|
||||
import android.graphics.Rect
|
||||
import android.view.KeyboardShortcutGroup
|
||||
import android.view.LayoutInflater
|
||||
import android.view.Menu
|
||||
import android.view.MotionEvent
|
||||
import android.view.ViewGroup
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import com.google.android.material.bottomsheet.BottomSheetDialog
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.GoodsPreviewAdapter
|
||||
import com.shuwei.dish.match.databinding.DialogGoodsPreviewBinding
|
||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
|
||||
/**
|
||||
* 用料明细预览弹窗,以 BottomSheetDialog 形式展示当前 goodsList
|
||||
* @param context 宿主 Context(Activity)
|
||||
* @param goodsList 需要展示的物品列表
|
||||
*/
|
||||
class GoodsPreviewDialog(
|
||||
context: android.content.Context,
|
||||
private val goodsList: List<CookFoodGoodsEntity>
|
||||
) : BottomSheetDialog(context, R.style.BottomSheet) {
|
||||
|
||||
private val binding = DialogGoodsPreviewBinding.inflate(LayoutInflater.from(context))
|
||||
|
||||
init {
|
||||
setContentView(binding.root)
|
||||
setCancelable(true)
|
||||
window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
|
||||
|
||||
binding.rvGoodsList.run {
|
||||
layoutManager = LinearLayoutManager(context)
|
||||
adapter = GoodsPreviewAdapter(goodsList)
|
||||
}
|
||||
// foodId 对同一菜品所有条目相同,统一显示在列表上方
|
||||
val foodId = goodsList.firstOrNull()?.foodId.orEmpty()
|
||||
binding.tvFoodId.text = "菜品ID:${foodId.ifEmpty { "-" }}"
|
||||
if (goodsList.isEmpty()) {
|
||||
binding.rvGoodsList.gone()
|
||||
binding.tvEmpty.visible()
|
||||
}
|
||||
}
|
||||
|
||||
/** 弹出时注入 Window.Callback,解决 RecyclerView 与 BottomSheet 拖拽的滑动冲突 */
|
||||
override fun show() {
|
||||
super.show()
|
||||
val originalCallback = window?.callback ?: return
|
||||
window?.callback = object : android.view.Window.Callback by originalCallback {
|
||||
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
val rect = Rect()
|
||||
binding.rvGoodsList.getGlobalVisibleRect(rect)
|
||||
behavior.isDraggable = !rect.contains(event.rawX.toInt(), event.rawY.toInt())
|
||||
}
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
behavior.isDraggable = true
|
||||
}
|
||||
}
|
||||
return originalCallback.dispatchTouchEvent(event)
|
||||
}
|
||||
|
||||
override fun onPointerCaptureChanged(hasCapture: Boolean) {
|
||||
originalCallback.onPointerCaptureChanged(hasCapture)
|
||||
}
|
||||
|
||||
override fun onProvideKeyboardShortcuts(
|
||||
data: List<KeyboardShortcutGroup?>?,
|
||||
menu: Menu?,
|
||||
deviceId: Int
|
||||
) {
|
||||
originalCallback.onProvideKeyboardShortcuts(data, menu, deviceId)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,28 @@
|
||||
package com.shuwei.dish.match.dialog
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.Dialog
|
||||
import android.content.Context
|
||||
import android.graphics.Color
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.LayoutInflater
|
||||
import android.view.WindowManager
|
||||
import androidx.core.graphics.drawable.toDrawable
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.databinding.DialogLoadingBinding
|
||||
|
||||
@SuppressLint("StaticFieldLeak")
|
||||
object Loading {
|
||||
|
||||
/** 默认超时兜底时长(毫秒):业务方未传值时使用 */
|
||||
const val DEFAULT_TIMEOUT_MS = 15_000L
|
||||
|
||||
private var dialog: LoadingDialog? = null
|
||||
/** 当前持有 Loading 的 context,用于隔离 Activity 销毁时的误关 */
|
||||
private var owner: Context? = null
|
||||
private val timeoutHandler = Handler(Looper.getMainLooper())
|
||||
private val timeoutRunnable = Runnable { dismiss() }
|
||||
|
||||
fun isShowing(): Boolean {
|
||||
return dialog != null && dialog!!.isShowing
|
||||
@@ -22,30 +33,71 @@ object Loading {
|
||||
dialog!!.updateContent(content)
|
||||
}
|
||||
|
||||
fun show(context: Context, message: String = "加载中……", onDismiss: () -> Unit = {}) {
|
||||
/**
|
||||
* 显示 Loading 弹窗
|
||||
*
|
||||
* @param context 上下文
|
||||
* @param message 提示文案
|
||||
* @param timeoutMs 超时兜底时长(毫秒):到期自动 dismiss;传 0 关闭兜底,由业务方自己负责
|
||||
* @param onDismiss 关闭回调
|
||||
*/
|
||||
fun show(
|
||||
context: Context,
|
||||
message: String = "加载中……",
|
||||
timeoutMs: Long = DEFAULT_TIMEOUT_MS,
|
||||
onDismiss: () -> Unit = {}
|
||||
) {
|
||||
try {
|
||||
// 节流:已显示中只更新文案 + 重置超时,不重新 attach 窗口
|
||||
// 避免反复触发 FocusEvent 在主线程繁忙时引发 ANR
|
||||
if (dialog?.isShowing == true) {
|
||||
dialog?.dismiss()
|
||||
}
|
||||
if (dialog == null) {
|
||||
dialog = LoadingDialog(context = context, message = message, onDismiss = onDismiss)
|
||||
dialog?.updateContent(message)
|
||||
owner = context // 同一弹窗最后一次 show 决定 owner
|
||||
resetTimeout(timeoutMs)
|
||||
return
|
||||
}
|
||||
dialog = LoadingDialog(context = context, message = message, onDismiss = onDismiss)
|
||||
owner = context
|
||||
dialog?.show()
|
||||
resetTimeout(timeoutMs)
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
fun dismiss() {
|
||||
timeoutHandler.removeCallbacks(timeoutRunnable)
|
||||
try {
|
||||
dialog?.let {
|
||||
if (it.isShowing) {
|
||||
it.dismiss()
|
||||
}
|
||||
}
|
||||
dialog = null
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
} finally {
|
||||
dialog = null
|
||||
owner = null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Activity 销毁专用:只关闭自己持有的 Loading,防止跨 Activity 误关
|
||||
* 单例 Loading 在多 Activity 共享时,若每个 Activity 的 onDestroy 都无脑 dismiss,
|
||||
* 会误关后启动 Activity 弹出的 Loading;由本方法做 owner 校验后才允许关闭
|
||||
*/
|
||||
fun dismissIfOwnedBy(context: Context) {
|
||||
if (owner === context) dismiss()
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置超时兜底定时器
|
||||
* @param timeoutMs <=0 表示不安排定时器(关闭兜底)
|
||||
*/
|
||||
private fun resetTimeout(timeoutMs: Long) {
|
||||
timeoutHandler.removeCallbacks(timeoutRunnable)
|
||||
if (timeoutMs > 0) {
|
||||
timeoutHandler.postDelayed(timeoutRunnable, timeoutMs)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,259 +1,259 @@
|
||||
package com.shuwei.dish.match.dialog
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.graphics.Typeface
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.text.SpannableStringBuilder
|
||||
import android.text.style.AbsoluteSizeSpan
|
||||
import android.text.style.ForegroundColorSpan
|
||||
import android.text.style.LineHeightSpan
|
||||
import android.text.style.StyleSpan
|
||||
import android.util.Log
|
||||
import android.view.Gravity
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.view.WindowManager
|
||||
import androidx.core.graphics.toColorInt
|
||||
import androidx.core.view.isEmpty
|
||||
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.RecyclerView
|
||||
import com.google.android.material.bottomsheet.BottomSheetDialog
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.SeasoningSearchAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.databinding.DialogSeasoningSearchBinding
|
||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.net.UiState
|
||||
import com.shuwei.dish.match.utils.KeyboardUtil
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
||||
import com.shuwei.dish.match.utils.ext.appendText
|
||||
import com.shuwei.dish.match.utils.ext.buildSpannableString
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import com.shuwei.dish.match.utils.ext.roundedDecimalPlace
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* 调料搜索弹窗,继承 BottomSheetDialog 确保只初始化一次
|
||||
* @param activity 宿主 Activity
|
||||
* @param weighIndex 秤的索引
|
||||
* @param weighAddress 秤的地址,用于监听重量和去皮
|
||||
* @param clickName 默认填充的调料名称(可选)
|
||||
* @param onItemSelected 用户点击某一调料时的回调,携带当前重量
|
||||
*/
|
||||
class SeasoningSearchDialog(
|
||||
private val activity: BaseActivity,
|
||||
private val weighIndex: Int,
|
||||
private val weighAddress: Int,
|
||||
private val clickName: String? = null,
|
||||
private val onItemSelected: (item: SeasoningEntity) -> Unit
|
||||
) : BottomSheetDialog(activity, R.style.BottomSheet) {
|
||||
|
||||
companion object {
|
||||
const val TAG = "BottomDialog2"
|
||||
}
|
||||
|
||||
private val binding = DialogSeasoningSearchBinding.inflate(LayoutInflater.from(activity))
|
||||
private val list = mutableListOf<SeasoningEntity>()
|
||||
private val adapter = SeasoningSearchAdapter(list).apply {
|
||||
setOnItemClickListener { _, _, position ->
|
||||
list[position].isClicked = true
|
||||
notifyItemChanged(position)
|
||||
Handler(Looper.getMainLooper()).postDelayed({
|
||||
onItemSelected(list[position].also { it.useWeight = currentWeight })
|
||||
dismiss()
|
||||
}, 300)
|
||||
}
|
||||
}
|
||||
|
||||
private var goodsName: String? = null
|
||||
private var currentWeight = 0.0
|
||||
private var pageNo = 1
|
||||
private val pageSize = 50
|
||||
|
||||
init {
|
||||
setContentView(binding.root)
|
||||
setCancelable(true)
|
||||
behavior.skipCollapsed = false
|
||||
window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
|
||||
window?.setGravity(Gravity.BOTTOM)
|
||||
window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
|
||||
window?.setWindowAnimations(R.style.DialogSoftInputAnimation)
|
||||
window?.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
|
||||
|
||||
setOnDismissListener {
|
||||
// 弹窗关闭时移除重量监听,避免内存泄漏
|
||||
WeightUtil.removeWeightListener(TAG)
|
||||
activity.hideStatusBar()
|
||||
}
|
||||
|
||||
// 输入框:清空时重置列表
|
||||
binding.etSheetInput.run {
|
||||
hint = "输入调料名称"
|
||||
addTextChangedListener(
|
||||
onTextChanged = { text, _, _, _ -> goodsName = text.toString() },
|
||||
afterTextChanged = {
|
||||
if (it.isNullOrBlank()) {
|
||||
list.clear()
|
||||
adapter.notifyDataSetChanged()
|
||||
}
|
||||
}
|
||||
)
|
||||
addOnActionSearchListener { searchGoods(this) }
|
||||
}
|
||||
|
||||
// RecyclerView 初始化及滑动冲突处理
|
||||
binding.recyclerView.let {
|
||||
it.layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
||||
it.adapter = adapter
|
||||
it.addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
||||
override fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) {
|
||||
super.onScrolled(rv, dx, dy)
|
||||
// 解决 RecyclerView 与 SmartRefreshLayout 滑动冲突
|
||||
val topRowVerticalPosition = if (rv.isEmpty()) 0 else rv.getChildAt(0).top
|
||||
binding.refreshLayout.setNestedScrollingEnabled(topRowVerticalPosition >= 0)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
binding.refreshLayout.run {
|
||||
setEnableRefresh(false)
|
||||
setEnableLoadMore(false)
|
||||
setOnRefreshListener { pageNo = 1; getGoodsList() }
|
||||
setOnLoadMoreListener { getGoodsList() }
|
||||
}
|
||||
|
||||
binding.ivSearch.setOnClickListener { searchGoods(it) }
|
||||
binding.root.setOnClickListener { KeyboardUtil.hideKeyboard(it) }
|
||||
|
||||
// 去皮按钮
|
||||
binding.tvClear.setOnClickListener {
|
||||
Log.d(TAG, "tareTwo: weighAddress=$weighAddress")
|
||||
WeightUtil.tareTwo(weighAddress)
|
||||
}
|
||||
|
||||
// 监听对应秤的重量变化
|
||||
WeightUtil.addWeightListener(
|
||||
weightKey = TAG,
|
||||
getWeight = { address, _, weight ->
|
||||
if (weighAddress == address) {
|
||||
currentWeight = weight.toDouble()
|
||||
binding.tvWeight.text = getTextSpan(weight)
|
||||
}
|
||||
}
|
||||
)
|
||||
binding.tvWeight.text = getTextSpan(0.0)
|
||||
|
||||
initObserver()
|
||||
|
||||
// 若有默认调料名称,自动填充并触发搜索
|
||||
if (!clickName.isNullOrBlank()) {
|
||||
binding.etSheetInput.setText(clickName.trim())
|
||||
pageNo = 1
|
||||
getGoodsList()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 收集 seasoningListState,统一处理 Loading / Success / Error 状态
|
||||
*/
|
||||
private fun initObserver() {
|
||||
activity.lifecycleScope.launch {
|
||||
activity.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
activity.netViewModel.seasoningListState.collect { state ->
|
||||
when (state) {
|
||||
is UiState.Success -> loadGoodsList(state.data)
|
||||
is UiState.Error -> {
|
||||
activity.toast(state.msg)
|
||||
finishRefresh()
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 触发搜索:校验输入、隐藏键盘、发起请求
|
||||
*/
|
||||
private fun searchGoods(v: View) {
|
||||
if (goodsName.isNullOrBlank()) {
|
||||
activity.toast("请${binding.etSheetInput.hint}")
|
||||
return
|
||||
}
|
||||
pageNo = 1
|
||||
getGoodsList()
|
||||
KeyboardUtil.hideKeyboard(v)
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求调料列表
|
||||
*/
|
||||
private fun getGoodsList() {
|
||||
val param = mutableMapOf<String, Any>(
|
||||
"goodsType" to "1",
|
||||
"placeId" to BaseApp.canteenId,
|
||||
"pageNum" to pageNo,
|
||||
"pageSize" to pageSize
|
||||
)
|
||||
if (!goodsName.isNullOrBlank()) {
|
||||
param["goodsName"] = goodsName!!
|
||||
}
|
||||
activity.netViewModel.querySeasoningList(param)
|
||||
}
|
||||
|
||||
/**
|
||||
* 将返回数据填充到列表
|
||||
*/
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun loadGoodsList(records: MutableList<SeasoningEntity>?) {
|
||||
finishRefresh()
|
||||
if (records.isNullOrEmpty()) {
|
||||
activity.toast("暂未搜索到调料信息")
|
||||
return
|
||||
}
|
||||
if (pageNo == 1) list.clear()
|
||||
list.addAll(records)
|
||||
adapter.notifyDataSetChanged()
|
||||
val isLoadMoreEnable = records.size >= pageSize
|
||||
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
|
||||
if (isLoadMoreEnable) pageNo++
|
||||
}
|
||||
|
||||
private fun finishRefresh() {
|
||||
if (pageNo == 1) binding.refreshLayout.finishRefresh()
|
||||
else binding.refreshLayout.finishLoadMore()
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成重量显示的富文本:数值大字加粗,单位小字灰色
|
||||
*/
|
||||
fun getTextSpan(weight: Double): SpannableStringBuilder {
|
||||
val topWeight = if (weight >= 1000) "${(weight / 1000).roundedDecimalPlace(3)}" else "$weight"
|
||||
val bottomUnit = if (weight >= 1000) "千克" else "克"
|
||||
return buildSpannableString {
|
||||
appendText(
|
||||
topWeight,
|
||||
ForegroundColorSpan("#000000".toColorInt()),
|
||||
StyleSpan(Typeface.BOLD),
|
||||
AbsoluteSizeSpan(72, true),
|
||||
LineHeightSpan { _, _, _, _, _, fm -> fm.descent += 10.dp }
|
||||
)
|
||||
append("\n")
|
||||
appendText(
|
||||
bottomUnit,
|
||||
ForegroundColorSpan("#999999".toColorInt()),
|
||||
AbsoluteSizeSpan(30, true)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
//package com.shuwei.dish.match.dialog
|
||||
//
|
||||
//import android.annotation.SuppressLint
|
||||
//import android.graphics.Typeface
|
||||
//import android.os.Handler
|
||||
//import android.os.Looper
|
||||
//import android.text.SpannableStringBuilder
|
||||
//import android.text.style.AbsoluteSizeSpan
|
||||
//import android.text.style.ForegroundColorSpan
|
||||
//import android.text.style.LineHeightSpan
|
||||
//import android.text.style.StyleSpan
|
||||
//import android.util.Log
|
||||
//import android.view.Gravity
|
||||
//import android.view.LayoutInflater
|
||||
//import android.view.View
|
||||
//import android.view.ViewGroup
|
||||
//import android.view.WindowManager
|
||||
//import androidx.core.graphics.toColorInt
|
||||
//import androidx.core.view.isEmpty
|
||||
//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.RecyclerView
|
||||
//import com.google.android.material.bottomsheet.BottomSheetDialog
|
||||
//import com.shuwei.dish.match.R
|
||||
//import com.shuwei.dish.match.adapter.SeasoningSearchAdapter
|
||||
//import com.shuwei.dish.match.base.BaseActivity
|
||||
//import com.shuwei.dish.match.base.BaseApp
|
||||
//import com.shuwei.dish.match.databinding.DialogSeasoningSearchBinding
|
||||
//import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
//import com.shuwei.dish.match.net.UiState
|
||||
//import com.shuwei.dish.match.utils.KeyboardUtil
|
||||
//import com.shuwei.dish.match.utils.WeightUtil
|
||||
//import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
||||
//import com.shuwei.dish.match.utils.ext.appendText
|
||||
//import com.shuwei.dish.match.utils.ext.buildSpannableString
|
||||
//import com.shuwei.dish.match.utils.ext.dp
|
||||
//import com.shuwei.dish.match.utils.ext.roundedDecimalPlace
|
||||
//import com.shuwei.dish.match.utils.ext.toast
|
||||
//import kotlinx.coroutines.launch
|
||||
//
|
||||
///**
|
||||
// * 调料搜索弹窗,继承 BottomSheetDialog 确保只初始化一次
|
||||
// * @param activity 宿主 Activity
|
||||
// * @param weighIndex 秤的索引
|
||||
// * @param weighAddress 秤的地址,用于监听重量和去皮
|
||||
// * @param clickName 默认填充的调料名称(可选)
|
||||
// * @param onItemSelected 用户点击某一调料时的回调,携带当前重量
|
||||
// */
|
||||
//class SeasoningSearchDialog(
|
||||
// private val activity: BaseActivity,
|
||||
// private val weighIndex: Int,
|
||||
// private val weighAddress: Int,
|
||||
// private val clickName: String? = null,
|
||||
// private val onItemSelected: (item: SeasoningEntity) -> Unit
|
||||
//) : BottomSheetDialog(activity, R.style.BottomSheet) {
|
||||
//
|
||||
// companion object {
|
||||
// const val TAG = "BottomDialog2"
|
||||
// }
|
||||
//
|
||||
// private val binding = DialogSeasoningSearchBinding.inflate(LayoutInflater.from(activity))
|
||||
// private val list = mutableListOf<SeasoningEntity>()
|
||||
// private val adapter = SeasoningSearchAdapter(list).apply {
|
||||
// setOnItemClickListener { _, _, position ->
|
||||
// list[position].isClicked = true
|
||||
// notifyItemChanged(position)
|
||||
// Handler(Looper.getMainLooper()).postDelayed({
|
||||
// onItemSelected(list[position].also { it.useWeight = currentWeight })
|
||||
// dismiss()
|
||||
// }, 300)
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private var goodsName: String? = null
|
||||
// private var currentWeight = 0.0
|
||||
// private var pageNo = 1
|
||||
// private val pageSize = 50
|
||||
//
|
||||
// init {
|
||||
// setContentView(binding.root)
|
||||
// setCancelable(true)
|
||||
// behavior.skipCollapsed = false
|
||||
// window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
|
||||
// window?.setGravity(Gravity.BOTTOM)
|
||||
// window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
|
||||
// window?.setWindowAnimations(R.style.DialogSoftInputAnimation)
|
||||
// window?.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
|
||||
//
|
||||
// setOnDismissListener {
|
||||
// // 弹窗关闭时移除重量监听,避免内存泄漏
|
||||
// WeightUtil.removeWeightListener(TAG)
|
||||
// activity.hideStatusBar()
|
||||
// }
|
||||
//
|
||||
// // 输入框:清空时重置列表
|
||||
// binding.etSheetInput.run {
|
||||
// hint = "输入调料名称"
|
||||
// addTextChangedListener(
|
||||
// onTextChanged = { text, _, _, _ -> goodsName = text.toString() },
|
||||
// afterTextChanged = {
|
||||
// if (it.isNullOrBlank()) {
|
||||
// list.clear()
|
||||
// adapter.notifyDataSetChanged()
|
||||
// }
|
||||
// }
|
||||
// )
|
||||
// addOnActionSearchListener { searchGoods(this) }
|
||||
// }
|
||||
//
|
||||
// // RecyclerView 初始化及滑动冲突处理
|
||||
// binding.recyclerView.let {
|
||||
// it.layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
||||
// it.adapter = adapter
|
||||
// it.addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
||||
// override fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) {
|
||||
// super.onScrolled(rv, dx, dy)
|
||||
// // 解决 RecyclerView 与 SmartRefreshLayout 滑动冲突
|
||||
// val topRowVerticalPosition = if (rv.isEmpty()) 0 else rv.getChildAt(0).top
|
||||
// binding.refreshLayout.setNestedScrollingEnabled(topRowVerticalPosition >= 0)
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
//
|
||||
// binding.refreshLayout.run {
|
||||
// setEnableRefresh(false)
|
||||
// setEnableLoadMore(false)
|
||||
// setOnRefreshListener { pageNo = 1; getGoodsList() }
|
||||
// setOnLoadMoreListener { getGoodsList() }
|
||||
// }
|
||||
//
|
||||
// binding.ivSearch.setOnClickListener { searchGoods(it) }
|
||||
// binding.root.setOnClickListener { KeyboardUtil.hideKeyboard(it) }
|
||||
//
|
||||
// // 去皮按钮
|
||||
// binding.tvClear.setOnClickListener {
|
||||
// Log.d(TAG, "tareTwo: weighAddress=$weighAddress")
|
||||
// WeightUtil.tareTwo(weighAddress)
|
||||
// }
|
||||
//
|
||||
// // 监听对应秤的重量变化
|
||||
// WeightUtil.addWeightListener(
|
||||
// weightKey = TAG,
|
||||
// getWeight = { address, _, weight ->
|
||||
// if (weighAddress == address) {
|
||||
// currentWeight = weight.toDouble()
|
||||
// binding.tvWeight.text = getTextSpan(weight)
|
||||
// }
|
||||
// }
|
||||
// )
|
||||
// binding.tvWeight.text = getTextSpan(0.0)
|
||||
//
|
||||
// initObserver()
|
||||
//
|
||||
// // 若有默认调料名称,自动填充并触发搜索
|
||||
// if (!clickName.isNullOrBlank()) {
|
||||
// binding.etSheetInput.setText(clickName.trim())
|
||||
// pageNo = 1
|
||||
// getGoodsList()
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 收集 seasoningListState,统一处理 Loading / Success / Error 状态
|
||||
// */
|
||||
// private fun initObserver() {
|
||||
// activity.lifecycleScope.launch {
|
||||
// activity.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
// activity.netViewModel.seasoningListState.collect { state ->
|
||||
// when (state) {
|
||||
// is UiState.Success -> loadGoodsList(state.data)
|
||||
// is UiState.Error -> {
|
||||
// activity.toast(state.msg)
|
||||
// finishRefresh()
|
||||
// }
|
||||
// else -> {}
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 触发搜索:校验输入、隐藏键盘、发起请求
|
||||
// */
|
||||
// private fun searchGoods(v: View) {
|
||||
// if (goodsName.isNullOrBlank()) {
|
||||
// activity.toast("请${binding.etSheetInput.hint}")
|
||||
// return
|
||||
// }
|
||||
// pageNo = 1
|
||||
// getGoodsList()
|
||||
// KeyboardUtil.hideKeyboard(v)
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 请求调料列表
|
||||
// */
|
||||
// private fun getGoodsList() {
|
||||
// val param = mutableMapOf<String, Any>(
|
||||
// "goodsType" to "1",
|
||||
// "placeId" to BaseApp.canteenId,
|
||||
// "pageNum" to pageNo,
|
||||
// "pageSize" to pageSize
|
||||
// )
|
||||
// if (!goodsName.isNullOrBlank()) {
|
||||
// param["goodsName"] = goodsName!!
|
||||
// }
|
||||
// activity.netViewModel.querySeasoningList(param)
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 将返回数据填充到列表
|
||||
// */
|
||||
// @SuppressLint("NotifyDataSetChanged")
|
||||
// private fun loadGoodsList(records: MutableList<SeasoningEntity>?) {
|
||||
// finishRefresh()
|
||||
// if (records.isNullOrEmpty()) {
|
||||
// activity.toast("暂未搜索到调料信息")
|
||||
// return
|
||||
// }
|
||||
// if (pageNo == 1) list.clear()
|
||||
// list.addAll(records)
|
||||
// adapter.notifyDataSetChanged()
|
||||
// val isLoadMoreEnable = records.size >= pageSize
|
||||
// binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
|
||||
// if (isLoadMoreEnable) pageNo++
|
||||
// }
|
||||
//
|
||||
// private fun finishRefresh() {
|
||||
// if (pageNo == 1) binding.refreshLayout.finishRefresh()
|
||||
// else binding.refreshLayout.finishLoadMore()
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 生成重量显示的富文本:数值大字加粗,单位小字灰色
|
||||
// */
|
||||
// fun getTextSpan(weight: Double): SpannableStringBuilder {
|
||||
// val topWeight = if (weight >= 1000) "${(weight / 1000).roundedDecimalPlace(3)}" else "$weight"
|
||||
// val bottomUnit = if (weight >= 1000) "千克" else "克"
|
||||
// return buildSpannableString {
|
||||
// appendText(
|
||||
// topWeight,
|
||||
// ForegroundColorSpan("#000000".toColorInt()),
|
||||
// StyleSpan(Typeface.BOLD),
|
||||
// AbsoluteSizeSpan(72, true),
|
||||
// LineHeightSpan { _, _, _, _, _, fm -> fm.descent += 10.dp }
|
||||
// )
|
||||
// append("\n")
|
||||
// appendText(
|
||||
// bottomUnit,
|
||||
// ForegroundColorSpan("#999999".toColorInt()),
|
||||
// AbsoluteSizeSpan(30, true)
|
||||
// )
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
|
||||
@@ -5,47 +5,55 @@ import android.graphics.Rect
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.Gravity
|
||||
import android.view.KeyboardShortcutGroup
|
||||
import android.view.LayoutInflater
|
||||
import android.view.Menu
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.view.Window
|
||||
import android.view.WindowManager
|
||||
import android.widget.FrameLayout
|
||||
import androidx.core.widget.addTextChangedListener
|
||||
import androidx.recyclerview.widget.GridLayoutManager
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import com.google.android.material.bottomsheet.BottomSheetDialog
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.SeasoningSearchAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.databinding.DialogSeasoningSelectBinding
|
||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
import com.shuwei.dish.match.model.SeasoningSearchItem
|
||||
import com.shuwei.dish.match.net.UiState
|
||||
import com.shuwei.dish.match.utils.KeyboardUtil
|
||||
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
|
||||
/**
|
||||
* 调料选择弹窗,不含重量显示,继承 BottomSheetDialog 确保只初始化一次
|
||||
* @param activity 宿主 Activity
|
||||
* @param clickIndex 点击的调料槽位索引
|
||||
* @param onItemSelected 用户点击某一调料时的回调
|
||||
*/
|
||||
class SeasoningSelectDialog(
|
||||
private val activity: BaseActivity,
|
||||
private val onItemSelected: (item: SeasoningEntity) -> Unit
|
||||
private val onItemSelected: (item: GoodsItem) -> Unit
|
||||
) : BottomSheetDialog(activity, R.style.BottomSheet) {
|
||||
|
||||
companion object {
|
||||
const val TAG = "SeasoningSelectDialog"
|
||||
const val PAGE_SIZE = 50
|
||||
}
|
||||
|
||||
private val binding = DialogSeasoningSelectBinding.inflate(LayoutInflater.from(activity))
|
||||
private val list = mutableListOf<SeasoningEntity>()
|
||||
private val list = mutableListOf<GoodsItem>()
|
||||
private val adapter = SeasoningSearchAdapter(list).apply {
|
||||
setOnItemClickListener { _, _, position ->
|
||||
list[position].isClicked = true
|
||||
isStateViewEnable = true
|
||||
setOnItemClickListener { _, v, position ->
|
||||
val item = list.getOrNull(position) ?: return@setOnItemClickListener
|
||||
item.isClicked = true
|
||||
notifyItemChanged(position)
|
||||
Handler(Looper.getMainLooper()).postDelayed({
|
||||
onItemSelected(list[position])
|
||||
v.postDelayed({
|
||||
onItemSelected(item)
|
||||
dismiss()
|
||||
}, 300)
|
||||
}
|
||||
@@ -53,7 +61,6 @@ class SeasoningSelectDialog(
|
||||
|
||||
private var goodsName: String? = null
|
||||
private var pageNo = 1
|
||||
private val pageSize = 50
|
||||
|
||||
init {
|
||||
setContentView(binding.root)
|
||||
@@ -91,7 +98,7 @@ class SeasoningSelectDialog(
|
||||
}
|
||||
|
||||
binding.refreshLayout.run {
|
||||
setEnableRefresh(false)
|
||||
setEnableRefresh(true)
|
||||
setEnableLoadMore(false)
|
||||
setOnRefreshListener { pageNo = 1; getGoodsList() }
|
||||
setOnLoadMoreListener { getGoodsList() }
|
||||
@@ -126,6 +133,18 @@ class SeasoningSelectDialog(
|
||||
}
|
||||
return originalCallback.dispatchTouchEvent(event)
|
||||
}
|
||||
|
||||
override fun onPointerCaptureChanged(hasCapture: Boolean) {
|
||||
originalCallback.onPointerCaptureChanged(hasCapture)
|
||||
}
|
||||
|
||||
override fun onProvideKeyboardShortcuts(
|
||||
data: List<KeyboardShortcutGroup?>?,
|
||||
menu: Menu?,
|
||||
deviceId: Int
|
||||
) {
|
||||
originalCallback.onProvideKeyboardShortcuts(data, menu, deviceId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,58 +162,117 @@ class SeasoningSelectDialog(
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求调料列表(临时使用本地模拟数据,正式联调时替换为真实接口)
|
||||
* 请求调料列表(新配比秤接口,回调版本)
|
||||
*/
|
||||
private fun getGoodsList() {
|
||||
// TODO: 联调时注释掉下方模拟数据,取消注释真实接口调用
|
||||
val nameList = listOf(
|
||||
"盐", "白砂糖","冰糖", "鸡精", "味精", "陈醋", "老抽", "生抽", "番茄酱", "胡椒粉", "孜然", "十三香",
|
||||
"料酒", "白醋", "蚝油", "辣椒面", "辣椒酱", "豆瓣酱", "淀粉", "葱", "蒜", "姜", "香菜", "油"
|
||||
activity.netViewModel.querySeasoningSearch(
|
||||
keyword = goodsName.takeUnless { it.isNullOrBlank() },
|
||||
pageNum = pageNo,
|
||||
pageSize = PAGE_SIZE,
|
||||
onResult = { state ->
|
||||
when (state) {
|
||||
is UiState.Success -> loadGoodsList(state.data)
|
||||
is UiState.Error -> {
|
||||
activity.toast(state.msg)
|
||||
finishRefresh()
|
||||
if (pageNo == 1) loadEmptyView()
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
)
|
||||
val mockData = mutableListOf<SeasoningEntity>()
|
||||
nameList.forEachIndexed { index, name ->
|
||||
val padString = "${index + 1}".padStart(2, '0')
|
||||
mockData.add(SeasoningEntity(goodsId = "1000$padString", goodsName = name))
|
||||
}
|
||||
loadGoodsList(mockData)
|
||||
|
||||
// val param = mutableMapOf<String, Any>(
|
||||
// "goodsType" to "1",
|
||||
// "placeId" to BaseApp.canteenId,
|
||||
// "pageNum" to pageNo,
|
||||
// "pageSize" to pageSize
|
||||
// )
|
||||
// if (!goodsName.isNullOrBlank()) {
|
||||
// param["goodsName"] = goodsName!!
|
||||
// }
|
||||
// activity.querySeasoningList(param = param, onSuccess = {
|
||||
// loadGoodsList(it)
|
||||
// }, onFailure = { _, msg ->
|
||||
// activity.toast(msg)
|
||||
// finishRefresh()
|
||||
// })
|
||||
}
|
||||
|
||||
/**
|
||||
* 将返回数据填充到列表
|
||||
* 加载本地模拟数据,仅用于联调时点击空布局快速验证 UI
|
||||
*/
|
||||
private fun loadMockData() {
|
||||
val nameList = listOf(
|
||||
"盐", "白砂糖", "冰糖", "鸡精", "味精", "陈醋", "老抽", "生抽", "番茄酱", "胡椒粉", "孜然", "十三香",
|
||||
"料酒", "白醋", "蚝油", "辣椒面", "辣椒酱", "豆瓣酱", "淀粉", "葱", "蒜", "姜", "香菜", "油"
|
||||
)
|
||||
val mockData = nameList.mapIndexed { index, name ->
|
||||
val padString = "${index + 1}".padStart(2, '0')
|
||||
SeasoningSearchItem(id = "1000$padString", materName = name)
|
||||
}
|
||||
pageNo = 1
|
||||
loadGoodsList(mockData)
|
||||
}
|
||||
|
||||
/**
|
||||
* 将新接口返回的 SeasoningSearchItem 映射为 GoodsItem 并填充到列表
|
||||
* 新接口的 id 即食材id,同时用作 goodsId 和 materId,无需再交换
|
||||
*/
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun loadGoodsList(records: MutableList<SeasoningEntity>?) {
|
||||
private fun loadGoodsList(records: List<SeasoningSearchItem>?) {
|
||||
finishRefresh()
|
||||
if (records.isNullOrEmpty()) {
|
||||
activity.toast("暂未搜索到调料信息")
|
||||
if (pageNo == 1) {
|
||||
loadEmptyView()
|
||||
}
|
||||
return
|
||||
}
|
||||
binding.recyclerView.layoutManager = GridLayoutManager(activity, 3, GridLayoutManager.VERTICAL, false)
|
||||
if (pageNo == 1) list.clear()
|
||||
list.addAll(records)
|
||||
val goodsItems = records.map { it.toGoodsItem() }
|
||||
list.addAll(goodsItems)
|
||||
adapter.notifyDataSetChanged()
|
||||
val isLoadMoreEnable = records.size >= pageSize
|
||||
val isLoadMoreEnable = records.size >= PAGE_SIZE
|
||||
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
|
||||
if (isLoadMoreEnable) pageNo++
|
||||
}
|
||||
|
||||
/**
|
||||
* SeasoningSearchItem → GoodsItem 映射
|
||||
* id 既是食材id也是提交时的 goodsId,不需要 oldGoodsId 交换
|
||||
*/
|
||||
private fun SeasoningSearchItem.toGoodsItem() = GoodsItem(
|
||||
goodsId = id,
|
||||
materId = id,
|
||||
goodsName = materName,
|
||||
materCode = materCode,
|
||||
popularName = alias
|
||||
)
|
||||
|
||||
private fun finishRefresh() {
|
||||
if (pageNo == 1) binding.refreshLayout.finishRefresh()
|
||||
else binding.refreshLayout.finishLoadMore()
|
||||
}
|
||||
|
||||
|
||||
private var emptyViewBinding: LayoutEmptyViewBinding? = null
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun loadEmptyView() {
|
||||
try {
|
||||
binding.refreshLayout.setEnableRefresh(true)
|
||||
binding.refreshLayout.setEnableLoadMore(false)
|
||||
list.clear()
|
||||
adapter.notifyDataSetChanged()
|
||||
if (emptyViewBinding == null) {
|
||||
emptyViewBinding = LayoutEmptyViewBinding.inflate(
|
||||
LayoutInflater.from(activity),
|
||||
binding.recyclerView,
|
||||
false
|
||||
)
|
||||
}
|
||||
emptyViewBinding?.let {
|
||||
it.tvContent.text = "暂无数据"
|
||||
it.tvSubContent.text = "未查询到调料信息,请联系管理员添加"
|
||||
// 点击空布局加载本地模拟数据,方便联调时验证 UI
|
||||
//it.root.setOnClickListener { loadMockData() }
|
||||
it.root.layoutParams = FrameLayout.LayoutParams(
|
||||
FrameLayout.LayoutParams.MATCH_PARENT,
|
||||
FrameLayout.LayoutParams.MATCH_PARENT
|
||||
)
|
||||
binding.recyclerView.layoutManager = LinearLayoutManager(activity)
|
||||
binding.recyclerView.post {
|
||||
it.root.minimumHeight = binding.recyclerView.height
|
||||
adapter.stateView = it.root
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.shuwei.dish.match.entity
|
||||
package com.shuwei.dish.match.model
|
||||
|
||||
/**
|
||||
* 已采集食材列表项数据模型
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.shuwei.dish.match.model
|
||||
|
||||
import com.shuwei.dish.match.db.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||
import java.io.Serializable
|
||||
|
||||
/**
|
||||
* 菜品详情接口传输对象(DTO),不依赖 Room
|
||||
* 对应接口:getConstituteByFoodId / saveConstitute
|
||||
*/
|
||||
data class CookFoodDTO(
|
||||
var foodId: String = "",
|
||||
var foodName: String? = null,
|
||||
var canteenId: String? = null,
|
||||
var foodWeight: Double = 0.0,
|
||||
// 0-制作模式,1-采样模式,2-品控模式
|
||||
var cookMode: Int = 0,
|
||||
var dinnerType: String? = "0",
|
||||
// 接口返回的食材构成列表
|
||||
var matchingConstituteInfoList: MutableList<CookFoodGoodsDTO>? = null,
|
||||
var foodConstituteList: MutableList<CookFoodGoodsDTO>? = null
|
||||
) : Serializable {
|
||||
|
||||
/**
|
||||
* 转换为 Room 实体,用于写入本地数据库
|
||||
* id/isDel/createTime 由 Room 自行管理,不从 DTO 携带
|
||||
*/
|
||||
fun toEntity(): CookFoodEntity = CookFoodEntity(
|
||||
foodId = foodId,
|
||||
foodName = foodName,
|
||||
canteenId = canteenId,
|
||||
foodWeight = foodWeight,
|
||||
cookMode = cookMode,
|
||||
dinnerType = dinnerType
|
||||
).also { entity ->
|
||||
entity.matchingConstituteInfoList = matchingConstituteInfoList
|
||||
?.map { it.toEntity() }
|
||||
?.toMutableList()
|
||||
entity.foodConstituteList = foodConstituteList
|
||||
?.map { it.toEntity() }
|
||||
?.toMutableList()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package com.shuwei.dish.match.model
|
||||
|
||||
import com.shuwei.dish.match.db.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||
import java.io.Serializable
|
||||
|
||||
/**
|
||||
* 菜品构成(主辅料/调料)接口传输对象(DTO),不依赖 Room
|
||||
* 对应 CookFoodDTO 中 foodConstituteList、matchingConstituteInfoList 的元素
|
||||
*/
|
||||
data class CookFoodGoodsDTO(
|
||||
var goodsId: String = "",
|
||||
var goodsName: String? = null,
|
||||
var foodId: String? = "",
|
||||
var goodsOrRelationCode: String? = "",
|
||||
// 调料数据顺序
|
||||
var sort: Int = 0,
|
||||
// 食材原材料:1,预制品:2
|
||||
var relateionType: Int = 0,
|
||||
// 物品类型:1主料 2辅料 3调料
|
||||
var materialType: Int = 0,
|
||||
// 物品 是否全部可食:true-全部可食,false-部分可食
|
||||
var allEdible: Boolean = true,
|
||||
// 物品 用料重量
|
||||
var useWeight: Double? = 0.0,
|
||||
var popularName: String? = "",
|
||||
var canteenId: String? = "",
|
||||
var relateionType_dictText: String? = "",
|
||||
var zjmCode: String? = "",
|
||||
var materId: String? = "",
|
||||
// 物料编码
|
||||
var goodsCode: String? = "",
|
||||
// 净材种类
|
||||
var rawMaterialsType: String? = null
|
||||
) : Serializable {
|
||||
|
||||
/**
|
||||
* 转换为 GoodsItem,用于 UI 层
|
||||
*/
|
||||
fun toGoodsItem(): GoodsItem = GoodsItem(
|
||||
goodsId = goodsId,
|
||||
goodsName = goodsName,
|
||||
popularName = popularName,
|
||||
zjmCode = zjmCode,
|
||||
materId = materId,
|
||||
materCode = goodsCode,
|
||||
materialType = materialType,
|
||||
useWeight = useWeight,
|
||||
relateionType = relateionType,
|
||||
allEdible = allEdible,
|
||||
goodsOrRelationCode = goodsOrRelationCode,
|
||||
rawMaterialsType = rawMaterialsType
|
||||
)
|
||||
|
||||
/**
|
||||
* 转换为 Room 实体,用于写入本地数据库
|
||||
* id/pid/isDel/createTime 由 Room 自行管理,不从 DTO 携带
|
||||
*/
|
||||
fun toEntity(): CookFoodGoodsEntity = CookFoodGoodsEntity(
|
||||
goodsId = goodsId,
|
||||
goodsName = goodsName,
|
||||
foodId = foodId,
|
||||
goodsOrRelationCode = goodsOrRelationCode,
|
||||
sort = sort,
|
||||
relateionType = relateionType,
|
||||
materialType = materialType,
|
||||
allEdible = allEdible,
|
||||
useWeight = useWeight,
|
||||
popularName = popularName,
|
||||
canteenId = canteenId,
|
||||
relateionType_dictText = relateionType_dictText,
|
||||
zjmCode = zjmCode,
|
||||
materId = materId,
|
||||
goodsCode = goodsCode,
|
||||
rawMaterialsType = rawMaterialsType
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Room 实体 → DTO 反向映射,用于将本地数据转为接口提交格式
|
||||
* id/pid/isDel/createTime 为本地数据库字段,不参与提交
|
||||
*/
|
||||
fun CookFoodGoodsEntity.toDTO(): CookFoodGoodsDTO = CookFoodGoodsDTO(
|
||||
goodsId = goodsId,
|
||||
goodsName = goodsName,
|
||||
foodId = foodId,
|
||||
goodsOrRelationCode = goodsOrRelationCode,
|
||||
sort = sort,
|
||||
relateionType = relateionType,
|
||||
materialType = materialType,
|
||||
allEdible = allEdible,
|
||||
useWeight = useWeight,
|
||||
popularName = popularName,
|
||||
canteenId = canteenId,
|
||||
relateionType_dictText = relateionType_dictText,
|
||||
zjmCode = zjmCode,
|
||||
materId = materId,
|
||||
goodsCode = goodsCode,
|
||||
rawMaterialsType = rawMaterialsType
|
||||
)
|
||||
|
||||
/**
|
||||
* Room 实体 → DTO 反向映射,用于将本地数据转为接口提交格式
|
||||
* id/isDel/createTime 为本地数据库字段,不参与提交
|
||||
*/
|
||||
fun CookFoodEntity.toDTO(): CookFoodDTO = CookFoodDTO(
|
||||
foodId = foodId,
|
||||
foodName = foodName,
|
||||
canteenId = canteenId,
|
||||
foodWeight = foodWeight,
|
||||
cookMode = cookMode,
|
||||
dinnerType = dinnerType,
|
||||
matchingConstituteInfoList = matchingConstituteInfoList
|
||||
?.map { it.toDTO() }
|
||||
?.toMutableList(),
|
||||
foodConstituteList = foodConstituteList
|
||||
?.map { it.toDTO() }
|
||||
?.toMutableList()
|
||||
)
|
||||
@@ -0,0 +1,146 @@
|
||||
package com.shuwei.dish.match.model
|
||||
|
||||
/**
|
||||
* 当日烹饪任务列表(按餐次分组)请求参数
|
||||
* 对应接口: POST /neglect/ratio-scale/cook-orders/page
|
||||
*/
|
||||
data class CookOrderPageRequest(
|
||||
/** 计划日期 yyyy-MM-dd,默认当天 */
|
||||
val date: String? = null,
|
||||
/** 餐次筛选: 1=早餐 / 2=午餐 / 3=晚餐 / 4=加餐,不传返回全部 */
|
||||
val mealType: Int? = null,
|
||||
/** 菜品名称模糊搜索 */
|
||||
val keyword: String? = null,
|
||||
/** 保留字段,当前不使用 */
|
||||
val pageNum: Int? = null,
|
||||
/** 保留字段,当前不使用 */
|
||||
val pageSize: Int? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 餐次分组,包含该餐次下的烹制单列表
|
||||
*/
|
||||
data class CookOrderMealGroup(
|
||||
/** 餐次: 1=早餐 / 2=午餐 / 3=晚餐 / 4=加餐 */
|
||||
val mealType: Int = 0,
|
||||
/** 餐次中文名称 */
|
||||
val mealTypeName: String = "",
|
||||
/** 该餐次下的烹制单列表 */
|
||||
val cookOrders: List<CookOrderItem> = emptyList()
|
||||
)
|
||||
|
||||
/**
|
||||
* 单个烹制单,对应接口响应中 cookOrders 数组的条目
|
||||
* 注意: Long 类型字段服务端序列化为 String
|
||||
*/
|
||||
data class CookOrderItem(
|
||||
/** 烹制单id(Long → String) */
|
||||
val cookOrderId: String = "",
|
||||
/** 烹制单号 */
|
||||
val cookNo: String = "",
|
||||
/** 菜品名称 */
|
||||
val dishName: String = "",
|
||||
/** 菜品id(关联 nut_food) */
|
||||
val foodId: String = "",
|
||||
/** 餐次: 1=早餐 / 2=午餐 / 3=晚餐 / 4=加餐 */
|
||||
val mealType: Int = 0,
|
||||
/** 餐次中文名称 */
|
||||
val mealTypeName: String = "",
|
||||
/** 烹制状态: 0=待烹制 / 1=烹制中 / 2=已完成 / 3=异常 */
|
||||
val cookStatus: Int = 0,
|
||||
/** 烹制状态中文 */
|
||||
val cookStatusName: String = "",
|
||||
/** 生重(kg),烹制完成后才有值 */
|
||||
val rawWeight: Double? = null,
|
||||
/** 熟重(kg),烹制完成后才有值 */
|
||||
val cookedWeight: Double? = null,
|
||||
/** 需求份数 */
|
||||
val needPortions: Int = 0,
|
||||
/** 烹制份数,烹制完成后才有值 */
|
||||
val cookedPortions: Int? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 菜品食材构成(主材+辅材),对应接口响应中单个食材
|
||||
* 对应接口: GET /neglect/ratio-scale/cook-orders/{cookOrderId}/composition
|
||||
* 注意: 此接口仅返回主材(ingredientClass=1)和辅材(ingredientClass=2),不含调料
|
||||
*/
|
||||
data class CookOrderCompositionItem(
|
||||
/** 食材id */
|
||||
val materId: String = "",
|
||||
/** 食材名称 */
|
||||
val ingredientName: String = "",
|
||||
/** 食材分类: 1=主材 / 2=辅材 */
|
||||
val ingredientClass: Int = 0,
|
||||
/** 食材分类中文名称 */
|
||||
val ingredientClassName: String = "",
|
||||
/** 标准用量(g) */
|
||||
val useWeight: Double = 0.0,
|
||||
/** 净菜类型id */
|
||||
val vegTypeId: String = ""
|
||||
)
|
||||
|
||||
// ==================== 调料模糊搜索 ====================
|
||||
|
||||
/**
|
||||
* 调料模糊搜索请求参数
|
||||
* 对应接口: POST /neglect/ratio-scale/seasoning-search
|
||||
* 数据源: nut_mater_base 一级分类为 18(糖蜜饯)、19(油脂)、20(调味品)
|
||||
*/
|
||||
data class SeasoningSearchRequest(
|
||||
/** 模糊匹配食材名称和别名,为空时返回全部 */
|
||||
val keyword: String? = null,
|
||||
/** 页码 */
|
||||
val pageNum: Int = 1,
|
||||
/** 每页条数 */
|
||||
val pageSize: Int = 20
|
||||
)
|
||||
|
||||
/**
|
||||
* 调料模糊搜索结果条目
|
||||
* 注意: Long 类型字段服务端序列化为 String
|
||||
*/
|
||||
data class SeasoningSearchItem(
|
||||
/** 食材id(Long → String) */
|
||||
val id: String = "",
|
||||
/** 食材名称 */
|
||||
val materName: String = "",
|
||||
/** 食材编码 */
|
||||
val materCode: String = "",
|
||||
/** 别名 */
|
||||
val alias: String = "",
|
||||
/** 归属食堂id(Long → String) */
|
||||
val canteenId: String = ""
|
||||
)
|
||||
|
||||
// ==================== 烹饪完成 ====================
|
||||
|
||||
/**
|
||||
* 烹饪完成 — 单个食材用量条目
|
||||
* 对应接口: POST /neglect/ratio-scale/cook-orders/complete
|
||||
*/
|
||||
data class CookCompleteItem(
|
||||
/** 食材id */
|
||||
val materId: String = "",
|
||||
/** 实际用量(g) */
|
||||
val actualQty: Double = 0.0,
|
||||
/** 调料首次使用时间 yyyy-MM-dd HH:mm:ss,仅调料需要,主辅材留空 */
|
||||
val putTime: String? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 烹饪完成请求,一次性提交主辅材用量+熟重+调料
|
||||
* 对应接口: POST /neglect/ratio-scale/cook-orders/complete
|
||||
*/
|
||||
data class CookCompleteRequest(
|
||||
/** 烹制单id */
|
||||
val cookOrderId: String = "",
|
||||
/** 烹饪开始时间 yyyy-MM-dd HH:mm:ss,进入提交页面时刻 */
|
||||
val cookStart: String? = null,
|
||||
/** 主辅材实际用量列表,至少1条 */
|
||||
val items: List<CookCompleteItem> = emptyList(),
|
||||
/** 熟重(kg) */
|
||||
val cookedWeight: Double = 0.0,
|
||||
/** 调料用量列表,选填 */
|
||||
val seasonings: List<CookCompleteItem>? = null
|
||||
)
|
||||
+1
-53
@@ -1,11 +1,10 @@
|
||||
package com.shuwei.dish.match.entity
|
||||
package com.shuwei.dish.match.model
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.net.Uri
|
||||
import java.io.File
|
||||
|
||||
data class HomeModeBean(
|
||||
|
||||
var modeName: String = "",
|
||||
var modeDesc: String = "",
|
||||
var modeIconId: Int = 0,
|
||||
@@ -14,34 +13,6 @@ data class HomeModeBean(
|
||||
var onClick: (() -> Unit)? = null
|
||||
)
|
||||
|
||||
data class FoodRecordBean(
|
||||
var records: MutableList<FoodRecord>? = null,
|
||||
var total: Int,
|
||||
var size: Int,
|
||||
var current: Int,
|
||||
var page: Int
|
||||
)
|
||||
|
||||
data class GoodsRecordBean(
|
||||
var records: MutableList<CookFoodGoodsEntity>? = null,
|
||||
var total: Int,
|
||||
var size: Int,
|
||||
var current: Int,
|
||||
var page: Int
|
||||
)
|
||||
|
||||
data class SeasoningRecordBean(
|
||||
var records: MutableList<SeasoningEntity>? = null,
|
||||
var total: Int,
|
||||
var size: Int,
|
||||
var current: Int,
|
||||
var page: Int
|
||||
)
|
||||
|
||||
data class ResetReasoningRecord(
|
||||
val list: MutableList<SeasoningEntity>
|
||||
)
|
||||
|
||||
data class FoodCollectionBean(
|
||||
var imageUri: Uri? = null,
|
||||
var bitmap: Bitmap? = null,
|
||||
@@ -79,26 +50,3 @@ data class FoodCollectionBean(
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
//data class DishDetailEntity(
|
||||
// var foodId: String? = null,
|
||||
// var foodWeight: Double? = null,
|
||||
// var foodRealWeight: Double? = null,
|
||||
// var voList: List<DishPartEntity>? = null
|
||||
//)
|
||||
|
||||
//data class DishPartEntity(
|
||||
// var foodId: String? = null,
|
||||
// var foodName: String? = null,
|
||||
// var foodWeight: Int? = null,
|
||||
// var useWeight: Int? = null,
|
||||
// var useRealWeight: Int? = null,
|
||||
// var goodsId: Int? = null,
|
||||
// var goodsName: String? = null,
|
||||
// var materialType: Int? = null,
|
||||
// var isSetFinished: Boolean = false,
|
||||
// var isItemClicked: Boolean = false,
|
||||
// var isSamplingPage: Boolean = false
|
||||
//)
|
||||
|
||||
|
||||
+9
-3
@@ -1,4 +1,4 @@
|
||||
package com.shuwei.dish.match.entity
|
||||
package com.shuwei.dish.match.model
|
||||
|
||||
import java.io.Serializable
|
||||
|
||||
@@ -15,6 +15,12 @@ data class FoodRecord(
|
||||
var dinnerType: String = "0",
|
||||
//true-原始数据,false-非原始数据
|
||||
var isOriginalData: Boolean = true,
|
||||
var sort: Int = 0
|
||||
var sort: Int = 0,
|
||||
// ===== 已提交采样列表(sample-list)扩展字段,制作模式不涉及 =====
|
||||
/** 实验编号(innovNo) */
|
||||
var innovNo: String? = null,
|
||||
/** 实验状态: 1=实验中 / 2=已评测 / 9=已转化 */
|
||||
var status: Int? = null,
|
||||
/** 实验状态中文 */
|
||||
var statusName: String? = null
|
||||
) : Serializable
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.shuwei.dish.match.model
|
||||
|
||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.db.entity.SeasoningEntity
|
||||
import java.io.Serializable
|
||||
|
||||
/**
|
||||
* 物品信息接口返回的数据类(DTO),不依赖 Room,同时承载 UI 状态字段
|
||||
* 对应接口:queryGoodsInfoList,食材(goodsType=0)和调料(goodsType=1)共用此结构
|
||||
*/
|
||||
data class GoodsItem(
|
||||
// 接口返回字段
|
||||
var goodsId: String = "",
|
||||
val goodsName: String? = null,
|
||||
val popularName: String? = null,
|
||||
val zjmCode: String? = null,
|
||||
var materId: String? = null,
|
||||
val materCode: String? = null,
|
||||
|
||||
// 从 CookFoodGoodsEntity 迁移的数据字段(DishPartAdapter 显示及转换用)
|
||||
var materialType: Int = 0,
|
||||
var useWeight: Double? = 0.0,
|
||||
var relateionType: Int = 0,
|
||||
var allEdible: Boolean = true,
|
||||
var goodsOrRelationCode: String? = "",
|
||||
|
||||
// 从 CookFoodGoodsEntity @Ignore 迁移的 UI 状态字段
|
||||
var isSetFinished: Boolean = false,
|
||||
// var isItemClicked: Boolean = false,
|
||||
var isSamplingPage: Boolean = false,
|
||||
var isNewDishType: Boolean = false,
|
||||
var isClicked: Boolean = false,
|
||||
// true-原始数据,false-非原始数据(识图新增)
|
||||
var isOriginalData: Boolean = true,
|
||||
// true-用户手动指定了主辅材,updateMaterialTypes 自动分配时跳过
|
||||
var isMaterialTypeManual: Boolean = false,
|
||||
// 识图匹配分数,-1 表示不显示
|
||||
var foodScore: Int = -1,
|
||||
// 净材种类(当前选中值)
|
||||
var rawMaterialsType: String? = null,
|
||||
// 净材种类候选列表(临时字段,逗号分隔,不持久化)
|
||||
var rawMaterialsTypes: String? = null,
|
||||
var oldGoodsId: String? = null
|
||||
) : Serializable {
|
||||
|
||||
/**
|
||||
* 物料编码,与查询接口返回的 materCode 同值,统一对外暴露为 goodsCode 供下游使用
|
||||
*/
|
||||
val goodsCode: String? get() = materCode
|
||||
|
||||
/**
|
||||
* 转换为 CookFoodGoodsEntity,用于写入数据库或传给 SubmitFoodActivity
|
||||
*/
|
||||
fun toCookFoodGoodsEntity(): CookFoodGoodsEntity = CookFoodGoodsEntity(
|
||||
goodsId = goodsId,
|
||||
goodsName = goodsName,
|
||||
popularName = popularName,
|
||||
zjmCode = zjmCode,
|
||||
materId = materId,
|
||||
goodsCode = goodsCode,
|
||||
materialType = materialType,
|
||||
useWeight = useWeight,
|
||||
relateionType = relateionType,
|
||||
allEdible = allEdible,
|
||||
goodsOrRelationCode = goodsOrRelationCode,
|
||||
rawMaterialsType = rawMaterialsType
|
||||
)
|
||||
|
||||
/**
|
||||
* 转换为 SeasoningEntity,用于保存调料完整信息到 dm_seasoning
|
||||
*/
|
||||
fun toSeasoningEntity(): SeasoningEntity = SeasoningEntity(
|
||||
goodsId = goodsId,
|
||||
goodsName = goodsName,
|
||||
popularName = popularName,
|
||||
zjmCode = zjmCode,
|
||||
materId = materId,
|
||||
goodsCode = goodsCode,
|
||||
materialType = materialType,
|
||||
relateionType = relateionType,
|
||||
allEdible = allEdible,
|
||||
goodsOrRelationCode = goodsOrRelationCode,
|
||||
rawMaterialsType = rawMaterialsType
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.shuwei.dish.match.model
|
||||
|
||||
/**
|
||||
* 物品名称批量查询入参 DTO
|
||||
* 用于 queryGoodsInfoList 接口 goodsNames 字段的元素类型
|
||||
* @param goodsName 物品名称
|
||||
* @param rawMaterialsType 净材种类
|
||||
*/
|
||||
data class GoodsNameQueryDTO(
|
||||
val goodsName: String,
|
||||
val rawMaterialsType: String
|
||||
)
|
||||
@@ -0,0 +1,251 @@
|
||||
package com.shuwei.dish.match.model
|
||||
|
||||
/**
|
||||
* 采样与制作模式相关模型,对应配比秤接口(Controller: NutRatioScaleController)
|
||||
* 路径前缀: /neglect/ratio-scale
|
||||
* 序列化规则: Long 字段服务端返回字符串;请求体字段按后端约定(id 类字段用 String 与现有代码一致)
|
||||
*/
|
||||
|
||||
/** 采样实验状态(味养创新 nut_innovation.status) */
|
||||
object SampleStatus {
|
||||
/** 实验中 */
|
||||
const val EXPERIMENTING = 1
|
||||
/** 已评测 */
|
||||
const val EVALUATED = 2
|
||||
/** 已转化 */
|
||||
const val CONVERTED = 9
|
||||
}
|
||||
|
||||
// ==================== 一、食材模糊搜索 ====================
|
||||
|
||||
/**
|
||||
* 食材模糊搜索请求参数
|
||||
* 对应接口: POST /neglect/ratio-scale/mater-search
|
||||
* 数据源: nut_mater_base,限定设备对应食堂
|
||||
*/
|
||||
data class MaterSearchRequest(
|
||||
/** 模糊匹配食材名称和别名,为空时返回全部 */
|
||||
val keyword: String? = null,
|
||||
/** 页码 */
|
||||
val pageNum: Int = 1,
|
||||
/** 每页条数 */
|
||||
val pageSize: Int = 20
|
||||
)
|
||||
|
||||
/**
|
||||
* 食材模糊搜索结果条目
|
||||
* 注意: id / canteenId 为 Long 类型,服务端序列化为 String
|
||||
*/
|
||||
data class MaterSearchItem(
|
||||
/** 食材id(Long → String,提交构成 items.materId 使用) */
|
||||
val id: String = "",
|
||||
/** 食材名称 */
|
||||
val materName: String = "",
|
||||
/** 食材编码(一级+二级+自编码,全局唯一) */
|
||||
val materCode: String = "",
|
||||
/** 别名,可能为 null */
|
||||
val alias: String? = null,
|
||||
/** 食材一级分类 */
|
||||
val materFirstClass: String? = null,
|
||||
/** 食材二级分类 */
|
||||
val materSecondClass: String? = null,
|
||||
/** 食材图片url */
|
||||
val materUrl: String? = null,
|
||||
/** 归属食堂id(Long → String) */
|
||||
val canteenId: String = ""
|
||||
)
|
||||
|
||||
// ==================== 二、搜菜品 ====================
|
||||
|
||||
/**
|
||||
* 搜菜品请求参数(制作模式选已有菜品)
|
||||
* 对应接口: POST /neglect/ratio-scale/food-search
|
||||
* 数据源: nut_food(status=1 上架)
|
||||
*/
|
||||
data class FoodSearchRequest(
|
||||
/** 菜品名称或编号模糊搜索 */
|
||||
val keyword: String? = null,
|
||||
/** 页码 */
|
||||
val pageNum: Int = 1,
|
||||
/** 每页条数 */
|
||||
val pageSize: Int = 20
|
||||
)
|
||||
|
||||
/**
|
||||
* 搜菜品结果条目
|
||||
* 注意: foodId 为 Long 类型,服务端序列化为 String
|
||||
*/
|
||||
data class FoodSearchItem(
|
||||
/** 菜品id(Long → String) */
|
||||
val foodId: String = "",
|
||||
/** 菜品编号 */
|
||||
val foodCode: String = "",
|
||||
/** 菜品名称 */
|
||||
val foodName: String = ""
|
||||
)
|
||||
|
||||
// ==================== 三、查菜品构成 ====================
|
||||
|
||||
/**
|
||||
* 查菜品构成响应 — 单个食材
|
||||
* 对应接口: GET /neglect/ratio-scale/food/{foodId}/composition
|
||||
*/
|
||||
data class FoodCompositionIngredient(
|
||||
/** 食材id(Long → String) */
|
||||
val materId: String = "",
|
||||
/** 食材名称 */
|
||||
val materName: String = "",
|
||||
/** 用量(g) */
|
||||
val useWeight: Double = 0.0,
|
||||
/** 1=主材 / 2=辅材 / 3=调料 */
|
||||
val isMain: Int = 0,
|
||||
/** 分类中文名 */
|
||||
val isMainName: String = ""
|
||||
)
|
||||
|
||||
/**
|
||||
* 查菜品构成响应(主辅料+调料 + 熟重)
|
||||
* 对应接口: GET /neglect/ratio-scale/food/{foodId}/composition
|
||||
*/
|
||||
data class FoodCompositionResponse(
|
||||
/** 菜品id(Long → String) */
|
||||
val foodId: String = "",
|
||||
/** 菜品名称 */
|
||||
val foodName: String = "",
|
||||
/** 熟重(g),从 nut_food_cook.output_weight 反查 */
|
||||
val foodWeight: Double = 0.0,
|
||||
/** 食材构成列表 */
|
||||
val ingredients: List<FoodCompositionIngredient> = emptyList()
|
||||
)
|
||||
|
||||
// ==================== 四、提交采样 ====================
|
||||
|
||||
/**
|
||||
* 提交采样 — 单个食材构成条目
|
||||
* 对应接口: POST /neglect/ratio-scale/constitute/save
|
||||
*/
|
||||
data class ConstituteSaveItem(
|
||||
/** 食材id(nut_mater_base.id) */
|
||||
val materId: String = "",
|
||||
/** 食材称量用量(g),必须 > 0 */
|
||||
val useWeight: Double = 0.0,
|
||||
/** 食材分类: 1=主材 / 2=辅材 / 3=调料 */
|
||||
val isMain: Int = 0
|
||||
)
|
||||
|
||||
/**
|
||||
* 提交采样请求(落库味养创新实验,status=1 实验中)
|
||||
* 对应接口: POST /neglect/ratio-scale/constitute/save
|
||||
* 制作模式已废弃本接口,统一为提交采样,不再传 cookMode/foodId
|
||||
*/
|
||||
data class ConstituteSaveRequest(
|
||||
/** 菜品名称 */
|
||||
val foodName: String? = null,
|
||||
/** 熟重(g),必须 > 0 */
|
||||
val foodWeight: Double = 0.0,
|
||||
/** 食材构成列表,至少 1 条 */
|
||||
val items: List<ConstituteSaveItem> = emptyList()
|
||||
)
|
||||
|
||||
// ==================== 五、已提交采样列表 ====================
|
||||
|
||||
/**
|
||||
* 已提交采样列表查询请求参数
|
||||
* 对应接口: POST /neglect/ratio-scale/sample-list
|
||||
* 数据源: nut_innovation(source=2 配比秤采样),按提交时间倒序,不分日期
|
||||
*/
|
||||
data class SampleHistoryRequest(
|
||||
/** 页码 */
|
||||
val pageNum: Int = 1,
|
||||
/** 每页条数 */
|
||||
val pageSize: Int = 10
|
||||
)
|
||||
|
||||
/**
|
||||
* 已提交采样列表结果条目
|
||||
* 注意: innovId 为 Long 类型,服务端序列化为 String
|
||||
*/
|
||||
data class SampleHistoryItem(
|
||||
/** 味养创新实验id(Long → String) */
|
||||
val innovId: String = "",
|
||||
/** 实验编号 */
|
||||
val innovNo: String = "",
|
||||
/** 餐品名称 */
|
||||
val foodName: String = "",
|
||||
/** 熟重(g) */
|
||||
val foodWeight: Double = 0.0,
|
||||
/** 状态: 1=实验中 / 2=已评测 / 9=已转化 */
|
||||
val status: Int = 0,
|
||||
/** 状态中文 */
|
||||
val statusName: String = "",
|
||||
/** 提交时间 */
|
||||
val createTime: String = ""
|
||||
)
|
||||
|
||||
// ==================== 六、制作历史 ====================
|
||||
|
||||
/**
|
||||
* 制作历史查询请求参数
|
||||
* 对应接口: POST /neglect/ratio-scale/make/history
|
||||
* 数据源: nut_food_matching_use,按设备过滤
|
||||
*/
|
||||
data class MakeHistoryRequest(
|
||||
/** 页码 */
|
||||
val pageNum: Int = 1,
|
||||
/** 每页条数 */
|
||||
val pageSize: Int = 10,
|
||||
/** 制作日期 yyyy-MM-dd,不传查全部 */
|
||||
val day: String? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 制作历史结果条目
|
||||
* 注意: id / foodId 为 Long 类型,服务端序列化为 String
|
||||
*/
|
||||
data class MakeHistoryItem(
|
||||
/** 制作记录id(Long → String) */
|
||||
val id: String = "",
|
||||
/** 菜品id(Long → String) */
|
||||
val foodId: String = "",
|
||||
/** 菜品名称 */
|
||||
val foodName: String = "",
|
||||
/** 熟重(g) */
|
||||
val foodWeight: Double = 0.0,
|
||||
/** 餐次: 1=早餐/2=午餐/3=晚餐/4=加餐 */
|
||||
val mealType: Int = 0,
|
||||
/** 餐次中文 */
|
||||
val mealTypeName: String = "",
|
||||
/** 制作日期 */
|
||||
val day: String = "",
|
||||
/** 制作时间 */
|
||||
val createTime: String = ""
|
||||
)
|
||||
|
||||
// ==================== 七、制作历史图表 ====================
|
||||
|
||||
/**
|
||||
* 制作历史图表 — 横轴项
|
||||
* 对应接口: GET /neglect/ratio-scale/make/history/{foodId}
|
||||
*/
|
||||
data class MakeHistoryChartAxis(
|
||||
/** 食材id(时间/熟重项为空字符串) */
|
||||
val goodId: String = "",
|
||||
/** 项名称(时间/熟重/食材名称) */
|
||||
val goodName: String = ""
|
||||
)
|
||||
|
||||
/**
|
||||
* 制作历史图表 — 纵轴值
|
||||
* value 为 String(时间项) 或 Double(数值项)
|
||||
*/
|
||||
data class MakeHistoryChartValue(
|
||||
val value: Any? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 制作历史图表 — 单条记录(xAxes 与 yAxes 一一对应)
|
||||
*/
|
||||
data class MakeHistoryChartRow(
|
||||
val xAxes: List<MakeHistoryChartAxis> = emptyList(),
|
||||
val yAxes: List<MakeHistoryChartValue> = emptyList()
|
||||
)
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.shuwei.dish.match.model
|
||||
|
||||
/**
|
||||
* 设置页面的列表项实体类
|
||||
*
|
||||
* @param type 菜单项类型,用于唯一标识每一项
|
||||
* @param title 主标题文字
|
||||
* @param subtitle 副标题文字,仅部分项目(如菜品模式)有值
|
||||
* @param isHidden 是否为隐藏项,隐藏项需触发开发者模式后才显示
|
||||
* @param onClick 点击回调,初始化时直接注入对应的业务逻辑
|
||||
*/
|
||||
data class SettingItem(
|
||||
val type: Type,
|
||||
val title: String,
|
||||
val subtitle: String? = null,
|
||||
val isHidden: Boolean = false,
|
||||
val onClick: () -> Unit
|
||||
) {
|
||||
/** 设置菜单项类型枚举 */
|
||||
enum class Type {
|
||||
/** 菜品模式切换 */
|
||||
COOK_MODE,
|
||||
/** 调料区设置 */
|
||||
SEASONING_CONFIG,
|
||||
/** 食材采集 */
|
||||
FOOD_COLLECT,
|
||||
/** 减重配置 */
|
||||
WEIGHT_CONFIG,
|
||||
/** 数据库查看(隐藏项) */
|
||||
DB_INSPECT,
|
||||
/** 秤数据监控(隐藏项) */
|
||||
SCALE_OBSERVE,
|
||||
/** 切换环境(隐藏项) */
|
||||
ENV_SWITCH,
|
||||
/** 数据清除(隐藏项) */
|
||||
CLEAR_DATA,
|
||||
/** 测试调料拿取(隐藏项) */
|
||||
TEST_SEASONING,
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,35 @@
|
||||
package com.shuwei.dish.match.net
|
||||
|
||||
import com.shuwei.dish.match.base.GlobalData
|
||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.entity.FoodRecord
|
||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.model.CookFoodDTO
|
||||
import com.shuwei.dish.match.model.CookOrderCompositionItem
|
||||
import com.shuwei.dish.match.model.CookOrderMealGroup
|
||||
import com.shuwei.dish.match.model.CookOrderPageRequest
|
||||
import com.shuwei.dish.match.model.FoodRecord
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
import com.shuwei.dish.match.model.ConstituteSaveRequest
|
||||
import com.shuwei.dish.match.model.CookCompleteRequest
|
||||
import com.shuwei.dish.match.model.FoodCompositionResponse
|
||||
import com.shuwei.dish.match.model.FoodSearchItem
|
||||
import com.shuwei.dish.match.model.FoodSearchRequest
|
||||
import com.shuwei.dish.match.model.MakeHistoryChartRow
|
||||
import com.shuwei.dish.match.model.MakeHistoryItem
|
||||
import com.shuwei.dish.match.model.MakeHistoryRequest
|
||||
import com.shuwei.dish.match.model.MaterSearchItem
|
||||
import com.shuwei.dish.match.model.MaterSearchRequest
|
||||
import com.shuwei.dish.match.model.SampleHistoryItem
|
||||
import com.shuwei.dish.match.model.SampleHistoryRequest
|
||||
import com.shuwei.dish.match.model.SeasoningSearchItem
|
||||
import com.shuwei.dish.match.model.SeasoningSearchRequest
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
import retrofit2.http.Body
|
||||
import retrofit2.http.GET
|
||||
import retrofit2.http.Multipart
|
||||
import retrofit2.http.POST
|
||||
import retrofit2.http.Part
|
||||
import retrofit2.http.PartMap
|
||||
import retrofit2.http.Path
|
||||
import retrofit2.http.Query
|
||||
import retrofit2.http.Url
|
||||
|
||||
@@ -18,9 +40,9 @@ interface ApiService {
|
||||
*/
|
||||
@GET
|
||||
suspend fun getFoodDetail(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/getConstituteByFoodId",
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/matching/app/getConstituteByFoodId",
|
||||
@Query("foodId") foodId: String
|
||||
): ApiResponse<CookFoodEntity?>
|
||||
): ApiResponse<CookFoodDTO?>
|
||||
|
||||
|
||||
/**
|
||||
@@ -28,16 +50,16 @@ interface ApiService {
|
||||
*/
|
||||
@POST
|
||||
suspend fun submitCookFood(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/saveConstitute",
|
||||
@Body param: CookFoodEntity
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/matching/app/saveConstitute",
|
||||
@Body param: CookFoodDTO
|
||||
): ApiResponse<Any?>
|
||||
|
||||
/**
|
||||
* 搜索菜品
|
||||
* 搜索菜品(旧接口,采样模式仍在使用)
|
||||
*/
|
||||
@POST
|
||||
suspend fun searchFoodList(
|
||||
@Url url:String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/queryPageList",
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/matching/app/queryPageList",
|
||||
@Body param: MutableMap<String, Any>
|
||||
): ApiResponse<MutableList<FoodRecord>?>
|
||||
|
||||
@@ -46,68 +68,129 @@ interface ApiService {
|
||||
*/
|
||||
@POST
|
||||
suspend fun getSamplingList(
|
||||
@Url url:String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/queryHistoryGoodsInfoList",
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/matching/app/queryHistoryGoodsInfoList",
|
||||
@Body param: MutableMap<String, Any>
|
||||
): ApiResponse<MutableList<FoodRecord>?>
|
||||
|
||||
/**
|
||||
* 物品信息
|
||||
* 物品信息(食材 goodsType=0,调料 goodsType=1 共用此接口)
|
||||
*/
|
||||
@POST
|
||||
suspend fun queryGoodsList(
|
||||
@Url url:String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/queryGoodsInfoList",
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/matching/app/queryGoodsInfoList",
|
||||
@Body param: MutableMap<String, Any>
|
||||
): ApiResponse<MutableList<CookFoodGoodsEntity>?>
|
||||
): ApiResponse<MutableList<GoodsItem>?>
|
||||
|
||||
/**
|
||||
* 调料信息
|
||||
* 提交采集图片数据
|
||||
*/
|
||||
@Multipart
|
||||
@POST
|
||||
suspend fun uploadFoodVectorData(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/matching/app/addWeighingCollectionData",
|
||||
@PartMap params: MutableMap<String, RequestBody>,
|
||||
@Part foodPics: List<MultipartBody.Part>
|
||||
): ApiResponse<List<String>?>
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 查询当日烹饪任务列表(按餐次分组),新配比秤接口
|
||||
*/
|
||||
@POST
|
||||
suspend fun querySeasoningList(
|
||||
@Url url:String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/queryGoodsInfoList",
|
||||
@Body param: MutableMap<String, Any>
|
||||
): ApiResponse<MutableList<SeasoningEntity>?>
|
||||
suspend fun getCookOrderPage(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/ratio-scale/cook-orders/list",
|
||||
@Body request: CookOrderPageRequest
|
||||
): ApiResponse<List<CookOrderMealGroup>?>
|
||||
|
||||
/**
|
||||
* 查询菜品食材构成(主材+辅材,不含调料),新配比秤接口
|
||||
*/
|
||||
@GET("nutrition/neglect/ratio-scale/cook-orders/{cookOrderId}/composition")
|
||||
suspend fun getCookOrderComposition(
|
||||
@Path("cookOrderId") cookOrderId: String
|
||||
): ApiResponse<List<CookOrderCompositionItem>?>
|
||||
|
||||
/**
|
||||
* 调料模糊搜索,新配比秤接口
|
||||
* 数据源: nut_mater_base 一级分类为 18(糖蜜饯)、19(油脂)、20(调味品)
|
||||
*/
|
||||
@POST
|
||||
suspend fun getSeasoningSearch(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/ratio-scale/seasoning-search",
|
||||
@Body request: SeasoningSearchRequest
|
||||
): ApiResponse<List<SeasoningSearchItem>?>
|
||||
|
||||
/**
|
||||
* 烹饪完成:提交主辅材用量+熟重+调料,一次性完成烹制
|
||||
* 新配比秤接口,替代旧 saveConstitute
|
||||
*/
|
||||
@POST
|
||||
suspend fun cookOrderComplete(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/ratio-scale/cook-orders/complete",
|
||||
@Body request: CookCompleteRequest
|
||||
): ApiResponse<Any?>
|
||||
|
||||
/**
|
||||
* 食材模糊搜索(采样/制作通用,称量前检索食材)
|
||||
* 数据源: nut_mater_base,限定设备对应食堂,模糊匹配名称和别名
|
||||
*/
|
||||
@POST
|
||||
suspend fun materSearch(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/ratio-scale/mater-search",
|
||||
@Body request: MaterSearchRequest
|
||||
): ApiResponse<MutableList<MaterSearchItem>?>
|
||||
|
||||
/**
|
||||
* 搜菜品(制作模式选已有上架菜品)
|
||||
*/
|
||||
@POST
|
||||
suspend fun foodSearch(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/ratio-scale/food-search",
|
||||
@Body request: FoodSearchRequest
|
||||
): ApiResponse<MutableList<FoodSearchItem>?>
|
||||
|
||||
/**
|
||||
* 查菜品构成(制作模式查看已有菜品主辅料+调料 + 熟重)
|
||||
*/
|
||||
@GET("nutrition/neglect/ratio-scale/food/{foodId}/composition")
|
||||
suspend fun getFoodComposition(
|
||||
@Path("foodId") foodId: String
|
||||
): ApiResponse<FoodCompositionResponse?>
|
||||
|
||||
// /**
|
||||
// *获取配置信息
|
||||
// */
|
||||
// @GET("/equipment/stEquipment/queryByEquipmentCode")
|
||||
// suspend fun getDeviceInfo(
|
||||
// @Query("equipmentCode") equipmentCode: String,
|
||||
// @Query("appVersion") appVersion: String = App.appVersion
|
||||
// ): ApiResponse<DeviceConfigInfo>
|
||||
//
|
||||
// @GET
|
||||
// suspend fun getAccessToken(
|
||||
// @Url url: String = UrlConfig.GET_ACCESS_TOKEN,
|
||||
// @Query("qrcodeId") qrcodeId: String
|
||||
// ): ApiResponse<String?>
|
||||
//
|
||||
// @GET
|
||||
// suspend fun getShelfList(
|
||||
// @Url url: String = UrlConfig.GET_SHELF_LIST,
|
||||
// @Query("deviceId") deviceId: String
|
||||
// ): ApiResponse<ShelfResult>
|
||||
//
|
||||
// @GET
|
||||
// suspend fun getGoodsList(
|
||||
// @Url url: String = UrlConfig.GET_GOODS_LIST,
|
||||
// @Query("canteenId") canteenId: String = "0",
|
||||
// @Query("goodsName") goodsName: String? = null,
|
||||
// @Query("pageNo") pageNo: Int = 1,
|
||||
// @Query("pageSize") pageSize: Int = 50
|
||||
// ): ApiResponse<MutableList<GoodsModel>?>
|
||||
//
|
||||
// @POST
|
||||
// suspend fun saveShelfGoodsList(
|
||||
// @Url url: String = UrlConfig.SAVE_SHELF_GOODS_LIST,
|
||||
// @Body body: ShelfBody
|
||||
// ): ApiResponse<Any?>
|
||||
/**
|
||||
* 提交采样(落库味养创新实验,制作模式已废弃本接口)
|
||||
*/
|
||||
@POST
|
||||
suspend fun constituteSave(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/ratio-scale/constitute/save",
|
||||
@Body request: ConstituteSaveRequest
|
||||
): ApiResponse<Any?>
|
||||
|
||||
/**
|
||||
* 已提交采样列表(本食堂 source=2,按提交时间倒序,不分日期)
|
||||
*/
|
||||
@POST
|
||||
suspend fun sampleHistory(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/ratio-scale/sample-list",
|
||||
@Body request: SampleHistoryRequest
|
||||
): ApiResponse<MutableList<SampleHistoryItem>?>
|
||||
|
||||
/**
|
||||
* 制作历史(本设备,按日期可选过滤)
|
||||
*/
|
||||
@POST
|
||||
suspend fun makeHistory(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/ratio-scale/make/history",
|
||||
@Body request: MakeHistoryRequest
|
||||
): ApiResponse<MutableList<MakeHistoryItem>?>
|
||||
|
||||
/**
|
||||
* 制作历史图表(按菜品id)
|
||||
*/
|
||||
@GET("nutrition/neglect/ratio-scale/make/history/{foodId}")
|
||||
suspend fun makeHistoryChart(
|
||||
@Path("foodId") foodId: String
|
||||
): ApiResponse<MutableList<MakeHistoryChartRow>?>
|
||||
|
||||
}
|
||||
@@ -2,14 +2,40 @@ package com.shuwei.dish.match.net
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.entity.FoodRecord
|
||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.model.CookFoodDTO
|
||||
import com.shuwei.dish.match.model.CookOrderCompositionItem
|
||||
import com.shuwei.dish.match.model.CookOrderMealGroup
|
||||
import com.shuwei.dish.match.model.CookOrderPageRequest
|
||||
import com.shuwei.dish.match.model.FoodRecord
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
import com.shuwei.dish.match.model.GoodsNameQueryDTO
|
||||
import com.shuwei.dish.match.model.ConstituteSaveRequest
|
||||
import com.shuwei.dish.match.model.CookCompleteRequest
|
||||
import com.shuwei.dish.match.model.FoodCompositionResponse
|
||||
import com.shuwei.dish.match.model.FoodSearchItem
|
||||
import com.shuwei.dish.match.model.FoodSearchRequest
|
||||
import com.shuwei.dish.match.model.MakeHistoryChartRow
|
||||
import com.shuwei.dish.match.model.MakeHistoryItem
|
||||
import com.shuwei.dish.match.model.MakeHistoryRequest
|
||||
import com.shuwei.dish.match.model.MaterSearchItem
|
||||
import com.shuwei.dish.match.model.MaterSearchRequest
|
||||
import com.shuwei.dish.match.model.SampleHistoryItem
|
||||
import com.shuwei.dish.match.model.SampleHistoryRequest
|
||||
import com.shuwei.dish.match.model.SeasoningSearchItem
|
||||
import com.shuwei.dish.match.model.SeasoningSearchRequest
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.RequestBody.Companion.asRequestBody
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* 网络请求 ViewModel,所有网络操作通过 RemoteRepository 发起,不直接依赖 apiService
|
||||
@@ -28,7 +54,7 @@ class NetViewModel(
|
||||
/**
|
||||
* 提交制作菜品
|
||||
*/
|
||||
fun submitCookFood(entity: CookFoodEntity) {
|
||||
fun submitCookFood(entity: CookFoodDTO) {
|
||||
viewModelScope.launch {
|
||||
_submitCookFoodState.value = UiState.Loading
|
||||
_submitCookFoodState.value = repository.submitCookFood(entity)
|
||||
@@ -38,8 +64,8 @@ class NetViewModel(
|
||||
/**
|
||||
* 查询菜品详情的 UI 状态流,UI 层通过 collect 监听
|
||||
*/
|
||||
private val _foodDetailState = MutableStateFlow<UiState<CookFoodEntity?>>(UiState.Idle)
|
||||
val foodDetailState: StateFlow<UiState<CookFoodEntity?>> = _foodDetailState.asStateFlow()
|
||||
private val _foodDetailState = MutableStateFlow<UiState<CookFoodDTO?>>(UiState.Idle)
|
||||
val foodDetailState: StateFlow<UiState<CookFoodDTO?>> = _foodDetailState.asStateFlow()
|
||||
|
||||
/**
|
||||
* 查询菜品详情
|
||||
@@ -51,24 +77,104 @@ class NetViewModel(
|
||||
}
|
||||
}
|
||||
|
||||
fun resetFoodDetailState() {
|
||||
_foodDetailState.value = UiState.Idle
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索菜品列表的 UI 状态流,UI 层通过 collect 监听
|
||||
* 查询菜品食材构成的 UI 状态流(新配比秤接口),UI 层通过 collect 监听
|
||||
*/
|
||||
private val _searchFoodState = MutableStateFlow<UiState<MutableList<FoodRecord>?>>(UiState.Idle)
|
||||
val searchFoodState: StateFlow<UiState<MutableList<FoodRecord>?>> = _searchFoodState.asStateFlow()
|
||||
private val _cookOrderCompositionState = MutableStateFlow<UiState<List<CookOrderCompositionItem>?>>(UiState.Idle)
|
||||
val cookOrderCompositionState: StateFlow<UiState<List<CookOrderCompositionItem>?>> = _cookOrderCompositionState.asStateFlow()
|
||||
|
||||
/**
|
||||
* 查询菜品食材构成(新配比秤接口,仅返回主材+辅材)
|
||||
* @param cookOrderId 烹制单 ID
|
||||
*/
|
||||
fun getCookOrderComposition(cookOrderId: String) {
|
||||
viewModelScope.launch {
|
||||
_cookOrderCompositionState.value = UiState.Loading
|
||||
_cookOrderCompositionState.value = repository.getCookOrderComposition(cookOrderId)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索菜品列表的 UI 状态流。
|
||||
* 使用 replay=1 保证 Fragment 重建后能收到最近一次结果;
|
||||
* emit 时包一层 Event wrapper 打破 equals 去重,确保相同数据也能触发 collect。
|
||||
*/
|
||||
private val _searchFoodState = MutableSharedFlow<UiState<MutableList<FoodRecord>?>>(
|
||||
replay = 1,
|
||||
extraBufferCapacity = 1
|
||||
)
|
||||
val searchFoodState: SharedFlow<UiState<MutableList<FoodRecord>?>> = _searchFoodState.asSharedFlow()
|
||||
|
||||
/**
|
||||
* 搜索菜品列表
|
||||
*/
|
||||
fun searchFoodList(param: MutableMap<String, Any>) {
|
||||
viewModelScope.launch {
|
||||
_searchFoodState.value = UiState.Loading
|
||||
_searchFoodState.value = repository.searchFoodList(param)
|
||||
// pageNum=1 时先 emit Idle 重置 replay 缓存,防止相同数据导致 SharedFlow 去重不触发
|
||||
if (param["pageNum"] == 1) {
|
||||
_searchFoodState.emit(UiState.Idle)
|
||||
}
|
||||
_searchFoodState.emit(UiState.Loading)
|
||||
_searchFoodState.emit(repository.searchFoodList(param))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索菜品列表(回调版本),结果通过 onResult 直接回调,不经过 StateFlow/SharedFlow
|
||||
* 适合需要每次都能触发的场景(下拉刷新、上拉加载更多)
|
||||
*/
|
||||
fun searchFoodListWithCallback(
|
||||
param: MutableMap<String, Any>,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<MutableList<FoodRecord>?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.searchFoodList(param))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 当日烹饪任务列表的 UI 状态流(新配比秤接口),UI 层通过 collect 监听
|
||||
* 使用 SharedFlow(replay=1) 保证 Fragment 重建后收到最近一次结果
|
||||
*/
|
||||
private val _cookOrderPageState = MutableSharedFlow<UiState<List<CookOrderMealGroup>?>>(
|
||||
replay = 1,
|
||||
extraBufferCapacity = 1
|
||||
)
|
||||
val cookOrderPageState: SharedFlow<UiState<List<CookOrderMealGroup>?>> = _cookOrderPageState.asSharedFlow()
|
||||
|
||||
/**
|
||||
* 查询当日烹饪任务列表(新配比秤接口,StateFlow 版本)
|
||||
* 适合 FoodSearchActivity 等通过 collect 监听结果的场景
|
||||
*/
|
||||
fun getCookOrderPage(request: CookOrderPageRequest) {
|
||||
viewModelScope.launch {
|
||||
_cookOrderPageState.emit(UiState.Loading)
|
||||
_cookOrderPageState.emit(repository.getCookOrderPage(request))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询当日烹饪任务列表(新配比秤接口,回调版本)
|
||||
* 适合 FoodListFragment 下拉刷新、Tab 切换等需要每次都能触发的场景
|
||||
*/
|
||||
fun getCookOrderPageWithCallback(
|
||||
request: CookOrderPageRequest,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<List<CookOrderMealGroup>?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.getCookOrderPage(request))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询采样数据列表的 UI 状态流,UI 层通过 collect 监听
|
||||
*/
|
||||
private val _samplingListState = MutableStateFlow<UiState<MutableList<FoodRecord>?>>(UiState.Idle)
|
||||
val samplingListState: StateFlow<UiState<MutableList<FoodRecord>?>> = _samplingListState.asStateFlow()
|
||||
@@ -87,15 +193,61 @@ class NetViewModel(
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询物品信息列表的 UI 状态流,UI 层通过 collect 监听
|
||||
* 查询采样数据列表(回调版本),结果通过 onResult 直接回调,不经过 StateFlow
|
||||
* 适合不需要跨生命周期持续监听的一次性查询场景
|
||||
*/
|
||||
private val _goodsListState = MutableStateFlow<UiState<MutableList<CookFoodGoodsEntity>?>>(UiState.Idle)
|
||||
val goodsListState: StateFlow<UiState<MutableList<CookFoodGoodsEntity>?>> = _goodsListState.asStateFlow()
|
||||
fun getSamplingListWithCallback(
|
||||
param: MutableMap<String, Any>,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<MutableList<FoodRecord>?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.getSamplingList(param))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询物品信息列表
|
||||
* 查询物品信息列表的 UI 状态流(食材/调料共用),UI 层通过 collect 监听
|
||||
*/
|
||||
fun queryGoodsList(param: MutableMap<String, Any>) {
|
||||
private val _goodsListState = MutableStateFlow<UiState<MutableList<GoodsItem>?>>(UiState.Idle)
|
||||
val goodsListState: StateFlow<UiState<MutableList<GoodsItem>?>> = _goodsListState.asStateFlow()
|
||||
|
||||
/**
|
||||
* 食材搜索弹窗专用的 UI 状态流,与 goodsListState 隔离,避免弹窗请求影响其他页面
|
||||
*/
|
||||
private val _foodSearchGoodsListState = MutableStateFlow<UiState<MutableList<GoodsItem>?>>(UiState.Idle)
|
||||
val foodSearchGoodsListState: StateFlow<UiState<MutableList<GoodsItem>?>> = _foodSearchGoodsListState.asStateFlow()
|
||||
|
||||
fun resetGoodsListState() {
|
||||
_goodsListState.value = UiState.Idle
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询物品信息列表(食材 goodsType=0,调料 goodsType=1 共用)
|
||||
* @param goodsType 物品类型:0=食材,1=调料
|
||||
* @param placeId 场所 ID,默认取当前食堂 ID
|
||||
* @param pageNum 页码,默认第 1 页
|
||||
* @param pageSize 每页条数,默认 50
|
||||
* @param goodsName 按名称模糊搜索,为 null 时不传该字段
|
||||
* @param goodsNames 按名称+净材种类列表批量查询,为 null 时不传该字段
|
||||
*/
|
||||
fun queryGoodsList(
|
||||
goodsType: String,
|
||||
placeId: String = BaseApp.canteenId,
|
||||
pageNum: Int = 1,
|
||||
pageSize: Int = 50,
|
||||
goodsName: String? = null,
|
||||
goodsNames: List<GoodsNameQueryDTO>? = null
|
||||
) {
|
||||
val param = mutableMapOf<String, Any>(
|
||||
"goodsType" to goodsType,
|
||||
"placeId" to placeId,
|
||||
"pageNum" to pageNum,
|
||||
"pageSize" to pageSize
|
||||
)
|
||||
goodsName?.let { param["goodsName"] = it }
|
||||
goodsNames?.let { param["goodsNames"] = it }
|
||||
viewModelScope.launch {
|
||||
_goodsListState.value = UiState.Loading
|
||||
_goodsListState.value = repository.queryGoodsList(param)
|
||||
@@ -103,18 +255,234 @@ class NetViewModel(
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询调料信息列表的 UI 状态流,UI 层通过 collect 监听
|
||||
* 食材搜索弹窗专用的查询方法,结果写入 foodSearchGoodsListState,不影响 goodsListState
|
||||
* @param goodsType 物品类型:0=食材,1=调料
|
||||
* @param placeId 场所 ID,默认取当前食堂 ID
|
||||
* @param pageNum 页码,默认第 1 页
|
||||
* @param pageSize 每页条数,默认 50
|
||||
* @param goodsName 按名称模糊搜索,为 null 时不传该字段
|
||||
* @param goodsNames 按名称+净材种类列表批量查询,为 null 时不传该字段
|
||||
*/
|
||||
private val _seasoningListState = MutableStateFlow<UiState<MutableList<SeasoningEntity>?>>(UiState.Idle)
|
||||
val seasoningListState: StateFlow<UiState<MutableList<SeasoningEntity>?>> = _seasoningListState.asStateFlow()
|
||||
|
||||
/**
|
||||
* 查询调料信息列表
|
||||
*/
|
||||
fun querySeasoningList(param: MutableMap<String, Any>) {
|
||||
fun queryFoodSearchGoodsList(
|
||||
goodsType: String,
|
||||
placeId: String = BaseApp.canteenId,
|
||||
pageNum: Int = 1,
|
||||
pageSize: Int = 50,
|
||||
goodsName: String? = null,
|
||||
goodsNames: List<GoodsNameQueryDTO>? = null
|
||||
) {
|
||||
val param = mutableMapOf<String, Any>(
|
||||
"goodsType" to goodsType,
|
||||
"placeId" to placeId,
|
||||
"pageNum" to pageNum,
|
||||
"pageSize" to pageSize
|
||||
)
|
||||
goodsName?.let { param["goodsName"] = it }
|
||||
goodsNames?.let { param["goodsNames"] = it }
|
||||
viewModelScope.launch {
|
||||
_seasoningListState.value = UiState.Loading
|
||||
_seasoningListState.value = repository.querySeasoningList(param)
|
||||
_foodSearchGoodsListState.value = UiState.Loading
|
||||
_foodSearchGoodsListState.value = repository.queryGoodsList(param)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 调料模糊搜索(新配比秤接口,回调版本)
|
||||
* 替代旧 queryGoodsList(goodsType=1) 调用
|
||||
* @param keyword 模糊匹配食材名称和别名,为 null 时不传该字段
|
||||
* @param pageNum 页码,默认第 1 页
|
||||
* @param pageSize 每页条数,默认 50
|
||||
* @param onLoading 请求发起前的回调
|
||||
* @param onResult 结果回调,直接接收 UiState<List<SeasoningSearchItem>?>
|
||||
*/
|
||||
fun querySeasoningSearch(
|
||||
keyword: String? = null,
|
||||
pageNum: Int = 1,
|
||||
pageSize: Int = 50,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<List<SeasoningSearchItem>?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.getSeasoningSearch(
|
||||
SeasoningSearchRequest(keyword = keyword, pageNum = pageNum, pageSize = pageSize)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 烹饪完成(新配比秤接口,回调版本),替代旧 submitCookFood
|
||||
* 仅在制作模式下 cookOrderId 可用的场景调用
|
||||
*/
|
||||
fun cookOrderComplete(
|
||||
request: CookCompleteRequest,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<Any?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.cookOrderComplete(request))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 食材模糊搜索(回调版本)
|
||||
* @param keyword 模糊匹配食材名称和别名,为 null 时不传该字段
|
||||
* @param pageNum 页码,默认第 1 页
|
||||
* @param pageSize 每页条数,默认 20
|
||||
*/
|
||||
fun materSearch(
|
||||
keyword: String? = null,
|
||||
pageNum: Int = 1,
|
||||
pageSize: Int = 20,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<MutableList<MaterSearchItem>?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.materSearch(
|
||||
MaterSearchRequest(keyword = keyword, pageNum = pageNum, pageSize = pageSize)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜菜品(回调版本,制作模式选已有上架菜品)
|
||||
*/
|
||||
fun foodSearch(
|
||||
keyword: String? = null,
|
||||
pageNum: Int = 1,
|
||||
pageSize: Int = 20,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<MutableList<FoodSearchItem>?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.foodSearch(
|
||||
FoodSearchRequest(keyword = keyword, pageNum = pageNum, pageSize = pageSize)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查菜品构成(回调版本,制作模式)
|
||||
*/
|
||||
fun getFoodComposition(
|
||||
foodId: String,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<FoodCompositionResponse?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.getFoodComposition(foodId))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交采样(回调版本,落库味养创新实验,制作模式已废弃本接口)
|
||||
*/
|
||||
fun constituteSave(
|
||||
request: ConstituteSaveRequest,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<Any?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.constituteSave(request))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 已提交采样列表(回调版本,本食堂 source=2,不分日期)
|
||||
* @param pageNum 页码,默认第 1 页
|
||||
* @param pageSize 每页条数,默认 10
|
||||
*/
|
||||
fun sampleHistory(
|
||||
pageNum: Int = 1,
|
||||
pageSize: Int = 10,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<MutableList<SampleHistoryItem>?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.sampleHistory(
|
||||
SampleHistoryRequest(
|
||||
pageNum = pageNum,
|
||||
pageSize = pageSize
|
||||
)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 制作历史(回调版本,本设备按日期可选过滤)
|
||||
*/
|
||||
fun makeHistory(
|
||||
pageNum: Int = 1,
|
||||
pageSize: Int = 10,
|
||||
day: String? = null,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<MutableList<MakeHistoryItem>?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.makeHistory(
|
||||
MakeHistoryRequest(pageNum = pageNum, pageSize = pageSize, day = day)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 制作历史图表(回调版本,按菜品id)
|
||||
*/
|
||||
fun makeHistoryChart(
|
||||
foodId: String,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<MutableList<MakeHistoryChartRow>?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.makeHistoryChart(foodId))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传采集菜品信息 UI 状态流,UI 层通过 collect 监听
|
||||
*/
|
||||
private val _uploadCollectState = MutableStateFlow<UiState<List<String>?>>(UiState.Idle)
|
||||
val uploadCollectState: StateFlow<UiState<List<String>?>> = _uploadCollectState.asStateFlow()
|
||||
|
||||
/**
|
||||
* 上传采集菜品信息(触发 StateFlow,适合单次上传场景)
|
||||
*/
|
||||
fun uploadFoodVectorData(
|
||||
fileList: List<File>,
|
||||
params: MutableMap<String, RequestBody>
|
||||
) {
|
||||
val fileParts = fileList.map { file ->
|
||||
file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
|
||||
.let { MultipartBody.Part.createFormData("foodPics", file.name, it) }
|
||||
}
|
||||
viewModelScope.launch {
|
||||
_uploadCollectState.value = UiState.Loading
|
||||
_uploadCollectState.value = repository.uploadFoodVectorData(params, fileParts)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传采集菜品信息(直接返回结果,适合分批循环上传场景)
|
||||
* @param fileList 图片文件列表
|
||||
* @param params 附加参数
|
||||
* @return UiState 包装的结果
|
||||
*/
|
||||
suspend fun uploadFoodVectorDataBatch(
|
||||
fileList: List<File>,
|
||||
params: MutableMap<String, RequestBody>
|
||||
): UiState<List<String>?> {
|
||||
val fileParts = fileList.map { file ->
|
||||
//multipart/form-data image/jpeg
|
||||
file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
|
||||
.let { MultipartBody.Part.createFormData("foodPics", file.name, it) }
|
||||
}
|
||||
return repository.uploadFoodVectorData(params, fileParts)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,27 @@
|
||||
package com.shuwei.dish.match.net
|
||||
|
||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.entity.FoodRecord
|
||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.model.CookFoodDTO
|
||||
import com.shuwei.dish.match.model.CookOrderCompositionItem
|
||||
import com.shuwei.dish.match.model.CookOrderMealGroup
|
||||
import com.shuwei.dish.match.model.CookOrderPageRequest
|
||||
import com.shuwei.dish.match.model.FoodRecord
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
import com.shuwei.dish.match.model.ConstituteSaveRequest
|
||||
import com.shuwei.dish.match.model.CookCompleteRequest
|
||||
import com.shuwei.dish.match.model.FoodCompositionResponse
|
||||
import com.shuwei.dish.match.model.FoodSearchItem
|
||||
import com.shuwei.dish.match.model.FoodSearchRequest
|
||||
import com.shuwei.dish.match.model.MakeHistoryChartRow
|
||||
import com.shuwei.dish.match.model.MakeHistoryItem
|
||||
import com.shuwei.dish.match.model.MakeHistoryRequest
|
||||
import com.shuwei.dish.match.model.MaterSearchItem
|
||||
import com.shuwei.dish.match.model.MaterSearchRequest
|
||||
import com.shuwei.dish.match.model.SampleHistoryItem
|
||||
import com.shuwei.dish.match.model.SampleHistoryRequest
|
||||
import com.shuwei.dish.match.model.SeasoningSearchItem
|
||||
import com.shuwei.dish.match.model.SeasoningSearchRequest
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
|
||||
/**
|
||||
* 网络数据仓库,封装所有 ApiService 调用
|
||||
@@ -11,101 +29,86 @@ import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
*/
|
||||
class RemoteRepository {
|
||||
|
||||
/**
|
||||
* 提交制作菜品
|
||||
* @param entity 菜品实体
|
||||
* @return UiState 包装的结果,Success 表示提交成功,Error 携带错误信息
|
||||
*/
|
||||
suspend fun submitCookFood(entity: CookFoodEntity): UiState<Any?> {
|
||||
/** 统一封装 API 调用:处理响应映射和异常转换,返回 UiState */
|
||||
private suspend fun <T> safeApiCall(call: suspend () -> ApiResponse<T>): UiState<T?> {
|
||||
return try {
|
||||
val resp = apiService.submitCookFood(param = entity)
|
||||
val resp = call()
|
||||
if (resp.isSuccess()) UiState.Success(resp.data)
|
||||
else UiState.Error(resp.code, resp.msg ?: "")
|
||||
} catch (e: Exception) {
|
||||
val ex = getApiException(e)
|
||||
UiState.Error("-1", ex.errorMsg)
|
||||
UiState.Error("-1", getApiException(e).errorMsg)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询菜品详情
|
||||
* @param foodId 菜品 ID
|
||||
* @return UiState 包装的结果,Success 携带详情数据,Error 携带错误信息
|
||||
*/
|
||||
suspend fun getFoodDetail(foodId: String): UiState<CookFoodEntity?> {
|
||||
return try {
|
||||
val resp = apiService.getFoodDetail(foodId = foodId)
|
||||
if (resp.isSuccess()) UiState.Success(resp.data)
|
||||
else UiState.Error(resp.code, resp.msg ?: "")
|
||||
} catch (e: Exception) {
|
||||
val ex = getApiException(e)
|
||||
UiState.Error("-1", ex.errorMsg)
|
||||
}
|
||||
}
|
||||
/** 提交制作菜品 */
|
||||
suspend fun submitCookFood(entity: CookFoodDTO): UiState<Any?> =
|
||||
safeApiCall { apiService.submitCookFood(param = entity) }
|
||||
|
||||
/**
|
||||
* 搜索菜品列表
|
||||
* @param param 查询参数
|
||||
* @return UiState 包装的结果,Success 携带列表数据,Error 携带错误信息
|
||||
*/
|
||||
suspend fun searchFoodList(param: MutableMap<String, Any>): UiState<MutableList<FoodRecord>?> {
|
||||
return try {
|
||||
val resp = apiService.searchFoodList(param = param)
|
||||
if (resp.isSuccess()) UiState.Success(resp.data)
|
||||
else UiState.Error(resp.code, resp.msg ?: "")
|
||||
} catch (e: Exception) {
|
||||
val ex = getApiException(e)
|
||||
UiState.Error("-1", ex.errorMsg)
|
||||
}
|
||||
}
|
||||
/** 查询菜品详情 */
|
||||
suspend fun getFoodDetail(foodId: String): UiState<CookFoodDTO?> =
|
||||
safeApiCall { apiService.getFoodDetail(foodId = foodId) }
|
||||
|
||||
/**
|
||||
* 查询采样数据列表
|
||||
* @param param 查询参数
|
||||
* @return UiState 包装的结果,Success 携带列表数据,Error 携带错误信息
|
||||
*/
|
||||
suspend fun getSamplingList(param: MutableMap<String, Any>): UiState<MutableList<FoodRecord>?> {
|
||||
return try {
|
||||
val resp = apiService.getSamplingList(param = param)
|
||||
if (resp.isSuccess()) UiState.Success(resp.data)
|
||||
else UiState.Error(resp.code, resp.msg ?: "")
|
||||
} catch (e: Exception) {
|
||||
val ex = getApiException(e)
|
||||
UiState.Error("-1", ex.errorMsg)
|
||||
}
|
||||
}
|
||||
/** 查询当日烹饪任务列表(按餐次分组),新配比秤接口 */
|
||||
suspend fun getCookOrderPage(request: CookOrderPageRequest): UiState<List<CookOrderMealGroup>?> =
|
||||
safeApiCall { apiService.getCookOrderPage(request = request) }
|
||||
|
||||
/**
|
||||
* 查询物品信息列表
|
||||
* @param param 查询参数
|
||||
* @return UiState 包装的结果,Success 携带列表数据,Error 携带错误信息
|
||||
*/
|
||||
suspend fun queryGoodsList(param: MutableMap<String, Any>): UiState<MutableList<CookFoodGoodsEntity>?> {
|
||||
return try {
|
||||
val resp = apiService.queryGoodsList(param = param)
|
||||
if (resp.isSuccess()) UiState.Success(resp.data)
|
||||
else UiState.Error(resp.code, resp.msg ?: "")
|
||||
} catch (e: Exception) {
|
||||
val ex = getApiException(e)
|
||||
UiState.Error("-1", ex.errorMsg)
|
||||
}
|
||||
}
|
||||
/** 查询菜品食材构成(主材+辅材),新配比秤接口 */
|
||||
suspend fun getCookOrderComposition(cookOrderId: String): UiState<List<CookOrderCompositionItem>?> =
|
||||
safeApiCall { apiService.getCookOrderComposition(cookOrderId = cookOrderId) }
|
||||
|
||||
/** 搜索菜品列表 */
|
||||
suspend fun searchFoodList(param: MutableMap<String, Any>): UiState<MutableList<FoodRecord>?> =
|
||||
safeApiCall { apiService.searchFoodList(param = param) }
|
||||
|
||||
/**
|
||||
* 查询调料信息列表
|
||||
* @param param 查询参数
|
||||
* @return UiState 包装的结果,Success 携带列表数据,Error 携带错误信息
|
||||
*/
|
||||
suspend fun querySeasoningList(param: MutableMap<String, Any>): UiState<MutableList<SeasoningEntity>?> {
|
||||
return try {
|
||||
val resp = apiService.querySeasoningList(param = param)
|
||||
if (resp.isSuccess()) UiState.Success(resp.data)
|
||||
else UiState.Error(resp.code, resp.msg ?: "")
|
||||
} catch (e: Exception) {
|
||||
val ex = getApiException(e)
|
||||
UiState.Error("-1", ex.errorMsg)
|
||||
}
|
||||
}
|
||||
/** 查询采样数据列表 */
|
||||
suspend fun getSamplingList(param: MutableMap<String, Any>): UiState<MutableList<FoodRecord>?> =
|
||||
safeApiCall { apiService.getSamplingList(param = param) }
|
||||
|
||||
/** 查询物品信息列表(食材 goodsType=0,调料 goodsType=1 共用) */
|
||||
suspend fun queryGoodsList(param: MutableMap<String, Any>): UiState<MutableList<GoodsItem>?> =
|
||||
safeApiCall { apiService.queryGoodsList(param = param) }
|
||||
|
||||
/** 调料模糊搜索,新配比秤接口 */
|
||||
suspend fun getSeasoningSearch(request: SeasoningSearchRequest): UiState<List<SeasoningSearchItem>?> =
|
||||
safeApiCall { apiService.getSeasoningSearch(request = request) }
|
||||
|
||||
/** 烹饪完成,新配比秤接口,替代旧 submitCookFood */
|
||||
suspend fun cookOrderComplete(request: CookCompleteRequest): UiState<Any?> =
|
||||
safeApiCall { apiService.cookOrderComplete(request = request) }
|
||||
|
||||
/** 食材模糊搜索 */
|
||||
suspend fun materSearch(request: MaterSearchRequest): UiState<MutableList<MaterSearchItem>?> =
|
||||
safeApiCall { apiService.materSearch(request = request) }
|
||||
|
||||
/** 搜菜品(制作模式选已有上架菜品) */
|
||||
suspend fun foodSearch(request: FoodSearchRequest): UiState<MutableList<FoodSearchItem>?> =
|
||||
safeApiCall { apiService.foodSearch(request = request) }
|
||||
|
||||
/** 查菜品构成(制作模式) */
|
||||
suspend fun getFoodComposition(foodId: String): UiState<FoodCompositionResponse?> =
|
||||
safeApiCall { apiService.getFoodComposition(foodId = foodId) }
|
||||
|
||||
/** 提交采样(落库味养创新实验,制作模式已废弃本接口) */
|
||||
suspend fun constituteSave(request: ConstituteSaveRequest): UiState<Any?> =
|
||||
safeApiCall { apiService.constituteSave(request = request) }
|
||||
|
||||
/** 已提交采样列表(本食堂 source=2,按提交时间倒序,不分日期) */
|
||||
suspend fun sampleHistory(request: SampleHistoryRequest): UiState<MutableList<SampleHistoryItem>?> =
|
||||
safeApiCall { apiService.sampleHistory(request = request) }
|
||||
|
||||
/** 制作历史(本设备,按日期可选过滤) */
|
||||
suspend fun makeHistory(request: MakeHistoryRequest): UiState<MutableList<MakeHistoryItem>?> =
|
||||
safeApiCall { apiService.makeHistory(request = request) }
|
||||
|
||||
/** 制作历史图表(按菜品id) */
|
||||
suspend fun makeHistoryChart(foodId: String): UiState<MutableList<MakeHistoryChartRow>?> =
|
||||
safeApiCall { apiService.makeHistoryChart(foodId = foodId) }
|
||||
|
||||
/** 上传采集数据 */
|
||||
suspend fun uploadFoodVectorData(
|
||||
params: MutableMap<String, RequestBody>,
|
||||
foodPics: List<MultipartBody.Part>
|
||||
): UiState<List<String>?> =
|
||||
safeApiCall { apiService.uploadFoodVectorData(params = params, foodPics = foodPics) }
|
||||
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ class RequestInterceptor : Interceptor {
|
||||
val requestBuilder = originalRequest.newBuilder()
|
||||
.header("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjYW50ZWVuSWQiOiJiZTE1NDgzMS0zNDY2LTNiYTItYTJlYS01NzY1MmM5MTlmZWQiLCJ0eXBlIjoiNCIsInVzZXJJZCI6IjAwMDAwMDAwMDAwMDAwMDAwMDEifQ.sN40cOC-O5WQFrF4IDUs8fFlkNdUKLbJt_rHyTsgYYM")
|
||||
.header("X-DEVICE-CODE", GlobalData.deviceId)
|
||||
.header("X-DEVICE-TOKEN", GlobalData.deviceId)
|
||||
.header("authorization", "57ee87183f2a4fa59683ec9ef41c8f5d")
|
||||
|
||||
val newRequest = requestBuilder.build()
|
||||
|
||||
@@ -3,7 +3,10 @@ package com.shuwei.dish.match.net
|
||||
data class ApiResponse<T>(
|
||||
val code: String,
|
||||
val msg: String? = "",
|
||||
val data: T? = null
|
||||
val data: T? = null,
|
||||
/** 分页总条数,仅新配比秤接口返回(如 seasoning-search),旧接口为 null */
|
||||
val total: Int? = null
|
||||
) {
|
||||
fun isSuccess() = code == "00000"
|
||||
/** 兼容旧接口成功码 "00000" 和新配比秤接口成功码 "200" */
|
||||
fun isSuccess() = code == "00000" || code == "200"
|
||||
}
|
||||
|
||||
@@ -11,7 +11,8 @@ data class Food(
|
||||
var name: String? = null,
|
||||
var foodIdx: Int = 0,
|
||||
@HnswIndex(dimensions = 512, distanceType = VectorDistanceType.DOT_PRODUCT)
|
||||
var foodVector: FloatArray? = null
|
||||
var foodVector: FloatArray? = null,
|
||||
var version: String? = null
|
||||
) {
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (this === other) return true
|
||||
@@ -23,6 +24,7 @@ data class Food(
|
||||
if (foodIdx != other.foodIdx) return false
|
||||
if (name != other.name) return false
|
||||
if (!foodVector.contentEquals(other.foodVector)) return false
|
||||
if (version != other.version) return false
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -32,6 +34,8 @@ data class Food(
|
||||
result = 31 * result + foodIdx
|
||||
result = 31 * result + (name?.hashCode() ?: 0)
|
||||
result = 31 * result + (foodVector?.contentHashCode() ?: 0)
|
||||
result = 31 * result + (version?.hashCode() ?: 0)
|
||||
return result
|
||||
}
|
||||
|
||||
}
|
||||
@@ -22,7 +22,7 @@ import java.io.InputStream
|
||||
|
||||
object FoodModule {
|
||||
|
||||
private lateinit var module_mobile: Module
|
||||
private lateinit var module: Module
|
||||
|
||||
private val NO_MEAN_RGB = floatArrayOf(0.0f, 0.0f, 0.0f)
|
||||
private val NO_STD_RGB = floatArrayOf(1.0f, 1.0f, 1.0f)
|
||||
@@ -37,8 +37,8 @@ object FoodModule {
|
||||
|
||||
suspend fun init(context: Context) {
|
||||
withContext(Dispatchers.IO) {
|
||||
module_mobile = Module.load(copyAssetToCache(context, "best_embedding_model_mobile.pt"))
|
||||
initDefFoodData(context)
|
||||
module = Module.load(copyAssetToCache(context, "best_embedding_model_mobile.pt"))
|
||||
// initDefFoodData(context)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,6 +51,11 @@ object FoodModule {
|
||||
// }
|
||||
|
||||
fun bitmap2FloatArray(originBitmap: Bitmap, isRecycle: Boolean): FloatArray? {
|
||||
// 模型未初始化时直接返回 null,避免 UninitializedPropertyAccessException
|
||||
if (!::module.isInitialized) {
|
||||
logInfo("bitmap2FloatArray: module 尚未初始化,跳过推理")
|
||||
return null
|
||||
}
|
||||
var rgb565Bitmap: Bitmap? = null
|
||||
try {
|
||||
val scaledBitmap = originBitmap.scale(MODEL_INPUT_WIDTH, MODEL_INPUT_HEIGHT)
|
||||
@@ -64,7 +69,7 @@ object FoodModule {
|
||||
NO_MEAN_RGB, // [0.485, 0.456, 0.406] TORCHVISION_NORM_MEAN_RGB
|
||||
NO_STD_RGB // [0.229, 0.224, 0.225] TORCHVISION_NORM_STD_RGB
|
||||
)
|
||||
val outputTensor = module_mobile.forward(IValue.from(inputTensor)).toTensor()
|
||||
val outputTensor = module.forward(IValue.from(inputTensor)).toTensor()
|
||||
return outputTensor.dataAsFloatArray
|
||||
} catch (e: OutOfMemoryError) {
|
||||
e.printStackTrace()
|
||||
@@ -124,7 +129,12 @@ object FoodModule {
|
||||
val nameScoreList = mutableListOf<IdNameScore>()
|
||||
idScoreList.forEach {
|
||||
val name = foodMap[it.id]?.name ?: ""
|
||||
nameScoreList.add(IdNameScore(id = it.id, name = name, score = it.score))
|
||||
val arr = name.split("&&")
|
||||
var rawMaterialsType = ""
|
||||
if (arr.size > 1) {
|
||||
rawMaterialsType = arr[1]
|
||||
}
|
||||
nameScoreList.add(IdNameScore(id = it.id, name = arr[0], score = it.score, rawMaterialsType = rawMaterialsType))
|
||||
}
|
||||
logInfo("queryFood数据:${nameScoreList.toJsonString()}")
|
||||
return nameScoreList
|
||||
@@ -176,7 +186,8 @@ object FoodModule {
|
||||
data class IdNameScore(
|
||||
val id: Long,
|
||||
var name: String,
|
||||
val score: Double
|
||||
val score: Double,
|
||||
val rawMaterialsType: String
|
||||
)
|
||||
|
||||
suspend fun initDefFoodData(context: Context, action: () -> Unit = {}) {
|
||||
|
||||
@@ -213,6 +213,11 @@ object ObjectBox {
|
||||
getBox<Food>()?.query(Food_.name.equal(name))?.build()?.remove()
|
||||
}
|
||||
|
||||
// 清除所有向量采集数据
|
||||
suspend fun removeAll() = safeDbOp {
|
||||
getBox<Food>()?.removeAll()
|
||||
}
|
||||
|
||||
/**
|
||||
* 按名称分组统计采集数量
|
||||
* 使用属性查询只加载 name 字段,不加载 foodVector,节省大量内存
|
||||
|
||||
@@ -28,7 +28,6 @@ class MdnsDiscoveryManager(private val context: Context) {
|
||||
|
||||
/** 待解析队列,串行处理避免并发解析失败 */
|
||||
private val resolveQueue = LinkedList<NsdServiceInfo>()
|
||||
@Volatile
|
||||
private var isResolving = false
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,7 +6,7 @@ package com.shuwei.dish.match.scale
|
||||
*/
|
||||
object ScaleDeviceConfig {
|
||||
|
||||
const val DEVICE_ID_2 = "8fc2ab34-2137-3112-acca-f884ea8736d4"
|
||||
const val DEVICE_ID_2 = "0bd74d78-c221-3182-b5ee-55d86dd79283"//测试0bd74d78-c221-3182-b5ee-55d86dd79283 正式8fc2ab34-2137-3112-acca-f884ea8736d4
|
||||
const val DEVICE_ID_22 = "a46fa55c-113c-3511-bb1f-41e5eff77c4b"
|
||||
const val DEVICE_ID_18 = "1038da9f-c6eb-326e-a1d9-d6d3af978b22"
|
||||
const val DEVICE_ID_1 = "7cc0f6ea-f13d-3013-a867-fc998eb554ac"
|
||||
@@ -17,6 +17,9 @@ object ScaleDeviceConfig {
|
||||
/** 18个秤的显示顺序(按物理位置排列) */
|
||||
val SCALE_ORDER_18 = listOf(6, 5, 4, 3, 2, 1, 12, 11, 10, 9, 8, 7, 18, 17, 16, 15, 14, 13)
|
||||
|
||||
/** 1个秤的地址列表 */
|
||||
val SCALE_ORDER_1 = listOf(1)
|
||||
|
||||
/** 设备在列表中的显示顺序 */
|
||||
val DEVICE_ORDER = listOf(DEVICE_ID_2, DEVICE_ID_22, DEVICE_ID_18, DEVICE_ID_1)
|
||||
}
|
||||
|
||||
@@ -34,5 +34,7 @@ data class ScaleEvent(
|
||||
const val TYPE_SEASONING_ADDED = "seasoning_added"
|
||||
/** 调料槽位配置同步事件:主设备配置变更后广播给子设备 */
|
||||
const val TYPE_SEASONING_CONFIG = "seasoning_config"
|
||||
/** 清除数据事件:主设备通知所有子设备清除本机测试数据 */
|
||||
const val TYPE_CLEAR_DATA = "clear_data"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ import com.shuwei.dish.match.utils.NetworkUtil
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@@ -34,6 +36,9 @@ object ScaleServiceManager {
|
||||
|
||||
private const val TAG = "ScaleServiceManager"
|
||||
|
||||
@Volatile private var isStarted = false
|
||||
private var serviceScope: CoroutineScope? = null
|
||||
|
||||
private var mdnsRegister: MdnsRegisterManager? = null
|
||||
private var wsServer: ScaleWebSocketServer? = null
|
||||
private var udpSender: UdpBroadcastSender? = null
|
||||
@@ -71,6 +76,14 @@ object ScaleServiceManager {
|
||||
get() = wsServer?.onSeasoningConfig
|
||||
set(value) { wsServer?.onSeasoningConfig = value }
|
||||
|
||||
/**
|
||||
* 收到主设备下发的清除数据事件时的回调,仅子设备有效
|
||||
* 在子线程中调用,需自行切换到主线程更新 UI
|
||||
*/
|
||||
var onClearData: ((ScaleEvent) -> Unit)?
|
||||
get() = wsServer?.onClearData
|
||||
set(value) { wsServer?.onClearData = value }
|
||||
|
||||
/**
|
||||
* 向所有已连接子设备广播调料配置(主设备调用)
|
||||
* @param slots 全量槽位配置列表
|
||||
@@ -79,6 +92,16 @@ object ScaleServiceManager {
|
||||
wsClient?.sendToAllSlaves(buildConfigEvent(slots))
|
||||
}
|
||||
|
||||
/**
|
||||
* 通知所有已连接子设备清除本机数据(主设备调用)
|
||||
* 子设备收到后执行与主设备相同的清除逻辑
|
||||
*/
|
||||
fun sendClearData() {
|
||||
wsClient?.sendToAllSlaves(
|
||||
ScaleEvent(type = ScaleEvent.TYPE_CLEAR_DATA, deviceId = GlobalData.deviceId)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 向单台刚连接的子设备推送调料配置(连接时按需调用)
|
||||
* @param deviceId 目标子设备 ID
|
||||
@@ -117,6 +140,9 @@ object ScaleServiceManager {
|
||||
* 启动所有秤服务,在 Application.onCreate() 中调用
|
||||
*/
|
||||
fun start(context: Context) {
|
||||
if (isStarted) return
|
||||
isStarted = true
|
||||
serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
val deviceId = GlobalData.deviceId
|
||||
val role = GlobalData.deviceRole
|
||||
Log.d(TAG, "启动秤服务, deviceId=$deviceId, role=$role")
|
||||
@@ -128,9 +154,8 @@ object ScaleServiceManager {
|
||||
if (role == DeviceRole.MASTER) {
|
||||
startMasterServices(context, deviceId)
|
||||
} else {
|
||||
// 子设备:启动 UDP 广播,作为 mDNS 的兜底发现机制
|
||||
val localIp = getLocalIp(context)
|
||||
udpSender = UdpBroadcastSender(deviceId, localIp).also { it.start() }
|
||||
// 子设备:启动 UDP 广播,作为 mDNS 的兜底发现机制;每次广播时动态获取 IP,避免启动时网络未就绪导致 IP 为空
|
||||
udpSender = UdpBroadcastSender(deviceId = deviceId, ipProvider = { getLocalIp(context) }).also { it.start() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,17 +181,21 @@ object ScaleServiceManager {
|
||||
val client = ScaleWebSocketClient().also {
|
||||
it.onScaleData = { data -> aggregator?.onRemoteScaleData(data) }
|
||||
it.onScaleEvent = { event -> _onScaleEvent?.invoke(event) }
|
||||
it.onDeviceDisconnected = { remoteId -> aggregator?.removeDevice(remoteId) }
|
||||
it.onDeviceDisconnected = { remoteId ->
|
||||
aggregator?.removeDevice(remoteId)
|
||||
// 清除 UDP 缓存,确保子设备下次广播时能重新触发 onDeviceFound,立即重连而非等待指数退避
|
||||
udpReceiver?.removeDevice(remoteId)
|
||||
}
|
||||
it.onDeviceConnected = { remoteId ->
|
||||
// 子设备连接成功时,从 Room 读取全量配置并单独推送给该设备
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
val slots = BaseApp.instance!!.database.seasoningSlotDao()
|
||||
.queryAll()
|
||||
.map { slot ->
|
||||
serviceScope?.launch {
|
||||
val slots = BaseApp.instance?.database?.seasoningSlotDao()
|
||||
?.queryAll()
|
||||
?.map { slot ->
|
||||
ScaleEvent.SlotConfig(
|
||||
slot.deviceId, slot.address, slot.goodsId, slot.goodsName
|
||||
)
|
||||
}
|
||||
} ?: return@launch
|
||||
if (slots.isNotEmpty()) sendSeasoningConfigTo(remoteId, slots)
|
||||
}
|
||||
}
|
||||
@@ -225,6 +254,9 @@ object ScaleServiceManager {
|
||||
* 停止所有秤服务,在 Application.onTerminate() 或退出时调用
|
||||
*/
|
||||
fun stop() {
|
||||
serviceScope?.cancel()
|
||||
serviceScope = null
|
||||
isStarted = false
|
||||
mdnsDiscovery?.stopDiscovery()
|
||||
udpReceiver?.stop()
|
||||
udpSender?.stop()
|
||||
|
||||
@@ -43,6 +43,11 @@ class ScaleWebSocketClient {
|
||||
private val reconnectDelays = ConcurrentHashMap<String, Long>()
|
||||
/** 已主动移除的设备集合,不对其触发重连 */
|
||||
private val removedDevices = ConcurrentHashMap.newKeySet<String>()
|
||||
/**
|
||||
* 各设备的连接版本号,每次调用 connect() 时递增
|
||||
* doConnect 执行前校验版本,版本不匹配说明已有更新的连接请求,直接放弃本次连接
|
||||
*/
|
||||
private val connectVersions = ConcurrentHashMap<String, Int>()
|
||||
|
||||
private val scheduler: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()
|
||||
|
||||
@@ -66,14 +71,24 @@ class ScaleWebSocketClient {
|
||||
*/
|
||||
fun connect(deviceId: String, host: String, port: Int) {
|
||||
removedDevices.remove(deviceId)
|
||||
// 取消旧 IP 的重连任务,防止 IP 变化时新旧任务并发竞争
|
||||
// 取消旧重连任务,防止 IP 变化时新旧任务并发竞争
|
||||
reconnectTasks.remove(deviceId)?.cancel(false)
|
||||
reconnectDelays[deviceId] = RECONNECT_BASE_MS
|
||||
doConnect(deviceId, host, port)
|
||||
// 递增版本号:doConnect 执行前会校验版本,旧任务版本不匹配时直接放弃
|
||||
val version = (connectVersions[deviceId] ?: 0) + 1
|
||||
connectVersions[deviceId] = version
|
||||
doConnect(deviceId, host, port, version)
|
||||
}
|
||||
|
||||
private fun doConnect(deviceId: String, host: String, port: Int) {
|
||||
val url = "ws://$host:$port"
|
||||
private fun doConnect(deviceId: String, host: String, port: Int, version: Int = connectVersions[deviceId] ?: 0) {
|
||||
// 版本校验:若当前版本已被更新的 connect() 调用覆盖,放弃本次连接
|
||||
if (connectVersions[deviceId] != version) {
|
||||
Log.d(TAG, "放弃过期连接任务: $deviceId, version=$version")
|
||||
return
|
||||
}
|
||||
// IPv6 地址在 URL 中需用方括号包裹,否则 OkHttp 会将冒号后内容误解析为端口
|
||||
val formattedHost = if (host.contains(':')) "[$host]" else host
|
||||
val url = "ws://$formattedHost:$port"
|
||||
val request = Request.Builder().url(url).build()
|
||||
|
||||
val ws = httpClient.newWebSocket(request, object : WebSocketListener() {
|
||||
@@ -103,34 +118,46 @@ class ScaleWebSocketClient {
|
||||
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
|
||||
Log.w(TAG, "连接子设备失败: $deviceId, ${t.message}")
|
||||
connections.remove(deviceId)
|
||||
onDeviceDisconnected?.invoke(deviceId)
|
||||
scheduleReconnect(deviceId, host, port)
|
||||
// 使用 remove(key, value) 确保只移除自己的实例
|
||||
// 避免旧连接超时触发时误删新连接引用,导致 aggregator 错误清空新连接数据
|
||||
val removed = connections.remove(deviceId, webSocket)
|
||||
if (removed) {
|
||||
onDeviceDisconnected?.invoke(deviceId)
|
||||
scheduleReconnect(deviceId, host, port)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
|
||||
Log.d(TAG, "子设备连接已关闭: $deviceId, reason=$reason")
|
||||
connections.remove(deviceId)
|
||||
onDeviceDisconnected?.invoke(deviceId)
|
||||
scheduleReconnect(deviceId, host, port)
|
||||
// 同上:只有移除的是自己,才触发断线回调和重连
|
||||
val removed = connections.remove(deviceId, webSocket)
|
||||
if (removed) {
|
||||
onDeviceDisconnected?.invoke(deviceId)
|
||||
scheduleReconnect(deviceId, host, port)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
connections[deviceId] = ws
|
||||
// 写入新连接前先关闭旧连接,避免 IP 变化时旧 ws 对象悬空造成 TCP 资源泄漏
|
||||
connections.put(deviceId, ws)?.close(1000, "新连接替换")
|
||||
}
|
||||
|
||||
/**
|
||||
* 指数退避重连
|
||||
* 入口不拦截 removedDevices,仅在延迟任务执行前检查,
|
||||
* 确保 disconnect() 后已入队的任务不执行,但新断线事件始终能进入重连流程
|
||||
* scheduler 已关闭(shutdown 后)时直接跳过,避免 RejectedExecutionException
|
||||
*/
|
||||
private fun scheduleReconnect(deviceId: String, host: String, port: Int) {
|
||||
if (scheduler.isShutdown) return
|
||||
val delay = reconnectDelays[deviceId] ?: RECONNECT_BASE_MS
|
||||
Log.d(TAG, "将在 ${delay}ms 后重连子设备: $deviceId")
|
||||
// 记录当前版本,延迟任务执行时再次校验,防止期间有新的 connect() 调用
|
||||
val version = connectVersions[deviceId] ?: 0
|
||||
|
||||
val future = scheduler.schedule({
|
||||
if (!removedDevices.contains(deviceId)) {
|
||||
doConnect(deviceId, host, port)
|
||||
doConnect(deviceId, host, port, version)
|
||||
}
|
||||
}, delay, TimeUnit.MILLISECONDS)
|
||||
|
||||
@@ -186,6 +213,7 @@ class ScaleWebSocketClient {
|
||||
reconnectTasks.remove(deviceId)?.cancel(false)
|
||||
connections.remove(deviceId)?.close(1000, "设备离线")
|
||||
reconnectDelays.remove(deviceId)
|
||||
connectVersions.remove(deviceId)
|
||||
Log.d(TAG, "已断开子设备: $deviceId")
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,11 @@ import org.java_websocket.WebSocket
|
||||
import org.java_websocket.handshake.ClientHandshake
|
||||
import org.java_websocket.server.WebSocketServer
|
||||
import java.net.InetSocketAddress
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.ScheduledFuture
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
* 秤数据 WebSocket 服务端(主设备和子设备均运行)
|
||||
@@ -20,10 +25,14 @@ class ScaleWebSocketServer(private val deviceId: String, private val context: Co
|
||||
private const val TAG = "ScaleWebSocketServer"
|
||||
/** 节流间隔:两次推送之间的最小间隔(毫秒) */
|
||||
private const val THROTTLE_MS = 100L
|
||||
/** latestData 为空时延迟补推的时间(毫秒),给 WeightUtil 时间产生第一次读数 */
|
||||
private const val RETRY_PUSH_DELAY_MS = 3_000L
|
||||
}
|
||||
|
||||
private val gson = Gson()
|
||||
private var server: InternalServer? = null
|
||||
/** 延迟补推任务的调度器 */
|
||||
private val scheduler = Executors.newSingleThreadScheduledExecutor()
|
||||
|
||||
/** 主设备连接状态变化回调:true=已连接,false=已断开;在主线程外调用,需自行切换线程 */
|
||||
var onConnectionChanged: ((connected: Boolean) -> Unit)? = null
|
||||
@@ -31,15 +40,21 @@ class ScaleWebSocketServer(private val deviceId: String, private val context: Co
|
||||
/** 收到主设备下发的调料配置同步事件时的回调,在子线程调用 */
|
||||
var onSeasoningConfig: ((event: ScaleEvent) -> Unit)? = null
|
||||
|
||||
/** 收到主设备下发的清除数据事件时的回调,在子线程调用 */
|
||||
var onClearData: ((event: ScaleEvent) -> Unit)? = null
|
||||
|
||||
/** 当前是否有主设备连接 */
|
||||
val isConnected: Boolean
|
||||
get() = server?.connections?.isNotEmpty() == true
|
||||
|
||||
/** 每个秤地址的最近一次推送时间,用于节流 */
|
||||
private val lastPushTime = mutableMapOf<Int, Long>()
|
||||
private val lastPushTime = ConcurrentHashMap<Int, Long>()
|
||||
|
||||
/** 缓存各秤最新数据,新客户端连接时立即同步当前状态 */
|
||||
private val latestData = mutableMapOf<Int, ScaleData>()
|
||||
private val latestData = ConcurrentHashMap<Int, ScaleData>()
|
||||
|
||||
/** 节流窗口内的延迟推送任务,key=address;保证窗口结束时最新数据被推送 */
|
||||
private val pendingPushTasks = ConcurrentHashMap<Int, ScheduledFuture<*>>()
|
||||
|
||||
/**
|
||||
* 启动 WebSocket 服务器,并注册 WeightUtil 回调
|
||||
@@ -52,11 +67,12 @@ class ScaleWebSocketServer(private val deviceId: String, private val context: Co
|
||||
|
||||
// 注册本机秤数据监听
|
||||
WeightUtil.addWeightListener(TAG) { address, state, weight ->
|
||||
Log.d(TAG, "WebSocket 设备${deviceId}推送数据, address=$address, state=$state, weight=$weight")
|
||||
val now = System.currentTimeMillis()
|
||||
// 节流:同一地址 100ms 内只推送一次
|
||||
if (now - (lastPushTime[address] ?: 0L) < THROTTLE_MS) return@addWeightListener
|
||||
// 数据未变化时直接跳过,避免无效推送
|
||||
val last = latestData[address]
|
||||
if (last?.weight == weight && last.state == state) return@addWeightListener
|
||||
|
||||
lastPushTime[address] = now
|
||||
val data = ScaleData(
|
||||
deviceId = deviceId,
|
||||
address = address,
|
||||
@@ -65,8 +81,28 @@ class ScaleWebSocketServer(private val deviceId: String, private val context: Co
|
||||
ts = now,
|
||||
ip = NetworkUtil.getLocalIpAddress(context)
|
||||
)
|
||||
// 始终更新 latestData,保证最新一帧不丢失
|
||||
latestData[address] = data
|
||||
broadcast(gson.toJson(data))
|
||||
|
||||
val lastPush = lastPushTime[address] ?: 0L
|
||||
if (now - lastPush >= THROTTLE_MS) {
|
||||
// 窗口已过:立即推送,并取消可能存在的延迟任务
|
||||
lastPushTime[address] = now
|
||||
pendingPushTasks.remove(address)?.cancel(false)
|
||||
broadcast(gson.toJson(data))
|
||||
} else if (pendingPushTasks[address] == null) {
|
||||
// 窗口内首次触发:安排 trailing 推送,保证窗口末尾推最新值
|
||||
val delay = THROTTLE_MS - (now - lastPush)
|
||||
if (!scheduler.isShutdown) {
|
||||
pendingPushTasks[address] = scheduler.schedule({
|
||||
val latest = latestData[address] ?: return@schedule
|
||||
lastPushTime[address] = System.currentTimeMillis()
|
||||
pendingPushTasks.remove(address)
|
||||
broadcast(gson.toJson(latest))
|
||||
}, delay, TimeUnit.MILLISECONDS)
|
||||
}
|
||||
}
|
||||
// 窗口内且已安排过 trailing 任务:仅更新 latestData,等 trailing 触发时推送
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,6 +113,8 @@ class ScaleWebSocketServer(private val deviceId: String, private val context: Co
|
||||
WeightUtil.removeWeightListener(TAG)
|
||||
onConnectionChanged = null
|
||||
onSeasoningConfig = null
|
||||
onClearData = null
|
||||
scheduler.shutdownNow()
|
||||
try {
|
||||
server?.stop(1000)
|
||||
} catch (e: Exception) {
|
||||
@@ -85,6 +123,8 @@ class ScaleWebSocketServer(private val deviceId: String, private val context: Co
|
||||
server = null
|
||||
latestData.clear()
|
||||
lastPushTime.clear()
|
||||
pendingPushTasks.values.forEach { it.cancel(false) }
|
||||
pendingPushTasks.clear()
|
||||
Log.d(TAG, "WebSocket 服务端已停止")
|
||||
}
|
||||
|
||||
@@ -117,23 +157,47 @@ class ScaleWebSocketServer(private val deviceId: String, private val context: Co
|
||||
private inner class InternalServer(port: Int) :
|
||||
WebSocketServer(InetSocketAddress(port)) {
|
||||
|
||||
/** 当前活跃连接计数,用于替代 connections.isNullOrEmpty() 避免竞态 */
|
||||
private val connectionCount = AtomicInteger(0)
|
||||
|
||||
override fun onOpen(conn: WebSocket, handshake: ClientHandshake) {
|
||||
connectionCount.incrementAndGet()
|
||||
Log.d(TAG, "主设备已连接: ${conn.remoteSocketAddress}")
|
||||
onConnectionChanged?.invoke(true)
|
||||
|
||||
// 新客户端连接后,立即推送所有秤的最新数据
|
||||
latestData.values.forEach { data ->
|
||||
try {
|
||||
conn.send(gson.toJson(data))
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "初始推送失败: ${e.message}")
|
||||
if (latestData.isNotEmpty()) {
|
||||
latestData.values.forEach { data ->
|
||||
try {
|
||||
conn.send(gson.toJson(data))
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "初始推送失败: ${e.message}")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// latestData 为空说明刚重启,WeightUtil 还未产生读数
|
||||
// 延迟 3 秒后补推一次,确保主设备能看到本机秤
|
||||
Log.d(TAG, "latestData 为空,${RETRY_PUSH_DELAY_MS}ms 后补推")
|
||||
scheduler.schedule({
|
||||
if (conn.isOpen && latestData.isNotEmpty()) {
|
||||
latestData.values.forEach { data ->
|
||||
try {
|
||||
conn.send(gson.toJson(data))
|
||||
Log.d(TAG, "补推数据: address=${data.address}, weight=${data.weight}")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "补推失败: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}, RETRY_PUSH_DELAY_MS, TimeUnit.MILLISECONDS)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onClose(conn: WebSocket, code: Int, reason: String, remote: Boolean) {
|
||||
Log.d(TAG, "主设备已断开: ${conn.remoteSocketAddress}, reason=$reason")
|
||||
// 若已无任何连接,通知子设备 UI 更新为未连接状态
|
||||
if (server?.connections.isNullOrEmpty()) {
|
||||
// 用计数器判断是否还有活跃连接,避免依赖 connections 集合的移除时机导致竞态
|
||||
if (connectionCount.decrementAndGet() <= 0) {
|
||||
connectionCount.set(0)
|
||||
onConnectionChanged?.invoke(false)
|
||||
}
|
||||
}
|
||||
@@ -146,6 +210,7 @@ class ScaleWebSocketServer(private val deviceId: String, private val context: Co
|
||||
val event = gson.fromJson(message, ScaleEvent::class.java)
|
||||
when (event.type) {
|
||||
ScaleEvent.TYPE_SEASONING_CONFIG -> onSeasoningConfig?.invoke(event)
|
||||
ScaleEvent.TYPE_CLEAR_DATA -> onClearData?.invoke(event)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -13,10 +13,12 @@ import java.util.concurrent.TimeUnit
|
||||
* UDP 广播发送器(子设备运行)
|
||||
* 每隔固定间隔向局域网广播本机的 deviceId、IP、WebSocket 端口
|
||||
* 作为 mDNS 的兜底发现机制,确保主设备能可靠发现子设备
|
||||
*
|
||||
* @param ipProvider 动态获取本机 IP 的函数,每次广播时调用;返回空字符串时跳过本次广播
|
||||
*/
|
||||
class UdpBroadcastSender(
|
||||
private val deviceId: String,
|
||||
private val localIp: String,
|
||||
private val ipProvider: () -> String,
|
||||
private val wsPort: Int = MdnsRegisterManager.WS_PORT
|
||||
) {
|
||||
|
||||
@@ -43,12 +45,18 @@ class UdpBroadcastSender(
|
||||
task = scheduler.scheduleWithFixedDelay({
|
||||
sendBroadcast()
|
||||
}, 0, INTERVAL_SEC, TimeUnit.SECONDS)
|
||||
Log.d(TAG, "UDP 广播已启动, deviceId=$deviceId, ip=$localIp, port=$wsPort")
|
||||
Log.d(TAG, "UDP 广播已启动, deviceId=$deviceId, port=$wsPort")
|
||||
}
|
||||
|
||||
private fun sendBroadcast() {
|
||||
try {
|
||||
val payload = gson.toJson(Payload(deviceId, localIp, wsPort))
|
||||
val ip = ipProvider()
|
||||
// 网络未就绪时跳过本次广播,等待下一个周期重试
|
||||
if (ip.isEmpty()) {
|
||||
Log.d(TAG, "IP 未就绪,跳过本次广播")
|
||||
return
|
||||
}
|
||||
val payload = gson.toJson(Payload(deviceId, ip, wsPort))
|
||||
val data = payload.toByteArray(Charsets.UTF_8)
|
||||
DatagramSocket().use { socket ->
|
||||
socket.broadcast = true
|
||||
|
||||
@@ -19,14 +19,16 @@ import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.databinding.ActivityCollectedFoodBinding
|
||||
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.entity.CollectedFoodItem
|
||||
import com.shuwei.dish.match.model.CollectedFoodItem
|
||||
import com.shuwei.dish.match.utils.KeyboardUtil
|
||||
import com.shuwei.dish.match.utils.ext.appendText
|
||||
import com.shuwei.dish.match.utils.ext.buildSpannableString
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.collections.getOrNull
|
||||
|
||||
/**
|
||||
* 已采集食材列表页面
|
||||
@@ -45,14 +47,31 @@ class CollectedFoodActivity : BaseActivity() {
|
||||
isStateViewEnable = true
|
||||
// 点击删除按钮,移除对应食材
|
||||
addOnItemChildClickListener(R.id.ivDelete) { _, _, position ->
|
||||
showDeleteDialog(foodList[position].foodName)
|
||||
val item = foodList.getOrNull(position) ?: return@addOnItemChildClickListener
|
||||
showDeleteDialog(item.foodName)
|
||||
}
|
||||
setOnItemClickListener { _, view, _ ->
|
||||
KeyboardUtil.hideKeyboard(view)
|
||||
setOnItemClickListener { _, _, _ ->
|
||||
hideKeyboard()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除所有采集数据确认弹窗
|
||||
*/
|
||||
private fun showClearAllDialog() {
|
||||
CommonDialog(this)
|
||||
.setTitle("清除提示")
|
||||
.setContent("清除后无法恢复,确认要清除所有采集数据吗?")
|
||||
.setNegativeButton("取消")
|
||||
.setPositiveButton("确认") {
|
||||
dbViewModel.clearAllCollectedFood {
|
||||
toast("已清除所有采集数据")
|
||||
}
|
||||
}
|
||||
.show()
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除弹窗
|
||||
*/
|
||||
@@ -69,7 +88,7 @@ class CollectedFoodActivity : BaseActivity() {
|
||||
.setContent(content)
|
||||
.setNegativeButton("取消")
|
||||
.setPositiveButton("确认") {
|
||||
appViewModel.removeCollectedFood(
|
||||
dbViewModel.removeCollectedFood(
|
||||
foodName = foodName,
|
||||
nameFilter = binding.editSearch.text.toString()
|
||||
)
|
||||
@@ -84,17 +103,22 @@ class CollectedFoodActivity : BaseActivity() {
|
||||
setContentView(binding.root)
|
||||
setHeaderBackground()
|
||||
binding.root.setOnClickListener { v ->
|
||||
KeyboardUtil.hideKeyboard(v)
|
||||
hideKeyboard()
|
||||
}
|
||||
setTitleBar(titleBarAction = {
|
||||
it.visible()
|
||||
it.setOnClickListener { v ->
|
||||
KeyboardUtil.hideKeyboard(v)
|
||||
hideKeyboard()
|
||||
}
|
||||
}, titleAction = {
|
||||
it.text = "已采集食材"
|
||||
}, rightIconActon = {
|
||||
it.gone()
|
||||
}, rightIconAction = {
|
||||
it.visible()
|
||||
it.setPaddingRelative(25.dp ,0 ,25.dp ,0)
|
||||
it.setImageResource(R.drawable.ic_trash_white)
|
||||
it.setOnClickListener {
|
||||
showClearAllDialog()
|
||||
}
|
||||
}, backAction = {
|
||||
it.visible()
|
||||
it.setOnClickListener {
|
||||
@@ -108,7 +132,7 @@ class CollectedFoodActivity : BaseActivity() {
|
||||
}
|
||||
|
||||
private fun loadCollectedFoodList(name: String = "") {
|
||||
appViewModel.loadCollectedFoodList(nameFilter = name)
|
||||
dbViewModel.loadCollectedFoodList(nameFilter = name)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -118,7 +142,7 @@ class CollectedFoodActivity : BaseActivity() {
|
||||
private fun initObserver() {
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
appViewModel.collectedFoodListState.collect { items ->
|
||||
dbViewModel.collectedFoodListState.collect { items ->
|
||||
foodList.clear()
|
||||
foodList.addAll(items)
|
||||
adapter.notifyDataSetChanged()
|
||||
@@ -156,7 +180,7 @@ class CollectedFoodActivity : BaseActivity() {
|
||||
performSearch {
|
||||
toast(binding.editSearch.hint.toString())
|
||||
}
|
||||
KeyboardUtil.hideKeyboard(v)
|
||||
hideKeyboard()
|
||||
}
|
||||
binding.editSearch.run {
|
||||
addTextChangedListener {
|
||||
@@ -169,7 +193,7 @@ class CollectedFoodActivity : BaseActivity() {
|
||||
performSearch {
|
||||
toast(binding.editSearch.hint.toString())
|
||||
}
|
||||
KeyboardUtil.hideKeyboard(v)
|
||||
hideKeyboard()
|
||||
true
|
||||
} else {
|
||||
false
|
||||
|
||||
@@ -3,13 +3,14 @@ package com.shuwei.dish.match.ui
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import androidx.activity.addCallback
|
||||
import androidx.core.widget.addTextChangedListener
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import kotlinx.coroutines.launch
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.databinding.ActivityCookingModeBinding
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.ui.fragment.DishListFragment
|
||||
import com.shuwei.dish.match.ui.fragment.FoodListFragment
|
||||
import com.shuwei.dish.match.utils.KeyboardUtil
|
||||
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
@@ -32,10 +33,10 @@ class CookingModeActivity : BaseActivity() {
|
||||
|
||||
private var dinnerType: String = "1"
|
||||
|
||||
private val fragmentList = mutableListOf<DishListFragment>().apply {
|
||||
add(DishListFragment.instance("1"))
|
||||
add(DishListFragment.instance("2"))
|
||||
add(DishListFragment.instance("3"))
|
||||
private val fragmentList = mutableListOf<FoodListFragment>().apply {
|
||||
add(FoodListFragment.instance("1"))
|
||||
add(FoodListFragment.instance("2"))
|
||||
add(FoodListFragment.instance("3"))
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
@@ -46,7 +47,7 @@ class CookingModeActivity : BaseActivity() {
|
||||
it.visible()
|
||||
}, titleAction = {
|
||||
it.text = "选择菜品"
|
||||
}, rightIconActon = {
|
||||
}, rightIconAction = {
|
||||
it.visible()
|
||||
it.setImageResource(R.drawable.ic_setting)
|
||||
it.setOnClickListener {
|
||||
@@ -62,7 +63,7 @@ class CookingModeActivity : BaseActivity() {
|
||||
|
||||
|
||||
fun getCookFoodList() {
|
||||
appViewModel.getCookFoodList(cookMode = 0, dinnerType = dinnerType)
|
||||
dbViewModel.getCookFoodList(cookMode = 0, dinnerType = dinnerType)
|
||||
}
|
||||
|
||||
private var configFinished = false
|
||||
@@ -72,7 +73,7 @@ class CookingModeActivity : BaseActivity() {
|
||||
// block()
|
||||
// return
|
||||
// }
|
||||
// appViewModel.loadSeasoning {
|
||||
// dbViewModel.loadSeasoning {
|
||||
// if (it.isEmpty()) {
|
||||
// showDeviceConfigDialog()
|
||||
// return@loadSeasoning
|
||||
@@ -92,22 +93,44 @@ class CookingModeActivity : BaseActivity() {
|
||||
.show()
|
||||
}
|
||||
|
||||
fun addViewListener() {
|
||||
binding.dishRadioGroup.setOnCheckedChangeListener { _, checkedId ->
|
||||
dinnerType = when (checkedId) {
|
||||
R.id.rbBreakfast -> "1"
|
||||
R.id.rbLunch -> "2"
|
||||
R.id.rbDinner -> "3"
|
||||
else -> "1"
|
||||
}
|
||||
loadFragment()
|
||||
}
|
||||
/** 切换餐次时清空输入框,用此标志跳过 afterTextChanged 的查询触发 */
|
||||
private var isClearingByTabSwitch = false
|
||||
|
||||
private fun addViewListener() {
|
||||
binding.tvBreakfast.setOnClickListener { selectTab("1") }
|
||||
binding.tvLunch.setOnClickListener { selectTab("2") }
|
||||
binding.tvDinner.setOnClickListener { selectTab("3") }
|
||||
binding.etInputDish.addOnActionSearchListener {
|
||||
jumpSearch()
|
||||
}
|
||||
binding.ivDishSearch.setOnClickListener {
|
||||
jumpSearch()
|
||||
}
|
||||
// 输入框清空时自动查询全部数据(切换餐次触发的清空除外,由 loadFragment 负责刷新)
|
||||
binding.etInputDish.addTextChangedListener(afterTextChanged = { text ->
|
||||
if (!isClearingByTabSwitch && text.isNullOrBlank()) {
|
||||
currentFragment()?.getDishList(pageNo = 1, dinnerType = dinnerType)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换餐次 Tab:更新选中态、清空搜索框、切换 Fragment
|
||||
* 由点击事件调用,不触发额外的 getDishList(),由 onHiddenChanged 负责刷新
|
||||
*/
|
||||
private fun selectTab(type: String) {
|
||||
if (dinnerType == type) return
|
||||
dinnerType = type
|
||||
binding.tvBreakfast.isChecked = type == "1"
|
||||
binding.tvLunch.isChecked = type == "2"
|
||||
binding.tvDinner.isChecked = type == "3"
|
||||
clearSearchText()
|
||||
loadFragment()
|
||||
}
|
||||
|
||||
/** 获取当前显示的 FoodListFragment */
|
||||
private fun currentFragment(): FoodListFragment? {
|
||||
return runCatching { fragmentList[dinnerType.toInt() - 1] }.getOrNull()
|
||||
}
|
||||
|
||||
private fun jumpSearch() {
|
||||
@@ -116,34 +139,31 @@ class CookingModeActivity : BaseActivity() {
|
||||
toast(binding.etInputDish.hint.toString())
|
||||
return
|
||||
}
|
||||
startActivity<FoodSearchActivity> {
|
||||
putExtra(FoodSearchActivity.PAGE_TYPE, 1)
|
||||
putExtra(FoodSearchActivity.DINNER_TYPE, dinnerType)
|
||||
putExtra(FoodSearchActivity.FOOD_NAME, searchText)
|
||||
}
|
||||
KeyboardUtil.hideKeyboard(binding.etInputDish)
|
||||
currentFragment()?.getDishList(pageNo = 1, dinnerType = dinnerType, foodName = searchText)
|
||||
hideKeyboard()
|
||||
}
|
||||
|
||||
private fun loadFragment() {
|
||||
runCatching {
|
||||
fragmentList[dinnerType.toInt() - 1].let {
|
||||
supportFragmentManager.beginTransaction().apply {
|
||||
if (fragmentList.contains(it)) {
|
||||
replace(R.id.flSubPage, it)
|
||||
val target = fragmentList[dinnerType.toInt() - 1]
|
||||
supportFragmentManager.beginTransaction().apply {
|
||||
fragmentList.forEach { fragment ->
|
||||
if (fragment.isAdded) {
|
||||
if (fragment == target) show(fragment) else hide(fragment)
|
||||
} else {
|
||||
add(R.id.flSubPage, it)
|
||||
if (fragment == target) add(R.id.flSubPage, fragment)
|
||||
}
|
||||
commit()
|
||||
}
|
||||
commit()
|
||||
}
|
||||
}.onFailure {
|
||||
it.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteCookFoodAndGoods(foodId: String, action: () -> Unit) {
|
||||
fun deleteCookFoodAndGoods(foodId: String, dinnerType: String, action: () -> Unit) {
|
||||
lifecycleScope.launch {
|
||||
appViewModel.deleteCookFoodAndGoods(cookMode = 0, foodId = foodId)
|
||||
dbViewModel.deleteCookFoodAndGoods(cookMode = 0, foodId = foodId, dinnerType = dinnerType)
|
||||
action()
|
||||
}
|
||||
}
|
||||
@@ -151,19 +171,19 @@ class CookingModeActivity : BaseActivity() {
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
runCatching {
|
||||
val isConfigPage = intent?.getBooleanExtra(IS_CONFIG_PAGE, false) ?: false
|
||||
val isConfigPage = intent.getBooleanExtra(IS_CONFIG_PAGE, false)
|
||||
if (isConfigPage) {
|
||||
return
|
||||
}
|
||||
val isCooking = intent?.getBooleanExtra(IS_COOKING, false) ?: false
|
||||
val lastDinnerType = intent?.getStringExtra(DINNER_TYPE) ?: "0"
|
||||
if (lastDinnerType == "1" || lastDinnerType == "2" || lastDinnerType == "3") {
|
||||
fragmentList[lastDinnerType.toInt() - 1].getDishList(1, lastDinnerType)
|
||||
}
|
||||
when (lastDinnerType) {
|
||||
"1" -> binding.dishRadioGroup.check(R.id.rbBreakfast)
|
||||
"2" -> binding.dishRadioGroup.check(R.id.rbLunch)
|
||||
"3" -> binding.dishRadioGroup.check(R.id.rbDinner)
|
||||
val lastDinnerType = intent.getStringExtra(DINNER_TYPE) ?: "0"
|
||||
if (lastDinnerType !in listOf("1", "2", "3")) return
|
||||
if (lastDinnerType == dinnerType) {
|
||||
// 同一 Tab:onHiddenChanged 不会触发,直接刷新
|
||||
clearSearchText()
|
||||
currentFragment()?.getDishList(1, lastDinnerType)
|
||||
} else {
|
||||
// 不同 Tab:selectTab → loadFragment → show → onHiddenChanged 负责刷新,无需直接调用
|
||||
selectTab(lastDinnerType)
|
||||
}
|
||||
}.onFailure {
|
||||
it.printStackTrace()
|
||||
@@ -181,8 +201,10 @@ class CookingModeActivity : BaseActivity() {
|
||||
isVisible = false
|
||||
}
|
||||
|
||||
public fun getFoodList(param: MutableMap<String, Any>) {
|
||||
netViewModel.searchFoodList(param = param)
|
||||
fun clearSearchText() {
|
||||
isClearingByTabSwitch = true
|
||||
binding.etInputDish.text?.clear()
|
||||
isClearingByTabSwitch = false
|
||||
}
|
||||
|
||||
}
|
||||
@@ -77,7 +77,7 @@
|
||||
// it.visible()
|
||||
// }, titleAction = {
|
||||
// it.text = "设备配置"
|
||||
// }, rightIconActon = {
|
||||
// }, rightIconAction = {
|
||||
// it.gone()
|
||||
//// it.alpha = 0.0F
|
||||
//// it.setImageResource(R.drawable.ic_setting)
|
||||
|
||||
@@ -7,19 +7,28 @@ import androidx.activity.addCallback
|
||||
import androidx.core.content.IntentCompat
|
||||
import androidx.recyclerview.widget.GridLayoutManager
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.shuwei.dish.match.adapter.GoodsInfoSearchAdapter
|
||||
import com.shuwei.dish.match.adapter.FoodAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.databinding.ActivityFoodRecognizeBinding
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.dialog.FoodSearchDialog
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
import com.shuwei.dish.match.model.GoodsNameQueryDTO
|
||||
import com.shuwei.dish.match.utils.ActivityManager
|
||||
import com.shuwei.dish.match.utils.AddressUtil
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
import androidx.core.net.toUri
|
||||
import androidx.core.view.updateLayoutParams
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import com.shuwei.dish.match.net.UiState
|
||||
import com.shuwei.dish.match.objbox.FoodModule
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import com.shuwei.dish.match.utils.showRawMaterialsDialog
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* 食材识别结果页面
|
||||
@@ -31,30 +40,32 @@ class FoodRecognizeActivity : BaseActivity() {
|
||||
private const val TAG = "FoodRecognizeActivity"
|
||||
private const val EXTRA_IMAGE_URI = "extra_image_uri"
|
||||
private const val EXTRA_CURRENT_WEIGHT = "extra_current_weight"
|
||||
private const val EXTRA_INITIAL_WEIGHT = "extra_initial_weight"
|
||||
const val EXTRA_SELECTED_ITEM = "extra_selected_item"
|
||||
const val IS_MANUAL_CANCEL = "isManualCancel"
|
||||
|
||||
/** 内存缓存食材列表,避免通过 Intent 序列化传递大数据 */
|
||||
private var pendingGoodsList: ArrayList<CookFoodGoodsEntity>? = null
|
||||
private var recognizeNameList: ArrayList<FoodModule.IdNameScore>? = null
|
||||
|
||||
/**
|
||||
* 启动本页面,通过 onResult 回调返回用户选中的食材
|
||||
* @param activity 宿主 Activity
|
||||
* @param imageUri 食材照片路径(可为空)
|
||||
* @param goodsList 识别到的食材列表
|
||||
* @param nameScoreList 识别到的食材列表
|
||||
* @param finishCallback 页面关闭后回调,携带用户选中的食材(未选中时为 null)
|
||||
*/
|
||||
fun start(
|
||||
activity: BaseActivity,
|
||||
imageUri: String? = null,
|
||||
currentWeight: Double = 0.0,
|
||||
goodsList: ArrayList<CookFoodGoodsEntity> = arrayListOf(),
|
||||
finishCallback: (Boolean, CookFoodGoodsEntity?) -> Unit = { _, _ -> }
|
||||
initialWeight: Double = 0.0,
|
||||
nameScoreList: ArrayList<FoodModule.IdNameScore> = arrayListOf(),
|
||||
finishCallback: (Boolean, GoodsItem?) -> Unit = { _, _ -> }
|
||||
) {
|
||||
pendingGoodsList = goodsList
|
||||
recognizeNameList = nameScoreList
|
||||
val launchIntent = Intent(activity, FoodRecognizeActivity::class.java).apply {
|
||||
putExtra(EXTRA_IMAGE_URI, imageUri)
|
||||
putExtra(EXTRA_CURRENT_WEIGHT, currentWeight)
|
||||
putExtra(EXTRA_INITIAL_WEIGHT, initialWeight)
|
||||
}
|
||||
activity.startActivity(launchIntent) { resultIntent ->
|
||||
val isManualCancel = resultIntent?.getBooleanExtra(IS_MANUAL_CANCEL, false) ?: false
|
||||
@@ -62,7 +73,8 @@ class FoodRecognizeActivity : BaseActivity() {
|
||||
IntentCompat.getSerializableExtra(
|
||||
it,
|
||||
EXTRA_SELECTED_ITEM,
|
||||
CookFoodGoodsEntity::class.java)
|
||||
GoodsItem::class.java
|
||||
)
|
||||
}
|
||||
finishCallback(isManualCancel, entity)
|
||||
}
|
||||
@@ -82,19 +94,22 @@ class FoodRecognizeActivity : BaseActivity() {
|
||||
|
||||
private lateinit var binding: ActivityFoodRecognizeBinding
|
||||
|
||||
private val list = mutableListOf<CookFoodGoodsEntity>()
|
||||
private val list = mutableListOf<GoodsItem>()
|
||||
|
||||
/** 当前选中的列表位置,-1 表示无选中 */
|
||||
private var selectedPosition = -1
|
||||
|
||||
/** 秤1当前实时重量 */
|
||||
/** 秤1当前实时净重(已减去初始读数) */
|
||||
private var currentWeight = 0.0
|
||||
|
||||
/** 重量减少时延迟更新的任务,页面关闭前取消可防止用错误重量 */
|
||||
private var pendingWeightRunnable: Runnable? = null
|
||||
/** 初始秤读数,净重 = 秤读数 - initialWeight */
|
||||
private var initialWeight = 0.0
|
||||
|
||||
/** 当前待延迟更新的目标重量,避免相同重量重复重置计时器 */
|
||||
private var pendingWeight = 0.0
|
||||
/**
|
||||
* 滑动窗口:保存最近 10 条稳定帧净重,用于关闭页面时判断数据是否稳定
|
||||
* 超过 10 条时移除队头,保持最新数据
|
||||
*/
|
||||
private val weightWindow = ArrayDeque<Double>(10)
|
||||
|
||||
/** 右侧自定义滚动指示条最小高度 */
|
||||
private val scrollIndicatorMinHeightPx by lazy { (24 * resources.displayMetrics.density).toInt() }
|
||||
@@ -102,20 +117,49 @@ class FoodRecognizeActivity : BaseActivity() {
|
||||
/** 食材搜索弹窗,持有引用防止重复打开 */
|
||||
private var foodSearchDialog: FoodSearchDialog? = null
|
||||
|
||||
/** 数据不稳定提示弹窗,持有引用通过 isShowing 防止重复弹出 */
|
||||
private var unstableDialog: CommonDialog? = null
|
||||
|
||||
/** 通过name查询IdNameScore */
|
||||
private val nameScoreMap = mutableMapOf<String, FoodModule.IdNameScore>()
|
||||
|
||||
/** 识别物品名称列表(名称 + 净材种类,用于批量查询接口) */
|
||||
private val goodsNameList = mutableListOf<GoodsNameQueryDTO>()
|
||||
|
||||
private val scrollListener = object : RecyclerView.OnScrollListener() {
|
||||
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
|
||||
updateScrollIndicator()
|
||||
}
|
||||
}
|
||||
|
||||
private val adapter = GoodsInfoSearchAdapter(list).apply {
|
||||
private val adapter = FoodAdapter(list).apply {
|
||||
setOnItemClickListener { _, _, position ->
|
||||
list.forEachIndexed { i, item -> item.isClicked = (i == position) }
|
||||
// rawMaterialsRemind(position)
|
||||
val item = list.getOrNull(position) ?: return@setOnItemClickListener
|
||||
list.forEachIndexed { i, it -> it.isClicked = (i == position) }
|
||||
// 点击选择时记录当前秤重量
|
||||
list[position].useWeight = currentWeight
|
||||
item.useWeight = currentWeight
|
||||
notifyDataSetChanged()
|
||||
selectedPosition = position
|
||||
binding.tvSelectedFood.text = list[position].goodsName ?: "-"
|
||||
binding.tvSelectedFood.text = item.goodsName ?: "-"
|
||||
}
|
||||
}
|
||||
|
||||
private fun rawMaterialsRemind(position: Int) {
|
||||
val item = list.getOrNull(position) ?: return
|
||||
// 弹出净材种类单选弹窗,确认后再选中该食材
|
||||
showRawMaterialsDialog(
|
||||
context = this@FoodRecognizeActivity,
|
||||
types = item.rawMaterialsTypes,
|
||||
checkedType = item.rawMaterialsType
|
||||
) { selectedType ->
|
||||
item.rawMaterialsType = selectedType
|
||||
list.forEachIndexed { i, it -> it.isClicked = (i == position) }
|
||||
// 点击选择时记录当前秤重量
|
||||
item.useWeight = currentWeight
|
||||
adapter.notifyDataSetChanged()
|
||||
selectedPosition = position
|
||||
binding.tvSelectedFood.text = item.goodsName ?: "-"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,8 +180,6 @@ class FoodRecognizeActivity : BaseActivity() {
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
initData()
|
||||
initRecyclerView()
|
||||
updateRvParentLayoutHeight()
|
||||
initClickListeners()
|
||||
@@ -145,6 +187,8 @@ class FoodRecognizeActivity : BaseActivity() {
|
||||
onBackPressedDispatcher.addCallback(this) {
|
||||
manualBack()
|
||||
}
|
||||
initObserver()
|
||||
initData()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -156,33 +200,117 @@ class FoodRecognizeActivity : BaseActivity() {
|
||||
|
||||
/**
|
||||
* 从 Intent 读取数据并初始化页面
|
||||
* Reads data from Intent and initializes the page
|
||||
*/
|
||||
private fun initData() {
|
||||
// 加载食材照片
|
||||
// Load food photo
|
||||
val imageUri = intent.getStringExtra(EXTRA_IMAGE_URI)
|
||||
if (!imageUri.isNullOrBlank()) {
|
||||
binding.ivFoodPhoto.setImageURI(imageUri.toUri())
|
||||
}
|
||||
currentWeight = intent.getDoubleExtra(EXTRA_CURRENT_WEIGHT, 0.0)
|
||||
initialWeight = intent.getDoubleExtra(EXTRA_INITIAL_WEIGHT, 0.0)
|
||||
binding.tvWeight.text = "${currentWeight}g"
|
||||
|
||||
// 取出内存缓存的食材列表,取用后立即清空
|
||||
val goodsList = pendingGoodsList?.also { pendingGoodsList = null }
|
||||
if (!goodsList.isNullOrEmpty()) {
|
||||
list.addAll(goodsList)
|
||||
// 默认选中第一项
|
||||
selectedPosition = 0
|
||||
list[0].isClicked = true
|
||||
list[0].useWeight = currentWeight
|
||||
binding.tvSelectedFood.text = list[0].goodsName ?: "-"
|
||||
recognizeNameList?.apply {
|
||||
forEach {
|
||||
val goodsName = it.name.split("WP").first()
|
||||
val rawMaterialsType = it.rawMaterialsType
|
||||
goodsNameList.add(GoodsNameQueryDTO(goodsName, rawMaterialsType))
|
||||
nameScoreMap.put(goodsName, it)
|
||||
}
|
||||
recognizeNameList = null
|
||||
}
|
||||
|
||||
if (goodsNameList.isNotEmpty()) {
|
||||
netViewModel.queryGoodsList(goodsType = "0", goodsNames = goodsNameList)
|
||||
} else {
|
||||
loadRecognizeList(emptyList())
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildTestData(item: FoodModule.IdNameScore): GoodsItem {
|
||||
var foodName = ""
|
||||
var foodId = ""
|
||||
item.name.split("WP").let {
|
||||
foodName = it[0]
|
||||
foodId = if (it.size > 1) {
|
||||
"WP${it[1]}"
|
||||
} else {
|
||||
item.name
|
||||
}
|
||||
}
|
||||
return GoodsItem(
|
||||
goodsId = foodId,
|
||||
goodsName = foodName
|
||||
).also {
|
||||
it.foodScore = ((1 - item.score) * 10000).toInt()
|
||||
it.isOriginalData = false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private fun initObserver() {
|
||||
lifecycleScope.launch {
|
||||
netViewModel.goodsListState.collect { state ->
|
||||
when (state) {
|
||||
is UiState.Loading -> {
|
||||
showLoading()
|
||||
}
|
||||
|
||||
is UiState.Success -> {
|
||||
delayDismissLoading()
|
||||
loadRecognizeList(state.data)
|
||||
}
|
||||
|
||||
is UiState.Error -> {
|
||||
delayDismissLoading()
|
||||
toast(state.msg)
|
||||
}
|
||||
|
||||
is UiState.Idle -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadRecognizeList(goodsList: List<GoodsItem>?) {
|
||||
if (goodsList.isNullOrEmpty()) {
|
||||
binding.flListContainer.updateLayoutParams {
|
||||
height = 260.dp
|
||||
}
|
||||
binding.rvRecognizeList.gone()
|
||||
binding.tvNoData.visible()
|
||||
return
|
||||
}
|
||||
binding.rvRecognizeList.visible()
|
||||
binding.tvNoData.gone()
|
||||
list.clear()
|
||||
goodsList.forEach { goods ->
|
||||
var foodScore = -1
|
||||
nameScoreMap[goods.goodsName]?.let { food ->
|
||||
foodScore = ((1 - food.score) * 10000).toInt()
|
||||
}
|
||||
//保存原goodsId
|
||||
goods.oldGoodsId = goods.goodsId
|
||||
//PrepareFoodActivity中的goodsId就是materId
|
||||
goods.goodsId = goods.materId ?: ""
|
||||
list.add(goods.also { it.foodScore = foodScore })
|
||||
}
|
||||
adapter.notifyDataSetChanged()
|
||||
updateRvParentLayoutHeight()
|
||||
// 默认选中第一项
|
||||
selectedPosition = 0
|
||||
list[0].isClicked = true
|
||||
list[0].useWeight = currentWeight
|
||||
binding.tvSelectedFood.text = list[0].goodsName ?: "-"
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化 RecyclerView
|
||||
*/
|
||||
private fun initRecyclerView() {
|
||||
binding.recyclerView.let {
|
||||
binding.rvRecognizeList.let {
|
||||
it.layoutManager = GridLayoutManager(this@FoodRecognizeActivity, 2)
|
||||
it.adapter = adapter
|
||||
it.isVerticalScrollBarEnabled = false
|
||||
@@ -206,11 +334,8 @@ class FoodRecognizeActivity : BaseActivity() {
|
||||
* 根据列表是否有数据控制 RecyclerView 显隐
|
||||
*/
|
||||
private fun updateListVisibility() {
|
||||
if (list.isEmpty()) {
|
||||
binding.flListContainer.gone()
|
||||
} else {
|
||||
binding.flListContainer.visible()
|
||||
binding.recyclerView.post { updateScrollIndicator() }
|
||||
if (list.isNotEmpty()) {
|
||||
binding.rvRecognizeList.post { updateScrollIndicator() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,7 +343,7 @@ class FoodRecognizeActivity : BaseActivity() {
|
||||
* 根据 RecyclerView 滚动状态刷新右侧自定义指示条
|
||||
*/
|
||||
private fun updateScrollIndicator() {
|
||||
val recyclerView = binding.recyclerView
|
||||
val recyclerView = binding.rvRecognizeList
|
||||
val track = binding.vScrollIndicatorTrack
|
||||
val thumb = binding.vScrollIndicatorThumb
|
||||
|
||||
@@ -281,7 +406,7 @@ class FoodRecognizeActivity : BaseActivity() {
|
||||
* 用新食材替换当前选中项(或追加到列表首位)
|
||||
*/
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun updateSelectedFood(item: CookFoodGoodsEntity) {
|
||||
private fun updateSelectedFood(item: GoodsItem) {
|
||||
val existIndex = list.indexOfFirst { it.goodsId == item.goodsId }
|
||||
if (existIndex >= 0) {
|
||||
list.forEachIndexed { i, e -> e.isClicked = (i == existIndex) }
|
||||
@@ -292,10 +417,14 @@ class FoodRecognizeActivity : BaseActivity() {
|
||||
selectedPosition = 0
|
||||
}
|
||||
adapter.notifyDataSetChanged()
|
||||
if (list.isNotEmpty()) {
|
||||
binding.rvRecognizeList.visible()
|
||||
binding.tvNoData.gone()
|
||||
}
|
||||
updateRvParentLayoutHeight()
|
||||
binding.tvSelectedFood.text = item.goodsName ?: "-"
|
||||
updateListVisibility()
|
||||
binding.recyclerView.post { updateScrollIndicator() }
|
||||
binding.rvRecognizeList.post { updateScrollIndicator() }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -304,58 +433,87 @@ class FoodRecognizeActivity : BaseActivity() {
|
||||
* 低于阈值说明食材已被取走,保留上次有效值等待页面关闭
|
||||
*/
|
||||
private fun registerWeightListener() {
|
||||
// WeightUtil.addWeightListener(TAG) { address, state, weight ->
|
||||
// if (address == AddressUtil.ONE && state == WeightUtil.STATE_STABLE) {
|
||||
// runOnUiThread {
|
||||
// currentWeight = weight
|
||||
// binding.tvWeight.run {
|
||||
// if (tag != weight) {
|
||||
// text = "$weight g"
|
||||
// tag = weight
|
||||
// }
|
||||
// }
|
||||
// if (weight >= PrepareCookActivity.WEIGHT_RECOGNIZE_VALUE) {
|
||||
// adapter.items.firstOrNull { it.isClicked }?.let { item ->
|
||||
// if (pendingWeight != weight) {
|
||||
// // 无论增减,均延迟更新,避免手拿物品时的瞬时增重干扰
|
||||
// cancelPendingWeightUpdate()
|
||||
// pendingWeight = weight
|
||||
// pendingWeightRunnable = Runnable {
|
||||
// item.useWeight = weight
|
||||
// pendingWeightRunnable = null
|
||||
// }.also { handler.postDelayed(it, 3000) }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
WeightUtil.addWeightListener(TAG) { address, state, weight ->
|
||||
if (address == AddressUtil.ONE && state == WeightUtil.STATE_STABLE) {
|
||||
runOnUiThread {
|
||||
// 净重 = 秤读数 - 初始读数
|
||||
val netWeight = weight - initialWeight
|
||||
currentWeight = netWeight
|
||||
binding.tvWeight.run {
|
||||
if (tag != netWeight) {
|
||||
text = "${netWeight}g"
|
||||
tag = netWeight
|
||||
}
|
||||
}
|
||||
// 入队,超过 10 条移除队头
|
||||
if (weightWindow.size >= 10) weightWindow.removeFirst()
|
||||
weightWindow.addLast(netWeight)
|
||||
// 实时更新选中食材重量
|
||||
list.getOrNull(selectedPosition)?.useWeight = netWeight
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消待执行的延迟重量更新任务
|
||||
* 从滑动窗口尾部向前查找连续稳定值:
|
||||
* 跳过尾部不稳定的过渡帧,找到第一段连续相同且大于阈值的序列
|
||||
* 连续条数 >= 3 时返回该值,否则返回 null(数据不稳定)
|
||||
*/
|
||||
private fun cancelPendingWeightUpdate() {
|
||||
// pendingWeightRunnable?.let { handler.removeCallbacks(it) }
|
||||
// pendingWeightRunnable = null
|
||||
private fun getStableWeightFromWindow(): Double? {
|
||||
val threshold = PrepareFoodActivity.WEIGHT_RECOGNIZE_VALUE
|
||||
var i = weightWindow.indices.last
|
||||
while (i >= 0) {
|
||||
val candidate = weightWindow[i]
|
||||
// 跳过低于阈值的过渡帧
|
||||
if (candidate <= threshold) {
|
||||
i--
|
||||
continue
|
||||
}
|
||||
// 以 candidate 为基准,向前统计连续相同条数
|
||||
var count = 0
|
||||
var j = i
|
||||
while (j >= 0 && weightWindow[j] == candidate) {
|
||||
count++
|
||||
j--
|
||||
}
|
||||
if (count >= 3) return candidate
|
||||
// 不足 3 条,继续向前找
|
||||
i = j
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 携带当前选中食材关闭页面
|
||||
* @param isManualCancel true=用户手动返回;false=被动关闭(重量低于阈值)
|
||||
*/
|
||||
private fun finishWithResult(isManualCancel: Boolean) {
|
||||
cancelPendingWeightUpdate()
|
||||
val item = list.getOrNull(selectedPosition)
|
||||
if (!isManualCancel && item != null) {
|
||||
// 被动关闭:从窗口取稳定值
|
||||
val stableWeight = getStableWeightFromWindow()
|
||||
if (stableWeight == null) {
|
||||
// 数据不稳定,不关闭页面,弹窗提示(通过 isShowing 防止重复弹出)
|
||||
if (unstableDialog?.isShowing == true) return
|
||||
if (unstableDialog == null) {
|
||||
unstableDialog = CommonDialog(this)
|
||||
.setTitle("提示")
|
||||
.setContent("秤数据不稳定,请放置食材进行重新识别")
|
||||
.setSingleButton("确认") {
|
||||
finishWithResult(true)
|
||||
}
|
||||
}
|
||||
unstableDialog?.show()
|
||||
return
|
||||
}
|
||||
item.useWeight = stableWeight
|
||||
}
|
||||
|
||||
val intent = Intent().apply {
|
||||
putExtra(IS_MANUAL_CANCEL, isManualCancel)
|
||||
if (isManualCancel.not()) {
|
||||
list.getOrNull(selectedPosition)?.let {
|
||||
// 兜底:若 useWeight 仍为空或0,使用当前实时重量
|
||||
if ((it.useWeight ?: 0.0) <= 0.0) {
|
||||
it.useWeight = currentWeight
|
||||
}
|
||||
putExtra(EXTRA_SELECTED_ITEM, it)
|
||||
}
|
||||
if (!isManualCancel) {
|
||||
item?.let { putExtra(EXTRA_SELECTED_ITEM, it) }
|
||||
}
|
||||
}
|
||||
setResult(RESULT_OK, intent)
|
||||
@@ -364,7 +522,6 @@ class FoodRecognizeActivity : BaseActivity() {
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
cancelPendingWeightUpdate()
|
||||
WeightUtil.removeWeightListener(TAG)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,59 +4,46 @@ import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.view.LayoutInflater
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.FoodRecordAdapter
|
||||
import com.shuwei.dish.match.adapter.Food2Adapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.databinding.ActivityFoodSearchBinding
|
||||
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
||||
import com.shuwei.dish.match.entity.FoodRecord
|
||||
import com.shuwei.dish.match.model.FoodRecord
|
||||
import com.shuwei.dish.match.model.FoodSearchItem
|
||||
import com.shuwei.dish.match.net.UiState
|
||||
import com.shuwei.dish.match.utils.KeyboardUtil
|
||||
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.startActivity
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
import java.io.Serializable
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.collections.getOrNull
|
||||
|
||||
/**
|
||||
* 菜品搜索页面
|
||||
* 菜品搜索页面(采样模式:搜索已有上架菜品作为称量模板)
|
||||
* 数据源: POST /neglect/ratio-scale/food-search
|
||||
*/
|
||||
class FoodSearchActivity : BaseActivity() {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "FoodSearchActivity"
|
||||
const val PAGE_TYPE = "pageType"
|
||||
const val FOOD_ITEM = "foodItem"
|
||||
const val FOOD_ID = "foodId"
|
||||
const val FOOD_NAME = "foodName"
|
||||
const val DINNER_TYPE = "dinnerType"
|
||||
}
|
||||
|
||||
private lateinit var binding: ActivityFoodSearchBinding
|
||||
|
||||
private var list: MutableList<FoodRecord> = mutableListOf()
|
||||
private var pageType = 0
|
||||
private var dinnerType = "1"
|
||||
private val recordAdapter by lazy {
|
||||
FoodRecordAdapter(list).apply {
|
||||
Food2Adapter(list).apply {
|
||||
isStateViewEnable = true
|
||||
setOnItemClickListener { adapter, view, position ->
|
||||
if (pageType == 1) {
|
||||
val jumpItem = list[position].also { it.dinnerType = dinnerType }
|
||||
startActivity<PrepareFoodActivity> {
|
||||
putExtra(PrepareFoodActivity.FOOD_ITEM, jumpItem as Serializable)
|
||||
}
|
||||
return@setOnItemClickListener
|
||||
}
|
||||
val jumpItem = list.getOrNull(position) ?: return@setOnItemClickListener
|
||||
setResult(RESULT_OK, Intent().apply {
|
||||
putExtra(FOOD_ID, list[position].foodId)
|
||||
putExtra(FOOD_NAME, list[position].foodName)
|
||||
putExtra(FOOD_ITEM, jumpItem as Serializable)
|
||||
})
|
||||
finish()
|
||||
}
|
||||
@@ -69,8 +56,6 @@ class FoodSearchActivity : BaseActivity() {
|
||||
super.onCreate(savedInstanceState)
|
||||
binding = ActivityFoodSearchBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
pageType = intent.getIntExtra(PAGE_TYPE, 0)
|
||||
dinnerType = intent.getStringExtra(DINNER_TYPE) ?: "0"
|
||||
setHeaderBackground()
|
||||
foodName = intent.getStringExtra(FOOD_NAME)
|
||||
binding.etInputDish.setText(foodName)
|
||||
@@ -78,7 +63,7 @@ class FoodSearchActivity : BaseActivity() {
|
||||
it.visible()
|
||||
}, titleAction = {
|
||||
it.text = "菜品搜索"
|
||||
}, rightIconActon = {
|
||||
}, rightIconAction = {
|
||||
it.gone()
|
||||
it.setImageResource(R.drawable.ic_setting)
|
||||
it.setOnClickListener {
|
||||
@@ -91,38 +76,13 @@ class FoodSearchActivity : BaseActivity() {
|
||||
adapter = recordAdapter
|
||||
}
|
||||
addViewListener()
|
||||
initObserver()
|
||||
}
|
||||
|
||||
/**
|
||||
* 收集 searchFoodState,统一处理 Loading / Success / Error 状态
|
||||
*/
|
||||
private fun initObserver() {
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
netViewModel.searchFoodState.collect { state ->
|
||||
when (state) {
|
||||
is UiState.Loading -> showLoading()
|
||||
is UiState.Success -> handleSearchResult(state.data)
|
||||
is UiState.Error -> {
|
||||
delayDismissLoading()
|
||||
finishRefresh()
|
||||
binding.refreshLayout.setEnableRefresh(true)
|
||||
toast(state.msg)
|
||||
if (pageNo == 1) loadEmptyView()
|
||||
}
|
||||
is UiState.Idle -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun addViewListener() {
|
||||
binding.ivDishSearch.setOnClickListener { v ->
|
||||
pageNo = 1
|
||||
getInputAndSearch()
|
||||
KeyboardUtil.hideKeyboard(v)
|
||||
hideKeyboard()
|
||||
}
|
||||
binding.refreshLayout.setEnableRefresh(true)
|
||||
binding.refreshLayout.setEnableLoadMore(false)
|
||||
@@ -139,13 +99,13 @@ class FoodSearchActivity : BaseActivity() {
|
||||
queryListInfo(foodName!!)
|
||||
}
|
||||
binding.root.setOnClickListener { v ->
|
||||
KeyboardUtil.hideKeyboard(v)
|
||||
hideKeyboard()
|
||||
}
|
||||
binding.etInputDish.let { v ->
|
||||
v.addOnActionSearchListener {
|
||||
pageNo = 1
|
||||
getInputAndSearch()
|
||||
KeyboardUtil.hideKeyboard( v)
|
||||
hideKeyboard()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -161,54 +121,65 @@ class FoodSearchActivity : BaseActivity() {
|
||||
}
|
||||
|
||||
private var pageNo = 1
|
||||
private var pageSize = 10
|
||||
fun getDinnerTypeText(): String {
|
||||
return when (dinnerType) {
|
||||
"1" -> "早餐"
|
||||
"2" -> "午餐"
|
||||
"3" -> "晚餐"
|
||||
else -> "早餐"
|
||||
}
|
||||
}
|
||||
private var pageSize = 20
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun queryListInfo(input: String) {
|
||||
val map = mutableMapOf<String, Any>(
|
||||
"foodName" to input.trim(),
|
||||
"pageNum" to pageNo,
|
||||
"pageSize" to pageSize,
|
||||
"placeId" to BaseApp.canteenId,
|
||||
"dinnerType" to getDinnerTypeText()
|
||||
netViewModel.foodSearch(
|
||||
keyword = input.trim(),
|
||||
pageNum = pageNo,
|
||||
pageSize = pageSize,
|
||||
onLoading = { showLoading() },
|
||||
onResult = { state ->
|
||||
when (state) {
|
||||
is UiState.Success -> handleSearchResult(state.data)
|
||||
is UiState.Error -> {
|
||||
delayDismissLoading()
|
||||
finishRefresh()
|
||||
binding.refreshLayout.setEnableRefresh(true)
|
||||
toast(state.msg)
|
||||
if (pageNo == 1) loadEmptyView()
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
)
|
||||
netViewModel.searchFoodList(param = map)
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理搜索结果,填充列表或展示空视图
|
||||
* FoodSearchItem → FoodRecord 映射,供 Food2Adapter 展示
|
||||
* 采样模式下返回给 PrepareFoodActivity 作为称量模板
|
||||
*/
|
||||
private fun FoodSearchItem.toFoodRecord(): FoodRecord = FoodRecord(
|
||||
foodId = foodId,
|
||||
foodName = foodName,
|
||||
cookMode = 1
|
||||
)
|
||||
|
||||
/**
|
||||
* 处理搜索结果:FoodSearchItem → FoodRecord 填充列表
|
||||
*/
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun handleSearchResult(records: MutableList<FoodRecord>?) {
|
||||
private fun handleSearchResult(items: List<FoodSearchItem>?) {
|
||||
delayDismissLoading()
|
||||
finishRefresh()
|
||||
binding.refreshLayout.setEnableRefresh(true)
|
||||
if (records.isNullOrEmpty()) {
|
||||
if (pageNo == 1) loadEmptyView()
|
||||
if (items.isNullOrEmpty()) {
|
||||
if (pageNo == 1) {
|
||||
loadEmptyView()
|
||||
}
|
||||
return
|
||||
}
|
||||
if (pageNo == 1) list.clear()
|
||||
list.addAll(records)
|
||||
list.addAll(items.map { it.toFoodRecord() })
|
||||
recordAdapter.notifyDataSetChanged()
|
||||
val isLoadMoreEnable = records.size >= pageSize
|
||||
val isLoadMoreEnable = items.size >= pageSize
|
||||
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
|
||||
if (isLoadMoreEnable) pageNo++
|
||||
}
|
||||
|
||||
private fun finishRefresh() {
|
||||
if (pageNo == 1) {
|
||||
binding.refreshLayout.finishRefresh(1200)
|
||||
} else {
|
||||
binding.refreshLayout.finishLoadMore(1200)
|
||||
}
|
||||
binding.refreshLayout.finishRefresh(1200)
|
||||
}
|
||||
|
||||
private var emptyViewBinding: LayoutEmptyViewBinding? = null
|
||||
|
||||
@@ -10,11 +10,12 @@ import com.shuwei.dish.match.adapter.HomeModeAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.databinding.ActivityHomeBinding
|
||||
import com.shuwei.dish.match.entity.HomeModeBean
|
||||
import com.shuwei.dish.match.model.HomeModeBean
|
||||
import com.shuwei.dish.match.utils.SpTool
|
||||
import com.shuwei.dish.match.utils.ext.startActivity
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.collections.getOrNull
|
||||
|
||||
/**
|
||||
* 主页,包括三种模式:制作模式、采样模式、品控模式
|
||||
@@ -42,12 +43,14 @@ class HomeActivity : BaseActivity() {
|
||||
binding = ActivityHomeBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
setHeaderBackground(isHomePage = true)
|
||||
// 根据当前 canteenId 恢复 RadioButton 选中状态
|
||||
binding.radioGroup.check(
|
||||
if (BaseApp.canteenId == "1678234139391512577") R.id.radioSw else R.id.radioZk
|
||||
)
|
||||
binding.radioGroup.setOnCheckedChangeListener { group, checkedId ->
|
||||
if (checkedId == R.id.radioSw) {
|
||||
BaseApp.canteenId = "1678234139391512577"
|
||||
} else {
|
||||
BaseApp.canteenId = "0"
|
||||
}
|
||||
val id = if (checkedId == R.id.radioSw) "1678234139391512577" else "0"
|
||||
SpTool.canteenId = id
|
||||
BaseApp.canteenId = id
|
||||
}
|
||||
onBackPressedDispatcher.addCallback(this) {}
|
||||
// binding.radioGroup.check(R.id.radioZk)
|
||||
@@ -63,18 +66,18 @@ class HomeActivity : BaseActivity() {
|
||||
// startActivity<SamplingListActivity>()
|
||||
// }
|
||||
|
||||
// appViewModel.deleteSeasoningBySort(12)
|
||||
// appViewModel.deleteSeasoningBySort(11)
|
||||
// appViewModel.deleteSeasoningBySort(13)
|
||||
// appViewModel.deleteSeasoningBySort(14)
|
||||
// appViewModel.deleteCookFoodAndGoods(0,"") {}
|
||||
// appViewModel.getCookFoodGoodsList("") {goodsList->
|
||||
// dbViewModel.deleteSeasoningBySort(12)
|
||||
// dbViewModel.deleteSeasoningBySort(11)
|
||||
// dbViewModel.deleteSeasoningBySort(13)
|
||||
// dbViewModel.deleteSeasoningBySort(14)
|
||||
// dbViewModel.deleteCookFoodAndGoods(0,"") {}
|
||||
// dbViewModel.getCookFoodGoodsList("") {goodsList->
|
||||
// goodsList.forEach {
|
||||
// it.foodId = "1594990392084779010"
|
||||
// appViewModel.updateGoods(it)
|
||||
// dbViewModel.updateGoods(it)
|
||||
// }
|
||||
// }
|
||||
// appViewModel.clearAllSeasoning(){}
|
||||
// dbViewModel.clearAllSeasoning(){}
|
||||
|
||||
|
||||
// binding.btnDeviceConfig.setOnClickListener {
|
||||
@@ -95,7 +98,7 @@ class HomeActivity : BaseActivity() {
|
||||
private val modeAdapter by lazy {
|
||||
HomeModeAdapter(modeList).apply {
|
||||
addOnItemChildClickListener(R.id.layoutCard) { adapter, view, position ->
|
||||
modeList[position].onClick?.invoke()
|
||||
modeList.getOrNull(position)?.onClick?.invoke()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -138,14 +141,14 @@ class HomeActivity : BaseActivity() {
|
||||
|
||||
private fun goSampling() {
|
||||
lifecycleScope.launch {
|
||||
val slots = appViewModel.loadSeasoningSlot()
|
||||
val slots = dbViewModel.loadSeasoningSlot()
|
||||
if (slots.isEmpty()) {
|
||||
// 无调料信息,打开采样历史列表页面,点击设置配置调料信息
|
||||
startActivity<SamplingModeActivity>()
|
||||
finish()
|
||||
return@launch
|
||||
}
|
||||
val count = appViewModel.countCookFood(cookMode = 1)
|
||||
val count = dbViewModel.countCookFood(cookMode = 1)
|
||||
if (count > 0) {
|
||||
// 有烹饪中数据,打开采样历史列表页面
|
||||
startActivity<SamplingModeActivity>()
|
||||
|
||||
@@ -18,9 +18,8 @@ import com.shuwei.dish.match.objbox.FoodModule
|
||||
import com.shuwei.dish.match.scale.ScaleServiceManager
|
||||
import com.shuwei.dish.match.utils.AddressUtil
|
||||
import com.shuwei.dish.match.utils.AppUtil
|
||||
import com.shuwei.dish.match.utils.NetworkUtils
|
||||
import com.shuwei.dish.match.utils.NetworkUtil
|
||||
import com.shuwei.dish.match.utils.SpTool
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.startActivity
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
@@ -55,7 +54,7 @@ class InitActivity : BaseActivity() {
|
||||
countdownHandler.postDelayed(this, 100)
|
||||
} else {
|
||||
// 倒计时结束,最后检测一次网络
|
||||
if (NetworkUtils.isNetworkConnected(this@InitActivity)) {
|
||||
if (NetworkUtil.isNetworkConnected(this@InitActivity)) {
|
||||
startNextPage()
|
||||
} else {
|
||||
// 网络未连接,显示"连接网络"按钮
|
||||
@@ -80,14 +79,8 @@ class InitActivity : BaseActivity() {
|
||||
setHeaderBgVisible(false)
|
||||
BaseApp.appVersion = AppUtil.getAppVersionCode(this).toString()
|
||||
|
||||
BaseApp.canteenId = "0"
|
||||
BaseApp.canteenId = SpTool.canteenId
|
||||
|
||||
WeightUtil.init()
|
||||
WeightUtil.getWeight()
|
||||
WeightUtil.startContinuousRead()
|
||||
//对净材秤1和熟食秤2称进行清零
|
||||
WeightUtil.tareTwo(AddressUtil.ONE)
|
||||
WeightUtil.tareTwo(AddressUtil.TWO)
|
||||
initViews()
|
||||
}
|
||||
|
||||
@@ -100,6 +93,9 @@ class InitActivity : BaseActivity() {
|
||||
// 子设备:直接进入小屏专属页面,不走原有大屏业务流程
|
||||
if (GlobalData.deviceRole == DeviceRole.SLAVE) {
|
||||
startActivity<SlaveActivity>()
|
||||
// 延迟到下一帧 finish,避免与 LaunchActivityItem 事务竞态导致
|
||||
// "Activity client record must not be null" 偶发崩溃
|
||||
window.decorView.post { finish() }
|
||||
return@launch
|
||||
}
|
||||
// 主设备:走原有路由逻辑
|
||||
@@ -116,34 +112,38 @@ class InitActivity : BaseActivity() {
|
||||
startActivity<HomeActivity>()
|
||||
}
|
||||
}
|
||||
// 延迟到下一帧 finish,避免与 LaunchActivityItem 事务竞态导致
|
||||
// "Activity client record must not be null" 偶发崩溃
|
||||
window.decorView.post { finish() }
|
||||
}
|
||||
}
|
||||
|
||||
private fun goSampling() {
|
||||
lifecycleScope.launch {
|
||||
val slots = appViewModel.loadSeasoningSlot()
|
||||
if (slots.isEmpty()) {
|
||||
// 无调料信息,打开采样历史列表页面,点击设置配置调料信息
|
||||
startActivity<SamplingModeActivity>()
|
||||
return@launch
|
||||
}
|
||||
val count = appViewModel.countCookFood(cookMode = 1)
|
||||
if (count > 0) {
|
||||
// 有烹饪中数据,打开采样历史列表页面
|
||||
startActivity<SamplingModeActivity>()
|
||||
return@launch
|
||||
}
|
||||
// 无烹饪数据,打开新增采样页面
|
||||
startActivity<PrepareFoodActivity> {
|
||||
putExtra(PrepareFoodActivity.PAGE_FROM, PrepareFoodActivity.HOME)
|
||||
}
|
||||
/**
|
||||
* 采样模式启动路由:根据本地调料配置和烹饪中数据决定跳转目标
|
||||
* 改为 suspend 后由外层协程串行等待,保证 startActivity 早于 finish() 执行,
|
||||
* 避免内部再嵌一层 lifecycleScope.launch 导致 finish 抢跑、跳转失败
|
||||
*/
|
||||
private suspend fun goSampling() {
|
||||
val slots = dbViewModel.loadSeasoningSlot()
|
||||
if (slots.isEmpty()) {
|
||||
// 无调料信息,打开采样历史列表页面,点击设置配置调料信息
|
||||
startActivity<SamplingModeActivity>()
|
||||
return
|
||||
}
|
||||
val count = dbViewModel.countCookFood(cookMode = 1)
|
||||
if (count > 0) {
|
||||
// 有烹饪中数据,打开采样历史列表页面
|
||||
startActivity<SamplingModeActivity>()
|
||||
return
|
||||
}
|
||||
// 无烹饪数据,打开新增采样页面
|
||||
startActivity<PrepareFoodActivity> {
|
||||
putExtra(PrepareFoodActivity.PAGE_FROM, PrepareFoodActivity.HOME)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
countdownHandler.removeCallbacksAndMessages(null)
|
||||
WeightUtil.stopContinuousRead()
|
||||
ScaleServiceManager.stop()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
@@ -176,7 +176,7 @@ class InitActivity : BaseActivity() {
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (NetworkUtils.isNetworkConnected(this)) {
|
||||
if (NetworkUtil.isNetworkConnected(this)) {
|
||||
// 有网络时隐藏网络检测区域,直接跳转
|
||||
binding.llNetwork.gone()
|
||||
startNextPage(withDelay = false)
|
||||
@@ -220,7 +220,7 @@ class InitActivity : BaseActivity() {
|
||||
* 检测网络连接
|
||||
*/
|
||||
private fun checkNetworkConnection() {
|
||||
if (NetworkUtils.isNetworkConnected(this)) {
|
||||
if (NetworkUtil.isNetworkConnected(this)) {
|
||||
// 网络连接成功,停止倒计时并跳转到 HomeActivity
|
||||
countdownHandler.removeCallbacks(countdownTask)
|
||||
startNextPage()
|
||||
@@ -251,4 +251,8 @@ class InitActivity : BaseActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
hasNavigated = false
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.Seasoning18GridAdapter
|
||||
import com.shuwei.dish.match.adapter.Seasoning22GridAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.base.GlobalData
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.databinding.ActivityMasterScaleBinding
|
||||
import com.shuwei.dish.match.databinding.ListTypeScale1Binding
|
||||
@@ -81,7 +82,7 @@ class MasterScaleActivity : BaseActivity() {
|
||||
/** 从 Room 加载槽位配置到 slotNameMap,加载完成后启动数据观测 */
|
||||
private fun loadSlotNames() {
|
||||
lifecycleScope.launch {
|
||||
val slots = appViewModel.loadSeasoningSlot()
|
||||
val slots = dbViewModel.loadSeasoningSlot()
|
||||
slots.forEach { slot ->
|
||||
slotNameMap["${slot.deviceId}#${slot.address}"] = slot.goodsName
|
||||
}
|
||||
@@ -99,7 +100,7 @@ class MasterScaleActivity : BaseActivity() {
|
||||
val flow = ScaleServiceManager.allScales ?: return
|
||||
lifecycleScope.launch {
|
||||
flow.collectLatest { scaleMap ->
|
||||
val localId = com.shuwei.dish.match.base.GlobalData.deviceId
|
||||
val localId = GlobalData.deviceId
|
||||
val localIp = NetworkUtil.getLocalIpAddress(this@MasterScaleActivity)
|
||||
val groups = scaleMap.values
|
||||
.groupBy { it.deviceId }
|
||||
@@ -337,7 +338,7 @@ class MasterScaleActivity : BaseActivity() {
|
||||
textSize = 22f
|
||||
}
|
||||
cell.tvState.run {
|
||||
text = stateStr(scale?.state)
|
||||
text = WeightUtil.getStateStr(scale?.state ?: -1)
|
||||
textSize = 22f
|
||||
}
|
||||
cell.root.updateLayoutParams { height = 400.dp }
|
||||
@@ -450,20 +451,12 @@ class MasterScaleActivity : BaseActivity() {
|
||||
b.tvAddr.text = scale?.let { "秤 ${it.address}" } ?: ""
|
||||
b.tvName.text = scale?.name?.takeIf { it.isNotBlank() } ?: "-"
|
||||
b.tvWeight.text = scale?.let { "${it.weight} g" } ?: ""
|
||||
b.tvState.text = stateStr(scale?.state)
|
||||
b.tvState.text = scale?.let { WeightUtil.getStateStr(it.state) } ?: ""
|
||||
}
|
||||
}
|
||||
|
||||
// ── 工具方法 ───────────────────────────────────────────────────────────
|
||||
|
||||
private fun stateStr(state: Int?) = when (state) {
|
||||
WeightUtil.STATE_STABLE -> "稳定"
|
||||
WeightUtil.STATE_UNSTABLE -> "不稳定"
|
||||
WeightUtil.STATE_OVER_WEIGHT -> "超量"
|
||||
null -> ""
|
||||
else -> "$state"
|
||||
}
|
||||
|
||||
/**
|
||||
* 弹出清零确认对话框
|
||||
* @param deviceId 目标设备 ID
|
||||
|
||||
@@ -5,34 +5,38 @@ import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import android.view.View
|
||||
import android.view.GestureDetector
|
||||
import android.view.MotionEvent
|
||||
import android.view.ViewGroup
|
||||
import androidx.activity.addCallback
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.core.content.IntentCompat
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.DishPartAdapter
|
||||
import com.shuwei.dish.match.adapter.FoodMaterialAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.databinding.ActivityPrepareFoodBinding
|
||||
import com.shuwei.dish.match.databinding.LayoutCameraPreviewBinding
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.entity.FoodRecord
|
||||
import com.shuwei.dish.match.dialog.FoodSearchDialog
|
||||
import com.shuwei.dish.match.model.CookOrderCompositionItem
|
||||
import com.shuwei.dish.match.model.FoodCompositionResponse
|
||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.model.FoodRecord
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
import com.shuwei.dish.match.net.UiState
|
||||
import com.shuwei.dish.match.objbox.FoodModule
|
||||
import com.shuwei.dish.match.utils.AddressUtil
|
||||
import com.shuwei.dish.match.utils.CameraUtils
|
||||
import com.shuwei.dish.match.utils.ImageUtil
|
||||
import com.shuwei.dish.match.utils.KeyboardUtil
|
||||
import com.shuwei.dish.match.utils.SpTool
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
||||
import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.roundedOneDecimalPlace
|
||||
import com.shuwei.dish.match.utils.ext.startActivity
|
||||
import com.shuwei.dish.match.utils.ext.toJsonString
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
@@ -50,13 +54,16 @@ import kotlin.math.abs
|
||||
class PrepareFoodActivity : BaseActivity() {
|
||||
|
||||
companion object {
|
||||
const val TAG = "CookActivity"
|
||||
const val TAG = "PrepareFoodActivity"
|
||||
const val FOOD_ITEM = "foodItem"
|
||||
const val FOOD_NAME = "foodName"
|
||||
const val COOK_ORDER_ID = "cookOrderId"
|
||||
const val PAGE_FROM = "pageFrom"
|
||||
const val HOME = "home"
|
||||
const val WEIGHT_CHANGE_VALUE = 15
|
||||
const val WEIGHT_CHANGE_VALUE = 5
|
||||
const val WEIGHT_RECOGNIZE_VALUE = 10
|
||||
|
||||
/** 主材数量上限 */
|
||||
const val MATERIAL_COUNT = 3
|
||||
}
|
||||
|
||||
private val binding by lazy { ActivityPrepareFoodBinding.inflate(layoutInflater) }
|
||||
@@ -65,58 +72,78 @@ class PrepareFoodActivity : BaseActivity() {
|
||||
|
||||
private var food: FoodRecord? = null
|
||||
|
||||
/** 采集模式下通过搜索页回填的 foodId */
|
||||
private var foodId: String? = null
|
||||
/** 烹制单 ID,制作模式从菜品列表传入,用于调用新配比秤接口 */
|
||||
private var cookOrderId: String? = null
|
||||
|
||||
/** 来源页面标识,HOME 时返回跳转 SamplingListActivity */
|
||||
private var pageFrom: String? = null
|
||||
|
||||
private var goodsList: MutableList<CookFoodGoodsEntity>? = null
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
/** 食材检索弹窗,手动新增构成时复用 */
|
||||
private var foodSearchDialog: FoodSearchDialog? = null
|
||||
|
||||
/** 手动录入卡当前选中的食材(含 materId),点击搜索后回填 */
|
||||
private var selectedIngredient: GoodsItem? = null
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContentView(binding.root)
|
||||
setHeaderBackground()
|
||||
pageFrom = intent.getStringExtra(PAGE_FROM)
|
||||
food = intent.extras?.getSerializable(FOOD_ITEM) as FoodRecord?
|
||||
|
||||
//food = intent.extras?.getSerializable(FOOD_ITEM) as FoodRecord?
|
||||
food = IntentCompat.getSerializableExtra(intent, FOOD_ITEM, FoodRecord::class.java)
|
||||
cookOrderId = intent.getStringExtra(COOK_ORDER_ID)
|
||||
val isSamplingMode = SpTool.cookMode == 1
|
||||
val titleText = if (isSamplingMode) "菜品采集" else "菜品制作"
|
||||
setTitleBar(titleBarAction = {
|
||||
it.visible()
|
||||
}, titleAction = {
|
||||
it.text = titleText
|
||||
}, rightIconActon = {
|
||||
}, rightIconAction = {
|
||||
it.gone()
|
||||
}, backAction = {
|
||||
it.setOnClickListener {
|
||||
onBackPressedDispatcher.onBackPressed()
|
||||
}
|
||||
})
|
||||
|
||||
food?.let {
|
||||
binding.etInputDish.run {
|
||||
setText(it.foodName)
|
||||
tag = it.foodName
|
||||
}
|
||||
}
|
||||
// 根据 cookMode 设置搜索栏可编辑性
|
||||
if (isSamplingMode) {
|
||||
// 采集模式:可编辑,支持搜索
|
||||
val foodName = intent.getStringExtra(FOOD_NAME)
|
||||
binding.etInputDish.setText(foodName ?: food?.foodName ?: "")
|
||||
binding.ivDishSearch.visible()
|
||||
binding.etInputDish.let {
|
||||
it.setSelection(it.length())
|
||||
}
|
||||
// 采集模式:启用食材信息录入卡(手动新增构成)
|
||||
initIngredientInput()
|
||||
} else {
|
||||
// 制作模式:不可编辑,仅展示菜名
|
||||
binding.etInputDish.setText(food?.foodName ?: "")
|
||||
binding.etInputDish.isFocusable = false
|
||||
binding.etInputDish.isFocusableInTouchMode = false
|
||||
binding.ivDishSearch.gone()
|
||||
// 制作模式:不展示手动新增卡
|
||||
binding.llIngredientInput.gone()
|
||||
}
|
||||
|
||||
addViewClickListener()
|
||||
addBackKeyListener()
|
||||
initCamera(binding.flCameraContainer)
|
||||
// 仅采样模式启用摄像头识别,制作模式不需要
|
||||
// if (isSamplingMode) {
|
||||
// initCamera(binding.flCameraContainer)
|
||||
// }
|
||||
initRecyclerView()
|
||||
initObserver()
|
||||
|
||||
if (!isSamplingMode) {
|
||||
getDishDetail()
|
||||
// 制作模式优先用 cookOrderId 调新接口,采样模式回退到旧 foodId
|
||||
if (!cookOrderId.isNullOrBlank()) {
|
||||
getCookOrderComposition(cookOrderId!!)
|
||||
} else if (food?.foodId.isNullOrBlank().not()) {
|
||||
getDishDetail(food!!.foodId!!)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,26 +153,51 @@ class PrepareFoodActivity : BaseActivity() {
|
||||
WeightUtil.tareTwo(AddressUtil.ONE)
|
||||
delayDismissLoading()
|
||||
}
|
||||
// // TODO: 测试功能-------------------------------
|
||||
// binding.btnTestConfirm.clickWithDebounce {
|
||||
// if (currentWeight <= 0.0) return@clickWithDebounce
|
||||
// val (index, item) = list.withIndex().find { (_, it) -> it.isOriginalData && it.isClicked && (it.useWeight?:0.0) <= 0.0 } ?: return@clickWithDebounce
|
||||
// item.useWeight = currentWeight
|
||||
// item.isSetFinished = true
|
||||
// list.forEachIndexed { i, it -> it.isClicked = i == index }
|
||||
// materialAdapter.notifyDataSetChanged()
|
||||
// }
|
||||
// // TODO: 测试功能-------------------------------
|
||||
//binding.root.setOnClickListener { hideKeyboard() }
|
||||
WeightUtil.addWeightListener(
|
||||
weightKey = TAG,
|
||||
getWeight = { address, state, weight ->
|
||||
if (address == AddressUtil.ONE && state == WeightUtil.STATE_STABLE) {
|
||||
runOnUiThread {
|
||||
// 首次收到稳定读数时,将其作为初始值(去皮基准)
|
||||
// if (!initialWeightReady) {
|
||||
// initialWeight = weight
|
||||
// initialWeightReady = true
|
||||
// }
|
||||
// 净重 = 秤读数 - 初始读数
|
||||
val netWeight = weight - initialWeight
|
||||
currentWeight = netWeight
|
||||
binding.tvShowWeight.run {
|
||||
if (tag != weight) {
|
||||
text = "称重:${weight}g"
|
||||
tag = weight
|
||||
if (tag != netWeight) {
|
||||
text = "称重:${netWeight}g"
|
||||
tag = netWeight
|
||||
}
|
||||
}
|
||||
recognizeFood(weight)
|
||||
// 仅采样模式:用量自动回填秤重 + 触发食材识别
|
||||
if (SpTool.cookMode == 1) {
|
||||
val displayWeight =
|
||||
if (netWeight > 0) netWeight.roundedOneDecimalPlace().toString() else ""
|
||||
binding.etAmount.setText(displayWeight)
|
||||
recognizeFood(netWeight)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if (SpTool.cookMode == 1) {
|
||||
// 采集模式:绑定搜索栏交互
|
||||
binding.ivDishSearch.setOnClickListener { v -> jumpSearch(v) }
|
||||
binding.etInputDish.addOnActionSearchListener { jumpSearch(binding.etInputDish) }
|
||||
binding.ivDishSearch.setOnClickListener { jumpSearch() }
|
||||
binding.etInputDish.addOnActionSearchListener { jumpSearch() }
|
||||
}
|
||||
|
||||
binding.btnCook.clickWithDebounce {
|
||||
@@ -160,17 +212,20 @@ class PrepareFoodActivity : BaseActivity() {
|
||||
toast("菜品构成信息未设置")
|
||||
return@clickWithDebounce
|
||||
}
|
||||
val foodRecord = FoodRecord()
|
||||
val foodRecord = food ?: FoodRecord()
|
||||
binding.etInputDish.let {
|
||||
if (it.tag != null && it.tag.toString() == it.text.toString()) {
|
||||
foodRecord.foodId = foodId
|
||||
if (it.tag == null || it.tag.toString() != it.text.toString()) {
|
||||
// 输入框内容与回填名称不一致,说明用户手动修改了菜名,清除 foodId
|
||||
foodRecord.foodId = null
|
||||
}
|
||||
}
|
||||
foodRecord.foodName = showFoodName
|
||||
foodRecord.cookMode = 1
|
||||
Log.d(TAG, "goToSubmit: goodsList:${list.toJsonString()}")
|
||||
// 采集模式传给 SubmitFoodActivity 时转换为 CookFoodGoodsEntity
|
||||
val submitList = list.map { it.toCookFoodGoodsEntity() }.toMutableList()
|
||||
startActivity<SubmitFoodActivity> {
|
||||
putExtra(SubmitFoodActivity.GOODS_LIST, list as Serializable)
|
||||
putExtra(SubmitFoodActivity.GOODS_LIST, submitList as Serializable)
|
||||
putExtra(SubmitFoodActivity.FOOD_ITEM, foodRecord as Serializable)
|
||||
}
|
||||
} else {
|
||||
@@ -186,17 +241,25 @@ class PrepareFoodActivity : BaseActivity() {
|
||||
}
|
||||
|
||||
private val isTakingPhoto = AtomicBoolean(false)
|
||||
|
||||
// 识别成功并查询到数据打开识别页面
|
||||
private var showRecognizePage = false
|
||||
|
||||
// 页面可见时允许识别,onPause 后禁止,onResume 后恢复
|
||||
private var pageVisible = true
|
||||
|
||||
// 手动取消标识
|
||||
private var manualCancelFlag = false
|
||||
private var lastPhotoUri: Uri? = null
|
||||
private var lastWeight = 0.0
|
||||
private var currentWeight = 0.0
|
||||
|
||||
/** 初始秤读数,净重 = 秤读数 - initialWeight,从 SpTool.configWeight 读取 */
|
||||
private var initialWeight = SpTool.configWeight.toDouble()
|
||||
|
||||
/** 初始读数是否已从秤获取 */
|
||||
// private var initialWeightReady = false
|
||||
|
||||
/**
|
||||
* 重量稳定时触发菜品识别
|
||||
* @param weight 当前稳定重量
|
||||
@@ -210,8 +273,15 @@ class PrepareFoodActivity : BaseActivity() {
|
||||
FoodRecognizeActivity.close()
|
||||
return
|
||||
}
|
||||
if (!pageVisible || manualCancelFlag || isTakingPhoto.get() || showRecognizePage || abs(lastWeight - weight) <= WEIGHT_CHANGE_VALUE) {
|
||||
Log.d(TAG, "recognizeFood, lastWeight:$lastWeight, weight:$weight, pageVisible:$pageVisible, manualCancelFlag:$manualCancelFlag, isTakingPhoto:${isTakingPhoto.get()}")
|
||||
if (
|
||||
!pageVisible || manualCancelFlag || isTakingPhoto.get() || showRecognizePage ||
|
||||
notRecognizeDialog?.isShowing == true ||
|
||||
abs(lastWeight - weight) <= WEIGHT_CHANGE_VALUE
|
||||
) {
|
||||
Log.d(
|
||||
TAG,
|
||||
"recognizeFood, lastWeight:$lastWeight, weight:$weight, pageVisible:$pageVisible, manualCancelFlag:$manualCancelFlag, isTakingPhoto:${isTakingPhoto.get()}"
|
||||
)
|
||||
return
|
||||
}
|
||||
showLoading("识别中……")
|
||||
@@ -227,20 +297,133 @@ class PrepareFoodActivity : BaseActivity() {
|
||||
* - list 中不含该 goodsId:直接新增,isNewDishType = true
|
||||
* - list 中已含该 goodsId:累加 useWeight
|
||||
*/
|
||||
private val foodSelectCallback: (CookFoodGoodsEntity) -> Unit = { entity ->
|
||||
val existing = list.firstOrNull { it.goodsId == entity.goodsId }
|
||||
if (existing != null) {
|
||||
existing.useWeight = (existing.useWeight ?: 0.0) + (entity.useWeight ?: 0.0)
|
||||
existing.isSetFinished = true
|
||||
dishPartAdapter.notifyItemChanged(list.indexOf(existing))
|
||||
private val foodSelectCallback: (GoodsItem) -> Unit = foodSelectCallback@{ entity ->
|
||||
val filterValue = list.withIndex().find { (_, it) -> it.goodsId == entity.goodsId }
|
||||
if (filterValue != null) {
|
||||
val index = filterValue.index
|
||||
val goods = filterValue.value
|
||||
goods.useWeight = (goods.useWeight ?: 0.0) + (entity.useWeight ?: 0.0)
|
||||
goods.isSetFinished = true
|
||||
list.forEachIndexed { i, it ->
|
||||
it.isClicked = i == index
|
||||
}
|
||||
} else {
|
||||
dishPartAdapter.add(entity.also {
|
||||
list.forEach { it.isClicked = false }
|
||||
list.add(entity.also {
|
||||
it.isNewDishType = true
|
||||
it.isSetFinished = true
|
||||
// 标记为非接口数据,否则 updateMaterialTypes 不会为其计算 materialType,
|
||||
// 导致列表中不显示"主辅材:主材/辅材"
|
||||
it.isOriginalData = false
|
||||
it.isClicked = true
|
||||
})
|
||||
|
||||
binding.rvDishPartList.smoothScrollToPosition(list.size - 1)
|
||||
binding.rvMaterialList.smoothScrollToPosition(list.size - 1)
|
||||
}
|
||||
updateMaterialTypes()
|
||||
}
|
||||
|
||||
/**
|
||||
* 重新计算 list 中非接口数据(isOriginalData=false)的 materialType
|
||||
*
|
||||
* 规则:
|
||||
* - 接口数据主材数量 n = list 中 isOriginalData=true 且 materialType=1 的数量
|
||||
* - 有接口数据且 MATERIAL_COUNT - n <= 0:所有非接口数据均为辅材(2)
|
||||
* - 无接口数据,或 MATERIAL_COUNT - n > 0:m = MATERIAL_COUNT - n,
|
||||
* 非接口数据按 useWeight 从大到小排序,前 m 个为主材(1),其余为辅材(2)
|
||||
*/
|
||||
private fun updateMaterialTypes() {
|
||||
val hasOriginalData = list.any { it.isOriginalData }
|
||||
// 接口数据中主材数量
|
||||
val n = list.count { it.isOriginalData && it.materialType == 1 }
|
||||
// 待分配的非接口数据(跳过手动指定过主辅材的项)
|
||||
val nonOriginalList = list.filter { !it.isOriginalData && !it.isMaterialTypeManual }
|
||||
|
||||
if (hasOriginalData && MATERIAL_COUNT - n <= 0) {
|
||||
// 主材已满,所有非接口数据均为辅材
|
||||
nonOriginalList.forEach { it.materialType = 2 }
|
||||
} else {
|
||||
// 剩余可分配主材名额
|
||||
val m = MATERIAL_COUNT - n
|
||||
// 按 useWeight 从大到小排序
|
||||
val sorted = nonOriginalList.sortedByDescending { it.useWeight ?: 0.0 }
|
||||
sorted.forEachIndexed { index, item ->
|
||||
item.materialType = if (index < m) 1 else 2
|
||||
}
|
||||
}
|
||||
materialAdapter.notifyDataSetChanged()
|
||||
}
|
||||
|
||||
/**
|
||||
* 食材信息录入卡初始化(仅采样模式):
|
||||
* 搜索食材 → 选中回填名称并暂存 GoodsItem(含 materId)→ 选择主辅材 → 输入用量 → 添加
|
||||
*/
|
||||
private fun initIngredientInput() {
|
||||
binding.ivIngredientSearch.setOnClickListener { openIngredientSearch() }
|
||||
binding.etIngredientName.setOnClickListener { openIngredientSearch() }
|
||||
binding.btnReset.setOnClickListener {
|
||||
binding.etAmount.setText("")
|
||||
}
|
||||
binding.btnAdd.clickWithDebounce {
|
||||
addManualIngredient()
|
||||
}
|
||||
}
|
||||
|
||||
/** 打开食材检索弹窗(食材名称不可手输,点击即搜索) */
|
||||
private fun openIngredientSearch() {
|
||||
if (foodSearchDialog?.isShowing == true) return
|
||||
foodSearchDialog = FoodSearchDialog(
|
||||
activity = this,
|
||||
onItemSelected = { item -> onIngredientSelected(item) }
|
||||
).also { it.show() }
|
||||
}
|
||||
|
||||
/**
|
||||
* 食材检索选中回调:回填名称,暂存 GoodsItem(materId 用于提交)
|
||||
*/
|
||||
private fun onIngredientSelected(item: GoodsItem) {
|
||||
selectedIngredient = item
|
||||
binding.etIngredientName.setText(item.goodsName)
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动添加食材到构成列表:名称(materId)+ 主辅材 + 用量(克,取自秤重)
|
||||
*/
|
||||
private fun addManualIngredient() {
|
||||
val ingredient = selectedIngredient
|
||||
if (ingredient == null || ingredient.materId.isNullOrBlank()) {
|
||||
toast("请先搜索选择食材")
|
||||
return
|
||||
}
|
||||
val amount = currentWeight.roundedOneDecimalPlace()
|
||||
if (amount <= 0) {
|
||||
toast("请先称重获取用量")
|
||||
return
|
||||
}
|
||||
val type = if (binding.rbAux.isChecked) 2 else 1
|
||||
val existing = list.firstOrNull { it.goodsId == ingredient.goodsId }
|
||||
if (existing != null) {
|
||||
// 已存在同食材:累加用量并同步主辅材
|
||||
existing.useWeight = (existing.useWeight ?: 0.0) + amount
|
||||
existing.materialType = type
|
||||
existing.isMaterialTypeManual = true
|
||||
existing.isSetFinished = true
|
||||
existing.isNewDishType = true
|
||||
} else {
|
||||
ingredient.materialType = type
|
||||
ingredient.useWeight = amount
|
||||
ingredient.isMaterialTypeManual = true
|
||||
ingredient.isNewDishType = true
|
||||
ingredient.isOriginalData = false
|
||||
ingredient.isSetFinished = true
|
||||
ingredient.isClicked = false
|
||||
list.add(ingredient)
|
||||
binding.rvMaterialList.smoothScrollToPosition(list.size - 1)
|
||||
}
|
||||
// 清空录入区
|
||||
selectedIngredient = null
|
||||
binding.etIngredientName.setText("")
|
||||
binding.etAmount.setText("")
|
||||
updateMaterialTypes()
|
||||
}
|
||||
|
||||
private fun openSubmitPage() {
|
||||
@@ -253,23 +436,20 @@ class PrepareFoodActivity : BaseActivity() {
|
||||
startActivity<SubmitFoodActivity> {
|
||||
putExtra(SubmitFoodActivity.GOODS_LIST, goodsList as Serializable)
|
||||
putExtra(SubmitFoodActivity.FOOD_ITEM, food as Serializable)
|
||||
putExtra(SubmitFoodActivity.COOK_ORDER_ID, cookOrderId)
|
||||
}
|
||||
}
|
||||
|
||||
private fun getGoodsList() {
|
||||
if (goodsList == null) {
|
||||
goodsList = mutableListOf()
|
||||
} else {
|
||||
goodsList!!.clear()
|
||||
}
|
||||
// 将 GoodsItem 转换为 CookFoodGoodsEntity 并补充菜品相关字段
|
||||
list.filter { it.isSetFinished }.forEach {
|
||||
goodsList?.add(CookFoodGoodsEntity().apply {
|
||||
goodsList?.add(it.toCookFoodGoodsEntity().apply {
|
||||
foodId = food!!.foodId
|
||||
goodsId = it.goodsId
|
||||
relateionType = it.relateionType
|
||||
allEdible = it.allEdible
|
||||
goodsName = it.goodsName
|
||||
materialType = it.materialType
|
||||
useWeight = it.useWeight ?: 0.toDouble()
|
||||
goodsOrRelationCode = it.goodsOrRelationCode
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -286,93 +466,139 @@ class PrepareFoodActivity : BaseActivity() {
|
||||
|
||||
|
||||
private fun initObserver() {
|
||||
// 新配比秤接口 observer(制作模式使用)
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
netViewModel.foodDetailState.collect { state ->
|
||||
when (state) {
|
||||
is UiState.Success -> {
|
||||
// 防止 StateFlow 重放导致 list 被重复清空
|
||||
if (isDetailLoaded) return@collect
|
||||
val detail = state.data
|
||||
if (detail == null) {
|
||||
toast("查询菜品信息为空")
|
||||
return@collect
|
||||
}
|
||||
isDetailLoaded = true
|
||||
loadDishDetail(detail)
|
||||
netViewModel.cookOrderCompositionState.collect { state ->
|
||||
when (state) {
|
||||
is UiState.Success -> {
|
||||
val items = state.data
|
||||
if (items.isNullOrEmpty()) {
|
||||
toast("查询菜品构成为空")
|
||||
return@collect
|
||||
}
|
||||
|
||||
is UiState.Error -> toast(state.msg)
|
||||
else -> {}
|
||||
loadDishComposition(items)
|
||||
}
|
||||
is UiState.Error -> toast(state.msg)
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun getDishDetail() {
|
||||
// //649
|
||||
// val url = "${UrlConfig.DISH_DETAIL}?foodId=${food?.foodId}"
|
||||
// HttpUtil.get(
|
||||
// url = url,
|
||||
// doSuccess = {
|
||||
// val json = it.toJsonString()
|
||||
// Log.d(TAG, "getDishDetail: json:$json")
|
||||
// val detail: CookFoodEntity? = json.toObject<CookFoodEntity>()
|
||||
// if (detail == null) {
|
||||
// toast("查询菜品信息为空")
|
||||
// return@get
|
||||
// }
|
||||
// loadDishDetail(detail)
|
||||
// }) { code, msg ->
|
||||
// toast(msg)
|
||||
// }
|
||||
/** 新接口:通过 foodId 查询菜品构成(采样模式称量模板) */
|
||||
private fun getDishDetail(foodId: String) {
|
||||
netViewModel.getFoodComposition(
|
||||
foodId = foodId,
|
||||
onResult = { state ->
|
||||
when (state) {
|
||||
is UiState.Success -> {
|
||||
val response = state.data
|
||||
if (response == null) {
|
||||
toast("查询菜品构成为空")
|
||||
} else {
|
||||
loadFoodComposition(response)
|
||||
}
|
||||
}
|
||||
is UiState.Error -> toast(state.msg)
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
netViewModel.getFoodDetail(food?.foodId ?: "")
|
||||
/** 新接口:通过 cookOrderId 查询菜品食材构成(制作模式使用) */
|
||||
private fun getCookOrderComposition(cookOrderId: String) {
|
||||
netViewModel.getCookOrderComposition(cookOrderId)
|
||||
}
|
||||
|
||||
|
||||
private fun loadDishDetail(detail: CookFoodEntity) {
|
||||
// val voList = detail.stFoodInfoConstituteList
|
||||
val voList = detail.foodConstituteList
|
||||
if (voList.isNullOrEmpty()) {
|
||||
return
|
||||
}
|
||||
//筛选出主材和辅材
|
||||
val tempData = voList.filter { it.materialType == 1 || it.materialType == 2 }
|
||||
.apply {
|
||||
forEach { it.useWeight = 0.toDouble() }
|
||||
/**
|
||||
* 采样模式:将 food/{foodId}/composition 返回的构成映射为 GoodsItem 并刷新 UI
|
||||
* 筛选主材(1)/辅材(2),调料(3)仍走槽位秤;useWeight 置零待重新称量
|
||||
*/
|
||||
private fun loadFoodComposition(response: FoodCompositionResponse) {
|
||||
val tempData = response.ingredients
|
||||
.filter { it.isMain == 1 || it.isMain == 2 }
|
||||
.map {
|
||||
GoodsItem(
|
||||
goodsId = it.materId,
|
||||
materId = it.materId,
|
||||
goodsName = it.materName,
|
||||
materialType = it.isMain,
|
||||
useWeight = 0.0,
|
||||
isOriginalData = true
|
||||
)
|
||||
}
|
||||
list.clear()
|
||||
firstReqSize = list.size
|
||||
list.addAll(tempData)
|
||||
dishPartAdapter.notifyDataSetChanged()
|
||||
materialAdapter.items = list
|
||||
materialAdapter.notifyDataSetChanged()
|
||||
firstReqSize = list.size
|
||||
}
|
||||
|
||||
/**
|
||||
* 将新配比秤接口的食材构成列表映射为 GoodsItem 并刷新 UI
|
||||
* 新接口天然仅返回主材(ingredientClass=1)和辅材(ingredientClass=2),不含调料
|
||||
* useWeight 保留接口返回值,不再强制置零
|
||||
*/
|
||||
private fun loadDishComposition(items: List<CookOrderCompositionItem>) {
|
||||
val tempData = items.map { item ->
|
||||
GoodsItem(
|
||||
goodsId = item.materId,
|
||||
goodsName = item.ingredientName,
|
||||
materId = item.materId,
|
||||
materialType = item.ingredientClass,
|
||||
useWeight = item.useWeight,
|
||||
rawMaterialsType = item.vegTypeId,
|
||||
isOriginalData = true
|
||||
)
|
||||
}
|
||||
list.clear()
|
||||
list.addAll(tempData)
|
||||
materialAdapter.items = list
|
||||
materialAdapter.notifyDataSetChanged()
|
||||
firstReqSize = list.size
|
||||
}
|
||||
|
||||
private var firstReqSize = 0
|
||||
private var isDetailLoaded = false
|
||||
private val list = mutableListOf<CookFoodGoodsEntity>()
|
||||
private val dishPartAdapter by lazy {
|
||||
DishPartAdapter(list = list).apply {
|
||||
val adapter = this
|
||||
onItemClick = { positon ->
|
||||
private val list = mutableListOf<GoodsItem>()
|
||||
private val materialAdapter by lazy {
|
||||
FoodMaterialAdapter(list).apply {
|
||||
onItemClick = { position ->
|
||||
list.forEachIndexed { index, entity ->
|
||||
entity.isItemClicked = index == positon
|
||||
entity.isClicked = index == position
|
||||
}
|
||||
// 选中食材时同步当前秤重(制作/采样均支持)
|
||||
val item = list.getOrNull(position)
|
||||
if (item != null && currentWeight > 0) {
|
||||
item.useWeight = currentWeight
|
||||
item.isSetFinished = true
|
||||
}
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
addOnItemChildClickListener(R.id.ivClearIcon) { _, _, positon ->
|
||||
Log.d(TAG, "onFoodItemClick: ${list[positon].toJsonString()}")
|
||||
if (list[positon].isOriginalData) {
|
||||
list[positon].run {
|
||||
isNewDishType = false
|
||||
useWeight = 0.0
|
||||
isSetFinished = false
|
||||
addOnItemChildClickListener(R.id.ivClearIcon) { _, _, position ->
|
||||
val item = list.getOrNull(position) ?:return@addOnItemChildClickListener
|
||||
Log.d(TAG, "onFoodItemClick: ${item.toJsonString()}")
|
||||
if (item.isOriginalData) {
|
||||
// 无重量信息时转为 item 整体点击(触发选中效果)
|
||||
if (item.useWeight == null || item.useWeight == 0.0) {
|
||||
onItemClick?.invoke(position)
|
||||
return@addOnItemChildClickListener
|
||||
}
|
||||
deleteRemindDialog("清除确认", "确定清除食材「${item.goodsName}」添加的重量吗?") {
|
||||
item.run {
|
||||
isNewDishType = false
|
||||
useWeight = 0.0
|
||||
isSetFinished = false
|
||||
}
|
||||
notifyItemChanged(position)
|
||||
}
|
||||
notifyItemChanged(positon)
|
||||
return@addOnItemChildClickListener
|
||||
}
|
||||
adapter.removeAt(positon)
|
||||
|
||||
deleteRemindDialog("删除确认", "确定删除食材「${item.goodsName}」吗?") {
|
||||
removeFood(position)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -380,37 +606,55 @@ class PrepareFoodActivity : BaseActivity() {
|
||||
/**
|
||||
* RecyclerView初始化
|
||||
*/
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
private fun initRecyclerView() {
|
||||
binding.rvDishPartList.run {
|
||||
layoutManager =
|
||||
LinearLayoutManager(this@PrepareFoodActivity, LinearLayoutManager.VERTICAL, false)
|
||||
// 仅 isNewDishType=true 的 item 显示侧滑删除菜单(必须在 setAdapter 之前调用)
|
||||
setSwipeMenuCreator { _, rightMenu, position ->
|
||||
if (list.getOrNull(position)?.isNewDishType == true) {
|
||||
binding.rvMaterialList.let {
|
||||
it.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
|
||||
// 采样模式下所有食材均可侧滑删除(必须在 setAdapter 之前调用)
|
||||
it.setSwipeMenuCreator { _, rightMenu, position ->
|
||||
if (SpTool.cookMode == 1) {
|
||||
rightMenu.addMenuItem(buildDeleteMenuItem())
|
||||
}
|
||||
}
|
||||
// 点击侧滑菜单项:先关闭菜单,再弹窗确认删除
|
||||
setOnItemMenuClickListener { menuBridge, position ->
|
||||
it.setOnItemMenuClickListener { menuBridge, position ->
|
||||
menuBridge.closeMenu()
|
||||
val item = list.getOrNull(position) ?: return@setOnItemMenuClickListener
|
||||
CommonDialog(this@PrepareFoodActivity)
|
||||
.setTitle("删除确认")
|
||||
.setContent("确定删除食材「${item.goodsName}」吗?")
|
||||
.setNegativeButton("取消")
|
||||
.setPositiveButton("删除") {
|
||||
dishPartAdapter.removeAt(position)
|
||||
toast("已删除")
|
||||
}.show()
|
||||
deleteRemindDialog("删除确认", "确定删除食材「${item.goodsName}」吗?") {
|
||||
removeFood(position)
|
||||
}
|
||||
}
|
||||
// item 点击事件
|
||||
setOnItemClickListener { _, position ->
|
||||
dishPartAdapter.onItemClick?.invoke(position)
|
||||
it.setOnItemClickListener { _, position ->
|
||||
materialAdapter.onItemClick?.invoke(position)
|
||||
}
|
||||
adapter = dishPartAdapter
|
||||
handleRvTouchHideKeyboard()
|
||||
it.adapter = materialAdapter
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除提醒
|
||||
*/
|
||||
private fun deleteRemindDialog(title: String, content: String, action: () -> Unit) {
|
||||
CommonDialog(this@PrepareFoodActivity)
|
||||
.setTitle(title)
|
||||
.setContent(content)
|
||||
.setNegativeButton("取消")
|
||||
.setPositiveButton("确认") {
|
||||
action()
|
||||
}.show()
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除菜品
|
||||
*/
|
||||
private fun removeFood(position: Int) {
|
||||
materialAdapter.removeAt(position)
|
||||
toast("已删除")
|
||||
updateMaterialTypes()
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建侧滑删除菜单项
|
||||
*/
|
||||
@@ -427,13 +671,17 @@ class PrepareFoodActivity : BaseActivity() {
|
||||
super.onResume()
|
||||
pageVisible = true
|
||||
showRecognizePage = false
|
||||
cameraUtils.bind()
|
||||
if (SpTool.cookMode == 1) {
|
||||
cameraUtils.bind()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
pageVisible = false
|
||||
cameraUtils.unbind()
|
||||
if (SpTool.cookMode == 1) {
|
||||
cameraUtils.unbind()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -510,14 +758,39 @@ class PrepareFoodActivity : BaseActivity() {
|
||||
dismissLoading()
|
||||
Log.d(TAG, "takePhoto foodScoreList is empty")
|
||||
isTakingPhoto.set(false)
|
||||
withContext(Dispatchers.Main) {
|
||||
showNotRecognizeDialog()
|
||||
}
|
||||
return@withContext
|
||||
}
|
||||
withContext(Dispatchers.Main) {
|
||||
queryFood(foodScoreList)
|
||||
Log.d(TAG, "takePhoto queryFood, list=$foodScoreList")
|
||||
postDelayed(1000) {
|
||||
dismissLoading()
|
||||
loadRecognizeResultPage(foodScoreList)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private var notRecognizeDialog: CommonDialog? = null
|
||||
private fun showNotRecognizeDialog() {
|
||||
notRecognizeDialog = CommonDialog(this)
|
||||
.setTitle("提示")
|
||||
.setContent("未识别到食材,请稍后重试")
|
||||
.setNegativeButton("取消") {
|
||||
manualCancelFlag = true
|
||||
}
|
||||
.setNeutralButton("重新识别") {
|
||||
recognizeFood(currentWeight)
|
||||
}
|
||||
.setPositiveButton("手动设置"){
|
||||
loadRecognizeResultPage(emptyList())
|
||||
}
|
||||
.also {
|
||||
it.show()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 拍照失败回调
|
||||
@@ -529,48 +802,10 @@ class PrepareFoodActivity : BaseActivity() {
|
||||
dismissLoading()
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用接口查询识别到的菜品
|
||||
* @param list 食材列表
|
||||
*/
|
||||
private fun queryFood(list: List<FoodModule.IdNameScore>) {
|
||||
Log.d(TAG, "takePhoto queryFood, list=$list")
|
||||
//调用接口成功,返回食材列表设置isTakingPhoto.set(false),暂时写死数据
|
||||
val foodList = mutableListOf<CookFoodGoodsEntity>()
|
||||
list.forEachIndexed { index, food ->
|
||||
Log.d(TAG, "takePhoto queryFood, index=${index},food=$food")
|
||||
var foodName = ""
|
||||
var foodId = ""
|
||||
food.name.split("WP").let {
|
||||
foodName = it[0]
|
||||
foodId = if (it.size > 1) {
|
||||
"WP${it[1]}"
|
||||
} else {
|
||||
food.name
|
||||
}
|
||||
}
|
||||
foodList.add(
|
||||
CookFoodGoodsEntity(
|
||||
goodsId = foodId,
|
||||
goodsName = foodName,
|
||||
foodId = index.toString()
|
||||
).also {
|
||||
it.foodScore = ((1 - food.score) * 10000).toInt()
|
||||
it.isOriginalData = false
|
||||
}
|
||||
)
|
||||
}
|
||||
Log.d(TAG, "takePhoto queryFood, 数据添加完成")
|
||||
postDelayed(1000) {
|
||||
dismissLoading()
|
||||
loadRecognizeResultPage(foodList)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载识别结果页面
|
||||
*/
|
||||
private fun loadRecognizeResultPage(foodList: List<CookFoodGoodsEntity>) {
|
||||
private fun loadRecognizeResultPage(nameScoreList: List<FoodModule.IdNameScore>) {
|
||||
if (currentWeight < WEIGHT_RECOGNIZE_VALUE) {
|
||||
Log.d(TAG, "takePhoto queryFood, 已取消")
|
||||
toast("已取消")
|
||||
@@ -582,9 +817,13 @@ class PrepareFoodActivity : BaseActivity() {
|
||||
activity = this,
|
||||
imageUri = lastPhotoUri?.toString(),
|
||||
currentWeight = currentWeight,
|
||||
goodsList = ArrayList(foodList),
|
||||
initialWeight = initialWeight,
|
||||
nameScoreList = ArrayList(nameScoreList),
|
||||
finishCallback = { isManualCancel, entity ->
|
||||
Log.d(TAG, "queryFood: isManualCancel=$isManualCancel, entity=${entity.toJsonString()}")
|
||||
Log.d(
|
||||
TAG,
|
||||
"queryFood: isManualCancel=$isManualCancel, entity=${entity.toJsonString()}"
|
||||
)
|
||||
manualCancelFlag = isManualCancel
|
||||
if (isManualCancel) {
|
||||
return@start
|
||||
@@ -600,24 +839,67 @@ class PrepareFoodActivity : BaseActivity() {
|
||||
|
||||
/**
|
||||
* 跳转食物搜索页(采集模式专用)
|
||||
* @param v 触发搜索的 View,用于收起键盘
|
||||
*/
|
||||
private fun jumpSearch(v: View) {
|
||||
val intent = Intent(this, FoodSearchActivity::class.java).apply {
|
||||
putExtra(FoodSearchActivity.FOOD_NAME, binding.etInputDish.text.toString().trim())
|
||||
private fun jumpSearch() {
|
||||
val searchContent = binding.etInputDish.text.toString().trim()
|
||||
if (searchContent.isBlank()) {
|
||||
toast(binding.etInputDish.hint.toString())
|
||||
return
|
||||
}
|
||||
startActivity(intent) {
|
||||
foodId = it?.getStringExtra(FoodSearchActivity.FOOD_ID)
|
||||
val name = it?.getStringExtra(FoodSearchActivity.FOOD_NAME)
|
||||
Log.d(TAG, "jumpSearch: foodId=$foodId, name=$name")
|
||||
if (name.isNullOrBlank()) return@startActivity
|
||||
val launchIntent = Intent(this, FoodSearchActivity::class.java).apply {
|
||||
putExtra(FoodSearchActivity.FOOD_NAME, searchContent)
|
||||
}
|
||||
startActivity(launchIntent) { resultIntent ->
|
||||
if (resultIntent == null) return@startActivity
|
||||
food = IntentCompat.getSerializableExtra(resultIntent, FOOD_ITEM, FoodRecord::class.java)
|
||||
Log.d(TAG, "jumpSearch: record=$food")
|
||||
if (food == null) return@startActivity
|
||||
// 将搜索结果写入 food,保留 cookMode
|
||||
food!!.cookMode = 1
|
||||
binding.etInputDish.run {
|
||||
setText(name)
|
||||
tag = name
|
||||
setText(food!!.foodName)
|
||||
tag = food!!.foodName
|
||||
setSelection(text.length)
|
||||
}
|
||||
// 有 foodId 时请求菜品构成
|
||||
if (!food!!.foodId.isNullOrBlank()) {
|
||||
getDishDetail(food!!.foodId!!)
|
||||
}
|
||||
}
|
||||
KeyboardUtil.hideKeyboard(v)
|
||||
hideKeyboard()
|
||||
}
|
||||
|
||||
private fun handleRvTouchHideKeyboard() {
|
||||
val gestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
|
||||
override fun onSingleTapUp(e: MotionEvent): Boolean {
|
||||
hideKeyboard()
|
||||
// 返回 false,不消费事件,不影响 item 点击和滚动
|
||||
return false
|
||||
}
|
||||
})
|
||||
binding.rvMaterialList.addOnItemTouchListener(object : RecyclerView.SimpleOnItemTouchListener() {
|
||||
private var startX = 0f
|
||||
private var startY = 0f
|
||||
|
||||
override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
|
||||
when (e.action) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
startX = e.x
|
||||
startY = e.y
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
val dx = abs(e.x - startX)
|
||||
val dy = abs(e.y - startY)
|
||||
// 水平滑动超过阈值时(侧滑手势),关闭键盘
|
||||
if (dx > dy && dx > 10) {
|
||||
hideKeyboard()
|
||||
}
|
||||
}
|
||||
}
|
||||
gestureDetector.onTouchEvent(e)
|
||||
return false
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
@@ -3,22 +3,21 @@ package com.shuwei.dish.match.ui
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import android.widget.FrameLayout
|
||||
import androidx.activity.addCallback
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.FoodListAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.databinding.ActivitySamplingModeBinding
|
||||
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.entity.FoodRecord
|
||||
import com.shuwei.dish.match.model.FoodRecord
|
||||
import com.shuwei.dish.match.model.SampleHistoryItem
|
||||
import com.shuwei.dish.match.net.UiState
|
||||
import com.shuwei.dish.match.utils.DateTimeUtil
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
@@ -49,82 +48,16 @@ class SamplingModeActivity : BaseActivity() {
|
||||
setHeaderBackground()
|
||||
initRecyclerView()
|
||||
addViewListener()
|
||||
initObserver()
|
||||
requestData(true)
|
||||
onBackPressedDispatcher.addCallback(this) { }
|
||||
}
|
||||
|
||||
/**
|
||||
* 收集 cookFoodListState,将本地烹饪中数据渲染到列表
|
||||
*/
|
||||
private fun initObserver() {
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
appViewModel.cookFoodListState.collect { cookFoodEntities ->
|
||||
if (binding.dishRadioGroup.checkedRadioButtonId != R.id.rbSamplingCooking) return@collect
|
||||
delayDismissLoading()
|
||||
if (cookFoodEntities.isNullOrEmpty()) {
|
||||
loadEmptyView()
|
||||
return@collect
|
||||
}
|
||||
val tempList = mutableListOf<FoodRecord>()
|
||||
cookFoodEntities.sortedByDescending { DateTimeUtil.convert(dateStr = it.createTime) }
|
||||
.forEach { entity ->
|
||||
tempList.add(FoodRecord().apply {
|
||||
foodId = entity.foodId
|
||||
foodName = entity.foodName
|
||||
cookMode = 1
|
||||
isCooking = true
|
||||
})
|
||||
}
|
||||
list.clear()
|
||||
list.addAll(tempList)
|
||||
dishAdapter.notifyDataSetChanged()
|
||||
finishRefresh()
|
||||
binding.refreshLayout.run {
|
||||
setEnableRefresh(false)
|
||||
setEnableLoadMore(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
netViewModel.samplingListState.collect { state ->
|
||||
when (state) {
|
||||
is UiState.Loading -> showLoading()
|
||||
is UiState.Success -> {
|
||||
if (binding.dishRadioGroup.checkedRadioButtonId != R.id.rbSamplingFinished) {
|
||||
delayDismissLoading()
|
||||
return@collect
|
||||
}
|
||||
loadDishList(state.data)
|
||||
}
|
||||
is UiState.Error -> {
|
||||
if (binding.dishRadioGroup.checkedRadioButtonId != R.id.rbSamplingFinished) {
|
||||
delayDismissLoading()
|
||||
return@collect
|
||||
}
|
||||
binding.refreshLayout.setEnableRefresh(true)
|
||||
toast(state.msg)
|
||||
finishRefresh()
|
||||
delayDismissLoading()
|
||||
if (pageNo == 1) loadEmptyView()
|
||||
}
|
||||
is UiState.Idle -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private fun setTitleBar() {
|
||||
setTitleBar(titleBarAction = {
|
||||
it.visible()
|
||||
}, titleAction = {
|
||||
it.text = "采样历史"
|
||||
}, rightIconActon = {
|
||||
}, rightIconAction = {
|
||||
it.visible()
|
||||
it.setImageResource(R.drawable.ic_setting)
|
||||
it.setOnClickListener {
|
||||
@@ -133,19 +66,44 @@ class SamplingModeActivity : BaseActivity() {
|
||||
}, backAction = {
|
||||
it.gone()
|
||||
})
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
fun getCookFoodList() {
|
||||
appViewModel.getCookFoodList(cookMode = 1)
|
||||
dbViewModel.getCookFoodListWithCallback(cookMode = 1) { cookFoodEntities ->
|
||||
// 回调期间用户可能已切换 Tab,需再次校验
|
||||
if (binding.rbSamplingCooking.isChecked.not()) return@getCookFoodListWithCallback
|
||||
delayDismissLoading()
|
||||
if (cookFoodEntities.isNullOrEmpty()) {
|
||||
loadEmptyView()
|
||||
return@getCookFoodListWithCallback
|
||||
}
|
||||
val tempList = mutableListOf<FoodRecord>()
|
||||
cookFoodEntities.sortedByDescending { DateTimeUtil.convert(dateStr = it.createTime) }
|
||||
.forEach { entity ->
|
||||
tempList.add(FoodRecord().apply {
|
||||
foodId = entity.foodId
|
||||
foodName = entity.foodName
|
||||
cookMode = 1
|
||||
isCooking = true
|
||||
dinnerType = entity.dinnerType ?: "0"
|
||||
})
|
||||
}
|
||||
list.clear()
|
||||
list.addAll(tempList)
|
||||
dishAdapter.notifyDataSetChanged()
|
||||
finishRefresh()
|
||||
binding.refreshLayout.run {
|
||||
setEnableRefresh(false)
|
||||
setEnableLoadMore(false)
|
||||
}
|
||||
}
|
||||
// }
|
||||
}
|
||||
|
||||
fun deleteCookFoodAndGoods(foodId: String, action: () -> Unit) {
|
||||
fun deleteCookFoodAndGoods(foodId: String, dinnerType: String, action: () -> Unit) {
|
||||
lifecycleScope.launch {
|
||||
appViewModel.deleteCookFoodAndGoods(cookMode = 1, foodId = foodId)
|
||||
dbViewModel.deleteCookFoodAndGoods(cookMode = 1, foodId = foodId, dinnerType = dinnerType)
|
||||
action()
|
||||
}
|
||||
}
|
||||
@@ -153,10 +111,13 @@ class SamplingModeActivity : BaseActivity() {
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
val isConfigPage = intent?.getBooleanExtra(IS_CONFIG_PAGE, false) ?: false
|
||||
Log.d(TAG, "onNewIntent, isConfigPage=$isConfigPage")
|
||||
if (isConfigPage) {
|
||||
getCookFoodList()
|
||||
return
|
||||
}
|
||||
val isCooking = intent?.getBooleanExtra(IS_COOKING, false) ?: false
|
||||
Log.d(TAG, "onNewIntent, isCooking=$isCooking")
|
||||
//toast("isCooking=$isCooking")
|
||||
refreshPage(isCooking)
|
||||
}
|
||||
@@ -182,7 +143,7 @@ class SamplingModeActivity : BaseActivity() {
|
||||
return
|
||||
}
|
||||
startActivity<PrepareFoodActivity> {
|
||||
putExtra(PrepareFoodActivity.FOOD_NAME, item.foodName)
|
||||
putExtra(PrepareFoodActivity.FOOD_ITEM, item as Serializable)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,7 +167,7 @@ class SamplingModeActivity : BaseActivity() {
|
||||
.setContent("确定要删除「${item.foodName}」吗?")
|
||||
.setNegativeButton("取消")
|
||||
.setPositiveButton("删除") {
|
||||
deleteCookFoodAndGoods(foodId = item.foodId ?: "") {
|
||||
deleteCookFoodAndGoods(foodId = item.foodId ?: "", dinnerType = item.dinnerType) {
|
||||
if (list.size > 1) {
|
||||
dishAdapter.removeAt(position)
|
||||
} else {
|
||||
@@ -247,7 +208,7 @@ class SamplingModeActivity : BaseActivity() {
|
||||
}
|
||||
binding.refreshLayout.setOnRefreshListener {
|
||||
pageNo = 1
|
||||
if (binding.dishRadioGroup.checkedRadioButtonId == R.id.rbSamplingFinished) {
|
||||
if (binding.rbSamplingFinished.isChecked) {
|
||||
getSamplingList()
|
||||
} else {
|
||||
finishRefresh()
|
||||
@@ -255,30 +216,33 @@ class SamplingModeActivity : BaseActivity() {
|
||||
}
|
||||
}
|
||||
binding.refreshLayout.setOnLoadMoreListener {
|
||||
if (binding.dishRadioGroup.checkedRadioButtonId == R.id.rbSamplingFinished) {
|
||||
if (binding.rbSamplingFinished.isChecked) {
|
||||
getSamplingList()
|
||||
} else {
|
||||
finishRefresh()
|
||||
}
|
||||
}
|
||||
|
||||
binding.rbSamplingCooking.setOnClickListener {
|
||||
// Log.d(TAG, "addViewListener: cooking:${binding.rbSamplingCooking.isChecked}")
|
||||
if (it.tag == true) {
|
||||
return@setOnClickListener
|
||||
binding.rbSamplingCooking.let {
|
||||
it.setOnClickListener { _ ->
|
||||
if (it.isChecked) {
|
||||
return@setOnClickListener
|
||||
}
|
||||
binding.rbSamplingCooking.isChecked = true
|
||||
binding.rbSamplingFinished.isChecked = false
|
||||
requestData(true)
|
||||
}
|
||||
requestData(true)
|
||||
binding.rbSamplingCooking.tag = binding.rbSamplingCooking.isChecked
|
||||
binding.rbSamplingFinished.tag = binding.rbSamplingFinished.isChecked
|
||||
}
|
||||
binding.rbSamplingFinished.setOnClickListener {
|
||||
binding.rbSamplingFinished.let {
|
||||
it.setOnClickListener { _ ->
|
||||
// Log.d(TAG, "addViewListener: finish:${binding.rbSamplingFinished.isChecked}")
|
||||
if (it.tag == true) {
|
||||
return@setOnClickListener
|
||||
if (it.isChecked) {
|
||||
return@setOnClickListener
|
||||
}
|
||||
binding.rbSamplingCooking.isChecked = false
|
||||
binding.rbSamplingFinished.isChecked = true
|
||||
requestData(false)
|
||||
}
|
||||
requestData(false)
|
||||
binding.rbSamplingCooking.tag = binding.rbSamplingCooking.isChecked
|
||||
binding.rbSamplingFinished.tag = binding.rbSamplingFinished.isChecked
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,15 +251,47 @@ class SamplingModeActivity : BaseActivity() {
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
fun getSamplingList() {
|
||||
netViewModel.getSamplingList(
|
||||
param = mutableMapOf(
|
||||
"pageNum" to pageNo,
|
||||
"pageSize" to pageSize,
|
||||
"placeId" to BaseApp.canteenId
|
||||
)
|
||||
)
|
||||
netViewModel.sampleHistory(
|
||||
pageNum = pageNo,
|
||||
pageSize = pageSize,
|
||||
onLoading = { showLoading() }
|
||||
) { state ->
|
||||
when (state) {
|
||||
is UiState.Success -> {
|
||||
// 回调期间用户可能已切换 Tab,需再次校验
|
||||
if (binding.rbSamplingFinished.isChecked.not()) {
|
||||
delayDismissLoading()
|
||||
return@sampleHistory
|
||||
}
|
||||
loadDishList(state.data?.map { it.toFoodRecord() }?.toMutableList())
|
||||
}
|
||||
is UiState.Error -> {
|
||||
if (binding.rbSamplingFinished.isChecked.not()) {
|
||||
delayDismissLoading()
|
||||
return@sampleHistory
|
||||
}
|
||||
binding.refreshLayout.setEnableRefresh(true)
|
||||
toast(state.msg)
|
||||
finishRefresh()
|
||||
delayDismissLoading()
|
||||
if (pageNo == 1) loadEmptyView()
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 已提交采样列表条目 → FoodRecord 映射,供 FoodListAdapter(SAMPLING_MODE) 展示 */
|
||||
private fun SampleHistoryItem.toFoodRecord(): FoodRecord = FoodRecord(
|
||||
foodId = innovId,
|
||||
foodName = foodName,
|
||||
foodWeight = foodWeight,
|
||||
cookMode = 1,
|
||||
innovNo = innovNo,
|
||||
status = status,
|
||||
statusName = statusName
|
||||
)
|
||||
|
||||
private fun finishRefresh() {
|
||||
if (pageNo == 1) {
|
||||
binding.refreshLayout.finishRefresh(1200)
|
||||
@@ -316,7 +312,7 @@ class SamplingModeActivity : BaseActivity() {
|
||||
)
|
||||
}
|
||||
emptyViewBinding!!.tvContent.text = "暂无数据"
|
||||
emptyViewBinding!!.tvSubContent.text = "今日暂无采样数据,点击下方按钮新增采样"
|
||||
emptyViewBinding!!.tvSubContent.text = "暂无采样数据,点击下方按钮新增采样"
|
||||
|
||||
// 方案B:沿用 adapter stateView,使用 FrameLayout.LayoutParams + minimumHeight 避免空态贴顶
|
||||
emptyViewBinding!!.root.layoutParams = FrameLayout.LayoutParams(
|
||||
@@ -331,18 +327,18 @@ class SamplingModeActivity : BaseActivity() {
|
||||
//dishAdapter.setStateViewLayout(requireContext(), R.layout-sw800dp.layout_empty_view)
|
||||
|
||||
binding.refreshLayout.run {
|
||||
setEnableRefresh(binding.dishRadioGroup.checkedRadioButtonId == R.id.rbSamplingFinished)
|
||||
setEnableRefresh(binding.rbSamplingFinished.isChecked)
|
||||
setEnableLoadMore(false)
|
||||
}
|
||||
}
|
||||
|
||||
fun refreshPage(isCooking: Boolean) {
|
||||
val checkedId = binding.dishRadioGroup.checkedRadioButtonId
|
||||
if (checkedId == R.id.rbSamplingFinished) {
|
||||
if (binding.rbSamplingFinished.isChecked) {
|
||||
//当前是已采样
|
||||
if (isCooking) {
|
||||
//需要切换到烹饪中
|
||||
binding.dishRadioGroup.check(R.id.rbSamplingCooking)
|
||||
binding.rbSamplingCooking.isChecked = true
|
||||
binding.rbSamplingFinished.isChecked = false
|
||||
requestData(true)
|
||||
return
|
||||
}
|
||||
@@ -353,7 +349,8 @@ class SamplingModeActivity : BaseActivity() {
|
||||
//当前是烹饪中
|
||||
if (isCooking.not()) {
|
||||
//需要切换到已采样
|
||||
binding.dishRadioGroup.check(R.id.rbSamplingFinished)
|
||||
binding.rbSamplingCooking.isChecked = false
|
||||
binding.rbSamplingFinished.isChecked = true
|
||||
requestData(false)
|
||||
return
|
||||
}
|
||||
@@ -361,21 +358,17 @@ class SamplingModeActivity : BaseActivity() {
|
||||
requestData(true)
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
fun refreshLocalData() {
|
||||
showLoading()
|
||||
appViewModel.resetCookFoodList()
|
||||
getCookFoodList()
|
||||
}
|
||||
|
||||
private fun requestData(isCooking: Boolean) {
|
||||
list.clear()
|
||||
dishAdapter.notifyDataSetChanged()
|
||||
if (isCooking) {
|
||||
// 清除上次网络请求的残留状态
|
||||
netViewModel.resetSamplingListState()
|
||||
refreshLocalData()
|
||||
} else {
|
||||
// 同理,清除本地数据残留状态
|
||||
appViewModel.resetCookFoodList()
|
||||
pageNo = 1
|
||||
getSamplingList()
|
||||
}
|
||||
@@ -414,7 +407,7 @@ class SamplingModeActivity : BaseActivity() {
|
||||
return
|
||||
}
|
||||
lifecycleScope.launch {
|
||||
val slots = appViewModel.loadSeasoningSlot()
|
||||
val slots = dbViewModel.loadSeasoningSlot()
|
||||
if (slots.isEmpty()) {
|
||||
showDeviceConfigDialog()
|
||||
return@launch
|
||||
|
||||
@@ -9,18 +9,23 @@ import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.provider.Settings
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import com.chad.library.adapter4.util.setOnDebouncedItemClick
|
||||
import com.shuwei.dish.match.adapter.SettingAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.databinding.ActivitySettingBinding
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.dialog.EnvSwitchDialog
|
||||
import com.shuwei.dish.match.model.SettingItem
|
||||
import com.shuwei.dish.match.scale.ScaleServiceManager
|
||||
import com.shuwei.dish.match.utils.SpTool
|
||||
import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.startActivity
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
|
||||
/**
|
||||
* 设置Activity
|
||||
* 功能:管理多个设置相关的Fragment,支持Fragment切换
|
||||
* 设置页面
|
||||
* 使用 RecyclerView 展示设置菜单项,点击逻辑内聚在各 SettingItem 的 onClick 中
|
||||
*/
|
||||
class SettingActivity : BaseActivity() {
|
||||
|
||||
@@ -29,10 +34,15 @@ class SettingActivity : BaseActivity() {
|
||||
}
|
||||
|
||||
private lateinit var binding: ActivitySettingBinding
|
||||
// private val cameraUtils: CameraUtils by lazy {
|
||||
// CameraUtils(this)
|
||||
// }
|
||||
// private lateinit var previewView: PreviewView
|
||||
|
||||
/** 包含全部菜单项的完整列表(含隐藏项) */
|
||||
private val allItems: List<SettingItem> by lazy { buildAllItems() }
|
||||
|
||||
private val adapter = SettingAdapter().apply {
|
||||
setOnDebouncedItemClick { _, _, position ->
|
||||
getItem(position)?.onClick()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
@@ -42,40 +52,111 @@ class SettingActivity : BaseActivity() {
|
||||
setTitleBar(titleBarAction = {
|
||||
it.visible()
|
||||
}, titleAction = {
|
||||
it.text = "设备设置"
|
||||
}, rightIconActon = {
|
||||
it.text = "设置"
|
||||
}, rightIconAction = {
|
||||
it.visible()
|
||||
// 点击右上角图标,展示全部隐藏的开发者选项
|
||||
it.clickWithDebounce {
|
||||
startActivity<MasterScaleActivity>()
|
||||
adapter.submitList(allItems.toList())
|
||||
}
|
||||
})
|
||||
|
||||
initView()
|
||||
|
||||
// // 默认显示设备配置Fragment
|
||||
// if (savedInstanceState == null) {
|
||||
// showDeviceConfigFragment()
|
||||
// }
|
||||
//
|
||||
// initUI()
|
||||
}
|
||||
|
||||
|
||||
private fun initView() {
|
||||
binding.tvCurrentMode.text = when (SpTool.cookMode) {
|
||||
0 -> "当前:制作模式"
|
||||
1 -> "当前:采样模式"
|
||||
else -> "当前:未知模式"
|
||||
}
|
||||
binding.llCookMode.clickWithDebounce {
|
||||
SingleFragmentActivity.start(this, SingleFragmentActivity.PageType.COOK_MODE)
|
||||
}
|
||||
binding.llSeasoningConfig.clickWithDebounce {
|
||||
SingleFragmentActivity.start(this, SingleFragmentActivity.PageType.SEASONING_CONFIG)
|
||||
}
|
||||
binding.llFoodCollect.clickWithDebounce {
|
||||
checkCameraPermission()
|
||||
}
|
||||
binding.rvSettings.layoutManager = LinearLayoutManager(this)
|
||||
binding.rvSettings.adapter = adapter
|
||||
// 默认只展示非隐藏项
|
||||
adapter.submitList(allItems.filter { !it.isHidden })
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建完整的设置菜单列表,每项的 onClick 直接注入对应业务逻辑
|
||||
*/
|
||||
private fun buildAllItems(): List<SettingItem> = listOf(
|
||||
SettingItem(
|
||||
type = SettingItem.Type.COOK_MODE,
|
||||
title = "菜品模式",
|
||||
subtitle = when (SpTool.cookMode) {
|
||||
0 -> "当前:制作模式"
|
||||
1 -> "当前:采样模式"
|
||||
else -> "当前:未知模式"
|
||||
},
|
||||
onClick = {
|
||||
SingleFragmentActivity.start(this, SingleFragmentActivity.PageType.COOK_MODE)
|
||||
}
|
||||
),
|
||||
SettingItem(
|
||||
type = SettingItem.Type.SEASONING_CONFIG,
|
||||
title = "调料区设置",
|
||||
onClick = {
|
||||
SingleFragmentActivity.start(this, SingleFragmentActivity.PageType.SEASONING_CONFIG)
|
||||
}
|
||||
),
|
||||
SettingItem(
|
||||
type = SettingItem.Type.FOOD_COLLECT,
|
||||
title = "食材采集",
|
||||
onClick = { checkCameraPermission() }
|
||||
),
|
||||
SettingItem(
|
||||
type = SettingItem.Type.WEIGHT_CONFIG,
|
||||
title = "减重配置",
|
||||
onClick = {
|
||||
SingleFragmentActivity.start(this, SingleFragmentActivity.PageType.WEIGHT_CONFIG)
|
||||
}
|
||||
),
|
||||
SettingItem(
|
||||
type = SettingItem.Type.DB_INSPECT,
|
||||
title = "数据库查看",
|
||||
isHidden = true,
|
||||
onClick = {
|
||||
SingleFragmentActivity.start(this, SingleFragmentActivity.PageType.DB_INSPECT)
|
||||
}
|
||||
),
|
||||
SettingItem(
|
||||
type = SettingItem.Type.SCALE_OBSERVE,
|
||||
title = "秤数据监控",
|
||||
isHidden = true,
|
||||
onClick = { startActivity<MasterScaleActivity>() }
|
||||
),
|
||||
SettingItem(
|
||||
type = SettingItem.Type.ENV_SWITCH,
|
||||
title = "切换环境",
|
||||
onClick = { EnvSwitchDialog(this).show() }
|
||||
),
|
||||
SettingItem(
|
||||
type = SettingItem.Type.CLEAR_DATA,
|
||||
title = "数据清除",
|
||||
isHidden = true,
|
||||
onClick = { showClearDataDialog() }
|
||||
),
|
||||
SettingItem(
|
||||
type = SettingItem.Type.TEST_SEASONING,
|
||||
title = "测试调料拿取",
|
||||
isHidden = true,
|
||||
onClick = { startActivity<SubmitFoodActivity> { } }
|
||||
),
|
||||
)
|
||||
|
||||
/**
|
||||
* 弹出清除测试数据的二次确认弹窗
|
||||
*/
|
||||
private fun showClearDataDialog() {
|
||||
CommonDialog(this)
|
||||
.setTitle("数据清除")
|
||||
.setContent("将物理删除全部 4 张表数据(菜品、食材、调料、槽位),此操作不可恢复,同时重置菜品模式和食堂id,确认继续?")
|
||||
.setNegativeButton("取消")
|
||||
.setPositiveButton("确认") {
|
||||
dbViewModel.clearAllData {
|
||||
SpTool.cookMode = -1
|
||||
SpTool.canteenId = "0"
|
||||
// 通知所有已连接子设备同步清除数据
|
||||
ScaleServiceManager.sendClearData()
|
||||
startActivity<InitActivity>()
|
||||
}
|
||||
}
|
||||
.show()
|
||||
}
|
||||
|
||||
private fun openCollectPage() {
|
||||
@@ -83,12 +164,11 @@ class SettingActivity : BaseActivity() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查相机权限并显示 CollectFragment
|
||||
* 检查相机权限,有权限则直接打开采集页,否则发起授权请求
|
||||
*/
|
||||
@SuppressLint("ObsoleteSdkInt")
|
||||
private fun checkCameraPermission() {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
|
||||
// Android 6.0 以下,直接打开
|
||||
openCollectPage()
|
||||
return
|
||||
}
|
||||
@@ -97,16 +177,12 @@ class SettingActivity : BaseActivity() {
|
||||
Manifest.permission.CAMERA
|
||||
) == PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
// 权限已授予,直接打开
|
||||
openCollectPage()
|
||||
} else {
|
||||
// 权限未授予,申请权限
|
||||
requestPermission(Manifest.permission.CAMERA) { isGranted ->
|
||||
if (isGranted) {
|
||||
// 权限已授予,直接打开
|
||||
openCollectPage()
|
||||
} else {
|
||||
// 权限被拒绝
|
||||
showNotGrantedCameraPermissionDialog()
|
||||
}
|
||||
}
|
||||
@@ -128,197 +204,4 @@ class SettingActivity : BaseActivity() {
|
||||
}
|
||||
.show()
|
||||
}
|
||||
|
||||
//
|
||||
// /**
|
||||
// * 初始化UI和事件监听
|
||||
// */
|
||||
// private fun initUI() {
|
||||
// // 设备配置按钮点击事件
|
||||
// binding.btnDeviceConfig.setOnClickListener {
|
||||
// showDeviceConfigFragment()
|
||||
//
|
||||
// loadTabStyle(button = binding.btnDeviceConfig, isSelected = true)
|
||||
// loadTabStyle(button = binding.btnSeasoningConfig, isSelected = false)
|
||||
// loadTabStyle(button = binding.btnFoodCollect, isSelected = false)
|
||||
// }
|
||||
//
|
||||
// // 调料配置按钮点击事件
|
||||
// binding.btnSeasoningConfig.setOnClickListener {
|
||||
// showSeasoningConfigFragment()
|
||||
//
|
||||
// loadTabStyle(button = binding.btnDeviceConfig, isSelected = false)
|
||||
// loadTabStyle(button = binding.btnSeasoningConfig, isSelected = true)
|
||||
// loadTabStyle(button = binding.btnFoodCollect, isSelected = false)
|
||||
// }
|
||||
//
|
||||
// // 菜品采集按钮点击事件
|
||||
// binding.btnFoodCollect.setOnClickListener {
|
||||
// checkCameraPermissionAndShowFragment()
|
||||
//
|
||||
// loadTabStyle(button = binding.btnDeviceConfig, isSelected = false)
|
||||
// loadTabStyle(button = binding.btnSeasoningConfig, isSelected = false)
|
||||
// loadTabStyle(button = binding.btnFoodCollect, isSelected = true)
|
||||
// }
|
||||
//
|
||||
// // 主设备显示「秤数据监控」入口
|
||||
// if (GlobalData.deviceRole == DeviceRole.MASTER) {
|
||||
// binding.btnScaleMonitor.visible()
|
||||
// binding.btnScaleMonitor.setOnClickListener {
|
||||
// startActivity<MasterScaleActivity>()
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // 初始化按钮颜色(默认设备配置为选中状态)
|
||||
//
|
||||
// loadTabStyle(button = binding.btnDeviceConfig, isSelected = true)
|
||||
// loadTabStyle(button = binding.btnSeasoningConfig, isSelected = false)
|
||||
// loadTabStyle(button = binding.btnFoodCollect, isSelected = false)
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 加载顶部Tab按钮样式
|
||||
// *
|
||||
// * @param button 按钮
|
||||
// * @param isSelected 是否选中
|
||||
// */
|
||||
// private fun loadTabStyle(button: AppCompatButton, isSelected: Boolean) {
|
||||
// button.apply {
|
||||
// if (isSelected){
|
||||
// // 选中
|
||||
// setTextColor(Color.WHITE)
|
||||
// textSize = 28f
|
||||
// setTypeface(null, android.graphics.Typeface.BOLD)
|
||||
// background = ContextCompat.getDrawable(this@SettingActivity, R.drawable.bg_btn_underline)
|
||||
// } else {
|
||||
// // 未选中
|
||||
// setTextColor("#5E7585".toColorInt())
|
||||
// textSize = 26f
|
||||
// setTypeface(null, android.graphics.Typeface.NORMAL)
|
||||
// background = null
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 检查相机权限并显示 CollectFragment
|
||||
// */
|
||||
// @SuppressLint("ObsoleteSdkInt")
|
||||
// private fun checkCameraPermissionAndShowFragment() {
|
||||
// val collectFragment = fragmentList[2]
|
||||
// if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
|
||||
// // Android 6.0 以下,直接显示 Fragment
|
||||
// showFragment(collectFragment)
|
||||
// return
|
||||
// }
|
||||
// if (ContextCompat.checkSelfPermission(
|
||||
// this,
|
||||
// Manifest.permission.CAMERA
|
||||
// ) == PackageManager.PERMISSION_GRANTED
|
||||
// ) {
|
||||
// // 权限已授予,直接显示 Fragment
|
||||
// showFragment(collectFragment)
|
||||
// } else {
|
||||
// // 权限未授予,申请权限
|
||||
// requestPermission(Manifest.permission.CAMERA) { isGranted ->
|
||||
// if (isGranted) {
|
||||
// // 权限已授予,显示 CollectFragment
|
||||
// showFragment(collectFragment)
|
||||
// } else {
|
||||
// // 权限被拒绝
|
||||
// toast("暂无相机权限,无法使用菜品采集功能")
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 初始化相机
|
||||
// * @param container 相机预览容器
|
||||
// */
|
||||
// fun initCamera(container: ViewGroup) {
|
||||
// cameraUtils.initCamera()
|
||||
// val previewBinding =
|
||||
// LayoutCameraPreviewBinding.inflate(layoutInflater, container)
|
||||
// previewView = previewBinding.previewView.also {
|
||||
// it.updateLayoutParams {
|
||||
// width = 456.dp
|
||||
// height = 342.dp
|
||||
// }
|
||||
// }
|
||||
// cameraUtils.setPreviewController(previewView)
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * Activity 恢复时绑定相机
|
||||
// */
|
||||
// override fun onResume() {
|
||||
// super.onResume()
|
||||
// cameraUtils.bind()
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * Activity 暂停时解绑相机
|
||||
// */
|
||||
// override fun onPause() {
|
||||
// super.onPause()
|
||||
// cameraUtils.unbind()
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 提供给 Fragment 调用的拍照方法
|
||||
// */
|
||||
// fun takePhoto(succCallback: (Uri) -> Unit, failCallback: (msg: String) -> Unit = {}) {
|
||||
// cameraUtils.takePhoto(succCallback = succCallback, failCallback = failCallback)
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 显示设备切换Fragment
|
||||
// */
|
||||
// private fun showDeviceConfigFragment() {
|
||||
// showFragment(fragmentList[0])
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 显示设调料配置Fragment
|
||||
// */
|
||||
// private fun showSeasoningConfigFragment() {
|
||||
// showFragment(fragmentList[1])
|
||||
// }
|
||||
//
|
||||
// private val fragmentList = mutableListOf<Fragment>().apply {
|
||||
// add(DeviceConfigFragment())
|
||||
// add(SeasoningConfigFragment())
|
||||
// add(CollectFragment())
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 显示指定的 Fragment
|
||||
// * 使用 add/show/hide 方式管理 Fragment,避免重复创建
|
||||
// * 已添加的 Fragment 直接显示,未添加的 Fragment 先添加再显示
|
||||
// */
|
||||
// private fun showFragment(fragment: Fragment) {
|
||||
// runCatching {
|
||||
// supportFragmentManager.beginTransaction().apply {
|
||||
// // 如果 Fragment 还未添加到容器中,则添加
|
||||
// if (!fragment.isAdded) {
|
||||
// add(binding.fragmentContainer.id, fragment)
|
||||
// } else {
|
||||
// // 已添加过,直接显示
|
||||
// show(fragment)
|
||||
// }
|
||||
//
|
||||
// // 隐藏其他 Fragment
|
||||
// fragmentList.forEach { otherFragment ->
|
||||
// if (otherFragment != fragment && otherFragment.isAdded) {
|
||||
// hide(otherFragment)
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// commit()
|
||||
// }
|
||||
// }.onFailure {
|
||||
// it.printStackTrace()
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
@@ -5,9 +5,11 @@ import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import androidx.fragment.app.Fragment
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.ui.fragment.DbInspectFragment
|
||||
import com.shuwei.dish.match.ui.fragment.VectorCollectionFragment
|
||||
import com.shuwei.dish.match.ui.fragment.DeviceConfigFragment
|
||||
import com.shuwei.dish.match.ui.fragment.SeasoningConfigFragment
|
||||
import com.shuwei.dish.match.ui.fragment.WeightConfigFragment
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
|
||||
@@ -35,6 +37,12 @@ class SingleFragmentActivity : BaseActivity() {
|
||||
|
||||
/** 调料配置页 */
|
||||
SEASONING_CONFIG,
|
||||
|
||||
/** 数据库调试查看页 */
|
||||
DB_INSPECT,
|
||||
|
||||
/** 默认减重配置页 */
|
||||
WEIGHT_CONFIG,
|
||||
}
|
||||
|
||||
companion object {
|
||||
@@ -77,7 +85,7 @@ class SingleFragmentActivity : BaseActivity() {
|
||||
setTitleBar(
|
||||
titleBarAction = { it.visible() },
|
||||
titleAction = { it.text = getTitleForPage(pageType) },
|
||||
rightIconActon = { it.gone() }
|
||||
rightIconAction = { it.gone() }
|
||||
)
|
||||
|
||||
// 首次创建时加载 Fragment,避免屏幕旋转重复添加
|
||||
@@ -96,6 +104,8 @@ class SingleFragmentActivity : BaseActivity() {
|
||||
PageType.FOOD_COLLECT -> "食材采集"
|
||||
PageType.COOK_MODE -> "菜品模式"
|
||||
PageType.SEASONING_CONFIG -> "调料区设置"
|
||||
PageType.DB_INSPECT -> "数据库查看"
|
||||
PageType.WEIGHT_CONFIG -> "减重配置"
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -105,6 +115,8 @@ class SingleFragmentActivity : BaseActivity() {
|
||||
PageType.FOOD_COLLECT -> VectorCollectionFragment()
|
||||
PageType.COOK_MODE -> DeviceConfigFragment()
|
||||
PageType.SEASONING_CONFIG -> SeasoningConfigFragment()
|
||||
PageType.DB_INSPECT -> DbInspectFragment()
|
||||
PageType.WEIGHT_CONFIG -> WeightConfigFragment()
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
|
||||
@@ -18,16 +18,16 @@ import com.shuwei.dish.match.adapter.Seasoning18GridAdapter
|
||||
import com.shuwei.dish.match.adapter.Seasoning22GridAdapter
|
||||
import com.shuwei.dish.match.adapter.ScaleRowAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.base.GlobalData
|
||||
import com.shuwei.dish.match.databinding.ActivitySlaveBinding
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.entity.SeasoningSlotEntity
|
||||
import com.shuwei.dish.match.db.entity.SeasoningSlotEntity
|
||||
import com.shuwei.dish.match.scale.ScaleData
|
||||
import com.shuwei.dish.match.scale.ScaleDeviceConfig
|
||||
import com.shuwei.dish.match.scale.ScaleServiceManager
|
||||
import com.shuwei.dish.match.utils.NetworkUtil
|
||||
import com.shuwei.dish.match.utils.SizeTool
|
||||
import com.shuwei.dish.match.utils.SpTool
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -77,6 +77,7 @@ class SlaveActivity : BaseActivity() {
|
||||
listenLocalScales()
|
||||
listenMasterConnection()
|
||||
listenSeasoningConfig()
|
||||
listenClearData()
|
||||
addBackKeyListener()
|
||||
}
|
||||
|
||||
@@ -109,6 +110,8 @@ class SlaveActivity : BaseActivity() {
|
||||
it.onItemClick = { scale, _ -> showTareDialog(scale.address) }
|
||||
}
|
||||
binding.rvScaleList.adapter = scale22Adapter
|
||||
// 启动时用空哨兵预填全部格子,不依赖 WeightUtil 回调才显示结构
|
||||
scale22Adapter!!.updateByAddress(emptyList())
|
||||
}
|
||||
ScaleDeviceConfig.DEVICE_ID_18 -> {
|
||||
binding.rvScaleList.updateLayoutParams<LinearLayout.LayoutParams> { topMargin = 0 }
|
||||
@@ -121,15 +124,18 @@ class SlaveActivity : BaseActivity() {
|
||||
it.onItemClick = { scale, _ -> showTareDialog(scale.address) }
|
||||
}
|
||||
binding.rvScaleList.adapter = scale18Adapter
|
||||
// 启动时用空哨兵预填全部格子,不依赖 WeightUtil 回调才显示结构
|
||||
scale18Adapter!!.updateByAddress(emptyList())
|
||||
}
|
||||
else -> {
|
||||
binding.rvScaleList.updateLayoutParams<LinearLayout.LayoutParams> { topMargin = 20.dp }
|
||||
binding.rvScaleList.layoutManager = LinearLayoutManager(this)
|
||||
linearAdapter.setOnItemClickListener { _, _, position ->
|
||||
val item = linearAdapter.items.getOrNull(position) ?: return@setOnItemClickListener
|
||||
showTareDialog(item.address)
|
||||
}
|
||||
linearAdapter.onItemClick = { item -> showTareDialog(item.address) }
|
||||
binding.rvScaleList.adapter = linearAdapter
|
||||
// 启动时预填空占位,不依赖 WeightUtil 回调才显示列表结构
|
||||
ScaleDeviceConfig.SCALE_ORDER_1.forEach { addr ->
|
||||
linearAdapter.updateItem(ScaleRowAdapter.ScaleItem(addr, 0.0, WeightUtil.STATE_STABLE))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -156,7 +162,7 @@ class SlaveActivity : BaseActivity() {
|
||||
*/
|
||||
private fun loadSlotsFromDb() {
|
||||
lifecycleScope.launch {
|
||||
val slots = appViewModel.getSeasoningSlotsByDeviceId(GlobalData.deviceId)
|
||||
val slots = dbViewModel.getSeasoningSlotsByDeviceId(GlobalData.deviceId)
|
||||
applySlots(slots)
|
||||
}
|
||||
}
|
||||
@@ -173,13 +179,30 @@ class SlaveActivity : BaseActivity() {
|
||||
?: return@onSeasoningConfig
|
||||
lifecycleScope.launch {
|
||||
// 全量替换:先删除本机所有旧槽位,再写入最新配置
|
||||
appViewModel.deleteAllSlotsByDeviceId(GlobalData.deviceId)
|
||||
appViewModel.upsertAllSeasoningSlots(mySlots)
|
||||
dbViewModel.deleteAllSlotsByDeviceId(GlobalData.deviceId)
|
||||
dbViewModel.upsertAllSeasoningSlots(mySlots)
|
||||
applySlots(mySlots)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 监听主设备下发的清除数据事件
|
||||
* 收到后清空本机全部 4 张表数据并重置 SP 状态,与主设备保持一致
|
||||
* 清除完成后刷新 UI,清空所有秤的调料名称显示
|
||||
*/
|
||||
private fun listenClearData() {
|
||||
ScaleServiceManager.onClearData = {
|
||||
lifecycleScope.launch {
|
||||
dbViewModel.clearAllData {
|
||||
SpTool.cookMode = -1
|
||||
SpTool.canteenId = "0"
|
||||
runOnUiThread { applySlots(emptyList()) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将槽位配置应用到对应 adapter(按地址匹配格子位置)
|
||||
* 同时以传入列表为准全量刷新 slotNameMap:
|
||||
@@ -203,12 +226,8 @@ class SlaveActivity : BaseActivity() {
|
||||
if (pos >= 0) scale18Adapter!!.updateItemName(pos, "")
|
||||
}
|
||||
else -> {
|
||||
val list = linearAdapter.items.toMutableList()
|
||||
val idx = list.indexOfFirst { it.address == addr }
|
||||
if (idx >= 0) {
|
||||
list[idx] = list[idx].copy(name = "")
|
||||
linearAdapter.submitList(list)
|
||||
}
|
||||
val idx = linearAdapter.items.indexOfFirst { it.address == addr }
|
||||
if (idx >= 0) linearAdapter.removeByAddress(addr)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -225,14 +244,7 @@ class SlaveActivity : BaseActivity() {
|
||||
val pos = ScaleDeviceConfig.SCALE_ORDER_18.indexOf(slot.address)
|
||||
if (pos >= 0) scale18Adapter!!.updateItemName(pos, slot.goodsName)
|
||||
}
|
||||
else -> {
|
||||
val list = linearAdapter.items.toMutableList()
|
||||
val idx = list.indexOfFirst { it.address == slot.address }
|
||||
if (idx >= 0) {
|
||||
list[idx] = list[idx].copy(name = slot.goodsName)
|
||||
linearAdapter.submitList(list)
|
||||
}
|
||||
}
|
||||
else -> linearAdapter.updateName(slot.address, slot.goodsName)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -272,15 +284,7 @@ class SlaveActivity : BaseActivity() {
|
||||
}
|
||||
else -> {
|
||||
val item = ScaleRowAdapter.ScaleItem(address, weight, state, slotNameMap[address] ?: "")
|
||||
val list = linearAdapter.items.toMutableList()
|
||||
val idx = list.indexOfFirst { it.address == address }
|
||||
if (idx >= 0) {
|
||||
list[idx] = item
|
||||
} else {
|
||||
list.add(item)
|
||||
list.sortBy { it.address }
|
||||
}
|
||||
linearAdapter.submitList(list)
|
||||
linearAdapter.updateItem(item)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,31 +12,38 @@ import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.recyclerview.widget.GridLayoutManager
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.SeasoningWeightAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.databinding.ActivitySubmitFoodBinding
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.entity.FoodRecord
|
||||
import com.shuwei.dish.match.dialog.GoodsPreviewDialog
|
||||
import com.shuwei.dish.match.db.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.model.ConstituteSaveItem
|
||||
import com.shuwei.dish.match.model.ConstituteSaveRequest
|
||||
import com.shuwei.dish.match.model.CookCompleteItem
|
||||
import com.shuwei.dish.match.model.CookCompleteRequest
|
||||
import com.shuwei.dish.match.model.FoodRecord
|
||||
import com.shuwei.dish.match.model.toDTO
|
||||
import com.shuwei.dish.match.net.UiState
|
||||
import com.shuwei.dish.match.scale.ScaleDeviceConfig
|
||||
import com.shuwei.dish.match.scale.ScaleServiceManager
|
||||
import com.shuwei.dish.match.utils.AddressUtil
|
||||
import com.shuwei.dish.match.utils.DateTimeUtil
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
import com.shuwei.dish.match.utils.ext.appendText
|
||||
import com.shuwei.dish.match.utils.ext.buildSpannableString
|
||||
import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.roundedDecimalPlace
|
||||
import com.shuwei.dish.match.utils.ext.roundedOneDecimalPlace
|
||||
import com.shuwei.dish.match.utils.ext.startActivity
|
||||
import com.shuwei.dish.match.utils.ext.toJsonString
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
import kotlinx.coroutines.flow.collectLatest
|
||||
import kotlinx.coroutines.launch
|
||||
import java.time.LocalDateTime
|
||||
|
||||
@SuppressLint("UseSparseArrays")
|
||||
class SubmitFoodActivity : BaseActivity() {
|
||||
@@ -45,6 +52,12 @@ class SubmitFoodActivity : BaseActivity() {
|
||||
const val TAG = "SubmitFoodActivity"
|
||||
const val FOOD_ITEM = "foodItem"
|
||||
const val GOODS_LIST = "goodsList"
|
||||
const val COOK_ORDER_ID = "cookOrderId"
|
||||
|
||||
/** 本地临时 foodId 前缀;以此开头说明菜品尚未在服务器登记,提交时需清空让服务器分配真实 ID */
|
||||
const val LOCAL_ID_PREFIX = "localId_"
|
||||
|
||||
const val WEIGHT_THRESHOLD = 0.01
|
||||
}
|
||||
|
||||
private lateinit var binding: ActivitySubmitFoodBinding
|
||||
@@ -52,6 +65,9 @@ class SubmitFoodActivity : BaseActivity() {
|
||||
private var food: FoodRecord? = null
|
||||
private var goodsList: MutableList<CookFoodGoodsEntity>? = null
|
||||
|
||||
/** 烹制单 ID,制作模式从 PrepareFoodActivity 传入,用于新配比秤烹饪完成接口 */
|
||||
private var cookOrderId: String? = null
|
||||
|
||||
private val cookFoodEntity by lazy {
|
||||
CookFoodEntity().apply {
|
||||
food?.let {
|
||||
@@ -91,15 +107,38 @@ class SubmitFoodActivity : BaseActivity() {
|
||||
*/
|
||||
private val baseSeasoningMap = mutableMapOf<String, Pair<String, Double>>()
|
||||
|
||||
/**
|
||||
* 各秤上一次处理过的 ts,用于跳过 StateFlow 因其他秤变化而重发的相同帧
|
||||
*/
|
||||
private val lastTsMap = mutableMapOf<String, Long>()
|
||||
|
||||
/** 主设备 2格秤的初始重量,首次收到数据时赋值;调用清零后重置为 0.0 */
|
||||
private var initWeight: Double = 0.0
|
||||
|
||||
/** 烹饪开始时间(进入本页面的时刻),提交烹饪完成接口时上报 */
|
||||
private var cookStartTime: String = ""
|
||||
|
||||
/**
|
||||
* 调料首次使用时间,key = goodsName,value = 首次拿取时间 yyyy-MM-dd HH:mm:ss
|
||||
* 秤首次检测到拿取(用量超阈值)时记录,提交时按 goodsName 匹配填入 putTime
|
||||
*/
|
||||
private val seasoningFirstUseMap = mutableMapOf<String, String>()
|
||||
|
||||
/** initWeight 是否已完成初始化 */
|
||||
// private var initWeightSet: Boolean = false
|
||||
|
||||
@Suppress("unchecked_cast", "DEPRECATION")
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
binding = ActivitySubmitFoodBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
// 以进入本页面的时刻作为烹饪开始时间
|
||||
cookStartTime = DateTimeUtil.formatDateTime(LocalDateTime.now())
|
||||
setHeaderBackground()
|
||||
intent.extras?.apply {
|
||||
food = getSerializable(FOOD_ITEM) as FoodRecord?
|
||||
Log.d(TAG, "onCreate: cookMode=${food?.cookMode}")
|
||||
cookOrderId = getString(COOK_ORDER_ID)
|
||||
Log.d(TAG, "onCreate: cookMode=${food?.cookMode}, cookOrderId=$cookOrderId")
|
||||
// isCooking=false:从前一页面带入主辅材数据;isCooking=true:从数据库查询
|
||||
if (food?.isCooking == false) {
|
||||
goodsList = getSerializable(GOODS_LIST) as MutableList<CookFoodGoodsEntity>?
|
||||
@@ -110,8 +149,15 @@ class SubmitFoodActivity : BaseActivity() {
|
||||
it.visible()
|
||||
}, titleAction = {
|
||||
it.text = food?.foodName
|
||||
}, rightIconActon = {
|
||||
it.gone()
|
||||
}, rightIconAction = {
|
||||
it.visible()
|
||||
it.setImageResource(R.drawable.ic_list_view)
|
||||
it.setOnClickListener {
|
||||
lifecycleScope.launch {
|
||||
val list = buildPreviewGoodsList()
|
||||
GoodsPreviewDialog(this@SubmitFoodActivity, list).show()
|
||||
}
|
||||
}
|
||||
}, backAction = {
|
||||
it.setOnClickListener {
|
||||
remindSaveDataDialog()
|
||||
@@ -147,7 +193,7 @@ class SubmitFoodActivity : BaseActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
/** 初始化 RecyclerView,24列 GridLayoutManager */
|
||||
/** 初始化 RecyclerView,默认 4 列 GridLayoutManager */
|
||||
private fun setupRecyclerView() {
|
||||
binding.rvSeasoning.let {
|
||||
it.itemAnimator = null
|
||||
@@ -158,11 +204,12 @@ class SubmitFoodActivity : BaseActivity() {
|
||||
|
||||
/**
|
||||
* 从 Room 加载槽位配置后,开始订阅子设备秤数据
|
||||
* isCooking=true 时先从数据库查询 goodsList,筛选调料预填充 adapter,再开始观测
|
||||
* isCooking=true 时从数据库查询 goodsList 并预填充调料 adapter;
|
||||
* isCooking=false 时从前一页面带入的 goodsList 中预填充调料 adapter,再开始观测
|
||||
*/
|
||||
private fun loadSlotsThenObserveScales() {
|
||||
lifecycleScope.launch {
|
||||
val slots = appViewModel.loadSeasoningSlot()
|
||||
val slots = dbViewModel.loadSeasoningSlot()
|
||||
slots.forEach { slot ->
|
||||
slotMap["${slot.deviceId}#${slot.address}"] = slot.goodsId to slot.goodsName
|
||||
}
|
||||
@@ -170,24 +217,34 @@ class SubmitFoodActivity : BaseActivity() {
|
||||
// 制作中:从数据库查询 goodsList,筛选调料数据预填充 adapter
|
||||
val foodId = food?.foodId ?: return@launch
|
||||
val cookMode = food?.cookMode ?: return@launch
|
||||
val list = appViewModel.getCookFoodGoodsList(foodId, cookMode)
|
||||
val list =
|
||||
dbViewModel.getCookFoodGoodsList(foodId, cookMode, food?.dinnerType ?: "0")
|
||||
goodsList = list
|
||||
list.filter { it.materialType == 3 }.forEach { item ->
|
||||
val name = item.goodsName ?: ""
|
||||
val weight = item.useWeight ?: 0.0
|
||||
baseSeasoningMap[name] = (item.goodsId) to weight
|
||||
seasoningAdapter.updateItem(
|
||||
SeasoningWeightAdapter.Item(
|
||||
goodsId = item.goodsId,
|
||||
goodsName = name,
|
||||
useWeight = weight
|
||||
)
|
||||
)
|
||||
}
|
||||
observeScaleData()
|
||||
prefillSeasoningFromGoodsList(list)
|
||||
} else {
|
||||
observeScaleData()
|
||||
// 非制作中:从前一页面带入的 goodsList 中筛选调料数据预填充 adapter
|
||||
goodsList?.let { prefillSeasoningFromGoodsList(it) }
|
||||
}
|
||||
observeScaleData()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 goodsList 中筛选 materialType==3 的调料数据,
|
||||
* 写入 baseSeasoningMap 作为历史用量基准,并预填充到 adapter
|
||||
*/
|
||||
private fun prefillSeasoningFromGoodsList(list: List<CookFoodGoodsEntity>) {
|
||||
list.filter { it.materialType == 3 }.forEach { item ->
|
||||
val name = item.goodsName ?: ""
|
||||
val weight = item.useWeight ?: 0.0
|
||||
baseSeasoningMap[name] = item.goodsId to weight
|
||||
seasoningAdapter.updateItem(
|
||||
SeasoningWeightAdapter.Item(
|
||||
goodsId = item.goodsId,
|
||||
goodsName = name,
|
||||
useWeight = weight
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,14 +255,21 @@ class SubmitFoodActivity : BaseActivity() {
|
||||
private fun observeScaleData() {
|
||||
val flow = ScaleServiceManager.allScales ?: return
|
||||
lifecycleScope.launch {
|
||||
flow.collectLatest { scaleMap ->
|
||||
flow.collect { scaleMap ->
|
||||
//Log.d(TAG, "observeScaleData,scaleMap=${scaleMap.toJsonString()}")
|
||||
scaleMap.forEach { (key, data) ->
|
||||
// ts 未变化说明是其他秤更新触发的 StateFlow 重发,跳过
|
||||
if (lastTsMap[key] == data.ts) return@forEach
|
||||
lastTsMap[key] = data.ts
|
||||
// 排除主设备 2格秤
|
||||
if (data.deviceId == ScaleDeviceConfig.DEVICE_ID_2) return@forEach
|
||||
|
||||
// 从槽位配置读取调料名,未配置则跳过
|
||||
val (goodsId, goodsName) = slotMap[key] ?: return@forEach
|
||||
|
||||
Log.d(
|
||||
TAG,
|
||||
"observeScaleData,1key=$key, goodsId=$goodsId, goodsName=$goodsName, data=$data"
|
||||
)
|
||||
// 首次收到稳定数据时记录基准重量
|
||||
val baseline = baselineMap[key]
|
||||
if (baseline == null) {
|
||||
@@ -214,19 +278,33 @@ class SubmitFoodActivity : BaseActivity() {
|
||||
}
|
||||
return@forEach
|
||||
}
|
||||
|
||||
Log.d(TAG, "observeScaleData,2key=$key, baseline=$baseline, data.weight=${data.weight}")
|
||||
// 用量 = 初始重量 - 当前重量,负值归零
|
||||
val useWeight = (baseline - data.weight)
|
||||
.coerceAtLeast(0.0)
|
||||
.roundedOneDecimalPlace()
|
||||
|
||||
// 更新原始用量 map,再按 goodsName 聚合刷新 adapter
|
||||
if (useWeight < 0.5) {
|
||||
rawWeightMap.remove(key)
|
||||
if (useWeight < WEIGHT_THRESHOLD) {
|
||||
// 放回场景:必须稳定后才移除,避免拿取过程中误删
|
||||
if (data.state != WeightUtil.STATE_STABLE) return@forEach
|
||||
if (rawWeightMap.remove(key) != null) {
|
||||
Log.d(TAG, "observeScaleData,移除key=${key}, goodsName=$goodsName")
|
||||
refreshAdapterByName(goodsName)
|
||||
}
|
||||
} else {
|
||||
rawWeightMap[key] = Triple(goodsId, goodsName, useWeight)
|
||||
// 拿取场景:实时响应,无需等待稳定
|
||||
val newTriple = Triple(goodsId, goodsName, useWeight)
|
||||
if (rawWeightMap[key] != newTriple) {
|
||||
// 该调料首次检测到拿取时,记录首次使用时间(同名调料只记最早一次)
|
||||
if (!seasoningFirstUseMap.containsKey(goodsName)) {
|
||||
seasoningFirstUseMap[goodsName] =
|
||||
DateTimeUtil.formatDateTime(LocalDateTime.now())
|
||||
}
|
||||
Log.d(TAG, "observeScaleData,新增:$newTriple")
|
||||
rawWeightMap[key] = newTriple
|
||||
refreshAdapterByName(goodsName)
|
||||
}
|
||||
}
|
||||
refreshAdapterByName(goodsName)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -235,39 +313,63 @@ class SubmitFoodActivity : BaseActivity() {
|
||||
/**
|
||||
* 按 goodsName 聚合 rawWeightMap,叠加历史用量后推给 adapter
|
||||
* isCooking=true 时只新增,不移除(历史调料数据不可减少)
|
||||
* 移除前检查 item 是否存在,更新前比较数据是否变化,避免无效操作
|
||||
*/
|
||||
private fun refreshAdapterByName(goodsName: String) {
|
||||
val grouped = rawWeightMap.values.filter { it.second == goodsName }
|
||||
val newWeight = grouped.sumOf { it.third }.roundedOneDecimalPlace()
|
||||
val (baseGoodsId, baseWeight) = baseSeasoningMap[goodsName] ?: ("" to 0.0)
|
||||
val totalWeight = (newWeight + baseWeight).roundedOneDecimalPlace()
|
||||
if (totalWeight < 0.5) {
|
||||
// 制作中模式:已有历史数据,不允许移除
|
||||
if (food?.isCooking != true) {
|
||||
seasoningAdapter.removeItem(goodsName)
|
||||
Log.d(TAG, "refreshAdapterByName, goodsName=$goodsName, newWeight=$newWeight, baseWeight=$baseWeight, totalWeight=$totalWeight, isCooking=${food?.isCooking}")
|
||||
if (totalWeight < WEIGHT_THRESHOLD) {
|
||||
Log.d(TAG, "refreshAdapterByName,重量小于${WEIGHT_THRESHOLD}g, isCooking=${food?.isCooking}, goodsName=$goodsName, totalWeight=$totalWeight")
|
||||
// 仅保护 baseSeasoningMap 中的历史调料;本次会话新加的调料可以移除
|
||||
if (!baseSeasoningMap.containsKey(goodsName)) {
|
||||
// 只有 item 确实存在时才调用 remove,避免无效遍历
|
||||
if (seasoningAdapter.items.any { it.goodsName == goodsName }) {
|
||||
seasoningAdapter.removeItem(goodsName)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
val goodsId = grouped.firstOrNull()?.first?.takeIf { it.isNotEmpty() } ?: baseGoodsId
|
||||
seasoningAdapter.updateItem(
|
||||
SeasoningWeightAdapter.Item(
|
||||
goodsId = goodsId,
|
||||
goodsName = goodsName,
|
||||
useWeight = totalWeight
|
||||
)
|
||||
// 数据未变化时跳过,避免触发不必要的 RecyclerView 刷新
|
||||
if (seasoningAdapter.items.any { it.goodsName == goodsName && it.useWeight == totalWeight && it.goodsId == goodsId }) return
|
||||
val item = SeasoningWeightAdapter.Item(
|
||||
goodsId = goodsId,
|
||||
goodsName = goodsName,
|
||||
useWeight = totalWeight
|
||||
)
|
||||
Log.d(TAG, "refreshAdapterByName,更新数据item=${item.toJsonString()}")
|
||||
seasoningAdapter.updateItem(item)
|
||||
}
|
||||
|
||||
private fun addViewListener() {
|
||||
// 切换调料列表布局:4 列卡片 ↔ 2 列水平,图标始终显示"目标布局"样式
|
||||
binding.ivSeasoningLayoutToggle.clickWithDebounce {
|
||||
seasoningAdapter.isListMode = !seasoningAdapter.isListMode
|
||||
val spanCount = if (seasoningAdapter.isListMode) 2 else 4
|
||||
(binding.rvSeasoning.layoutManager as? GridLayoutManager)?.spanCount = spanCount
|
||||
seasoningAdapter.notifyDataSetChanged()
|
||||
binding.ivSeasoningLayoutToggle.setImageResource(
|
||||
if (seasoningAdapter.isListMode) R.drawable.ic_layout_grid else R.drawable.ic_layout_list
|
||||
)
|
||||
}
|
||||
binding.btnCook.clickWithDebounce {
|
||||
val content = getRemindSpannable("开始制作")
|
||||
showRemindDialog(content) { cook() }
|
||||
}
|
||||
binding.btnWeightClear.clickWithDebounce { WeightUtil.tareTwo(2) }
|
||||
binding.btnWeightClear.clickWithDebounce {
|
||||
WeightUtil.tareTwo(2)
|
||||
// 清零后将初始重量重置为 0,后续以秤读数直接作为净重
|
||||
initWeight = 0.0
|
||||
}
|
||||
binding.btnSubmit.clickWithDebounce {
|
||||
if (cookFoodEntity.foodWeight <= 0.toDouble()) {
|
||||
toast("未识别到菜品熟重")
|
||||
return@clickWithDebounce
|
||||
// 测试设备无秤硬件,使用模拟熟重 500g
|
||||
cookFoodEntity.foodWeight = 500.0
|
||||
binding.tvTotalWeight.text = "500.0"
|
||||
binding.tvWeightUnit.text = "克"
|
||||
}
|
||||
val content = getRemindSpannable("制作完成")
|
||||
showRemindDialog(content) { submit() }
|
||||
@@ -276,12 +378,19 @@ class SubmitFoodActivity : BaseActivity() {
|
||||
// 监听主设备 2格秤的熟重
|
||||
WeightUtil.addWeightListener(TAG) { address, _, weight ->
|
||||
if (address == AddressUtil.TWO) {
|
||||
cookFoodEntity.foodWeight = weight
|
||||
if (weight > 1000) {
|
||||
binding.tvTotalWeight.text = "${(weight / 1000f).roundedDecimalPlace(3)}"
|
||||
// 首次收到数据时记录初始重量
|
||||
// if (!initWeightSet) {
|
||||
// initWeight = weight
|
||||
// initWeightSet = true
|
||||
// }
|
||||
// 实际净重 = 秤读数 - 初始重量
|
||||
val netWeight = weight - initWeight
|
||||
cookFoodEntity.foodWeight = netWeight
|
||||
if (netWeight > 1000) {
|
||||
binding.tvTotalWeight.text = "${(netWeight / 1000f).roundedDecimalPlace(3)}"
|
||||
binding.tvWeightUnit.text = "千克"
|
||||
} else {
|
||||
binding.tvTotalWeight.text = "$weight"
|
||||
binding.tvTotalWeight.text = "$netWeight"
|
||||
binding.tvWeightUnit.text = "克"
|
||||
}
|
||||
}
|
||||
@@ -293,43 +402,32 @@ class SubmitFoodActivity : BaseActivity() {
|
||||
toast("未获取到菜品或构成信息")
|
||||
return
|
||||
}
|
||||
val seasoningData = seasoningAdapter.items
|
||||
// if (seasoningData.isEmpty()) {
|
||||
// toast("未获取到调料信息")
|
||||
// return
|
||||
// }
|
||||
showLoading()
|
||||
|
||||
// 将调料数据转为 CookFoodGoodsEntity 追加到 goodsList
|
||||
// val typeToken = object : TypeToken<List<CookFoodGoodsEntity>>() {}
|
||||
val tempSeasoningList = seasoningData.map { item ->
|
||||
CookFoodGoodsEntity().also { entity ->
|
||||
entity.goodsId = item.goodsId
|
||||
entity.goodsName = item.goodsName
|
||||
entity.useWeight = item.useWeight
|
||||
entity.materialType = 3
|
||||
}
|
||||
}
|
||||
goodsList?.addAll(tempSeasoningList)
|
||||
|
||||
cookFoodEntity.let {
|
||||
it.dinnerType = when (it.dinnerType) {
|
||||
"早餐" -> "1"
|
||||
"午餐" -> "2"
|
||||
"晚餐" -> "3"
|
||||
else -> it.dinnerType
|
||||
}
|
||||
}
|
||||
|
||||
val isSamplingData = food!!.cookMode == 1
|
||||
if (isSamplingData) {
|
||||
val tempFoodId = cookFoodEntity.foodId.ifBlank { "${System.currentTimeMillis()}" }
|
||||
val tempFoodId = cookFoodEntity.foodId
|
||||
.ifBlank { "$LOCAL_ID_PREFIX${System.currentTimeMillis()}" }
|
||||
cookFoodEntity.foodId = tempFoodId
|
||||
}
|
||||
// 主辅材统一在此赋 foodId;新加的调料行 foodId 由 buildSeasoningEntity 内部设置
|
||||
goodsList?.forEach { it.foodId = cookFoodEntity.foodId }
|
||||
|
||||
lifecycleScope.launch {
|
||||
appViewModel.saveCookFoodAndGoods(
|
||||
cookFoodEntity.let {
|
||||
it.dinnerType = when (it.dinnerType) {
|
||||
"早餐" -> "1"
|
||||
"午餐" -> "2"
|
||||
"晚餐" -> "3"
|
||||
else -> it.dinnerType
|
||||
}
|
||||
}
|
||||
// 先移除 goodsList 中已有的调料数据(materialType==3),再以 adapter 中最新调料覆盖
|
||||
goodsList?.removeAll { it.materialType == 3 }
|
||||
seasoningAdapter.items
|
||||
.filter { it.useWeight > 0.0 }
|
||||
.forEach { goodsList?.add(buildSeasoningEntity(it)) }
|
||||
dbViewModel.saveCookFoodAndGoods(
|
||||
cookMode = food!!.cookMode,
|
||||
entity = cookFoodEntity,
|
||||
list = goodsList
|
||||
@@ -344,39 +442,195 @@ class SubmitFoodActivity : BaseActivity() {
|
||||
toast("未获取到菜品或构成信息")
|
||||
return
|
||||
}
|
||||
val seasoningData = seasoningAdapter.items
|
||||
showLoading()
|
||||
|
||||
// 将重量大于0且不重复的调料追加到 goodsList
|
||||
seasoningData.forEach { item ->
|
||||
if (item.useWeight > 0.0 && goodsList?.none { it.goodsId == item.goodsId } == true) {
|
||||
goodsList?.add(CookFoodGoodsEntity().also { entity ->
|
||||
entity.goodsId = item.goodsId
|
||||
entity.goodsName = item.goodsName
|
||||
entity.useWeight = item.useWeight
|
||||
entity.materialType = 3
|
||||
})
|
||||
lifecycleScope.launch {
|
||||
// 先移除 goodsList 中已有的调料数据(materialType==3),再以 adapter 中最新调料覆盖
|
||||
goodsList?.removeAll { it.materialType == 3 }
|
||||
goodsList?.forEach { it.foodId = cookFoodEntity.foodId }
|
||||
seasoningAdapter.items
|
||||
.filter { it.useWeight > 0.0 }
|
||||
.forEach { goodsList?.add(buildSeasoningEntity(it)) }
|
||||
|
||||
// 制作模式 + 有烹制单 ID → 调新配比秤烹饪完成接口
|
||||
if (!cookOrderId.isNullOrBlank() && food?.cookMode == 0) {
|
||||
submitWithNewApi()
|
||||
return@launch
|
||||
}
|
||||
}
|
||||
|
||||
cookFoodEntity.let {
|
||||
it.matchingConstituteInfoList = this@SubmitFoodActivity.goodsList
|
||||
it.dinnerType = when (it.dinnerType) {
|
||||
"1" -> "早餐"
|
||||
"2" -> "午餐"
|
||||
"3" -> "晚餐"
|
||||
else -> null
|
||||
// 采样模式 → 调新配比秤提交采样接口(落库味养创新实验,状态=实验中)
|
||||
if (food?.cookMode == 1) {
|
||||
submitConstitute()
|
||||
return@launch
|
||||
}
|
||||
|
||||
// 旧接口路径(无烹制单 ID 的制作模式兜底)
|
||||
cookFoodEntity.let {
|
||||
it.matchingConstituteInfoList = this@SubmitFoodActivity.goodsList
|
||||
it.dinnerType = when (it.dinnerType) {
|
||||
"1" -> "早餐"
|
||||
"2" -> "午餐"
|
||||
"3" -> "晚餐"
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
if (cookFoodEntity.foodId.startsWith(LOCAL_ID_PREFIX)) {
|
||||
cookFoodEntity.foodId = ""
|
||||
goodsList?.forEach { it.foodId = "" }
|
||||
}
|
||||
|
||||
Log.d(TAG, "submit: json=${cookFoodEntity.toJsonString()}")
|
||||
netViewModel.submitCookFood(entity = cookFoodEntity.toDTO())
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 新配比秤烹饪完成接口:从 goodsList 提取主辅材和调料,组装 CookCompleteRequest 提交
|
||||
* 熟重 foodWeight(g) → cookedWeight(kg)
|
||||
*/
|
||||
private fun submitWithNewApi() {
|
||||
val allGoods = goodsList ?: return
|
||||
|
||||
// 主辅材:materialType 1(主材) 或 2(辅材)
|
||||
val items = allGoods
|
||||
.filter { it.materialType == 1 || it.materialType == 2 }
|
||||
.map { CookCompleteItem(
|
||||
materId = it.materId?.takeIf { mid -> mid.isNotEmpty() } ?: it.goodsId,
|
||||
actualQty = it.useWeight ?: 0.0
|
||||
) }
|
||||
|
||||
if (items.isEmpty()) {
|
||||
toast("无主辅材构成信息")
|
||||
dismissLoading()
|
||||
return
|
||||
}
|
||||
|
||||
val isSamplingData = food!!.cookMode == 1
|
||||
if (isSamplingData) {
|
||||
cookFoodEntity.foodId = ""
|
||||
goodsList?.forEach { it.foodId = "" }
|
||||
// 调料:materialType 3,按 goodsName 匹配首次使用时间填入 putTime
|
||||
val seasonings = allGoods
|
||||
.filter { it.materialType == 3 }
|
||||
.map { CookCompleteItem(
|
||||
materId = it.materId?.takeIf { mid -> mid.isNotEmpty() } ?: it.goodsId,
|
||||
actualQty = it.useWeight ?: 0.0,
|
||||
putTime = it.goodsName?.let { name -> seasoningFirstUseMap[name] }
|
||||
) }
|
||||
.takeIf { it.isNotEmpty() }
|
||||
|
||||
// 熟重 g → kg,保留 3 位小数
|
||||
val cookedWeightKg = (cookFoodEntity.foodWeight / 1000.0).roundedDecimalPlace(3)
|
||||
|
||||
val request = CookCompleteRequest(
|
||||
cookOrderId = cookOrderId ?: "",
|
||||
cookStart = cookStartTime,
|
||||
items = items,
|
||||
cookedWeight = cookedWeightKg,
|
||||
seasonings = seasonings
|
||||
)
|
||||
|
||||
Log.d(TAG, "submitWithNewApi: ${request.toJsonString()}")
|
||||
|
||||
val isSamplingData = food?.cookMode == 1
|
||||
netViewModel.cookOrderComplete(
|
||||
request = request,
|
||||
onResult = { state ->
|
||||
when (state) {
|
||||
is UiState.Success -> submitSuccess(isSamplingData)
|
||||
is UiState.Error -> {
|
||||
toast(state.msg)
|
||||
dismissLoading()
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交采样:从 goodsList 提取全部构成(主材/辅材/调料),组装 ConstituteSaveRequest 提交
|
||||
* 落库味养创新实验;熟重 foodWeight 单位为 g,isMain 直接取 materialType(1主/2辅/3调)
|
||||
*/
|
||||
private fun submitConstitute() {
|
||||
val allGoods = goodsList ?: run {
|
||||
toast("未获取到菜品或构成信息")
|
||||
dismissLoading()
|
||||
return
|
||||
}
|
||||
val foodName = cookFoodEntity.foodName ?: food?.foodName ?: ""
|
||||
if (foodName.isBlank()) {
|
||||
toast("菜品名称为空")
|
||||
dismissLoading()
|
||||
return
|
||||
}
|
||||
|
||||
Log.d(TAG, "submit: json=${cookFoodEntity.toJsonString()}")
|
||||
netViewModel.submitCookFood(entity = cookFoodEntity)
|
||||
// 仅保留用量 > 0 的食材;materId 优先取 materId,为空时回退 goodsId
|
||||
val items = allGoods
|
||||
.filter { (it.useWeight ?: 0.0) > 0.0 }
|
||||
.map {
|
||||
ConstituteSaveItem(
|
||||
materId = it.materId?.takeIf { mid -> mid.isNotEmpty() } ?: it.goodsId,
|
||||
useWeight = it.useWeight ?: 0.0,
|
||||
isMain = it.materialType
|
||||
)
|
||||
}
|
||||
if (items.isEmpty()) {
|
||||
toast("请完善菜品构成信息")
|
||||
dismissLoading()
|
||||
return
|
||||
}
|
||||
if (items.any { it.materId.isBlank() }) {
|
||||
toast("菜品食材不能为空")
|
||||
dismissLoading()
|
||||
return
|
||||
}
|
||||
val foodWeight = cookFoodEntity.foodWeight
|
||||
if (foodWeight <= 0.0) {
|
||||
toast("熟重必须大于0")
|
||||
dismissLoading()
|
||||
return
|
||||
}
|
||||
|
||||
val request = ConstituteSaveRequest(
|
||||
foodName = foodName,
|
||||
foodWeight = foodWeight,
|
||||
items = items
|
||||
)
|
||||
Log.d(TAG, "submitConstitute: ${request.toJsonString()}")
|
||||
|
||||
netViewModel.constituteSave(
|
||||
request = request,
|
||||
onResult = { state ->
|
||||
when (state) {
|
||||
is UiState.Success -> submitSuccess(isSamplingData = true)
|
||||
is UiState.Error -> {
|
||||
toast(state.msg)
|
||||
dismissLoading()
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 adapter 中的调料 item 转换为 CookFoodGoodsEntity
|
||||
* 从本地 dm_seasoning 表补充完整字段(popularName、zjmCode、materId、goodsCode 等)
|
||||
*/
|
||||
private suspend fun buildSeasoningEntity(item: SeasoningWeightAdapter.Item): CookFoodGoodsEntity {
|
||||
val seasoning = dbViewModel.getSeasoningByGoodsId(item.goodsId)
|
||||
return CookFoodGoodsEntity().also { entity ->
|
||||
entity.foodId = cookFoodEntity.foodId
|
||||
entity.goodsId = item.goodsId
|
||||
entity.goodsName = item.goodsName
|
||||
entity.useWeight = item.useWeight
|
||||
entity.materialType = 3
|
||||
entity.popularName = seasoning?.popularName
|
||||
entity.zjmCode = seasoning?.zjmCode
|
||||
entity.materId = seasoning?.materId
|
||||
entity.goodsCode = seasoning?.goodsCode
|
||||
entity.relateionType = seasoning?.relateionType ?: 0
|
||||
entity.allEdible = seasoning?.allEdible ?: true
|
||||
entity.goodsOrRelationCode = seasoning?.goodsOrRelationCode
|
||||
}
|
||||
}
|
||||
|
||||
private fun submitSuccess(isSamplingData: Boolean) {
|
||||
@@ -385,14 +639,15 @@ class SubmitFoodActivity : BaseActivity() {
|
||||
jumpPage(isSamplingData, false)
|
||||
return
|
||||
}
|
||||
lifecycleScope.launch {
|
||||
appViewModel.deleteCookFoodAndGoods(
|
||||
cookMode = food!!.cookMode,
|
||||
foodId = food!!.foodId!!
|
||||
)
|
||||
dismissLoading()
|
||||
jumpPage(isSamplingData, false)
|
||||
}
|
||||
// 用 viewModelScope 执行删除,不受当前 Activity 生命周期影响
|
||||
// singleTask 跳转会销毁本 Activity 并取消 lifecycleScope,导致删除被中断
|
||||
dbViewModel.markSubmittedAndDeleteAsync(
|
||||
cookMode = food!!.cookMode,
|
||||
foodId = food!!.foodId!!,
|
||||
dinnerType = food!!.dinnerType
|
||||
)
|
||||
dismissLoading()
|
||||
jumpPage(isSamplingData, false)
|
||||
}
|
||||
|
||||
private fun jumpPage(isSampling: Boolean, isCooking: Boolean) {
|
||||
@@ -409,6 +664,19 @@ class SubmitFoodActivity : BaseActivity() {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 构建用于预览弹窗的 goodsList:
|
||||
* 取 goodsList 中的主辅材,再用 adapter 中最新调料覆盖原有调料数据(materialType==3)
|
||||
* 调料的完整字段(含 goodsCode)通过 buildSeasoningEntity 从 DB 补全
|
||||
*/
|
||||
private suspend fun buildPreviewGoodsList(): List<CookFoodGoodsEntity> {
|
||||
val base = goodsList?.filter { it.materialType != 3 }?.toMutableList() ?: mutableListOf()
|
||||
seasoningAdapter.items
|
||||
.filter { it.useWeight > 0.0 }
|
||||
.forEach { base.add(buildSeasoningEntity(it)) }
|
||||
return base
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
WeightUtil.removeWeightListener(TAG)
|
||||
super.onDestroy()
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
package com.shuwei.dish.match.ui.fragment
|
||||
|
||||
import android.graphics.Color
|
||||
import android.graphics.Typeface
|
||||
import android.text.InputType
|
||||
import android.view.Gravity
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.EditText
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.RadioButton
|
||||
import android.widget.TextView
|
||||
import androidx.cardview.widget.CardView
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.recyclerview.widget.GridLayoutManager
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.base.BaseFragment
|
||||
import com.shuwei.dish.match.databinding.FragmentDbInspectBinding
|
||||
import com.shuwei.dish.match.db.DbViewModel
|
||||
import com.shuwei.dish.match.ui.SingleFragmentActivity
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
import kotlinx.coroutines.launch
|
||||
import androidx.core.graphics.toColorInt
|
||||
|
||||
/**
|
||||
* 数据库调试查看页面
|
||||
* 支持按表切换、isDel 过滤开关、多字段筛选、分页加载
|
||||
*/
|
||||
class DbInspectFragment : BaseFragment<FragmentDbInspectBinding>() {
|
||||
|
||||
private lateinit var currentActivity: SingleFragmentActivity
|
||||
|
||||
/** 当前选中的表索引:0=菜品 1=食材 2=调料 3=槽位 */
|
||||
private var currentTableIndex = 0
|
||||
|
||||
/** 是否显示已删除记录(槽位表忽略此参数) */
|
||||
private var showDel = true
|
||||
|
||||
/** 防止代码中设置 Switch 状态时误触发监听器 */
|
||||
private var ignoreSwitch = false
|
||||
|
||||
private val adapter = DbRecordAdapter()
|
||||
|
||||
/** Tab RadioButton 列表,用于统一更新选中样式 */
|
||||
private val tabButtons = mutableListOf<RadioButton>()
|
||||
|
||||
/**
|
||||
* 每张表对应的筛选字段配置
|
||||
* @param key SQL 列名
|
||||
* @param label 显示标签
|
||||
* @param hint 输入框提示文字
|
||||
* @param isLike true=模糊匹配(LIKE),false=精确匹配(=)
|
||||
*/
|
||||
data class FilterField(
|
||||
val key: String,
|
||||
val label: String,
|
||||
val hint: String,
|
||||
val isLike: Boolean = false
|
||||
)
|
||||
|
||||
/** 各表的筛选字段配置 */
|
||||
private val filterConfigs = mapOf(
|
||||
0 to listOf(
|
||||
FilterField("foodId", "菜品ID", "精确匹配"),
|
||||
FilterField("foodName", "菜品名", "模糊搜索", isLike = true),
|
||||
FilterField("canteenId", "食堂ID", "精确匹配"),
|
||||
FilterField("cookMode", "菜品模式", "0制作/1采样/2品控"),
|
||||
FilterField("dinnerType", "餐次", "0默认无/1早餐/2午餐/3晚餐"),
|
||||
FilterField("submitState", "提交状态", "0本地或手动删除/1接口提交删除")
|
||||
),
|
||||
1 to listOf(
|
||||
FilterField("pid", "父ID", "精确匹配"),
|
||||
FilterField("foodId", "菜品ID", "精确匹配"),
|
||||
FilterField("goodsId", "食材ID", "精确匹配"),
|
||||
FilterField("goodsName", "食材名", "模糊搜索", isLike = true),
|
||||
FilterField("materialType", "物品类型", "1主料/2辅料/3调料"),
|
||||
FilterField("rawMaterialsType", "净材种类", "精确匹配"),
|
||||
FilterField("goodsCode", "物料编码", "1主料/2辅料/3调料")
|
||||
),
|
||||
2 to listOf(
|
||||
FilterField("goodsId", "调料ID", "精确匹配"),
|
||||
FilterField("goodsName", "调料名", "模糊搜索", isLike = true),
|
||||
FilterField("goodsCode", "物料编码", "1主料/2辅料/3调料")
|
||||
),
|
||||
3 to listOf(
|
||||
FilterField("deviceId", "设备ID", "精确匹配"),
|
||||
FilterField("address", "秤硬件地址", "精确匹配"),
|
||||
FilterField("goodsId", "调料ID", "精确匹配"),
|
||||
FilterField("goodsName", "调料名", "模糊搜索", isLike = true)
|
||||
)
|
||||
)
|
||||
|
||||
/** key=列名,value=对应的 EditText,用于查询时收集筛选值 */
|
||||
private val filterEditTexts = mutableMapOf<String, EditText>()
|
||||
|
||||
override fun inflateBinding(
|
||||
inflater: LayoutInflater,
|
||||
container: ViewGroup?
|
||||
): FragmentDbInspectBinding = FragmentDbInspectBinding.inflate(inflater, container, false)
|
||||
|
||||
override fun initialize() {
|
||||
currentActivity = requireActivity() as SingleFragmentActivity
|
||||
|
||||
binding.rvRecords.layoutManager = LinearLayoutManager(requireContext())
|
||||
binding.rvRecords.adapter = adapter
|
||||
|
||||
tabButtons.addAll(
|
||||
listOf(binding.rbCookFood, binding.rbGoods, binding.rbSeasoning, binding.rbSlot)
|
||||
)
|
||||
|
||||
// Tab 切换:重置筛选框并加载第一页
|
||||
binding.rgTabs.setOnCheckedChangeListener { _, checkedId ->
|
||||
currentTableIndex = when (checkedId) {
|
||||
R.id.rbCookFood -> 0
|
||||
R.id.rbGoods -> 1
|
||||
R.id.rbSeasoning -> 2
|
||||
R.id.rbSlot -> 3
|
||||
else -> 0
|
||||
}
|
||||
updateTabStyles()
|
||||
moveIndicator(currentTableIndex)
|
||||
updateDelControlsVisibility()
|
||||
rebuildFilterUI()
|
||||
loadFirstPage()
|
||||
}
|
||||
|
||||
// isDel 开关:切换后重新加载第一页
|
||||
binding.swShowDel.setOnCheckedChangeListener { _, isChecked ->
|
||||
if (ignoreSwitch) return@setOnCheckedChangeListener
|
||||
showDel = isChecked
|
||||
loadFirstPage()
|
||||
}
|
||||
|
||||
// 查询按钮:收集筛选条件并加载第一页
|
||||
binding.tvRefresh.setOnClickListener { loadFirstPage() }
|
||||
|
||||
// 加载更多按钮:筛选条件从 state 中复用,无需重新传入
|
||||
binding.tvLoadMore.setOnClickListener {
|
||||
currentActivity.dbViewModel.loadMoreDbInspect(currentTableIndex)
|
||||
}
|
||||
|
||||
// 订阅 UI 状态
|
||||
viewLifecycleOwner.lifecycleScope.launch {
|
||||
currentActivity.dbViewModel.dbInspectState.collect { state ->
|
||||
renderState(state)
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化样式并加载
|
||||
updateTabStyles()
|
||||
updateDelControlsVisibility()
|
||||
rebuildFilterUI()
|
||||
binding.vTabIndicator.post { moveIndicator(currentTableIndex) }
|
||||
loadFirstPage()
|
||||
}
|
||||
|
||||
/** 收集当前筛选框的值,构建 DbInspectFilter */
|
||||
private fun collectFilter(): DbViewModel.DbInspectFilter {
|
||||
val exactFields = mutableMapOf<String, String>()
|
||||
val likeFields = mutableMapOf<String, String>()
|
||||
filterConfigs[currentTableIndex]?.forEach { field ->
|
||||
val value = filterEditTexts[field.key]?.text?.toString()?.trim() ?: ""
|
||||
if (value.isNotEmpty()) {
|
||||
if (field.isLike) likeFields[field.key] = value
|
||||
else exactFields[field.key] = value
|
||||
}
|
||||
}
|
||||
return DbViewModel.DbInspectFilter(
|
||||
showDel = showDel,
|
||||
exactFields = exactFields,
|
||||
likeFields = likeFields
|
||||
)
|
||||
}
|
||||
|
||||
private fun loadFirstPage() {
|
||||
currentActivity.dbViewModel.loadDbInspect(currentTableIndex, collectFilter())
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据当前 Tab 重新生成筛选框区域
|
||||
* 每行展示 2 个字段,最后一个为奇数时右侧补空占位
|
||||
*/
|
||||
private fun rebuildFilterUI() {
|
||||
binding.llFilterContainer.removeAllViews()
|
||||
filterEditTexts.clear()
|
||||
|
||||
val configs = filterConfigs[currentTableIndex] ?: return
|
||||
val ctx = requireContext()
|
||||
val hPad = 4.dp
|
||||
val vPad = 2.dp
|
||||
|
||||
configs.chunked(2).forEach { rowFields ->
|
||||
val row = LinearLayout(ctx).apply {
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
layoutParams = LinearLayout.LayoutParams(
|
||||
LinearLayout.LayoutParams.MATCH_PARENT,
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT
|
||||
)
|
||||
}
|
||||
|
||||
rowFields.forEach { field ->
|
||||
val cell = LinearLayout(ctx).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
setPadding(hPad, vPad, hPad, vPad)
|
||||
}
|
||||
|
||||
// 字段标签
|
||||
cell.addView(TextView(ctx).apply {
|
||||
text = field.label
|
||||
textSize = 10f
|
||||
setTextColor("#888888".toColorInt())
|
||||
})
|
||||
|
||||
// 输入框
|
||||
val et = EditText(ctx).apply {
|
||||
hint = field.hint
|
||||
textSize = 12f
|
||||
setSingleLine(true)
|
||||
inputType = InputType.TYPE_CLASS_TEXT
|
||||
setPadding(hPad, vPad, hPad, vPad)
|
||||
}
|
||||
filterEditTexts[field.key] = et
|
||||
cell.addView(et)
|
||||
|
||||
row.addView(cell, LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f))
|
||||
}
|
||||
|
||||
// 奇数字段时右侧补空 View 保持对齐
|
||||
if (rowFields.size == 1) {
|
||||
row.addView(View(ctx), LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f))
|
||||
}
|
||||
|
||||
binding.llFilterContainer.addView(row)
|
||||
}
|
||||
}
|
||||
|
||||
private fun renderState(state: DbViewModel.DbInspectUiState) {
|
||||
binding.tvCount.text = when {
|
||||
state.isLoading && state.items.isEmpty() -> "加载中..."
|
||||
state.hasMore -> "已加载 ${state.items.size} / 共 ${state.totalCount} 条"
|
||||
else -> "共 ${state.totalCount} 条"
|
||||
}
|
||||
when {
|
||||
state.isLoading && state.hasMore -> {
|
||||
binding.tvLoadMore.visible()
|
||||
binding.tvLoadMore.text = "加载中..."
|
||||
binding.tvLoadMore.isClickable = false
|
||||
}
|
||||
state.hasMore -> {
|
||||
binding.tvLoadMore.visible()
|
||||
binding.tvLoadMore.text = "加载更多"
|
||||
binding.tvLoadMore.isClickable = true
|
||||
}
|
||||
else -> binding.tvLoadMore.gone()
|
||||
}
|
||||
adapter.setData(state.items)
|
||||
}
|
||||
|
||||
/**
|
||||
* 槽位表无 isDel 字段,切换到时隐藏相关控件;切换回其他 Tab 时恢复
|
||||
*/
|
||||
private fun updateDelControlsVisibility() {
|
||||
val isSlot = currentTableIndex == 3
|
||||
if (isSlot) {
|
||||
binding.tvDelLabel.gone()
|
||||
binding.swShowDel.gone()
|
||||
} else {
|
||||
binding.tvDelLabel.visible()
|
||||
binding.swShowDel.visible()
|
||||
ignoreSwitch = true
|
||||
binding.swShowDel.isChecked = showDel
|
||||
ignoreSwitch = false
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateTabStyles() {
|
||||
tabButtons.forEachIndexed { index, btn ->
|
||||
val selected = index == currentTableIndex
|
||||
btn.setTextColor(if (selected) Color.parseColor("#5C77F7") else Color.parseColor("#888888"))
|
||||
btn.setTypeface(null, if (selected) Typeface.BOLD else Typeface.NORMAL)
|
||||
}
|
||||
}
|
||||
|
||||
private fun moveIndicator(index: Int) {
|
||||
val btn = tabButtons.getOrNull(index) ?: return
|
||||
val tabWidth = btn.width.toFloat()
|
||||
val indicatorWidth = tabWidth / 2f
|
||||
val indicatorX = btn.x + (tabWidth - indicatorWidth) / 2f
|
||||
binding.vTabIndicator.animate().translationX(indicatorX).setDuration(150).start()
|
||||
binding.vTabIndicator.post {
|
||||
val lp = binding.vTabIndicator.layoutParams
|
||||
lp.width = indicatorWidth.toInt()
|
||||
binding.vTabIndicator.layoutParams = lp
|
||||
}
|
||||
}
|
||||
|
||||
/** dp 转 px 便捷扩展 */
|
||||
private val Int.dp: Int get() = (this * resources.displayMetrics.density + 0.5f).toInt()
|
||||
|
||||
// ---- 外层 Adapter:每条数据库记录对应一个 CardView ----
|
||||
|
||||
/** 外层列表适配器,每个 item 内嵌一个 GridLayoutManager 的 RecyclerView 展示字段 */
|
||||
private inner class DbRecordAdapter : RecyclerView.Adapter<DbRecordAdapter.VH>() {
|
||||
|
||||
private val data = mutableListOf<DbViewModel.DbRecord>()
|
||||
|
||||
fun setData(list: List<DbViewModel.DbRecord>) {
|
||||
data.clear()
|
||||
data.addAll(list)
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
|
||||
val view = LayoutInflater.from(parent.context)
|
||||
.inflate(R.layout.list_item_db_record, parent, false)
|
||||
return VH(view)
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: VH, position: Int) {
|
||||
val record = data[position]
|
||||
|
||||
if (record.isDel) {
|
||||
holder.card.setCardBackgroundColor(Color.parseColor("#FFF3F3"))
|
||||
holder.vDelMark.visibility = View.VISIBLE
|
||||
} else {
|
||||
holder.card.setCardBackgroundColor(Color.WHITE)
|
||||
holder.vDelMark.visibility = View.GONE
|
||||
}
|
||||
val textColor = if (record.isDel) Color.parseColor("#C62828") else Color.parseColor("#333333")
|
||||
|
||||
holder.rvFields.layoutManager = GridLayoutManager(holder.rvFields.context, record.columnsPerRow)
|
||||
holder.rvFields.adapter = DbFieldAdapter(record.fields, textColor)
|
||||
}
|
||||
|
||||
override fun getItemCount() = data.size
|
||||
|
||||
inner class VH(itemView: View) : RecyclerView.ViewHolder(itemView) {
|
||||
val card: CardView = itemView.findViewById(R.id.cardRecord)
|
||||
val vDelMark: View = itemView.findViewById(R.id.vDelMark)
|
||||
val rvFields: RecyclerView = itemView.findViewById(R.id.rvFields)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 内层 Adapter:每个字段对应一个 TextView,垂直显示字段名和值 ----
|
||||
|
||||
/** 内层字段适配器,每个 item 为单个 TextView,显示格式:字段名\n字段值 */
|
||||
private inner class DbFieldAdapter(
|
||||
private val fields: List<Pair<String, String>>,
|
||||
private val textColor: Int
|
||||
) : RecyclerView.Adapter<DbFieldAdapter.VH>() {
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
|
||||
val view = LayoutInflater.from(parent.context)
|
||||
.inflate(R.layout.list_item_db_field, parent, false)
|
||||
return VH(view)
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: VH, position: Int) {
|
||||
val (key, value) = fields[position]
|
||||
holder.tvField.text = "$key\n$value"
|
||||
holder.tvField.setTextColor(textColor)
|
||||
}
|
||||
|
||||
override fun getItemCount() = fields.size
|
||||
|
||||
inner class VH(itemView: View) : RecyclerView.ViewHolder(itemView) {
|
||||
val tvField: TextView = itemView.findViewById(R.id.tvField)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,327 +0,0 @@
|
||||
package com.shuwei.dish.match.ui.fragment
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.os.Bundle
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import android.widget.FrameLayout
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.FoodListAdapter
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.base.BaseFragment
|
||||
import com.shuwei.dish.match.databinding.FragmentDishListBinding
|
||||
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.entity.FoodRecord
|
||||
import com.shuwei.dish.match.net.UiState
|
||||
import com.shuwei.dish.match.ui.CookingModeActivity
|
||||
import com.shuwei.dish.match.ui.PrepareFoodActivity
|
||||
import com.shuwei.dish.match.ui.SubmitFoodActivity
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import com.shuwei.dish.match.utils.ext.startActivity
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import com.yanzhenjie.recyclerview.SwipeMenuItem
|
||||
import java.io.Serializable
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class DishListFragment : BaseFragment<FragmentDishListBinding>() {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "DishListFragment"
|
||||
|
||||
const val DINNER_TYPE = "dinnerType"
|
||||
public fun instance(dinnerType: String): DishListFragment {
|
||||
return DishListFragment().apply {
|
||||
arguments = Bundle().apply {
|
||||
putString(DINNER_TYPE, dinnerType)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var pageNo = 1
|
||||
private val pageSize = 30
|
||||
|
||||
private var dinnerType = "0"
|
||||
|
||||
private lateinit var activity: CookingModeActivity
|
||||
|
||||
private var list: MutableList<FoodRecord> = mutableListOf()
|
||||
private val dishAdapter by lazy {
|
||||
FoodListAdapter(list = list).apply {
|
||||
isStateViewEnable = true
|
||||
onItemClick = { position ->
|
||||
if (isAdded && isVisible) {
|
||||
activity.judgeDeviceConfig {
|
||||
onItemClick(position)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun onItemClick(position: Int) {
|
||||
val item = list[position]
|
||||
if (item.isCooking) {
|
||||
// 烹饪中,跳到称熟重页面
|
||||
activity.startActivity<SubmitFoodActivity> {
|
||||
putExtra(SubmitFoodActivity.FOOD_ITEM, item as Serializable)
|
||||
}
|
||||
return
|
||||
}
|
||||
item.dinnerType = dinnerType
|
||||
activity.startActivity<PrepareFoodActivity> {
|
||||
putExtra(SubmitFoodActivity.FOOD_ITEM, item as Serializable)
|
||||
}
|
||||
}
|
||||
|
||||
override fun inflateBinding(
|
||||
inflater: LayoutInflater,
|
||||
container: ViewGroup?
|
||||
): FragmentDishListBinding {
|
||||
return FragmentDishListBinding.inflate(inflater, container, false)
|
||||
}
|
||||
|
||||
override fun initialize() {
|
||||
activity = requireActivity() as CookingModeActivity
|
||||
dinnerType = arguments?.getString(DINNER_TYPE, "0") ?: "0"
|
||||
binding.rvDishList.run {
|
||||
layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
|
||||
// 侧滑菜单:仅烹饪中的 item 显示删除按钮(必须在 setAdapter 之前调用)
|
||||
setSwipeMenuCreator { _, rightMenu, position ->
|
||||
if (list.getOrNull(position)?.isCooking == true) {
|
||||
rightMenu.addMenuItem(buildDeleteMenuItem(requireContext()))
|
||||
}
|
||||
}
|
||||
// 菜单点击:先关闭菜单,再弹确认弹窗
|
||||
setOnItemMenuClickListener { menuBridge, position ->
|
||||
menuBridge.closeMenu()
|
||||
val item = list.getOrNull(position) ?: return@setOnItemMenuClickListener
|
||||
CommonDialog(activity)
|
||||
.setTitle("删除确认")
|
||||
.setContent("确定要删除「${item.foodName}」吗?")
|
||||
.setNegativeButton("取消")
|
||||
.setPositiveButton("删除") {
|
||||
activity.deleteCookFoodAndGoods(foodId = item.foodId ?: "") {
|
||||
activity.toast("已删除")
|
||||
pageNo = 1
|
||||
getDishList()
|
||||
}
|
||||
}
|
||||
.show()
|
||||
}
|
||||
// item 点击
|
||||
setOnItemClickListener { _, position ->
|
||||
if (isAdded && isVisible) {
|
||||
activity.judgeDeviceConfig { onItemClick(position) }
|
||||
}
|
||||
}
|
||||
adapter = dishAdapter
|
||||
}
|
||||
addViewListener()
|
||||
initObserver()
|
||||
|
||||
pageNo = 1
|
||||
activity.showLoading()
|
||||
getDishList()
|
||||
binding.refreshLayout.setEnableRefresh(true)
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建统一样式的删除菜单项
|
||||
*/
|
||||
private fun buildDeleteMenuItem(context: Context): SwipeMenuItem {
|
||||
return SwipeMenuItem(context).apply {
|
||||
setImage(R.drawable.ic_trash_white)
|
||||
setBackground(R.drawable.bg_swipe_delete)
|
||||
width = 160.dp
|
||||
height = ViewGroup.LayoutParams.MATCH_PARENT
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用 combine 同时监听网络结果与本地数据,网络成功时统一合并渲染
|
||||
* pageNo > 1(加载更多)时 cookFoodListState 不参与合并,直接追加网络数据
|
||||
*/
|
||||
private fun initObserver() {
|
||||
viewLifecycleOwner.lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
combine(
|
||||
activity.netViewModel.searchFoodState,
|
||||
activity.appViewModel.cookFoodListState
|
||||
) { networkState, localList -> Pair(networkState, localList) }
|
||||
.collect { (networkState, localList) ->
|
||||
when (networkState) {
|
||||
is UiState.Loading -> activity.showLoading()
|
||||
is UiState.Success -> {
|
||||
activity.delayDismissLoading()
|
||||
finishRefresh()
|
||||
loadAndMergeDishList(networkState.data, localList)
|
||||
}
|
||||
is UiState.Error -> {
|
||||
if (isAdded.not()) return@collect
|
||||
toast(networkState.msg)
|
||||
finishRefresh()
|
||||
activity.delayDismissLoading()
|
||||
if (pageNo == 1) {
|
||||
if (localList.isNullOrEmpty()) {
|
||||
loadEmptyView()
|
||||
} else {
|
||||
loadAndMergeDishList(null, localList)
|
||||
}
|
||||
}
|
||||
}
|
||||
is UiState.Idle -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun addViewListener() {
|
||||
binding.refreshLayout.run {
|
||||
setEnableRefresh(true)
|
||||
setEnableLoadMore(false)
|
||||
setOnRefreshListener {
|
||||
pageNo = 1
|
||||
getDishList()
|
||||
}
|
||||
setOnLoadMoreListener {
|
||||
getDishList()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getDishList(pageNo: Int, dinnerType: String) {
|
||||
this.pageNo = pageNo
|
||||
this.dinnerType = dinnerType
|
||||
getDishList()
|
||||
}
|
||||
|
||||
fun getDinnerTypeText(): String {
|
||||
return when (dinnerType) {
|
||||
"1" -> "早餐"
|
||||
"2" -> "午餐"
|
||||
"3" -> "晚餐"
|
||||
else -> "早餐"
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
@Suppress("unchecked_cast")
|
||||
fun getDishList() {
|
||||
val param = mutableMapOf<String, Any>(
|
||||
"pageNum" to pageNo,
|
||||
"pageSize" to pageSize,
|
||||
"placeId" to BaseApp.canteenId,
|
||||
"dinnerType" to getDinnerTypeText()
|
||||
)
|
||||
activity.getFoodList(param = param)
|
||||
if (pageNo == 1) activity.getCookFoodList()
|
||||
}
|
||||
|
||||
private var emptyViewBinding: LayoutEmptyViewBinding? = null
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun loadEmptyView() {
|
||||
try {
|
||||
binding.refreshLayout.setEnableRefresh(true)
|
||||
binding.refreshLayout.setEnableLoadMore(false)
|
||||
list.clear()
|
||||
dishAdapter.notifyDataSetChanged()
|
||||
if (emptyViewBinding == null) {
|
||||
emptyViewBinding = LayoutEmptyViewBinding.inflate(
|
||||
LayoutInflater.from(requireContext()),
|
||||
binding.rvDishList,
|
||||
false
|
||||
)
|
||||
}
|
||||
emptyViewBinding!!.tvContent.text = "暂无数据"
|
||||
emptyViewBinding!!.tvSubContent.text = "获取菜品数据失败,请检查网络设置或稍后重试"
|
||||
emptyViewBinding!!.root.layoutParams = FrameLayout.LayoutParams(
|
||||
FrameLayout.LayoutParams.MATCH_PARENT,
|
||||
FrameLayout.LayoutParams.MATCH_PARENT
|
||||
)
|
||||
binding.rvDishList.post {
|
||||
emptyViewBinding!!.root.minimumHeight = binding.rvDishList.height
|
||||
dishAdapter.stateView = emptyViewBinding!!.root
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
private fun finishRefresh() {
|
||||
if (pageNo == 1) {
|
||||
binding.refreshLayout.finishRefresh(1200)
|
||||
} else {
|
||||
binding.refreshLayout.finishLoadMore(1200)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将网络数据与本地烹饪中数据合并后渲染列表
|
||||
*/
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun loadAndMergeDishList(
|
||||
records: MutableList<FoodRecord>?,
|
||||
localList: MutableList<CookFoodEntity>?
|
||||
) {
|
||||
try {
|
||||
if (isAdded.not()) return
|
||||
val effectiveLocalList = if (pageNo == 1) localList else null
|
||||
if (records.isNullOrEmpty() && effectiveLocalList.isNullOrEmpty()) {
|
||||
if (pageNo == 1) loadEmptyView()
|
||||
return
|
||||
}
|
||||
if (pageNo == 1) list.clear()
|
||||
|
||||
val mergedList = records?.toMutableList() ?: mutableListOf()
|
||||
|
||||
if (!effectiveLocalList.isNullOrEmpty()) {
|
||||
val cookingItems = mutableListOf<FoodRecord>()
|
||||
effectiveLocalList.forEachIndexed { index, entity ->
|
||||
val food = mergedList.firstOrNull { it.foodId == entity.foodId }
|
||||
if (food != null) {
|
||||
mergedList.remove(food)
|
||||
food.isCooking = true
|
||||
food.sort = index
|
||||
food.dinnerType = entity.dinnerType ?: "0"
|
||||
cookingItems.add(food)
|
||||
} else {
|
||||
cookingItems.add(
|
||||
FoodRecord(
|
||||
foodId = entity.foodId,
|
||||
foodName = entity.foodName,
|
||||
sort = index,
|
||||
dinnerType = entity.dinnerType ?: "0",
|
||||
isCooking = true
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
mergedList.addAll(0, cookingItems)
|
||||
}
|
||||
|
||||
if (pageNo >= 2 && !localList.isNullOrEmpty()) {
|
||||
val localIds = localList.map { it.foodId }.toHashSet()
|
||||
mergedList.removeAll { it.foodId in localIds }
|
||||
}
|
||||
|
||||
list.addAll(mergedList)
|
||||
dishAdapter.notifyDataSetChanged()
|
||||
val isLoadMoreEnable = (records?.size ?: 0) >= pageSize
|
||||
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
|
||||
if (isLoadMoreEnable) pageNo++
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
package com.shuwei.dish.match.ui.fragment
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import android.widget.FrameLayout
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.FoodListAdapter
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.base.BaseFragment
|
||||
import com.shuwei.dish.match.databinding.FragmentFoodListBinding
|
||||
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.db.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.model.CookOrderItem
|
||||
import com.shuwei.dish.match.model.CookOrderMealGroup
|
||||
import com.shuwei.dish.match.model.CookOrderPageRequest
|
||||
import com.shuwei.dish.match.model.FoodRecord
|
||||
import com.shuwei.dish.match.net.UiState
|
||||
import com.shuwei.dish.match.ui.CookingModeActivity
|
||||
import com.shuwei.dish.match.ui.PrepareFoodActivity
|
||||
import com.shuwei.dish.match.ui.SubmitFoodActivity
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import com.shuwei.dish.match.net.NetViewModel
|
||||
import com.shuwei.dish.match.utils.ext.startActivity
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import com.yanzhenjie.recyclerview.SwipeMenuItem
|
||||
import androidx.fragment.app.viewModels
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import java.io.Serializable
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class FoodListFragment : BaseFragment<FragmentFoodListBinding>() {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "DishListFragment"
|
||||
|
||||
const val DINNER_TYPE = "dinnerType"
|
||||
public fun instance(dinnerType: String): FoodListFragment {
|
||||
return FoodListFragment().apply {
|
||||
arguments = Bundle().apply {
|
||||
putString(DINNER_TYPE, dinnerType)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val netViewModel: NetViewModel by viewModels()
|
||||
|
||||
private var pageNo = 1
|
||||
private val pageSize = 100
|
||||
|
||||
private var dinnerType = "0"
|
||||
|
||||
/** 跟踪当前请求协程,新请求发起前取消旧的,防止并发竞态导致数据错乱 */
|
||||
private var currentJob: Job? = null
|
||||
|
||||
/** 缓存最后一次搜索词,返回二级页面后 onResume 可复用,避免搜索态被重置为全量查询 */
|
||||
private var currentFoodName: String? = null
|
||||
|
||||
private lateinit var activity: CookingModeActivity
|
||||
|
||||
/** 首次加载标记,首次请求时传 mealType=null 获取全餐次数据,后续切换传具体餐次 */
|
||||
private var isFirstLoad = true
|
||||
|
||||
/** foodId → cookOrderId 映射,用于跳转 PrepareFoodActivity 时传递烹制单 ID */
|
||||
private val cookOrderIdMap = mutableMapOf<String, String>()
|
||||
|
||||
/** 第一页时先查数据库存入此字段,网络结果回来后直接使用,避免时序问题 */
|
||||
private var pendingLocalList: MutableList<CookFoodEntity>? = null
|
||||
|
||||
private var list: MutableList<FoodRecord> = mutableListOf()
|
||||
private val dishAdapter by lazy {
|
||||
FoodListAdapter(list = list).apply {
|
||||
isStateViewEnable = true
|
||||
onItemClick = { position ->
|
||||
if (isAdded && isVisible) {
|
||||
activity.judgeDeviceConfig {
|
||||
onItemClick(position)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun onItemClick(position: Int) {
|
||||
val item = list.getOrNull(position) ?: return
|
||||
if (item.isCooking) {
|
||||
// 烹饪中,跳到称熟重页面
|
||||
activity.startActivity<SubmitFoodActivity> {
|
||||
putExtra(SubmitFoodActivity.FOOD_ITEM, item as Serializable)
|
||||
putExtra(SubmitFoodActivity.COOK_ORDER_ID, cookOrderIdMap[item.foodId])
|
||||
}
|
||||
return
|
||||
}
|
||||
item.dinnerType = dinnerType
|
||||
activity.startActivity<PrepareFoodActivity> {
|
||||
putExtra(PrepareFoodActivity.FOOD_ITEM, item as Serializable)
|
||||
putExtra(PrepareFoodActivity.COOK_ORDER_ID, cookOrderIdMap[item.foodId])
|
||||
}
|
||||
}
|
||||
|
||||
override fun inflateBinding(
|
||||
inflater: LayoutInflater,
|
||||
container: ViewGroup?
|
||||
): FragmentFoodListBinding {
|
||||
return FragmentFoodListBinding.inflate(inflater, container, false)
|
||||
}
|
||||
|
||||
override fun initialize() {
|
||||
activity = requireActivity() as CookingModeActivity
|
||||
dinnerType = arguments?.getString(DINNER_TYPE, "0") ?: "0"
|
||||
binding.rvDishList.run {
|
||||
layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
|
||||
// 侧滑菜单:仅烹饪中的 item 显示删除按钮(必须在 setAdapter 之前调用)
|
||||
setSwipeMenuCreator { _, rightMenu, position ->
|
||||
if (list.getOrNull(position)?.isCooking == true) {
|
||||
rightMenu.addMenuItem(buildDeleteMenuItem(requireContext()))
|
||||
}
|
||||
}
|
||||
// 菜单点击:先关闭菜单,再弹确认弹窗
|
||||
setOnItemMenuClickListener { menuBridge, position ->
|
||||
menuBridge.closeMenu()
|
||||
val item = list.getOrNull(position) ?: return@setOnItemMenuClickListener
|
||||
CommonDialog(activity)
|
||||
.setTitle("删除确认")
|
||||
.setContent("确定要删除「${item.foodName}」吗?")
|
||||
.setNegativeButton("取消")
|
||||
.setPositiveButton("删除") {
|
||||
activity.deleteCookFoodAndGoods(foodId = item.foodId ?: "", dinnerType = item.dinnerType) {
|
||||
activity.toast("已删除")
|
||||
pageNo = 1
|
||||
getDishList()
|
||||
}
|
||||
}
|
||||
.show()
|
||||
}
|
||||
// // item 点击
|
||||
// setOnItemClickListener { _, position ->
|
||||
// if (isAdded && isVisible) {
|
||||
// activity.judgeDeviceConfig { onItemClick(position) }
|
||||
// }
|
||||
// }
|
||||
adapter = dishAdapter
|
||||
}
|
||||
addViewListener()
|
||||
binding.refreshLayout.setEnableRefresh(true)
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
Log.d(TAG, "onResume, dinnerType=$dinnerType, isVisible=${isVisible}, isHidden=${isHidden}")
|
||||
if (isHidden) return // 过滤 Activity 回前台时隐藏 tab 的无效触发
|
||||
runCatching {
|
||||
pageNo = 1
|
||||
getDishList(currentFoodName)
|
||||
}.onFailure {
|
||||
it.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建统一样式的删除菜单项
|
||||
*/
|
||||
private fun buildDeleteMenuItem(context: Context): SwipeMenuItem {
|
||||
return SwipeMenuItem(context).apply {
|
||||
setImage(R.drawable.ic_trash_white)
|
||||
setBackground(R.drawable.bg_swipe_delete)
|
||||
width = 160.dp
|
||||
height = ViewGroup.LayoutParams.MATCH_PARENT
|
||||
}
|
||||
}
|
||||
|
||||
private fun addViewListener() {
|
||||
binding.refreshLayout.run {
|
||||
setEnableRefresh(true)
|
||||
setEnableLoadMore(false)
|
||||
setOnRefreshListener {
|
||||
Log.d("FoodList", "下拉刷新触发, pageNo reset to 1")
|
||||
pageNo = 1
|
||||
getDishList()
|
||||
}
|
||||
setOnLoadMoreListener {
|
||||
getDishList()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onHiddenChanged(hidden: Boolean) {
|
||||
super.onHiddenChanged(hidden)
|
||||
if (!hidden) {
|
||||
Log.d("FoodList", "显示")
|
||||
pageNo = 1
|
||||
getDishList()
|
||||
}
|
||||
}
|
||||
|
||||
fun getDishList(pageNo: Int, dinnerType: String, foodName: String? = null) {
|
||||
this.pageNo = pageNo
|
||||
this.dinnerType = dinnerType
|
||||
getDishList(foodName)
|
||||
}
|
||||
|
||||
fun getDinnerTypeText(): String {
|
||||
return when (dinnerType) {
|
||||
"1" -> "早餐"
|
||||
"2" -> "午餐"
|
||||
"3" -> "晚餐"
|
||||
else -> "早餐"
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
@Suppress("unchecked_cast")
|
||||
fun getDishList(foodName: String? = null) {
|
||||
currentFoodName = foodName
|
||||
currentJob?.cancel()
|
||||
currentJob = viewLifecycleOwner.lifecycleScope.launch {
|
||||
// 首次加载传 mealType=null 获取所有餐次,切换 Tab 时传当前餐次精确请求
|
||||
val mealType = if (isFirstLoad) null else when (dinnerType) {
|
||||
"1", "2", "3", "4" -> dinnerType.toInt()
|
||||
else -> null // "0" 或非法值不传,由后端返回全部餐次
|
||||
}
|
||||
val request = CookOrderPageRequest(
|
||||
mealType = mealType,
|
||||
keyword = foodName
|
||||
)
|
||||
if (pageNo == 1) {
|
||||
pendingLocalList = activity.dbViewModel.getCookFoodListDirect(
|
||||
cookMode = 0,
|
||||
dinnerType = dinnerType
|
||||
)
|
||||
}
|
||||
val localList = pendingLocalList
|
||||
netViewModel.getCookOrderPageWithCallback(
|
||||
request = request,
|
||||
onLoading = { activity.showLoading(timeoutMs = 35_000L) }
|
||||
) { result ->
|
||||
when (result) {
|
||||
is UiState.Success -> {
|
||||
if (isAdded.not()) return@getCookOrderPageWithCallback
|
||||
Log.d(TAG, "getDishList, UiState.Success")
|
||||
isFirstLoad = false
|
||||
activity.delayDismissLoading()
|
||||
finishRefresh()
|
||||
loadAndMergeCookOrders(result.data, localList)
|
||||
}
|
||||
is UiState.Error -> {
|
||||
if (isAdded.not()) return@getCookOrderPageWithCallback
|
||||
Log.d(TAG, "getDishList, UiState.Error")
|
||||
isFirstLoad = false
|
||||
toast(result.msg)
|
||||
finishRefresh()
|
||||
activity.delayDismissLoading()
|
||||
if (localList.isNullOrEmpty()) loadEmptyView()
|
||||
else loadAndMergeCookOrders(null, localList)
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var emptyViewBinding: LayoutEmptyViewBinding? = null
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun loadEmptyView() {
|
||||
try {
|
||||
binding.refreshLayout.setEnableRefresh(true)
|
||||
binding.refreshLayout.setEnableLoadMore(false)
|
||||
list.clear()
|
||||
dishAdapter.notifyDataSetChanged()
|
||||
if (emptyViewBinding == null) {
|
||||
emptyViewBinding = LayoutEmptyViewBinding.inflate(
|
||||
LayoutInflater.from(requireContext()),
|
||||
binding.rvDishList,
|
||||
false
|
||||
)
|
||||
}
|
||||
emptyViewBinding!!.tvContent.text = "暂无数据"
|
||||
emptyViewBinding!!.tvSubContent.text = "获取菜品数据失败,请检查网络设置或稍后重试"
|
||||
emptyViewBinding!!.root.layoutParams = FrameLayout.LayoutParams(
|
||||
FrameLayout.LayoutParams.MATCH_PARENT,
|
||||
FrameLayout.LayoutParams.MATCH_PARENT
|
||||
)
|
||||
binding.rvDishList.post {
|
||||
emptyViewBinding!!.root.minimumHeight = binding.rvDishList.height
|
||||
dishAdapter.stateView = emptyViewBinding!!.root
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
private fun finishRefresh() {
|
||||
binding.refreshLayout.finishRefresh(1200)
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 CookOrderItem 映射为 FoodRecord,适配现有 Adapter
|
||||
* rawWeight 单位 kg → totalWeight 单位 g
|
||||
*/
|
||||
private fun CookOrderItem.toFoodRecord(): FoodRecord {
|
||||
return FoodRecord(
|
||||
foodId = foodId,
|
||||
foodName = dishName,
|
||||
totalWeight = ((cookedWeight ?: 0.0) * 1000),
|
||||
foodWeight = ((cookedWeight ?: 0.0) * 1000),
|
||||
count = cookedPortions,
|
||||
cookMode = 0,
|
||||
isCooking = cookStatus == 1,
|
||||
dinnerType = mealType.toString(),
|
||||
isOriginalData = true
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 将新接口的餐次分组响应与本地烹饪中数据合并后渲染列表
|
||||
* 从分组中按当前 dinnerType 筛选对应餐次的 cookOrders,映射为 FoodRecord 后合并本地数据
|
||||
*/
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun loadAndMergeCookOrders(
|
||||
groups: List<CookOrderMealGroup>?,
|
||||
localList: MutableList<CookFoodEntity>?
|
||||
) {
|
||||
try {
|
||||
if (isAdded.not()) return
|
||||
val targetMealType = dinnerType.toIntOrNull() ?: return
|
||||
// 从分组中筛选当前餐次的烹制单列表
|
||||
val cookOrders = groups
|
||||
?.firstOrNull { it.mealType == targetMealType }
|
||||
?.cookOrders
|
||||
// 更新 foodId → cookOrderId 映射(从全量分组构建,跨餐次)
|
||||
groups?.forEach { group ->
|
||||
group.cookOrders.forEach { order ->
|
||||
cookOrderIdMap[order.foodId] = order.cookOrderId
|
||||
}
|
||||
}
|
||||
|
||||
if (cookOrders.isNullOrEmpty() && localList.isNullOrEmpty()) {
|
||||
loadEmptyView()
|
||||
finishRefresh()
|
||||
binding.refreshLayout.setEnableLoadMore(false)
|
||||
return
|
||||
}
|
||||
list.clear()
|
||||
|
||||
val mergedList = cookOrders?.map { it.toFoodRecord() }?.toMutableList() ?: mutableListOf()
|
||||
mergeCookingItems(mergedList, localList)
|
||||
|
||||
list.addAll(mergedList)
|
||||
dishAdapter.notifyDataSetChanged()
|
||||
binding.refreshLayout.setEnableRefresh(true)
|
||||
binding.refreshLayout.setEnableLoadMore(false)
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将本地烹饪中条目置顶合并到网络列表:
|
||||
* 网络列表中已有的条目标记 isCooking 并移至顶部,没有的则新建占位条目
|
||||
*/
|
||||
private fun mergeCookingItems(
|
||||
mergedList: MutableList<FoodRecord>,
|
||||
cookingEntities: List<CookFoodEntity>?
|
||||
) {
|
||||
if (cookingEntities.isNullOrEmpty()) return
|
||||
val cookingItems = mutableListOf<FoodRecord>()
|
||||
cookingEntities.forEachIndexed { index, entity ->
|
||||
val existing = mergedList.firstOrNull { it.foodId == entity.foodId }
|
||||
if (existing != null) {
|
||||
mergedList.remove(existing)
|
||||
existing.isCooking = true
|
||||
existing.sort = index
|
||||
existing.dinnerType = entity.dinnerType ?: "0"
|
||||
cookingItems.add(existing)
|
||||
} else {
|
||||
cookingItems.add(
|
||||
FoodRecord(
|
||||
foodId = entity.foodId,
|
||||
foodName = entity.foodName,
|
||||
sort = index,
|
||||
dinnerType = entity.dinnerType ?: "0",
|
||||
isCooking = true
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
mergedList.addAll(0, cookingItems)
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ import com.shuwei.dish.match.base.GlobalData
|
||||
import com.shuwei.dish.match.databinding.FragmentSeasoningConfigBinding
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.dialog.SeasoningSelectDialog
|
||||
import com.shuwei.dish.match.entity.SeasoningSlotEntity
|
||||
import com.shuwei.dish.match.db.entity.SeasoningSlotEntity
|
||||
import com.shuwei.dish.match.scale.ScaleDeviceConfig
|
||||
import com.shuwei.dish.match.scale.ScaleEvent
|
||||
import com.shuwei.dish.match.scale.ScaleServiceManager
|
||||
@@ -50,7 +50,7 @@ class SeasoningConfigFragment : BaseFragment<FragmentSeasoningConfigBinding>() {
|
||||
) = FragmentSeasoningConfigBinding.inflate(inflater, container, false)
|
||||
|
||||
private lateinit var currentActivity: SingleFragmentActivity
|
||||
// private lateinit var appViewModel: DbViewModel
|
||||
// private lateinit var dbViewModel: DbViewModel
|
||||
|
||||
private val adapter22 by lazy { buildAdapter22() }
|
||||
private val adapter18 by lazy {
|
||||
@@ -184,14 +184,20 @@ class SeasoningConfigFragment : BaseFragment<FragmentSeasoningConfigBinding>() {
|
||||
onItemSelected = { item ->
|
||||
val name = item.goodsName ?: ""
|
||||
onUpdateName(name)
|
||||
saveSlotAndBroadcast(
|
||||
SeasoningSlotEntity(
|
||||
deviceId = deviceId,
|
||||
address = address,
|
||||
goodsId = item.goodsId,
|
||||
goodsName = name
|
||||
lifecycleScope.launch {
|
||||
// 保存槽位配置
|
||||
currentActivity.dbViewModel.upsertSeasoningSlot(
|
||||
SeasoningSlotEntity(
|
||||
deviceId = deviceId,
|
||||
address = address,
|
||||
goodsId = item.goodsId,
|
||||
goodsName = name
|
||||
)
|
||||
)
|
||||
)
|
||||
// 按 goodsId 去重保存完整调料信息到 dm_seasoning
|
||||
currentActivity.dbViewModel.upsertSeasoningByGoodsId(item.toSeasoningEntity())
|
||||
broadcastAllSlots()
|
||||
}
|
||||
}
|
||||
).show()
|
||||
}
|
||||
@@ -199,7 +205,7 @@ class SeasoningConfigFragment : BaseFragment<FragmentSeasoningConfigBinding>() {
|
||||
/** 将单个槽位写入 Room,再广播全量配置给子设备 */
|
||||
private fun saveSlotAndBroadcast(slot: SeasoningSlotEntity) {
|
||||
lifecycleScope.launch {
|
||||
currentActivity.appViewModel.upsertSeasoningSlot(slot)
|
||||
currentActivity.dbViewModel.upsertSeasoningSlot(slot)
|
||||
broadcastAllSlots()
|
||||
}
|
||||
}
|
||||
@@ -227,14 +233,14 @@ class SeasoningConfigFragment : BaseFragment<FragmentSeasoningConfigBinding>() {
|
||||
/** 从 Room 删除指定槽位,再广播全量配置给子设备 */
|
||||
private fun deleteSlotAndBroadcast(deviceId: String, address: Int) {
|
||||
lifecycleScope.launch {
|
||||
currentActivity.appViewModel.deleteSeasoningSlot(deviceId, address)
|
||||
currentActivity.dbViewModel.deleteSeasoningSlot(deviceId, address)
|
||||
broadcastAllSlots()
|
||||
}
|
||||
}
|
||||
|
||||
/** 读取全量槽位配置并通过 wsClient 推送给所有已连接子设备 */
|
||||
private suspend fun broadcastAllSlots() {
|
||||
val allSlots = currentActivity.appViewModel.loadSeasoningSlot().map {
|
||||
val allSlots = currentActivity.dbViewModel.loadSeasoningSlot().map {
|
||||
SlotConfig(it.deviceId, it.address, it.goodsId, it.goodsName)
|
||||
}
|
||||
ScaleServiceManager.sendSeasoningConfig(allSlots)
|
||||
@@ -243,7 +249,7 @@ class SeasoningConfigFragment : BaseFragment<FragmentSeasoningConfigBinding>() {
|
||||
// /** 初始化 ViewModel */
|
||||
// private fun initViewModel() {
|
||||
// val factory = AppFactory(DbRepository(BaseApp.instance!!.database.appDao()))
|
||||
// appViewModel = ViewModelProvider(this, factory)[DbViewModel::class.java]
|
||||
// dbViewModel = ViewModelProvider(this, factory)[DbViewModel::class.java]
|
||||
// }
|
||||
|
||||
|
||||
@@ -286,9 +292,9 @@ class SeasoningConfigFragment : BaseFragment<FragmentSeasoningConfigBinding>() {
|
||||
adapter22.update(emptyList())
|
||||
adapter18.update(emptyList())
|
||||
lifecycleScope.launch {
|
||||
val slots22 = currentActivity.appViewModel.getSeasoningSlotsByDeviceId(ScaleDeviceConfig.DEVICE_ID_22)
|
||||
val slots18 = currentActivity.appViewModel.getSeasoningSlotsByDeviceId(ScaleDeviceConfig.DEVICE_ID_18)
|
||||
val slotsOil = currentActivity.appViewModel.getSeasoningSlotsByDeviceId(ScaleDeviceConfig.DEVICE_ID_1)
|
||||
val slots22 = currentActivity.dbViewModel.getSeasoningSlotsByDeviceId(ScaleDeviceConfig.DEVICE_ID_22)
|
||||
val slots18 = currentActivity.dbViewModel.getSeasoningSlotsByDeviceId(ScaleDeviceConfig.DEVICE_ID_18)
|
||||
val slotsOil = currentActivity.dbViewModel.getSeasoningSlotsByDeviceId(ScaleDeviceConfig.DEVICE_ID_1)
|
||||
slots22.forEach { slot ->
|
||||
val pos = ScaleDeviceConfig.SCALE_ORDER_22.indexOf(slot.address)
|
||||
if (pos >= 0) adapter22.updateItemName(pos, slot.goodsName)
|
||||
|
||||
@@ -14,27 +14,46 @@ import android.view.inputmethod.InputMethodManager
|
||||
import androidx.camera.view.PreviewView
|
||||
import androidx.core.view.doOnLayout
|
||||
import androidx.core.view.updateLayoutParams
|
||||
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.chad.library.adapter4.util.setOnDebouncedItemClick
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.VectorCollectionAdapter
|
||||
import com.shuwei.dish.match.adapter.FoodSearchAdapter
|
||||
import com.shuwei.dish.match.adapter.Food3Adapter
|
||||
import com.shuwei.dish.match.base.BaseFragment
|
||||
import com.shuwei.dish.match.databinding.FragmentVectorCollectionBinding
|
||||
import com.shuwei.dish.match.databinding.LayoutCameraPreviewBinding
|
||||
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
||||
import com.shuwei.dish.match.dialog.Loading
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.entity.FoodCollectionBean
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.model.FoodCollectionBean
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
import com.shuwei.dish.match.net.UiState
|
||||
import com.shuwei.dish.match.objbox.Food
|
||||
import com.shuwei.dish.match.objbox.FoodModule
|
||||
import com.shuwei.dish.match.objbox.ObjectBox
|
||||
import com.shuwei.dish.match.ui.CollectedFoodActivity
|
||||
import com.shuwei.dish.match.ui.SingleFragmentActivity
|
||||
import com.shuwei.dish.match.utils.BitmapSaver
|
||||
import com.shuwei.dish.match.utils.CameraUtils
|
||||
import com.shuwei.dish.match.utils.Debouncer
|
||||
import com.shuwei.dish.match.utils.ImageUploader
|
||||
import com.shuwei.dish.match.utils.ImageUtil
|
||||
import com.shuwei.dish.match.utils.LogSaveUtil
|
||||
import com.shuwei.dish.match.utils.showRawMaterialsDialog
|
||||
import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import com.shuwei.dish.match.utils.ext.toJsonString
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>() {
|
||||
@@ -53,29 +72,34 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
||||
}
|
||||
}
|
||||
|
||||
private val searchList = mutableListOf<CookFoodGoodsEntity>().apply {
|
||||
add(CookFoodGoodsEntity(goodsId = "200001", goodsName = "土豆丝"))
|
||||
add(CookFoodGoodsEntity(goodsId = "200002", goodsName = "土豆片"))
|
||||
add(CookFoodGoodsEntity(goodsId = "200003", goodsName = "土豆丁"))
|
||||
add(CookFoodGoodsEntity(goodsId = "200004", goodsName = "胡萝卜丝"))
|
||||
add(CookFoodGoodsEntity(goodsId = "200005", goodsName = "胡萝卜片"))
|
||||
add(CookFoodGoodsEntity(goodsId = "200006", goodsName = "胡萝卜丁"))
|
||||
add(CookFoodGoodsEntity(goodsId = "200007", goodsName = "黄瓜丝"))
|
||||
add(CookFoodGoodsEntity(goodsId = "200008", goodsName = "黄瓜片"))
|
||||
add(CookFoodGoodsEntity(goodsId = "200009", goodsName = "黄瓜丁"))
|
||||
add(CookFoodGoodsEntity(goodsId = "200010", goodsName = "洋葱丝"))
|
||||
add(CookFoodGoodsEntity(goodsId = "200011", goodsName = "洋葱丁"))
|
||||
}
|
||||
private var checkedItem: CookFoodGoodsEntity? = null
|
||||
private val searchList = mutableListOf<GoodsItem>()
|
||||
private var checkedItem: GoodsItem? = null
|
||||
private val searchAdapter by lazy {
|
||||
FoodSearchAdapter(searchList).apply {
|
||||
setOnItemClickListener { adapter, view, position ->
|
||||
searchList.forEachIndexed { index, item -> item.isClicked = index == position }
|
||||
checkedItem = searchList[position]
|
||||
notifyDataSetChanged()
|
||||
checkedItem?.let {
|
||||
selectedFoodId = it.foodId
|
||||
selectedFoodName = it.goodsName
|
||||
Food3Adapter(searchList).apply {
|
||||
// 开启空状态视图能力,否则 stateView 赋值不会生效
|
||||
isStateViewEnable = true
|
||||
setOnDebouncedItemClick { _, _, position ->
|
||||
val item = searchList.getOrNull(position) ?: return@setOnDebouncedItemClick
|
||||
// 弹出净材种类单选弹窗
|
||||
showRawMaterialsDialog(
|
||||
context = requireContext(),
|
||||
types = item.rawMaterialsTypes,
|
||||
checkedType = item.rawMaterialsType
|
||||
) { selectedType ->
|
||||
// 清空其他已选项的状态
|
||||
searchList.forEachIndexed { index, it ->
|
||||
if (index != position) {
|
||||
it.isClicked = false
|
||||
it.rawMaterialsType = null
|
||||
}
|
||||
}
|
||||
// 设置当前选中项
|
||||
item.isClicked = true
|
||||
item.rawMaterialsType = selectedType
|
||||
checkedItem = item
|
||||
selectedFoodId = item.goodsId
|
||||
selectedFoodName = item.goodsName
|
||||
notifyDataSetChanged()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -87,7 +111,7 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
||||
private val vectorAdapter: VectorCollectionAdapter by lazy {
|
||||
VectorCollectionAdapter(vectorList).apply {
|
||||
addOnItemChildClickListener(R.id.ivDelete) { _, _, position ->
|
||||
vectorList[position].let {
|
||||
vectorList.getOrNull(position)?.let {
|
||||
it.bitmap = null
|
||||
it.imageVector = null
|
||||
it.imageFile = null
|
||||
@@ -95,8 +119,8 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
||||
it.isShowCamera = true
|
||||
it.isFinish = false
|
||||
it.uploadSuccess = false
|
||||
notifyItemChanged(position)
|
||||
}
|
||||
notifyItemChanged(position)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -111,15 +135,16 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
||||
|
||||
//typealias CameraCallback = (Uri) -> Unit
|
||||
|
||||
private val cameraCallback: (Uri) -> Unit = cameraCallback@{ uri ->
|
||||
try {
|
||||
val index = vectorList.indexOfFirst { it.imageFile == null }
|
||||
if (index == -1) {
|
||||
toast("每次只允许保存${MAX_COUNT}条数据")
|
||||
hideWaitingDialog()
|
||||
return@cameraCallback
|
||||
}
|
||||
activity?.runOnUiThread {
|
||||
private val cameraCallback: (Uri) -> Unit = { uri ->
|
||||
lifecycleScope.launch {
|
||||
try {
|
||||
val index = vectorList.indexOfFirst { it.imageFile == null }
|
||||
if (index == -1) {
|
||||
toast("每次只允许保存${MAX_COUNT}条数据")
|
||||
hideWaitingDialog()
|
||||
return@launch
|
||||
}
|
||||
// 主线程更新 UI
|
||||
vectorList[index].let {
|
||||
it.imageVector = null
|
||||
it.bitmap = null
|
||||
@@ -128,53 +153,50 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
||||
it.imageUri = uri
|
||||
}
|
||||
vectorAdapter.notifyItemChanged(index)
|
||||
}
|
||||
// hideWaitingDialog()
|
||||
Thread {
|
||||
ImageUtil.uriToBitmap(requireActivity(), uri)?.let { bitmap ->
|
||||
getImageVector(index, bitmap)
|
||||
// 切到 IO 线程执行耗时的 Bitmap 解码
|
||||
val bitmap = withContext(Dispatchers.IO) {
|
||||
ImageUtil.uriToBitmap(requireActivity(), uri)
|
||||
}
|
||||
}.start()
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
hideWaitingDialog()
|
||||
toast("程序异常${e.message}")
|
||||
log("程序异常${e.message}")
|
||||
bitmap?.let { getImageVector(index, it) }
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
hideWaitingDialog()
|
||||
toast("程序异常${e.message}")
|
||||
log("程序异常${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun getImageVector(index: Int, bitmap: Bitmap) {
|
||||
// val bitmap = BitmapCropper.cropCenter(
|
||||
// original = srcBmp,
|
||||
// targetWidth = 900, targetHeight = 900,
|
||||
//// offsetX = 30, offsetY = 100
|
||||
// )
|
||||
val imageVector = try {
|
||||
FoodModule.bitmap2FloatArray(bitmap, false)
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
private suspend fun getImageVector(index: Int, bitmap: Bitmap) {
|
||||
// 切到 IO 线程执行耗时的向量计算和文件保存
|
||||
val (imageVector, file) = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val vector = FoodModule.bitmap2FloatArray(bitmap, false)
|
||||
val file = BitmapSaver.saveToAppFilesDir(
|
||||
bitmap, requireActivity(), "IMG_CROP_${System.currentTimeMillis()}.jpg"
|
||||
)
|
||||
log("${this.javaClass.simpleName}-cameraCallback-裁剪bitmap保存文件路径:${file?.absolutePath}")
|
||||
vector to file
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
log("操作失败:${e.message}")
|
||||
null to null
|
||||
}
|
||||
}
|
||||
// 回到主线程处理结果
|
||||
if (imageVector == null) {
|
||||
toast("操作失败")
|
||||
log("操作失败:${e.message}")
|
||||
hideWaitingDialog()
|
||||
return
|
||||
}
|
||||
val file = BitmapSaver.saveToAppFilesDir(
|
||||
bitmap, requireActivity(), "IMG_CROP_${System.currentTimeMillis()}.jpg"
|
||||
)
|
||||
log("${this.javaClass.simpleName}-cameraCallback-裁剪bitmap保存文件路径:${file?.absolutePath}")
|
||||
|
||||
activity?.runOnUiThread {
|
||||
vectorList[index].let {
|
||||
it.imageVector = imageVector
|
||||
it.bitmap = null
|
||||
it.isShowCamera = false
|
||||
it.imageFile = file
|
||||
}
|
||||
vectorAdapter.notifyItemChanged(index)
|
||||
}
|
||||
if (bitmap.isRecycled.not()) {
|
||||
bitmap.recycle()
|
||||
vectorList[index].let {
|
||||
it.imageVector = imageVector
|
||||
it.bitmap = null
|
||||
it.isShowCamera = false
|
||||
it.imageFile = file
|
||||
}
|
||||
vectorAdapter.notifyItemChanged(index)
|
||||
if (bitmap.isRecycled.not()) bitmap.recycle()
|
||||
hideWaitingDialog()
|
||||
}
|
||||
|
||||
@@ -235,27 +257,35 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
||||
}
|
||||
|
||||
binding.btnSave.setOnClickListener {
|
||||
// if (checkedItem == null || checkedItem!!.isChecked.not()) {
|
||||
// toast("请选择菜品名称")
|
||||
// return@setOnClickListener
|
||||
// }
|
||||
// val count = foodCollectionList.count { it.imageFile != null }
|
||||
// if (count == 0) {
|
||||
// toast("请拍摄菜品照片")
|
||||
// return@setOnClickListener
|
||||
// }
|
||||
// upload()
|
||||
if (checkedItem == null || checkedItem!!.isClicked.not()) {
|
||||
toast("请选择菜品名称")
|
||||
return@setOnClickListener
|
||||
}
|
||||
val count = vectorList.count { it.imageFile != null }
|
||||
if (count == 0) {
|
||||
toast("请拍摄菜品照片")
|
||||
return@setOnClickListener
|
||||
}
|
||||
upload()
|
||||
}
|
||||
|
||||
binding.editFoodName.setOnEditorActionListener { v, actionId, event ->
|
||||
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
|
||||
searchFood()
|
||||
val imm =
|
||||
v.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
|
||||
imm.hideSoftInputFromWindow(v.windowToken, 0)
|
||||
true
|
||||
} else {
|
||||
false
|
||||
binding.editFoodName.let {
|
||||
it.addTextChangedListener { editable ->
|
||||
if (editable?.isEmpty() == true) {
|
||||
searchFood()
|
||||
return@addTextChangedListener
|
||||
}
|
||||
}
|
||||
it.setOnEditorActionListener { v, actionId, event ->
|
||||
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
|
||||
searchFood()
|
||||
val imm =
|
||||
v.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
|
||||
imm.hideSoftInputFromWindow(v.windowToken, 0)
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -270,86 +300,174 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
||||
}
|
||||
takePhoto()
|
||||
}
|
||||
binding.btnClearData.setOnClickListener { clearData() }
|
||||
binding.btnClearData.setOnClickListener {
|
||||
CommonDialog(requireContext())
|
||||
.setTitle("清空确认")
|
||||
.setContent("确认清空所有已采集的图片数据?")
|
||||
.setNegativeButton("取消")
|
||||
.setPositiveButton("确认") { clearData() }
|
||||
.show()
|
||||
}
|
||||
binding.rvSearchFood.let {
|
||||
it.layoutManager = GridLayoutManager(context, 2)
|
||||
it.adapter = searchAdapter
|
||||
}
|
||||
|
||||
// 统一订阅一次,避免每次 searchFood() 重复创建 collect 协程导致多次回调
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
currentActivity.netViewModel.goodsListState.collect { state ->
|
||||
when (state) {
|
||||
is UiState.Success -> {
|
||||
val list = state.data ?: emptyList()
|
||||
if (list.isEmpty()) loadEmptyView() else fillSearchList(list)
|
||||
currentActivity.netViewModel.resetGoodsListState()
|
||||
}
|
||||
|
||||
is UiState.Error -> {
|
||||
toast(state.msg)
|
||||
loadEmptyView()
|
||||
currentActivity.netViewModel.resetGoodsListState()
|
||||
}
|
||||
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
searchFood()
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun upload() {
|
||||
// lifecycleScope.launch {
|
||||
// val totalFileCount = foodCollectionList.count { it.imageFile != null }
|
||||
// showWaitingDialog2("图片上传中0/$totalFileCount")
|
||||
// val params = HashMap<String, RequestBody>()
|
||||
// //params["placeId"] = restId.toRequestBody()
|
||||
// params["foodId"] = checkedItem!!.foodId.toRequestBody()
|
||||
// params["foodName"] = checkedItem!!.foodName!!.toRequestBody()
|
||||
// params["version"] = GlobalData.foodModelVersion.toRequestBody()
|
||||
//
|
||||
// ImageUploader(totalList = foodCollectionList, uploadImage = { batch ->
|
||||
// val files = batch.map { it.imageFile }
|
||||
// val foodVectorList = batch.filter { it.imageVector != null }.map {
|
||||
// it.imageVector!!.joinToString(
|
||||
// separator = ",", prefix = "[", postfix = "]"
|
||||
// )
|
||||
// }
|
||||
// val foodVectorJson =
|
||||
// foodVectorList.joinToString(separator = ",", prefix = "[", postfix = "]")
|
||||
// log("json=$foodVectorJson")
|
||||
// params["foodVector"] = foodVectorJson.toRequestBody()
|
||||
// viewModel?.uploadCollectFoodPics(files, params)
|
||||
// }, onProgress = { count, batch, idList ->
|
||||
// //batch.forEach {
|
||||
// // it.uploadSuccess = true
|
||||
// //}
|
||||
// runBlocking {
|
||||
// activity?.runOnUiThread {
|
||||
// showWaitingDialog("图片上传中$count/$totalFileCount")
|
||||
// }
|
||||
// val foodList = batch.mapIndexed { index, it ->
|
||||
// Food(
|
||||
// collectId = if (index < idList.size) idList[index] else null,
|
||||
// foodId = checkedItem!!.foodId,
|
||||
// foodName = checkedItem!!.foodName,
|
||||
// foodVector = it.imageVector,
|
||||
// version = GlobalData.foodModelVersion
|
||||
// )
|
||||
// }
|
||||
// ObjectBox.putAll(foodList)
|
||||
// activity?.runOnUiThread {
|
||||
// batch.forEach { it.isFinish = true }
|
||||
// collectionAdapter.notifyDataSetChanged()
|
||||
// }
|
||||
// }
|
||||
// }, onError = {
|
||||
// activity?.runOnUiThread {
|
||||
// binding.root.postDelayed({
|
||||
// hideWaitingDialog()
|
||||
// toast("上传失败,请稍后重试")
|
||||
// }, 1000)
|
||||
// }
|
||||
// }, onComplete = {
|
||||
// //vectorThread()
|
||||
// binding.root.postDelayed({
|
||||
// hideWaitingDialog()
|
||||
// toast("上传成功")
|
||||
// }, 1000)
|
||||
// }).processUploads()
|
||||
// }
|
||||
lifecycleScope.launch {
|
||||
val totalFileCount = vectorList.count { it.imageFile != null }
|
||||
// 上传场景单批可能耗时较长(含图片传输 + 网络往返),用 60s 超时兜底
|
||||
// 每次 onProgress 都会重新调用 showWaitingDialog,会重置定时器,正常进度不会触发兜底
|
||||
showWaitingDialog("图片上传中0/$totalFileCount", timeoutMs = 60_000L)
|
||||
val params = mutableMapOf<String, RequestBody>()
|
||||
params["goodsId"] = checkedItem!!.goodsId.toRequestBody()
|
||||
params["goodsName"] = checkedItem!!.goodsName!!.toRequestBody()
|
||||
//净材种类
|
||||
params["rawMaterialsTypes"] = checkedItem!!.rawMaterialsType!!.toRequestBody()
|
||||
//params["version"] = "1.0.0".toRequestBody()
|
||||
|
||||
ImageUploader(totalList = vectorList, uploadImage = { batch ->
|
||||
val files = batch.mapNotNull { it.imageFile }
|
||||
val foodVectorList = batch.filter { it.imageVector != null }.map {
|
||||
it.imageVector!!.joinToString(
|
||||
separator = ",", prefix = "[", postfix = "]"
|
||||
)
|
||||
}
|
||||
val foodVectorJson =
|
||||
foodVectorList.joinToString(separator = ",", prefix = "[", postfix = "]")
|
||||
log("json=$foodVectorJson")
|
||||
params["foodVector"] = foodVectorJson.toRequestBody()
|
||||
// 直接 await 单批上传结果,成功返回 id 列表,失败返回 null 触发 onError
|
||||
val result = currentActivity.netViewModel.uploadFoodVectorDataBatch(files, params)
|
||||
log("uploadImage返回:result=${result.toJsonString()}")
|
||||
if (result is UiState.Success) result.data to null
|
||||
else null to (result as? UiState.Error)?.msg
|
||||
}, onProgress = { count, batch, idList ->
|
||||
showWaitingDialog("图片上传中$count/$totalFileCount", timeoutMs = 60_000L)
|
||||
val foodList = batch.mapIndexed { index, it ->
|
||||
val name = checkedItem!!.goodsName + "&&" + checkedItem!!.rawMaterialsType
|
||||
Food(
|
||||
name = name,
|
||||
foodVector = it.imageVector,
|
||||
)
|
||||
}
|
||||
ObjectBox.putAll(foodList)
|
||||
batch.forEach { it.isFinish = true }
|
||||
vectorAdapter.notifyDataSetChanged()
|
||||
}, onError = { _, errorMsg ->
|
||||
binding.root.postDelayed({
|
||||
hideWaitingDialog()
|
||||
toast("上传失败:${(errorMsg ?: "").ifBlank { "请稍后重试" }}")
|
||||
}, 1000)
|
||||
}, onComplete = {
|
||||
binding.root.postDelayed({
|
||||
hideWaitingDialog()
|
||||
toast("上传成功")
|
||||
}, 1000)
|
||||
}).processUploads()
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
fun searchFood() {
|
||||
log("searchFood")
|
||||
// 立即重置,防止 StateFlow 向新订阅者重播旧的错误状态
|
||||
currentActivity.netViewModel.resetGoodsListState()
|
||||
debouncer.debounce {
|
||||
searchByFoodName(binding.editFoodName.text.toString()) {
|
||||
// searchFoodList.clear()
|
||||
// searchFoodList.addAll(it)
|
||||
// searchFoodAdapter.notifyDataSetChanged()
|
||||
val keyword = binding.editFoodName.text.toString().trim()
|
||||
currentActivity.netViewModel.queryGoodsList(
|
||||
goodsType = "0",
|
||||
goodsName = keyword.ifEmpty { null }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将数据列表填充到 searchAdapter 并切换为网格布局
|
||||
* @param list 查询到的食材列表
|
||||
*/
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun fillSearchList(list: List<GoodsItem>) {
|
||||
// 将 rawMaterialsType 转存到 rawMaterialsTypes,并清空 rawMaterialsType
|
||||
list.forEach {
|
||||
it.rawMaterialsTypes = it.rawMaterialsType
|
||||
it.rawMaterialsType = null
|
||||
it.oldGoodsId = it.goodsId
|
||||
it.goodsId = it.materId ?: ""
|
||||
}
|
||||
// 空布局切过 LinearLayoutManager,此处恢复为 2 列 GridLayoutManager
|
||||
if (binding.rvSearchFood.layoutManager !is GridLayoutManager) {
|
||||
binding.rvSearchFood.layoutManager = GridLayoutManager(context, 2)
|
||||
}
|
||||
// 清空 stateView 否则空视图会一直占位导致无法显示列表项
|
||||
searchAdapter.stateView = null
|
||||
searchList.clear()
|
||||
searchList.addAll(list)
|
||||
searchAdapter.notifyDataSetChanged()
|
||||
Log.d(TAG, "fillSearchList,${searchList.toJsonString()}")
|
||||
}
|
||||
|
||||
private var emptyViewBinding: LayoutEmptyViewBinding? = null
|
||||
|
||||
/**
|
||||
* 展示空布局
|
||||
* 默认 GridLayoutManager 会把 stateView 限制在单列宽度内,切换为 LinearLayoutManager 让空布局横向铺满;
|
||||
* 点击空布局时临时填充假数据用于效果测试,联调完成后可去除点击逻辑
|
||||
*/
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun loadEmptyView() {
|
||||
try {
|
||||
searchList.clear()
|
||||
searchAdapter.notifyDataSetChanged()
|
||||
// 切换为线性布局让空视图横向铺满,避免 Grid 模式下空布局只占一列
|
||||
binding.rvSearchFood.layoutManager = LinearLayoutManager(requireContext())
|
||||
if (emptyViewBinding == null) {
|
||||
emptyViewBinding = LayoutEmptyViewBinding.inflate(
|
||||
LayoutInflater.from(requireContext()),
|
||||
binding.rvSearchFood,
|
||||
false
|
||||
)
|
||||
}
|
||||
emptyViewBinding?.let {
|
||||
it.tvContent.text = "暂无数据"
|
||||
it.tvSubContent.text = "未查询到食材信息,请稍后重试"
|
||||
binding.rvSearchFood.post {
|
||||
it.root.minimumHeight = binding.rvSearchFood.height
|
||||
// 在 stateView 挂载完成后再设置点击监听,避免 adapter 重置 view 状态时丢失监听器
|
||||
it.root.setOnClickListener {
|
||||
searchFood()
|
||||
}
|
||||
searchAdapter.stateView = it.root
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -369,8 +487,8 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
||||
vectorAdapter.notifyDataSetChanged()
|
||||
|
||||
clickIndex = -1
|
||||
// setText("") 会触发 addTextChangedListener → searchFood(),无需再次直接调用
|
||||
binding.editFoodName.setText("")
|
||||
searchFood()
|
||||
}
|
||||
|
||||
private var isFirstOpen = true
|
||||
@@ -396,17 +514,18 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
||||
LogSaveUtil.saveLogFile(msg)
|
||||
}
|
||||
|
||||
private fun searchByFoodName(name: String, block: (String) -> Unit) {}
|
||||
private fun hideWaitingDialog() {
|
||||
currentActivity.dismissLoading()
|
||||
}
|
||||
|
||||
private fun showWaitingDialog(msg: String) {
|
||||
if (Loading.isShowing()) {
|
||||
Loading.updateContent(msg)
|
||||
return
|
||||
}
|
||||
currentActivity.showLoading(msg)
|
||||
/**
|
||||
* 显示等待弹窗
|
||||
* @param msg 提示文案
|
||||
* @param timeoutMs 超时兜底时长(毫秒):到期自动关闭,传 0 关闭兜底
|
||||
* Loading 内部已做节流,重复调用只会更新文案 + 重置超时定时器
|
||||
*/
|
||||
private fun showWaitingDialog(msg: String, timeoutMs: Long = Loading.DEFAULT_TIMEOUT_MS) {
|
||||
currentActivity.showLoading(msg, timeoutMs)
|
||||
}
|
||||
|
||||
private lateinit var previewView: PreviewView
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.shuwei.dish.match.ui.fragment
|
||||
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import com.shuwei.dish.match.base.BaseFragment
|
||||
import com.shuwei.dish.match.databinding.FragmentWeightConfigBinding
|
||||
import com.shuwei.dish.match.utils.SpTool
|
||||
import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
|
||||
/**
|
||||
* 默认减重配置 Fragment
|
||||
* 允许用户设置打开 PrepareFoodActivity 时的初始减重基准值(单位:克)
|
||||
*/
|
||||
class WeightConfigFragment : BaseFragment<FragmentWeightConfigBinding>() {
|
||||
|
||||
override fun inflateBinding(
|
||||
inflater: LayoutInflater,
|
||||
container: ViewGroup?
|
||||
): FragmentWeightConfigBinding {
|
||||
return FragmentWeightConfigBinding.inflate(inflater, container, false)
|
||||
}
|
||||
|
||||
override fun initialize() {
|
||||
// 若已有配置值则回填到输入框
|
||||
val saved = SpTool.configWeight
|
||||
if (saved != 0) {
|
||||
binding.etConfigWeight.setText(saved.toString())
|
||||
}
|
||||
|
||||
binding.btnConfirm.clickWithDebounce {
|
||||
val input = binding.etConfigWeight.text.toString().trim()
|
||||
if (input.isEmpty()) {
|
||||
toast("请输入减重值")
|
||||
return@clickWithDebounce
|
||||
}
|
||||
val weight = input.toIntOrNull()
|
||||
if (weight == null || weight < 0) {
|
||||
toast("请输入有效的减重值")
|
||||
return@clickWithDebounce
|
||||
}
|
||||
SpTool.configWeight = weight
|
||||
toast("保存成功")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import android.os.Looper
|
||||
import android.os.Process
|
||||
import android.util.Log
|
||||
import com.shuwei.dish.match.ui.HomeActivity
|
||||
import com.shuwei.dish.match.ui.InitActivity
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.io.IOException
|
||||
@@ -75,7 +76,7 @@ class CrashHandler private constructor(private val context: Context) :
|
||||
private fun restartApp() {
|
||||
// 延迟1秒后重启应用
|
||||
Handler(Looper.getMainLooper()).postDelayed({
|
||||
val intent = Intent(context, HomeActivity::class.java).apply {
|
||||
val intent = Intent(context, InitActivity::class.java).apply {
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,26 +1,26 @@
|
||||
package com.shuwei.dish.match.utils
|
||||
|
||||
import com.google.gson.TypeAdapter
|
||||
import com.google.gson.stream.JsonReader
|
||||
import com.google.gson.stream.JsonToken
|
||||
import com.google.gson.stream.JsonWriter
|
||||
|
||||
class DecimalAdapter : TypeAdapter<Number>() {
|
||||
override fun write(out: JsonWriter, value: Number) {
|
||||
// out.value(value.toString()) // 强制以字符串形式写入
|
||||
out.value("$value") // 强制以字符串形式写入
|
||||
}
|
||||
|
||||
override fun read(reader: JsonReader): Number {
|
||||
return when (reader.peek()) {
|
||||
JsonToken.NUMBER -> reader.nextDouble()
|
||||
JsonToken.STRING -> reader.nextString().toDouble()
|
||||
else -> 0.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 使用方式
|
||||
//val gson = GsonBuilder()
|
||||
// .registerTypeAdapter(Double::class.java, DecimalAdapter())
|
||||
// .create()
|
||||
//package com.shuwei.dish.match.utils
|
||||
//
|
||||
//import com.google.gson.TypeAdapter
|
||||
//import com.google.gson.stream.JsonReader
|
||||
//import com.google.gson.stream.JsonToken
|
||||
//import com.google.gson.stream.JsonWriter
|
||||
//
|
||||
//class DecimalAdapter : TypeAdapter<Number>() {
|
||||
// override fun write(out: JsonWriter, value: Number) {
|
||||
//// out.value(value.toString()) // 强制以字符串形式写入
|
||||
// out.value("$value") // 强制以字符串形式写入
|
||||
// }
|
||||
//
|
||||
// override fun read(reader: JsonReader): Number {
|
||||
// return when (reader.peek()) {
|
||||
// JsonToken.NUMBER -> reader.nextDouble()
|
||||
// JsonToken.STRING -> reader.nextString().toDouble()
|
||||
// else -> 0.0
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
//
|
||||
//// 使用方式
|
||||
////val gson = GsonBuilder()
|
||||
//// .registerTypeAdapter(Double::class.java, DecimalAdapter())
|
||||
//// .create()
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.shuwei.dish.match.utils
|
||||
|
||||
import com.shuwei.dish.match.model.FoodCollectionBean
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
class ImageUploader(
|
||||
private val totalList: List<FoodCollectionBean>,
|
||||
private val uploadImage: suspend (List<FoodCollectionBean>) -> Pair<List<String>?, String?>,
|
||||
private val onProgress: suspend (Int, List<FoodCollectionBean>, List<String>) -> Unit,
|
||||
private val onError: (List<FoodCollectionBean>, String?) -> Unit,
|
||||
private val onComplete: () -> Unit
|
||||
) {
|
||||
companion object {
|
||||
private const val BATCH_SIZE = 3
|
||||
}
|
||||
private val uploadedCount = AtomicInteger(0)
|
||||
|
||||
suspend fun processUploads() {
|
||||
val batches = totalList.filter { it.imageVector!=null }.chunked(BATCH_SIZE)
|
||||
|
||||
for (batch in batches) {
|
||||
val (idList, errorMsg) = uploadImage(batch)
|
||||
if (idList.isNullOrEmpty()) {
|
||||
onError(batch, errorMsg)
|
||||
return
|
||||
}
|
||||
val fileCount = batch.count { it.imageFile!=null }
|
||||
uploadedCount.addAndGet(fileCount)
|
||||
onProgress(uploadedCount.get(), batch, idList)
|
||||
//println("已上传 ${uploadedCount.get()}/$totalImages")
|
||||
}
|
||||
|
||||
onComplete()
|
||||
//println("流程完成,总计上传 ${uploadedCount.get()} 张图片")
|
||||
}
|
||||
|
||||
}
|
||||
@@ -3,15 +3,28 @@ package com.shuwei.dish.match.utils
|
||||
import android.content.Context
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.LinkProperties
|
||||
import android.net.NetworkCapabilities
|
||||
import android.net.wifi.WifiManager
|
||||
import android.os.Build
|
||||
import java.net.Inet4Address
|
||||
|
||||
/**
|
||||
* 网络工具类
|
||||
* 网络工具类,提供网络状态检测和本机 IP 获取功能
|
||||
*/
|
||||
object NetworkUtil {
|
||||
|
||||
/**
|
||||
* 检测设备是否连接到网络
|
||||
* @param context 应用上下文
|
||||
* @return true 表示已连接网络,false 表示未连接
|
||||
*/
|
||||
fun isNetworkConnected(context: Context): Boolean {
|
||||
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
val network = cm.activeNetwork ?: return false
|
||||
val capabilities = cm.getNetworkCapabilities(network) ?: return false
|
||||
return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取本机局域网 IPv4 地址
|
||||
* - Android 12+(API 31+):使用 ConnectivityManager + LinkProperties,避免废弃 API
|
||||
@@ -60,3 +73,4 @@ object NetworkUtil {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.shuwei.dish.match.utils
|
||||
|
||||
import android.content.Context
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.NetworkCapabilities
|
||||
|
||||
/**
|
||||
* 网络连接检测工具类
|
||||
* 提供检测设备网络连接状态的功能
|
||||
*/
|
||||
object NetworkUtils {
|
||||
|
||||
/**
|
||||
* 检测设备是否连接到网络
|
||||
* @param context 应用上下文
|
||||
* @return true 表示已连接网络,false 表示未连接
|
||||
*/
|
||||
fun isNetworkConnected(context: Context): Boolean {
|
||||
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
val network = connectivityManager.activeNetwork ?: return false
|
||||
val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return false
|
||||
return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package com.shuwei.dish.match.utils
|
||||
|
||||
import android.content.Context
|
||||
import android.content.res.ColorStateList
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.google.android.material.chip.Chip
|
||||
import com.google.android.material.chip.ChipGroup
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
|
||||
///**
|
||||
// * 构造用于效果测试的食材假数据
|
||||
// * TODO: 联调完成后删除
|
||||
// */
|
||||
//fun buildMockGoodsList(): List<GoodsItem> = mutableListOf(
|
||||
// GoodsItem(goodsId = "1", goodsName = "土豆", rawMaterialsType = "土豆丝,土豆条,土豆片,土豆丁"),
|
||||
// GoodsItem(goodsId = "2", goodsName = "胡萝卜", rawMaterialsType = "胡萝卜丝,胡萝卜片,胡萝卜丁"),
|
||||
// GoodsItem(goodsId = "3", goodsName = "黄瓜", rawMaterialsType = "黄瓜丝,黄瓜片,黄瓜丁,黄瓜块"),
|
||||
// GoodsItem(goodsId = "4", goodsName = "洋葱", rawMaterialsType = "洋葱丝,洋葱丁,洋葱圈"),
|
||||
// GoodsItem(goodsId = "5", goodsName = "白菜", rawMaterialsType = "白菜丝,白菜块,白菜叶"),
|
||||
// GoodsItem(goodsId = "6", goodsName = "豆腐", rawMaterialsType = "豆腐块,豆腐丁"),
|
||||
// GoodsItem(goodsId = "7", goodsName = "猪肉", rawMaterialsType = "猪肉丝,猪肉片,猪肉丁,猪肉块"),
|
||||
// GoodsItem(goodsId = "8", goodsName = "鸡胸肉", rawMaterialsType = "鸡胸肉丝,鸡胸肉片,鸡胸肉丁"),
|
||||
// GoodsItem(goodsId = "9", goodsName = "牛肉", rawMaterialsType = "牛肉丝,牛肉片,牛肉块"),
|
||||
// GoodsItem(goodsId = "10", goodsName = "虾仁", rawMaterialsType = "整虾仁,切段虾仁"),
|
||||
// GoodsItem(goodsId = "11", goodsName = "茄子", rawMaterialsType = "茄子丝,茄子片,茄子块,茄子条"),
|
||||
// GoodsItem(goodsId = "12", goodsName = "青椒", rawMaterialsType = "青椒丝,青椒片,青椒块"),
|
||||
// GoodsItem(goodsId = "13", goodsName = "西红柿", rawMaterialsType = "西红柿片,西红柿块,西红柿丁"),
|
||||
// GoodsItem(goodsId = "14", goodsName = "芹菜", rawMaterialsType = "芹菜段,芹菜丝"),
|
||||
// GoodsItem(goodsId = "15", goodsName = "莲藕", rawMaterialsType = "莲藕片,莲藕丁,莲藕丝"),
|
||||
// // 以下5条 rawMaterialsType 为空,测试无净材数据场景
|
||||
// GoodsItem(goodsId = "16", goodsName = "菠菜"),
|
||||
// GoodsItem(goodsId = "17", goodsName = "生菜"),
|
||||
// GoodsItem(goodsId = "18", goodsName = "香菇"),
|
||||
// GoodsItem(goodsId = "19", goodsName = "木耳"),
|
||||
// GoodsItem(goodsId = "20", goodsName = "豆芽"),
|
||||
//)
|
||||
|
||||
/**
|
||||
* 弹出净材种类单选弹窗
|
||||
* 确认选中后通过 onConfirmed 回调返回选中的种类文本,业务逻辑由调用方自行处理;
|
||||
* 无净材数据时展示提示文字,点击确认直接关闭弹窗。
|
||||
*
|
||||
* @param context 上下文
|
||||
* @param types 净材种类字符串(逗号分隔),为空时提示无数据
|
||||
* @param checkedType 弹窗打开时的默认选中项(与 types 中元素对比),null 表示无默认选中
|
||||
* @param onConfirmed 用户选中并确认后的回调,参数为选中的净材种类文本
|
||||
*/
|
||||
fun showRawMaterialsDialog(
|
||||
context: Context,
|
||||
types: String?,
|
||||
checkedType: String?,
|
||||
onConfirmed: (selectedType: String) -> Unit
|
||||
) {
|
||||
val typeList = types?.split(",")?.map { it.trim() }?.filter { it.isNotEmpty() } ?: emptyList()
|
||||
|
||||
val dialog = CommonDialog(context)
|
||||
.setTitle("选择净材种类")
|
||||
.setNegativeButton("取消")
|
||||
|
||||
if (typeList.isEmpty()) {
|
||||
// 无净材数据时仅展示提示文字
|
||||
dialog.setContent("暂无净材种类,联系管理员添加")
|
||||
.setSingleButton("确认") {}
|
||||
} else {
|
||||
// 构建单选 ChipGroup 作为自定义内容
|
||||
val chipGroup = buildSingleChoiceChipGroup(context, typeList, checkedType)
|
||||
dialog.addContentView(chipGroup) { tvContent -> tvContent.gone() }
|
||||
dialog.setPositiveButtonInterceptable("确认") {
|
||||
val checkedId = chipGroup.checkedChipId
|
||||
if (checkedId == View.NO_ID) {
|
||||
context.toast("请选择净材种类")
|
||||
// 返回 false 阻止弹窗关闭
|
||||
return@setPositiveButtonInterceptable false
|
||||
}
|
||||
onConfirmed(typeList[checkedId])
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
dialog.show()
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建单选样式的 ChipGroup
|
||||
*
|
||||
* @param context 上下文
|
||||
* @param typeList 选项文本列表,每一项作为一个 Chip 的文字
|
||||
* @param checkedType 默认选中项的文本,与 typeList 中元素相等的 Chip 会被勾选;为空则无默认选中
|
||||
* @return 配置完成的 ChipGroup,每个 Chip 的 id 即为其在 typeList 中的下标
|
||||
*/
|
||||
fun buildSingleChoiceChipGroup(
|
||||
context: Context,
|
||||
typeList: List<String>,
|
||||
checkedType: String?
|
||||
): ChipGroup {
|
||||
return ChipGroup(context).apply {
|
||||
isSingleSelection = true
|
||||
isSelectionRequired = false
|
||||
setPadding(5.dp, 40.dp, 5.dp, 40.dp)
|
||||
chipSpacingVertical = 10.dp
|
||||
chipSpacingHorizontal = 20.dp
|
||||
typeList.forEachIndexed { index, typeName ->
|
||||
val chip = Chip(context).apply {
|
||||
id = index
|
||||
text = typeName
|
||||
textSize = 22f
|
||||
isCheckable = true
|
||||
textAlignment = View.TEXT_ALIGNMENT_CENTER
|
||||
chipStartPadding = 15.dp.toFloat()
|
||||
chipEndPadding = 15.dp.toFloat()
|
||||
chipMinHeight = textSize + 15.dp * 2
|
||||
// 选中/未选中态背景色:主题绿 / 浅灰
|
||||
chipBackgroundColor = ColorStateList(
|
||||
arrayOf(
|
||||
intArrayOf(android.R.attr.state_checked),
|
||||
intArrayOf(-android.R.attr.state_checked)
|
||||
),
|
||||
intArrayOf(
|
||||
ContextCompat.getColor(context, R.color.dish_green),
|
||||
ContextCompat.getColor(context, R.color.gray_eb)
|
||||
)
|
||||
)
|
||||
// 选中/未选中态文字色:白 / 深灰
|
||||
setTextColor(
|
||||
ColorStateList(
|
||||
arrayOf(
|
||||
intArrayOf(android.R.attr.state_checked),
|
||||
intArrayOf(-android.R.attr.state_checked)
|
||||
),
|
||||
intArrayOf(
|
||||
ContextCompat.getColor(context, R.color.white),
|
||||
ContextCompat.getColor(context, R.color.black333)
|
||||
)
|
||||
)
|
||||
)
|
||||
// 隐藏默认的左侧勾选图标,让填充色作为唯一选中反馈
|
||||
isCheckedIconVisible = false
|
||||
// 去除描边
|
||||
chipStrokeWidth = 0f
|
||||
// 若当前项已有选中值则默认勾选对应选项
|
||||
isChecked = (typeName == checkedType)
|
||||
}
|
||||
// 先用 UNSPECIFIED 测出自然宽度,再取 max(自然宽, 120dp),实现"最小宽度 120dp"
|
||||
chip.measure(
|
||||
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
|
||||
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
|
||||
)
|
||||
addView(chip, ViewGroup.LayoutParams(maxOf(120.dp, chip.measuredWidth), ViewGroup.LayoutParams.WRAP_CONTENT))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.shuwei.dish.match.utils
|
||||
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.base.GlobalKey
|
||||
import com.shuwei.dish.match.utils.ext.put
|
||||
|
||||
object SpTool {
|
||||
@@ -13,6 +14,10 @@ object SpTool {
|
||||
const val DEVICE_ROLE = "deviceRole"
|
||||
/** 秤串口路径,默认 /dev/ttyS7,子设备可能需要配置为其他值 */
|
||||
const val SCALE_DEVICE_PORT = "scaleDevicePort"
|
||||
/** 食堂 ID,默认 "0" */
|
||||
const val CANTEEN_ID = "canteenId"
|
||||
/** 默认减重克数 */
|
||||
const val CONFIG_WEIGHT = "configWeight"
|
||||
|
||||
val pref = BaseApp.getSharedPref()!!
|
||||
|
||||
@@ -37,4 +42,25 @@ object SpTool {
|
||||
set(value) {
|
||||
put(LAUNCH_PAGE_TYPE, value)
|
||||
}
|
||||
|
||||
/** 默认减重(克),打开 PrepareFoodActivity 时作为 initialWeight 基准值 */
|
||||
var configWeight: Int
|
||||
get() = getInt(CONFIG_WEIGHT, 0)
|
||||
set(value) {
|
||||
put(CONFIG_WEIGHT, value)
|
||||
}
|
||||
|
||||
/** 食堂 ID,持久化存储,默认 "0" */
|
||||
var canteenId: String
|
||||
get() = getString(CANTEEN_ID, "0")
|
||||
set(value) {
|
||||
put(CANTEEN_ID, value)
|
||||
}
|
||||
|
||||
/** 环境 BaseUrl,持久化存储,默认空字符串(空时使用 GlobalData 默认值) */
|
||||
var baseUrl: String
|
||||
get() = getString(GlobalKey.KEY_BASE_URL, "")
|
||||
set(value) {
|
||||
put(GlobalKey.KEY_BASE_URL, value)
|
||||
}
|
||||
}
|
||||
@@ -1,66 +1,66 @@
|
||||
package com.shuwei.dish.match.utils
|
||||
|
||||
import androidx.recyclerview.widget.ItemTouchHelper
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.adapter.DishPartAdapter
|
||||
import com.shuwei.dish.match.adapter.FoodListAdapter
|
||||
|
||||
class SwipeCallback(
|
||||
private val adapter: BaseQuickAdapter<*,*>,
|
||||
private val callback: (position: Int) -> Unit = {}
|
||||
) :
|
||||
ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
|
||||
override fun onMove(
|
||||
recyclerView: RecyclerView,
|
||||
viewHolder: RecyclerView.ViewHolder,
|
||||
target: RecyclerView.ViewHolder
|
||||
): Boolean {
|
||||
return false // 不允许拖动,只允许滑动删除
|
||||
}
|
||||
|
||||
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
|
||||
val position = viewHolder.getBindingAdapterPosition()
|
||||
callback(position)
|
||||
}
|
||||
|
||||
override fun getMovementFlags(
|
||||
recyclerView: RecyclerView,
|
||||
viewHolder: RecyclerView.ViewHolder
|
||||
): Int {
|
||||
val position = viewHolder.getBindingAdapterPosition()
|
||||
if (position < 0) {
|
||||
return makeMovementFlags(0, 0)
|
||||
}
|
||||
// 默认的拖动和滑动方向
|
||||
val dragFlags = 0
|
||||
// ItemTouchHelper.UP or ItemTouchHelper.DOWN
|
||||
var swipeFlags = ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
|
||||
|
||||
if (adapter is FoodListAdapter) {
|
||||
if (adapter.items.isEmpty()) {
|
||||
return makeMovementFlags(0, 0)
|
||||
}
|
||||
if (!adapter.items[position].isCooking) {
|
||||
swipeFlags = 0
|
||||
}
|
||||
} else if (adapter is DishPartAdapter) {
|
||||
if (adapter.items.isEmpty()) {
|
||||
return makeMovementFlags(0, 0)
|
||||
}
|
||||
if (!adapter.items[position].isNewDishType) {
|
||||
swipeFlags = 0
|
||||
}
|
||||
}
|
||||
|
||||
// 根据viewHolder的逻辑判断是否允许滑动
|
||||
val count = recyclerView.adapter?.itemCount ?:0
|
||||
//BaseQuickAdapter中空布局使用的ViewHolder是这个import com.chad.library.adapter4.viewholder.StateLayoutVH
|
||||
if (count == 1 && viewHolder !is QuickViewHolder) {
|
||||
swipeFlags = 0 // 不允许滑动
|
||||
}
|
||||
return makeMovementFlags(dragFlags, swipeFlags)
|
||||
}
|
||||
|
||||
}
|
||||
//package com.shuwei.dish.match.utils
|
||||
//
|
||||
//import androidx.recyclerview.widget.ItemTouchHelper
|
||||
//import androidx.recyclerview.widget.RecyclerView
|
||||
//import com.chad.library.adapter4.BaseQuickAdapter
|
||||
//import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
//import com.shuwei.dish.match.adapter.DishPartAdapter
|
||||
//import com.shuwei.dish.match.adapter.FoodListAdapter
|
||||
//
|
||||
//class SwipeCallback(
|
||||
// private val adapter: BaseQuickAdapter<*,*>,
|
||||
// private val callback: (position: Int) -> Unit = {}
|
||||
//) :
|
||||
// ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
|
||||
// override fun onMove(
|
||||
// recyclerView: RecyclerView,
|
||||
// viewHolder: RecyclerView.ViewHolder,
|
||||
// target: RecyclerView.ViewHolder
|
||||
// ): Boolean {
|
||||
// return false // 不允许拖动,只允许滑动删除
|
||||
// }
|
||||
//
|
||||
// override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
|
||||
// val position = viewHolder.getBindingAdapterPosition()
|
||||
// callback(position)
|
||||
// }
|
||||
//
|
||||
// override fun getMovementFlags(
|
||||
// recyclerView: RecyclerView,
|
||||
// viewHolder: RecyclerView.ViewHolder
|
||||
// ): Int {
|
||||
// val position = viewHolder.getBindingAdapterPosition()
|
||||
// if (position < 0) {
|
||||
// return makeMovementFlags(0, 0)
|
||||
// }
|
||||
// // 默认的拖动和滑动方向
|
||||
// val dragFlags = 0
|
||||
// // ItemTouchHelper.UP or ItemTouchHelper.DOWN
|
||||
// var swipeFlags = ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
|
||||
//
|
||||
// if (adapter is FoodListAdapter) {
|
||||
// if (adapter.items.isEmpty()) {
|
||||
// return makeMovementFlags(0, 0)
|
||||
// }
|
||||
// if (!adapter.items[position].isCooking) {
|
||||
// swipeFlags = 0
|
||||
// }
|
||||
// } else if (adapter is DishPartAdapter) {
|
||||
// if (adapter.items.isEmpty()) {
|
||||
// return makeMovementFlags(0, 0)
|
||||
// }
|
||||
// if (!adapter.items[position].isNewDishType) {
|
||||
// swipeFlags = 0
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // 根据viewHolder的逻辑判断是否允许滑动
|
||||
// val count = recyclerView.adapter?.itemCount ?:0
|
||||
// //BaseQuickAdapter中空布局使用的ViewHolder是这个import com.chad.library.adapter4.viewholder.StateLayoutVH
|
||||
// if (count == 1 && viewHolder !is QuickViewHolder) {
|
||||
// swipeFlags = 0 // 不允许滑动
|
||||
// }
|
||||
// return makeMovementFlags(dragFlags, swipeFlags)
|
||||
// }
|
||||
//
|
||||
//}
|
||||
@@ -8,6 +8,8 @@ package com.shuwei.dish.match.utils;
|
||||
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
|
||||
import com.aithings.Weigher;
|
||||
import com.blankj.utilcode.util.Utils;
|
||||
import com.t507.System;
|
||||
import com.wabon.wbintelligenthardwaresdk.api.SensorScale;
|
||||
@@ -73,6 +75,7 @@ public class Weigher2 {
|
||||
|
||||
public static void unInit() {
|
||||
// $FF: Couldn't be decompiled
|
||||
Weigher.unInit();
|
||||
}
|
||||
|
||||
public static void config() {
|
||||
|
||||
@@ -3,7 +3,6 @@ package com.shuwei.dish.match.utils
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import com.shuwei.dish.match.utils.ext.roundedOneDecimalPlace
|
||||
//import com.aithings.Weigher
|
||||
import com.wabon.wbintelligenthardwaresdk.api.SensorScale
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
@@ -11,16 +10,33 @@ typealias WeightCallback = (address: Int, state: Int, weight: Double) -> Unit
|
||||
|
||||
object WeightUtil {
|
||||
private const val TAG = "WeightUtil"
|
||||
const val STATE_STABLE = SensorScale.STATE_STABLE
|
||||
const val STATE_UNSTABLE = SensorScale.STATE_UNSTABLE
|
||||
const val STATE_OVER_WEIGHT = SensorScale.STATE_OVER_WEIGHT
|
||||
// 使用字面量常量,避免在非 ARM 设备上触发 SensorScale 类加载
|
||||
const val STATE_STABLE = 1
|
||||
const val STATE_UNSTABLE = 0
|
||||
const val STATE_OVER_WEIGHT = 2
|
||||
|
||||
var isConnected = false
|
||||
/** 秤 SDK 是否可用;非 ARM 设备上为 false,所有秤操作将静默跳过 */
|
||||
var isAvailable = false
|
||||
val weightFuncMap: ConcurrentHashMap<String, WeightCallback?> = ConcurrentHashMap()
|
||||
|
||||
fun init() {
|
||||
SensorScale.isLog = true
|
||||
Weigher2.init()
|
||||
val abi = Build.SUPPORTED_ABIS.firstOrNull() ?: ""
|
||||
if (!abi.startsWith("arm")) {
|
||||
Log.w(TAG, "当前架构 $abi 不支持秤 SDK,已跳过初始化")
|
||||
return
|
||||
}
|
||||
try {
|
||||
SensorScale.isLog = true
|
||||
Weigher2.init()
|
||||
} catch (e: UnsatisfiedLinkError) {
|
||||
Log.w(TAG, "秤 SDK 加载失败(非 ARM 设备),已跳过: ${e.message}")
|
||||
return
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "秤 SDK 初始化异常,已跳过: ${e.message}")
|
||||
return
|
||||
}
|
||||
isAvailable = true
|
||||
Weigher2.setListener(object : WeightListenerImpl() {
|
||||
override fun onInit(connect: Boolean) {
|
||||
super.onInit(connect)
|
||||
@@ -39,12 +55,7 @@ object WeightUtil {
|
||||
|
||||
override fun onGetWeight(address: Int, state: Int, weight: Double) {
|
||||
super.onGetWeight(address, state, weight)
|
||||
val stateStr = when (state) {
|
||||
STATE_STABLE -> "稳定"
|
||||
STATE_UNSTABLE -> "不稳定"
|
||||
STATE_OVER_WEIGHT -> "量程溢出"
|
||||
else -> "$state"
|
||||
}
|
||||
val stateStr = getStateStr(state)
|
||||
val useWeight = (weight*1000).roundedOneDecimalPlace()
|
||||
Log.d(TAG, "readWeight, address=$address,state=$stateStr, weight=$useWeight")
|
||||
weightFuncMap.forEach { (key, value) ->
|
||||
@@ -56,6 +67,7 @@ object WeightUtil {
|
||||
}
|
||||
|
||||
fun getWeight() {
|
||||
if (!isAvailable) return
|
||||
try {
|
||||
Weigher2.getWeight()
|
||||
} catch (e: Exception) {
|
||||
@@ -64,10 +76,12 @@ object WeightUtil {
|
||||
}
|
||||
|
||||
fun startContinuousRead() {
|
||||
if (!isAvailable) return
|
||||
Weigher2.startContinuousRead()
|
||||
}
|
||||
|
||||
fun stopContinuousRead() {
|
||||
if (!isAvailable) return
|
||||
try {
|
||||
Weigher2.stopContinuousRead()
|
||||
Weigher2.unInit()
|
||||
@@ -77,6 +91,7 @@ object WeightUtil {
|
||||
}
|
||||
|
||||
fun tareTwo(address: Int) {
|
||||
if (!isAvailable) return
|
||||
try {
|
||||
Log.d(TAG, "tareTwo,执行清零操作: address=$address")
|
||||
// SDK 内部自动管理总线,直接发送清零命令
|
||||
@@ -87,6 +102,14 @@ object WeightUtil {
|
||||
}
|
||||
}
|
||||
|
||||
/** 将秤状态码转为可读字符串 */
|
||||
fun getStateStr(state: Int): String = when (state) {
|
||||
STATE_STABLE -> "稳定"
|
||||
STATE_UNSTABLE -> "不稳定"
|
||||
STATE_OVER_WEIGHT -> "量程溢出"
|
||||
else -> "$state"
|
||||
}
|
||||
|
||||
fun removeWeightListener(weightKey: String) {
|
||||
weightFuncMap.remove(weightKey)
|
||||
}
|
||||
@@ -117,14 +140,6 @@ open class WeightListenerImpl : Weigher2.Listener {
|
||||
}
|
||||
|
||||
override fun onGetWeight(address: Int, state: Int, weight: Double) {
|
||||
// val stateStr = when (state) {
|
||||
// SensorScale.STATE_STABLE -> "稳定"
|
||||
// SensorScale.STATE_UNSTABLE -> "不稳定"
|
||||
// SensorScale.STATE_OVER_WEIGHT -> "量程溢出"
|
||||
// else -> ""
|
||||
// }
|
||||
// val result1 = String.format("$stateStr 重量:%s kg", weight / 1000f)
|
||||
// Log.d("WeightUtil", "ttlReturn, address:$address,$result1")
|
||||
}
|
||||
|
||||
override fun onReadIdentify(rate: Int) {
|
||||
|
||||
@@ -31,10 +31,7 @@ fun Context.toast(
|
||||
message: String?,
|
||||
duration: Int = Toast.LENGTH_SHORT,
|
||||
) {
|
||||
if (message.isNullOrBlank()) {
|
||||
return
|
||||
}
|
||||
//Toast.makeText(this, message, duration).show()
|
||||
if (message.isNullOrBlank()) return
|
||||
ToastUtil.show(this, message, duration)
|
||||
}
|
||||
|
||||
@@ -45,28 +42,6 @@ fun Fragment.toast(
|
||||
activity?.toast(message, duration)
|
||||
}
|
||||
|
||||
//fun Fragment.toast(
|
||||
// message: String?,
|
||||
// duration: Int = 2000
|
||||
//) {
|
||||
// if (isAdded.not()) {
|
||||
// return
|
||||
// }
|
||||
// CustomToast(
|
||||
// activity = requireActivity(),
|
||||
// message = message,
|
||||
// duration = duration
|
||||
// ).show()
|
||||
//}
|
||||
//
|
||||
//public fun BaseActivity.toast(message: String?, duration: Int = 2000) {
|
||||
// CustomToast(
|
||||
// activity = this,
|
||||
// message = message,
|
||||
// duration = duration
|
||||
// ).show()
|
||||
//}
|
||||
|
||||
fun View.visible() {
|
||||
visibility = View.VISIBLE
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user