Compare commits
66
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8383af120 | ||
|
|
2f18376236 | ||
|
|
14ccc39bfd | ||
|
|
01ff7241cd | ||
|
|
ad9291243f | ||
|
|
c81e2d14bb | ||
|
|
0cc1d9189c | ||
|
|
32ec1d9b74 | ||
|
|
3fe66b513f | ||
|
|
9801534aad | ||
|
|
48d331f05d | ||
|
|
c2cf7289b7 | ||
|
|
3884738911 | ||
|
|
a25ee7d987 | ||
|
|
4a2abf6eec | ||
|
|
5d6df58e46 | ||
|
|
c4a2105737 | ||
|
|
d7a1b75fef | ||
|
|
11963b8b12 | ||
|
|
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 |
@@ -16,7 +16,7 @@ android {
|
|||||||
compileSdk = 36
|
compileSdk = 36
|
||||||
|
|
||||||
defaultConfig {
|
defaultConfig {
|
||||||
applicationId = "com.shuwei.dish.match"
|
applicationId = "com.shuwei.dish.match.new"
|
||||||
minSdk = 29
|
minSdk = 29
|
||||||
targetSdk = 36
|
targetSdk = 36
|
||||||
versionCode = 1
|
versionCode = 1
|
||||||
@@ -24,9 +24,8 @@ android {
|
|||||||
|
|
||||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
ndk {
|
ndk {
|
||||||
//设置支持的SO库架构
|
//设置支持的SO库架构;x86_64 仅用于在 Windows 模拟器上调试(秤功能不可用)
|
||||||
abiFilters.addAll(listOf("armeabi-v7a"))
|
abiFilters.addAll(listOf("armeabi-v7a", "x86_64"))
|
||||||
//, 'x86', 'armeabi-v7a', 'x86_64', 'arm64-v8a'
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 设置输出APK文件名格式
|
// 设置输出APK文件名格式
|
||||||
@@ -48,12 +47,13 @@ android {
|
|||||||
"proguard-rules.pro"
|
"proguard-rules.pro"
|
||||||
)
|
)
|
||||||
signingConfig = signingConfigs.getByName("debug_507")
|
signingConfig = signingConfigs.getByName("debug_507")
|
||||||
// buildConfigField("boolean", "DEBUG", "false")
|
buildConfigField("Boolean", "IS_TEST_DEVICE", "false")
|
||||||
}
|
}
|
||||||
debug {
|
debug {
|
||||||
//507扫码秤主板在android.buildTypes{}内增加
|
//507扫码秤主板在android.buildTypes{}内增加
|
||||||
signingConfig = signingConfigs.getByName("debug_507")
|
signingConfig = signingConfigs.getByName("debug_507")
|
||||||
// buildConfigField("boolean", "DEBUG", "true")
|
// 调试构建视为测试设备,使用固定的 DEVICE_ID_1 代替真实 UDID
|
||||||
|
buildConfigField("Boolean", "IS_TEST_DEVICE", "false")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
compileOptions {
|
compileOptions {
|
||||||
@@ -98,6 +98,7 @@ dependencies {
|
|||||||
androidTestImplementation(libs.androidx.junit)
|
androidTestImplementation(libs.androidx.junit)
|
||||||
androidTestImplementation(libs.androidx.espresso.core)
|
androidTestImplementation(libs.androidx.espresso.core)
|
||||||
implementation(libs.androidx.activity.ktx)
|
implementation(libs.androidx.activity.ktx)
|
||||||
|
implementation(libs.androidx.fragment.ktx)
|
||||||
implementation(libs.androidx.lifecycle.runtime.ktx)
|
implementation(libs.androidx.lifecycle.runtime.ktx)
|
||||||
implementation(libs.androidx.lifecycle.viewmodel.ktx)
|
implementation(libs.androidx.lifecycle.viewmodel.ktx)
|
||||||
|
|
||||||
|
|||||||
@@ -46,6 +46,7 @@
|
|||||||
android:name=".ui.InitActivity"
|
android:name=".ui.InitActivity"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
android:launchMode="singleTask"
|
android:launchMode="singleTask"
|
||||||
|
android:screenOrientation="portrait"
|
||||||
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboardHidden|keyboard|navigation|uiMode|locale|layoutDirection|fontScale|density"
|
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboardHidden|keyboard|navigation|uiMode|locale|layoutDirection|fontScale|density"
|
||||||
tools:ignore="DiscouragedApi,LockedOrientationActivity">
|
tools:ignore="DiscouragedApi,LockedOrientationActivity">
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
@@ -59,6 +60,36 @@
|
|||||||
android:screenOrientation="portrait"
|
android:screenOrientation="portrait"
|
||||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||||
|
|
||||||
|
<activity android:name=".ui.HomeV2Activity"
|
||||||
|
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||||
|
android:screenOrientation="portrait"
|
||||||
|
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||||
|
|
||||||
|
<activity android:name=".ui.CleanPackActivity"
|
||||||
|
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||||
|
android:screenOrientation="portrait"
|
||||||
|
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||||
|
|
||||||
|
<activity android:name=".ui.MealListActivity"
|
||||||
|
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||||
|
android:screenOrientation="portrait"
|
||||||
|
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||||
|
|
||||||
|
<activity android:name=".ui.PackActivity"
|
||||||
|
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||||
|
android:screenOrientation="portrait"
|
||||||
|
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||||
|
|
||||||
|
<activity android:name=".ui.TaskActivity"
|
||||||
|
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||||
|
android:screenOrientation="portrait"
|
||||||
|
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||||
|
|
||||||
|
<activity android:name=".ui.TaskDetailActivity"
|
||||||
|
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||||
|
android:screenOrientation="portrait"
|
||||||
|
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||||
|
|
||||||
<activity
|
<activity
|
||||||
android:name=".ui.CookingModeActivity"
|
android:name=".ui.CookingModeActivity"
|
||||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||||
@@ -128,6 +159,7 @@
|
|||||||
android:launchMode="singleTask"
|
android:launchMode="singleTask"
|
||||||
android:screenOrientation="landscape"
|
android:screenOrientation="landscape"
|
||||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||||
|
<activity android:name="com.shuwei.dish.match.ui.FoodSearchV2Activity" />
|
||||||
|
|
||||||
<receiver
|
<receiver
|
||||||
android:name=".utils.BootReceiver"
|
android:name=".utils.BootReceiver"
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import android.view.ViewGroup
|
|||||||
import com.chad.library.adapter4.BaseQuickAdapter
|
import com.chad.library.adapter4.BaseQuickAdapter
|
||||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||||
import com.shuwei.dish.match.databinding.ListItemCollectedFoodBinding
|
import com.shuwei.dish.match.databinding.ListItemCollectedFoodBinding
|
||||||
import com.shuwei.dish.match.entity.CollectedFoodItem
|
import com.shuwei.dish.match.model.CollectedFoodItem
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 已采集食材列表适配器
|
* 已采集食材列表适配器
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
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.ListItemDropdownBinding
|
||||||
|
import com.shuwei.dish.match.model.DictType
|
||||||
|
import com.shuwei.dish.match.utils.ext.gone
|
||||||
|
import com.shuwei.dish.match.utils.ext.visible
|
||||||
|
|
||||||
|
class DropdownAdapter(var list: MutableList<DictType>) :
|
||||||
|
BaseQuickAdapter<DictType, DropdownAdapter.VH>(list) {
|
||||||
|
|
||||||
|
inner class VH(var binding: ListItemDropdownBinding) : QuickViewHolder(binding.root)
|
||||||
|
|
||||||
|
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
||||||
|
val inflater = LayoutInflater.from(context)
|
||||||
|
val binding = ListItemDropdownBinding.inflate(inflater, parent, false)
|
||||||
|
return VH(binding)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBindViewHolder(holder: VH, position: Int, item: DictType?) {
|
||||||
|
holder.binding.tvDropdown.text = item?.value
|
||||||
|
holder.binding.divider.run {
|
||||||
|
if (position == list.size - 1) gone() else visible()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -6,7 +6,7 @@ import android.view.ViewGroup
|
|||||||
import com.chad.library.adapter4.BaseQuickAdapter
|
import com.chad.library.adapter4.BaseQuickAdapter
|
||||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||||
import com.shuwei.dish.match.databinding.ListItemFood2Binding
|
import com.shuwei.dish.match.databinding.ListItemFood2Binding
|
||||||
import com.shuwei.dish.match.entity.FoodRecord
|
import com.shuwei.dish.match.model.FoodRecord
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 菜品搜索页面的适配器
|
* 菜品搜索页面的适配器
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import android.view.ViewGroup
|
|||||||
import com.chad.library.adapter4.BaseQuickAdapter
|
import com.chad.library.adapter4.BaseQuickAdapter
|
||||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||||
import com.shuwei.dish.match.databinding.ListItemFood3Binding
|
import com.shuwei.dish.match.databinding.ListItemFood3Binding
|
||||||
import com.shuwei.dish.match.entity.GoodsItem
|
import com.shuwei.dish.match.model.GoodsItem
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 向量采集页面的适配器
|
* 向量采集页面的适配器
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import com.chad.library.adapter4.BaseQuickAdapter
|
|||||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||||
import com.shuwei.dish.match.R
|
import com.shuwei.dish.match.R
|
||||||
import com.shuwei.dish.match.databinding.ListItemFoodBinding
|
import com.shuwei.dish.match.databinding.ListItemFoodBinding
|
||||||
import com.shuwei.dish.match.entity.GoodsItem
|
import com.shuwei.dish.match.model.GoodsItem
|
||||||
import com.shuwei.dish.match.utils.ext.gone
|
import com.shuwei.dish.match.utils.ext.gone
|
||||||
import com.shuwei.dish.match.utils.ext.roundedDecimalPlace
|
import com.shuwei.dish.match.utils.ext.roundedDecimalPlace
|
||||||
import com.shuwei.dish.match.utils.ext.visible
|
import com.shuwei.dish.match.utils.ext.visible
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import com.chad.library.adapter4.BaseQuickAdapter
|
|||||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||||
import com.shuwei.dish.match.R
|
import com.shuwei.dish.match.R
|
||||||
import com.shuwei.dish.match.databinding.ListItemFoodListBinding
|
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.utils.ext.gone
|
import com.shuwei.dish.match.utils.ext.gone
|
||||||
import com.shuwei.dish.match.utils.ext.visible
|
import com.shuwei.dish.match.utils.ext.visible
|
||||||
import java.text.DecimalFormat
|
import java.text.DecimalFormat
|
||||||
@@ -86,6 +86,8 @@ class FoodListAdapter(
|
|||||||
return@run
|
return@run
|
||||||
}
|
}
|
||||||
// 非烹饪中,采样模式
|
// 非烹饪中,采样模式
|
||||||
|
tvDishName.setTextColor(ContextCompat.getColor(holder.itemView.context, R.color.dish_green))
|
||||||
|
clBlock.setBackgroundResource(R.drawable.shape_white_fb_15_corners)
|
||||||
val realTotalWeight = if (totalWeight > 0.0) totalWeight else foodWeight
|
val realTotalWeight = if (totalWeight > 0.0) totalWeight else foodWeight
|
||||||
val showTotalWeight = if (realTotalWeight == 0.0) "-" else df.format(realTotalWeight / 1000.0F)
|
val showTotalWeight = if (realTotalWeight == 0.0) "-" else df.format(realTotalWeight / 1000.0F)
|
||||||
tvDishCount.text = "累计统计:${showTotalWeight}kg(${item.count ?: "-"}次)"
|
tvDishCount.text = "累计统计:${showTotalWeight}kg(${item.count ?: "-"}次)"
|
||||||
|
|||||||
@@ -9,11 +9,12 @@ import com.chad.library.adapter4.BaseQuickAdapter
|
|||||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||||
import com.shuwei.dish.match.R
|
import com.shuwei.dish.match.R
|
||||||
import com.shuwei.dish.match.databinding.ListItemFoodMaterialBinding
|
import com.shuwei.dish.match.databinding.ListItemFoodMaterialBinding
|
||||||
import com.shuwei.dish.match.entity.GoodsItem
|
import com.shuwei.dish.match.model.GoodsItem
|
||||||
import com.shuwei.dish.match.utils.ext.gone
|
import com.shuwei.dish.match.utils.ext.gone
|
||||||
import com.shuwei.dish.match.utils.ext.roundedOneDecimalPlace
|
import com.shuwei.dish.match.utils.ext.roundedOneDecimalPlace
|
||||||
import com.shuwei.dish.match.utils.ext.visible
|
import com.shuwei.dish.match.utils.ext.visible
|
||||||
import androidx.core.graphics.toColorInt
|
import androidx.core.graphics.toColorInt
|
||||||
|
import com.shuwei.dish.match.ui.MaterialTypeTool
|
||||||
|
|
||||||
class FoodMaterialAdapter(list: MutableList<GoodsItem>) :
|
class FoodMaterialAdapter(list: MutableList<GoodsItem>) :
|
||||||
BaseQuickAdapter<GoodsItem, FoodMaterialAdapter.VH>(list) {
|
BaseQuickAdapter<GoodsItem, FoodMaterialAdapter.VH>(list) {
|
||||||
@@ -36,12 +37,17 @@ class FoodMaterialAdapter(list: MutableList<GoodsItem>) :
|
|||||||
clBlock.setOnClickListener {
|
clBlock.setOnClickListener {
|
||||||
onItemClick?.invoke(holder.bindingAdapterPosition)
|
onItemClick?.invoke(holder.bindingAdapterPosition)
|
||||||
}
|
}
|
||||||
if (data.isOriginalData) {
|
tvDishName.text = data.goodsName
|
||||||
tvDishName.text = data.goodsName
|
//if (data.isOriginalData) {
|
||||||
} else {
|
// tvDishName.text = data.goodsName
|
||||||
tvDishName.text = data.goodsName + "-${data.rawMaterialsType}"
|
//} else {
|
||||||
}
|
// tvDishName.text = data.goodsName + "-${data.rawMaterialsType}"
|
||||||
tvDishType.text = if (data.materialType == 1) "主辅材:主材" else if (data.materialType == 2) "主辅材:辅材" else ""
|
//}
|
||||||
|
val showGoodsCode = (data.materCode ?: "").ifBlank { "-" }
|
||||||
|
tvGoodsCode.text = "溯源码:$showGoodsCode"
|
||||||
|
val materialText = MaterialTypeTool.getMaterialText(data.materialType)
|
||||||
|
tvDishType.text = "主辅材:$materialText"
|
||||||
|
//if (data.materialType == 1) "主辅材:主材" else if (data.materialType == 2) "主辅材:辅材" else ""
|
||||||
tvDishWeight.text =
|
tvDishWeight.text =
|
||||||
if (data.useWeight == null || data.useWeight == 0.toDouble()) "" else "${data.useWeight!!.roundedOneDecimalPlace()}克"
|
if (data.useWeight == null || data.useWeight == 0.toDouble()) "" else "${data.useWeight!!.roundedOneDecimalPlace()}克"
|
||||||
tvDishWeight.setTextColor(
|
tvDishWeight.setTextColor(
|
||||||
@@ -54,11 +60,11 @@ class FoodMaterialAdapter(list: MutableList<GoodsItem>) :
|
|||||||
ivOperateIcon.run {
|
ivOperateIcon.run {
|
||||||
if (data.isSamplingPage) gone() else visible()
|
if (data.isSamplingPage) gone() else visible()
|
||||||
}
|
}
|
||||||
ivClearIcon.visible()
|
// ivClearIcon.visible()
|
||||||
ivClearIcon.setImageResource(
|
// ivClearIcon.setImageResource(
|
||||||
if (data.isOriginalData) R.drawable.ic_dish_clear
|
// if (data.isOriginalData) R.drawable.ic_dish_clear
|
||||||
else R.drawable.ic_delete
|
// else R.drawable.ic_delete
|
||||||
)
|
// )
|
||||||
// isOriginalData 时根据是否有重量信息控制图标颜色:无重量染灰色,有重量恢复原色
|
// isOriginalData 时根据是否有重量信息控制图标颜色:无重量染灰色,有重量恢复原色
|
||||||
if (data.isOriginalData) {
|
if (data.isOriginalData) {
|
||||||
val hasWeight = data.useWeight != null && data.useWeight != 0.0
|
val hasWeight = data.useWeight != null && data.useWeight != 0.0
|
||||||
|
|||||||
@@ -0,0 +1,245 @@
|
|||||||
|
package com.shuwei.dish.match.adapter
|
||||||
|
|
||||||
|
import android.app.DatePickerDialog
|
||||||
|
import android.content.Context
|
||||||
|
import android.text.Editable
|
||||||
|
import android.text.InputType
|
||||||
|
import android.text.Spannable
|
||||||
|
import android.text.SpannableStringBuilder
|
||||||
|
import android.text.TextWatcher
|
||||||
|
import android.text.style.ForegroundColorSpan
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import androidx.core.graphics.toColorInt
|
||||||
|
import androidx.recyclerview.widget.LinearLayoutManager
|
||||||
|
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.ListItemFormFieldBinding
|
||||||
|
import com.shuwei.dish.match.dialog.DropdownPopup
|
||||||
|
import com.shuwei.dish.match.model.FieldType
|
||||||
|
import com.shuwei.dish.match.model.FormField
|
||||||
|
import com.shuwei.dish.match.utils.ext.dp
|
||||||
|
import com.shuwei.dish.match.utils.ext.gone
|
||||||
|
import com.shuwei.dish.match.utils.ext.hideKeyboard
|
||||||
|
import com.shuwei.dish.match.utils.ext.visible
|
||||||
|
import java.text.SimpleDateFormat
|
||||||
|
import java.util.Calendar
|
||||||
|
import java.util.Locale
|
||||||
|
import kotlin.math.min
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 动态表单字段 Adapter,配合 FlexboxLayoutManager 实现两列自动换行布局
|
||||||
|
* 单一 item 布局,通过 visibility 控制 TEXT/INTEGER/DECIMAL/FIXED/DROPDOWN/DATE_PICKER 六种类型渲染
|
||||||
|
*
|
||||||
|
* @param fields 表单字段列表(hidden=false 的字段,由外部过滤后传入)
|
||||||
|
*/
|
||||||
|
class FormFieldAdapter(
|
||||||
|
fields: MutableList<FormField>
|
||||||
|
) : BaseQuickAdapter<FormField, FormFieldAdapter.VH>(fields) {
|
||||||
|
|
||||||
|
private val isoFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
|
||||||
|
private val displayDateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
|
||||||
|
|
||||||
|
inner class VH(val binding: ListItemFormFieldBinding) : QuickViewHolder(binding.root)
|
||||||
|
|
||||||
|
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
||||||
|
val binding = ListItemFormFieldBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||||
|
return VH(binding)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBindViewHolder(holder: VH, position: Int, item: FormField?) {
|
||||||
|
item ?: return
|
||||||
|
val b = holder.binding
|
||||||
|
|
||||||
|
// 设置标签,必填项追加红色星号
|
||||||
|
b.tvLabel.text = buildLabelSpannable(item.label, item.required)
|
||||||
|
|
||||||
|
// 先全部隐藏,再按类型显示对应控件
|
||||||
|
b.flInputArea.gone()
|
||||||
|
b.etInput.gone()
|
||||||
|
b.flDropdown.gone()
|
||||||
|
b.flDatePicker.gone()
|
||||||
|
b.llChildren.gone()
|
||||||
|
|
||||||
|
// 移除旧的 TextWatcher,防止 RecyclerView 复用时错误触发
|
||||||
|
(b.etInput.tag as? TextWatcher)?.let { b.etInput.removeTextChangedListener(it) }
|
||||||
|
b.etInput.tag = null
|
||||||
|
|
||||||
|
when (item.type) {
|
||||||
|
FieldType.TEXT -> bindEditText(b, item, InputType.TYPE_CLASS_TEXT)
|
||||||
|
FieldType.INTEGER -> bindEditText(b, item, InputType.TYPE_CLASS_NUMBER)
|
||||||
|
FieldType.DECIMAL -> bindEditText(
|
||||||
|
b, item,
|
||||||
|
InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL or InputType.TYPE_NUMBER_FLAG_SIGNED
|
||||||
|
)
|
||||||
|
FieldType.FIXED -> bindFixed(b, item)
|
||||||
|
FieldType.DROPDOWN -> bindDropdown(b, item)
|
||||||
|
FieldType.DATE_PICKER -> bindDatePicker(b, item)
|
||||||
|
FieldType.CHILDREN -> bindChildren(b, item)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.type == FieldType.CHILDREN) {
|
||||||
|
b.flInputArea.gone()
|
||||||
|
b.llChildren.visible()
|
||||||
|
} else {
|
||||||
|
b.flInputArea.visible()
|
||||||
|
b.llChildren.gone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 绑定可编辑文本框(TEXT / NUMBER) */
|
||||||
|
private fun bindEditText(b: ListItemFormFieldBinding, item: FormField, inputType: Int) {
|
||||||
|
b.etInput.visible()
|
||||||
|
b.etInput.isEnabled = true
|
||||||
|
b.etInput.inputType = inputType
|
||||||
|
b.etInput.hint = item.hint.ifBlank { item.label }
|
||||||
|
b.etInput.setBackgroundResource(R.drawable.bg_white_radius10_stroke2)
|
||||||
|
b.etInput.setText(item.value)
|
||||||
|
b.etInput.setSelection(b.etInput.text.length)
|
||||||
|
|
||||||
|
val watcher = object : TextWatcher {
|
||||||
|
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
|
||||||
|
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
|
||||||
|
override fun afterTextChanged(s: Editable?) {
|
||||||
|
item.value = s?.toString() ?: ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.etInput.addTextChangedListener(watcher)
|
||||||
|
b.etInput.tag = watcher
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 绑定固定值(不可编辑,灰色背景区分) */
|
||||||
|
private fun bindFixed(b: ListItemFormFieldBinding, item: FormField) {
|
||||||
|
b.etInput.visible()
|
||||||
|
b.etInput.isEnabled = false
|
||||||
|
b.etInput.inputType = InputType.TYPE_CLASS_TEXT
|
||||||
|
b.etInput.hint = ""
|
||||||
|
b.etInput.setBackgroundResource(R.drawable.bg_gray_radius10)
|
||||||
|
b.etInput.setText(item.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 绑定下拉选择框,点击时创建 DropdownPopup */
|
||||||
|
private fun bindDropdown(b: ListItemFormFieldBinding, item: FormField) {
|
||||||
|
b.flDropdown.visible()
|
||||||
|
b.tvDropdownValue.hint = item.hint.ifBlank { "请选择${item.label}" }
|
||||||
|
b.tvDropdownValue.text = item.value.ifBlank { null }
|
||||||
|
|
||||||
|
b.flDropdown.setOnClickListener { v ->
|
||||||
|
v.hideKeyboard()
|
||||||
|
val popHeight = min(item.options.size.coerceAtLeast(1), 4) * 71.dp
|
||||||
|
DropdownPopup(
|
||||||
|
context = context,
|
||||||
|
list = item.options.toMutableList(),
|
||||||
|
popWidth = v.width,
|
||||||
|
popHeight = popHeight
|
||||||
|
) { dictType ->
|
||||||
|
item.value = dictType.value ?: ""
|
||||||
|
b.tvDropdownValue.text = item.value
|
||||||
|
// 将 extraApiKeys 映射的 DictType 字段值写入 extraValues
|
||||||
|
item.extraValues.clear()
|
||||||
|
item.extraApiKeys.forEach { (apiKey, dictField) ->
|
||||||
|
item.extraValues[apiKey] = dictType[dictField]
|
||||||
|
}
|
||||||
|
// 触发选中回调
|
||||||
|
item.onDropdownSelected?.invoke(dictType)
|
||||||
|
}.also {
|
||||||
|
it.bgLayout = b.flDropdown
|
||||||
|
it.showAsDropDown(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 绑定日期选择器,点击时弹出 DatePickerDialog */
|
||||||
|
private fun bindDatePicker(b: ListItemFormFieldBinding, item: FormField) {
|
||||||
|
b.flDatePicker.visible()
|
||||||
|
b.tvDateValue.hint = item.hint.ifBlank { "请选择日期" }
|
||||||
|
b.tvDateValue.text = item.value.ifBlank { null }
|
||||||
|
|
||||||
|
b.flDatePicker.setOnClickListener { v ->
|
||||||
|
v.hideKeyboard()
|
||||||
|
val cal = Calendar.getInstance()
|
||||||
|
DatePickerDialog(
|
||||||
|
context,
|
||||||
|
{ _, year, month, dayOfMonth ->
|
||||||
|
val selected = Calendar.getInstance().apply {
|
||||||
|
set(year, month, dayOfMonth, 0, 0, 0)
|
||||||
|
set(Calendar.MILLISECOND, 0)
|
||||||
|
}
|
||||||
|
// value 存日期显示格式,供提交使用
|
||||||
|
item.value = displayDateFormat.format(selected.time)
|
||||||
|
b.tvDateValue.text = item.value
|
||||||
|
},
|
||||||
|
cal.get(Calendar.YEAR),
|
||||||
|
cal.get(Calendar.MONTH),
|
||||||
|
cal.get(Calendar.DAY_OF_MONTH)
|
||||||
|
).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 构建带红色星号的必填标签 */
|
||||||
|
private fun buildLabelSpannable(label: String, required: Boolean): SpannableStringBuilder {
|
||||||
|
return SpannableStringBuilder().apply {
|
||||||
|
append(label)
|
||||||
|
if (required) {
|
||||||
|
val start = length
|
||||||
|
append(" *")
|
||||||
|
setSpan(
|
||||||
|
ForegroundColorSpan("#FFCC0000".toColorInt()),
|
||||||
|
start, length,
|
||||||
|
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 绑定 CHILDREN 类型:渲染子列表(表头 + 嵌套 RecyclerView + 添加按钮) */
|
||||||
|
private fun bindChildren(b: ListItemFormFieldBinding, item: FormField) {
|
||||||
|
b.llChildren.visible()
|
||||||
|
b.tvAddChild.text = item.childAddLabel ?: "+ 添加"
|
||||||
|
|
||||||
|
// 初始化嵌套 RecyclerView
|
||||||
|
if (b.rvChildren.adapter == null) {
|
||||||
|
b.rvChildren.layoutManager = LinearLayoutManager(context)
|
||||||
|
}
|
||||||
|
b.rvChildren.adapter = createRowAdapter(b, item)
|
||||||
|
|
||||||
|
// 添加按钮点击
|
||||||
|
b.tvAddChild.setOnClickListener {
|
||||||
|
item.children?.let { template ->
|
||||||
|
val newRow = template.map { field ->
|
||||||
|
FormField(
|
||||||
|
label = field.label,
|
||||||
|
type = field.type,
|
||||||
|
apiKey = field.apiKey,
|
||||||
|
extraApiKeys = field.extraApiKeys,
|
||||||
|
required = field.required,
|
||||||
|
hint = field.hint,
|
||||||
|
options = field.options
|
||||||
|
)
|
||||||
|
}.toMutableList()
|
||||||
|
item.childrenRows.add(newRow)
|
||||||
|
b.rvChildren.adapter?.notifyItemInserted(item.childrenRows.size - 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 创建子列表行 Adapter */
|
||||||
|
private fun createRowAdapter(b: ListItemFormFieldBinding, item: FormField): IngredientRowAdapter {
|
||||||
|
return IngredientRowAdapter(
|
||||||
|
rows = item.childrenRows,
|
||||||
|
onDelete = onDelete@{ position ->
|
||||||
|
val adapter = b.rvChildren.adapter as? IngredientRowAdapter ?: return@onDelete
|
||||||
|
item.childrenRows.removeAt(position)
|
||||||
|
adapter.notifyItemRemoved(position)
|
||||||
|
if (position < item.childrenRows.size) {
|
||||||
|
adapter.notifyItemRangeChanged(position, item.childrenRows.size - position)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onChildClick = { _, _, _ ->
|
||||||
|
// 子字段值已直接更新到 row 的 FormField 中,无需额外操作
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -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.chad.library.adapter4.viewholder.QuickViewHolder
|
||||||
import com.shuwei.dish.match.R
|
import com.shuwei.dish.match.R
|
||||||
import com.shuwei.dish.match.databinding.ListItemHomeModeBinding
|
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.gone
|
||||||
import com.shuwei.dish.match.utils.ext.visible
|
import com.shuwei.dish.match.utils.ext.visible
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
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.R
|
||||||
|
import com.shuwei.dish.match.databinding.ListItemInboundIngredientBinding
|
||||||
|
import com.shuwei.dish.match.model.NutCleanInboundIngredientVO
|
||||||
|
import com.shuwei.dish.match.utils.ext.formatDecimal
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 已入库净菜食材列表适配器
|
||||||
|
*/
|
||||||
|
class InboundIngredientAdapter(list: MutableList<NutCleanInboundIngredientVO>) :
|
||||||
|
BaseQuickAdapter<NutCleanInboundIngredientVO, InboundIngredientAdapter.VH>(list) {
|
||||||
|
|
||||||
|
inner class VH(var binding: ListItemInboundIngredientBinding) : QuickViewHolder(binding.root)
|
||||||
|
|
||||||
|
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
||||||
|
val binding = ListItemInboundIngredientBinding.inflate(
|
||||||
|
LayoutInflater.from(context), parent, false
|
||||||
|
)
|
||||||
|
return VH(binding)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBindViewHolder(holder: VH, position: Int, item: NutCleanInboundIngredientVO?) {
|
||||||
|
item ?: return
|
||||||
|
holder.binding.run {
|
||||||
|
tvIngredientName.text = item.ingredientName ?: "-"
|
||||||
|
|
||||||
|
val traceCode = item.traceCode.takeUnless { it.isNullOrBlank() } ?: "-"
|
||||||
|
tvTraceCode.text = "溯源码:$traceCode"
|
||||||
|
|
||||||
|
val stock = item.currentStock.takeUnless { it.isNullOrBlank() } ?: "0"
|
||||||
|
tvStock.text = "库存:${stock.formatDecimal()}kg"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
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.ListItemInboundIngredient2Binding
|
||||||
|
import com.shuwei.dish.match.model.NutCleanInboundIngredientVO
|
||||||
|
import com.shuwei.dish.match.utils.ext.formatDecimal
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 已入库净菜食材列表适配器 V2
|
||||||
|
*/
|
||||||
|
class InboundIngredientV2Adapter(list: MutableList<NutCleanInboundIngredientVO>) :
|
||||||
|
BaseQuickAdapter<NutCleanInboundIngredientVO, InboundIngredientV2Adapter.VH>(list) {
|
||||||
|
|
||||||
|
inner class VH(var binding: ListItemInboundIngredient2Binding) :
|
||||||
|
QuickViewHolder(binding.root)
|
||||||
|
|
||||||
|
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
||||||
|
val binding = ListItemInboundIngredient2Binding.inflate(
|
||||||
|
LayoutInflater.from(context), parent, false
|
||||||
|
)
|
||||||
|
return VH(binding)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBindViewHolder(holder: VH, position: Int, item: NutCleanInboundIngredientVO?) {
|
||||||
|
item ?: return
|
||||||
|
holder.binding.run {
|
||||||
|
tvIngredientName.text = item.ingredientName ?: "-"
|
||||||
|
|
||||||
|
val traceCode = item.traceCode.takeUnless { it.isNullOrBlank() } ?: "-"
|
||||||
|
tvTraceCode.text = "溯源码:$traceCode"
|
||||||
|
|
||||||
|
val stock = item.currentStock.takeUnless { it.isNullOrBlank() } ?: "0"
|
||||||
|
tvStock.text = "库存:${stock.formatDecimal()}kg"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
package com.shuwei.dish.match.adapter
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.text.Editable
|
||||||
|
import android.text.TextWatcher
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.widget.TextView
|
||||||
|
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.ListItemIngredientRowBinding
|
||||||
|
import com.shuwei.dish.match.dialog.DropdownPopup
|
||||||
|
import com.shuwei.dish.match.model.FormField
|
||||||
|
import com.shuwei.dish.match.utils.ext.dp
|
||||||
|
import com.shuwei.dish.match.utils.ext.hideKeyboard
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 食材行 Adapter,用于「包含食材」子列表的嵌套渲染
|
||||||
|
* @param context Activity 上下文
|
||||||
|
* @param rows 每行包含多个 FormField,对应溯源码、食材名称、分类、用量
|
||||||
|
* @param onDelete 删除行回调
|
||||||
|
* @param onChildClick 子字段点击回调(如下拉框点击)
|
||||||
|
*/
|
||||||
|
class IngredientRowAdapter(
|
||||||
|
rows: MutableList<MutableList<FormField>>,
|
||||||
|
private val onDelete: (Int) -> Unit,
|
||||||
|
private val onChildClick: (Int, Int, FormField) -> Unit
|
||||||
|
) : BaseQuickAdapter<MutableList<FormField>, IngredientRowAdapter.VH>(rows) {
|
||||||
|
|
||||||
|
inner class VH(val binding: ListItemIngredientRowBinding) : QuickViewHolder(binding.root)
|
||||||
|
|
||||||
|
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
||||||
|
val binding = ListItemIngredientRowBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||||
|
return VH(binding)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBindViewHolder(holder: VH, position: Int, item: MutableList<FormField>?) {
|
||||||
|
item ?: return
|
||||||
|
val b = holder.binding
|
||||||
|
|
||||||
|
// 假设 children 模板顺序:[溯源码(TEXT), 食材名称(DROPDOWN), 分类(DROPDOWN), 用量(TEXT)]
|
||||||
|
val traceCodeField = item.getOrNull(0)
|
||||||
|
val materNameField = item.getOrNull(1)
|
||||||
|
val classifyField = item.getOrNull(2)
|
||||||
|
val amountField = item.getOrNull(3)
|
||||||
|
|
||||||
|
// 溯源码 - TEXT
|
||||||
|
traceCodeField?.let { field ->
|
||||||
|
b.etTraceCode.setText(field.value)
|
||||||
|
b.etTraceCode.hint = field.hint.ifBlank { field.label }
|
||||||
|
(b.etTraceCode.tag as? TextWatcher)?.let { b.etTraceCode.removeTextChangedListener(it) }
|
||||||
|
val watcher = object : TextWatcher {
|
||||||
|
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
|
||||||
|
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
|
||||||
|
override fun afterTextChanged(s: Editable?) {
|
||||||
|
field.value = s?.toString() ?: ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.etTraceCode.addTextChangedListener(watcher)
|
||||||
|
b.etTraceCode.tag = watcher
|
||||||
|
}
|
||||||
|
|
||||||
|
// 食材名称
|
||||||
|
materNameField?.let { field ->
|
||||||
|
when (field.type) {
|
||||||
|
com.shuwei.dish.match.model.FieldType.FIXED -> {
|
||||||
|
b.flMaterName.setOnClickListener { v -> v.hideKeyboard() }
|
||||||
|
b.flMaterName.isClickable = false
|
||||||
|
b.tvMaterName.text = field.value
|
||||||
|
}
|
||||||
|
else -> {
|
||||||
|
b.tvMaterName.hint = field.hint.ifBlank { "请选择${field.label}" }
|
||||||
|
b.tvMaterName.text = field.value.ifBlank { null }
|
||||||
|
b.flMaterName.setOnClickListener { v ->
|
||||||
|
v.hideKeyboard()
|
||||||
|
showDropdown(b.flMaterName, field, b.tvMaterName, holder.getAdapterPosition(), 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 分类 - DROPDOWN
|
||||||
|
classifyField?.let { field ->
|
||||||
|
b.tvClassify.hint = field.hint.ifBlank { "请选择${field.label}" }
|
||||||
|
b.tvClassify.text = field.value.ifBlank { null }
|
||||||
|
b.flClassify.setOnClickListener { v ->
|
||||||
|
v.hideKeyboard()
|
||||||
|
showDropdown(b.flClassify, field, b.tvClassify, holder.getAdapterPosition(), 2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 用量 - TEXT
|
||||||
|
amountField?.let { field ->
|
||||||
|
b.etAmount.setText(field.value)
|
||||||
|
b.etAmount.hint = field.hint.ifBlank { field.label }
|
||||||
|
(b.etAmount.tag as? TextWatcher)?.let { b.etAmount.removeTextChangedListener(it) }
|
||||||
|
val watcher = object : TextWatcher {
|
||||||
|
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
|
||||||
|
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
|
||||||
|
override fun afterTextChanged(s: Editable?) {
|
||||||
|
field.value = s?.toString() ?: ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.etAmount.addTextChangedListener(watcher)
|
||||||
|
b.etAmount.tag = watcher
|
||||||
|
}
|
||||||
|
|
||||||
|
// 删除按钮
|
||||||
|
b.tvRemove.setOnClickListener {
|
||||||
|
val pos = holder.layoutPosition
|
||||||
|
if (pos != RecyclerView.NO_POSITION) {
|
||||||
|
onDelete(pos)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 显示下拉弹出框 */
|
||||||
|
private fun showDropdown(
|
||||||
|
anchorView: ViewGroup,
|
||||||
|
field: FormField,
|
||||||
|
valueView: TextView,
|
||||||
|
rowPosition: Int,
|
||||||
|
childIndex: Int
|
||||||
|
) {
|
||||||
|
DropdownPopup(
|
||||||
|
context = context,
|
||||||
|
list = field.options.toMutableList(),
|
||||||
|
popWidth = anchorView.width,
|
||||||
|
popHeight = kotlin.math.min(field.options.size.coerceAtLeast(1), 4) * 50.dp
|
||||||
|
) { dictType ->
|
||||||
|
field.value = dictType.value ?: ""
|
||||||
|
valueView.text = field.value
|
||||||
|
// 将 extraApiKeys 映射值写入 extraValues
|
||||||
|
field.extraValues.clear()
|
||||||
|
field.extraApiKeys.forEach { (apiKey, dictField) ->
|
||||||
|
field.extraValues[apiKey] = dictType[dictField]
|
||||||
|
}
|
||||||
|
field.onDropdownSelected?.invoke(dictType)
|
||||||
|
// 回调通知外部更新
|
||||||
|
onChildClick(rowPosition, childIndex, field)
|
||||||
|
}.also {
|
||||||
|
it.bgLayout = anchorView
|
||||||
|
it.showAsDropDown(anchorView)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
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.ListItemFood2Binding
|
||||||
|
import com.shuwei.dish.match.model.NutFoodOptionVO
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 餐品列表适配器
|
||||||
|
*/
|
||||||
|
class MealListAdapter(list: MutableList<NutFoodOptionVO>) :
|
||||||
|
BaseQuickAdapter<NutFoodOptionVO, MealListAdapter.VH>(list) {
|
||||||
|
|
||||||
|
inner class VH(var binding: ListItemFood2Binding) : QuickViewHolder(binding.root)
|
||||||
|
|
||||||
|
override fun onBindViewHolder(
|
||||||
|
holder: VH,
|
||||||
|
position: Int,
|
||||||
|
item: NutFoodOptionVO?
|
||||||
|
) {
|
||||||
|
holder.binding.tvDishInfo.text = item?.foodName
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreateViewHolder(
|
||||||
|
context: Context,
|
||||||
|
parent: ViewGroup,
|
||||||
|
viewType: Int
|
||||||
|
): VH {
|
||||||
|
val inflater = LayoutInflater.from(context)
|
||||||
|
val binding = ListItemFood2Binding.inflate(inflater, parent, false)
|
||||||
|
return VH(binding)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,9 +3,11 @@ package com.shuwei.dish.match.adapter
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.view.LayoutInflater
|
import android.view.LayoutInflater
|
||||||
import android.view.ViewGroup
|
import android.view.ViewGroup
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
import androidx.recyclerview.widget.RecyclerView
|
import androidx.recyclerview.widget.RecyclerView
|
||||||
import com.chad.library.adapter4.BaseQuickAdapter
|
import com.chad.library.adapter4.BaseQuickAdapter
|
||||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
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.databinding.ListItemScaleRowBinding
|
||||||
import com.shuwei.dish.match.utils.WeightUtil
|
import com.shuwei.dish.match.utils.WeightUtil
|
||||||
|
|
||||||
@@ -40,11 +42,20 @@ class ScaleRowAdapter : BaseQuickAdapter<ScaleRowAdapter.ScaleItem, ScaleRowAdap
|
|||||||
holder.b.tvScaleLabel.text = "秤 ${item.address}"
|
holder.b.tvScaleLabel.text = "秤 ${item.address}"
|
||||||
holder.b.tvName.text = item.name.ifEmpty { "-" }
|
holder.b.tvName.text = item.name.ifEmpty { "-" }
|
||||||
holder.b.tvWeight.text = "${item.weight} g"
|
holder.b.tvWeight.text = "${item.weight} g"
|
||||||
holder.b.tvState.text = when (item.state) {
|
holder.b.tvState.text = WeightUtil.getStateStr(item.state)
|
||||||
WeightUtil.STATE_STABLE -> "稳定"
|
if (item.state == WeightUtil.STATE_OVER_WEIGHT) {
|
||||||
WeightUtil.STATE_UNSTABLE -> "不稳定"
|
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell_over_weight)
|
||||||
WeightUtil.STATE_OVER_WEIGHT -> "超量"
|
val white = ContextCompat.getColor(holder.b.root.context, R.color.white)
|
||||||
else -> "${item.state}"
|
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
|
// 点击时通过 bindingAdapterPosition 取最新数据,避免闭包捕获过期 item
|
||||||
holder.b.root.setOnClickListener {
|
holder.b.root.setOnClickListener {
|
||||||
|
|||||||
@@ -90,24 +90,34 @@ class Seasoning18GridAdapter(
|
|||||||
holder.b.tvAddress.text = "秤${item!!.address}"
|
holder.b.tvAddress.text = "秤${item!!.address}"
|
||||||
holder.b.tvName.text = if (!item.name.isNullOrBlank()) item.name else "-"
|
holder.b.tvName.text = if (!item.name.isNullOrBlank()) item.name else "-"
|
||||||
holder.b.tvWeight.text = "${item.weight}g"
|
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) {
|
val white = ContextCompat.getColor(holder.b.root.context, R.color.white)
|
||||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell_highlight)
|
when {
|
||||||
val white = ContextCompat.getColor(holder.b.root.context, R.color.white)
|
valid && item!!.state == WeightUtil.STATE_OVER_WEIGHT -> {
|
||||||
holder.b.tvAddress.setTextColor(white)
|
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell_over_weight)
|
||||||
holder.b.tvName.setTextColor(white)
|
holder.b.tvAddress.setTextColor(white)
|
||||||
holder.b.tvWeight.setTextColor(white)
|
holder.b.tvName.setTextColor(white)
|
||||||
holder.b.tvState.setTextColor(white)
|
holder.b.tvWeight.setTextColor(white)
|
||||||
} else {
|
holder.b.tvState.setTextColor(white)
|
||||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell)
|
}
|
||||||
val normal = ContextCompat.getColor(holder.b.root.context, R.color.home_title)
|
position == highlightedPosition -> {
|
||||||
val sub = ContextCompat.getColor(holder.b.root.context, R.color.home_sub_title)
|
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell_highlight)
|
||||||
val black = ContextCompat.getColor(holder.b.root.context, R.color.black)
|
holder.b.tvAddress.setTextColor(white)
|
||||||
holder.b.tvAddress.setTextColor(sub)
|
holder.b.tvName.setTextColor(white)
|
||||||
holder.b.tvName.setTextColor(black)
|
holder.b.tvWeight.setTextColor(white)
|
||||||
holder.b.tvWeight.setTextColor(normal)
|
holder.b.tvState.setTextColor(white)
|
||||||
holder.b.tvState.setTextColor(sub)
|
}
|
||||||
|
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>) {
|
fun updateByAddress(scales: List<ScaleData>) {
|
||||||
update(scales)
|
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.tvAddress.text = "秤${item!!.address}"
|
||||||
holder.b.tvName.text = if (!item.name.isNullOrBlank()) item.name else "-"
|
holder.b.tvName.text = if (!item.name.isNullOrBlank()) item.name else "-"
|
||||||
holder.b.tvWeight.text = "${item.weight}g"
|
holder.b.tvWeight.text = "${item.weight}g"
|
||||||
holder.b.tvState.text = stateStr(item.state)
|
holder.b.tvState.text = WeightUtil.getStateStr(item.state)
|
||||||
}
|
}
|
||||||
// 高亮格子:红底白字;其余恢复默认
|
val white = ContextCompat.getColor(holder.b.root.context, R.color.white)
|
||||||
if (position == highlightedPosition) {
|
when {
|
||||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell_highlight)
|
valid && item!!.state == WeightUtil.STATE_OVER_WEIGHT -> {
|
||||||
val white = ContextCompat.getColor(holder.b.root.context, R.color.white)
|
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell_over_weight)
|
||||||
holder.b.tvAddress.setTextColor(white)
|
holder.b.tvAddress.setTextColor(white)
|
||||||
holder.b.tvName.setTextColor(white)
|
holder.b.tvName.setTextColor(white)
|
||||||
holder.b.tvWeight.setTextColor(white)
|
holder.b.tvWeight.setTextColor(white)
|
||||||
holder.b.tvState.setTextColor(white)
|
holder.b.tvState.setTextColor(white)
|
||||||
} else {
|
}
|
||||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell)
|
position == highlightedPosition -> {
|
||||||
val normal = ContextCompat.getColor(holder.b.root.context, R.color.home_title)
|
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell_highlight)
|
||||||
val sub = ContextCompat.getColor(holder.b.root.context, R.color.home_sub_title)
|
holder.b.tvAddress.setTextColor(white)
|
||||||
val black = ContextCompat.getColor(holder.b.root.context, R.color.black)
|
holder.b.tvName.setTextColor(white)
|
||||||
holder.b.tvAddress.setTextColor(sub)
|
holder.b.tvWeight.setTextColor(white)
|
||||||
holder.b.tvName.setTextColor(black)
|
holder.b.tvState.setTextColor(white)
|
||||||
holder.b.tvWeight.setTextColor(normal)
|
}
|
||||||
holder.b.tvState.setTextColor(sub)
|
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>) {
|
fun updateByAddress(scales: List<ScaleData>) {
|
||||||
update(scales)
|
update(scales)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun stateStr(state: Int) = when (state) {
|
|
||||||
WeightUtil.STATE_STABLE -> "稳定"
|
|
||||||
WeightUtil.STATE_UNSTABLE -> "不稳定"
|
|
||||||
WeightUtil.STATE_OVER_WEIGHT -> "超量"
|
|
||||||
else -> ""
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,8 +7,8 @@ import androidx.core.content.ContextCompat
|
|||||||
import com.chad.library.adapter4.BaseQuickAdapter
|
import com.chad.library.adapter4.BaseQuickAdapter
|
||||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||||
import com.shuwei.dish.match.R
|
import com.shuwei.dish.match.R
|
||||||
import com.shuwei.dish.match.databinding.ListItemFoodBinding
|
import com.shuwei.dish.match.databinding.ListItemSeasoningBinding
|
||||||
import com.shuwei.dish.match.entity.GoodsItem
|
import com.shuwei.dish.match.model.GoodsItem
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 调料搜索弹窗适配器
|
* 调料搜索弹窗适配器
|
||||||
@@ -23,10 +23,6 @@ class SeasoningSearchAdapter(private var list: MutableList<GoodsItem>) :
|
|||||||
) {
|
) {
|
||||||
holder.binding.tvGoodsInfo.run {
|
holder.binding.tvGoodsInfo.run {
|
||||||
text = item?.goodsName
|
text = item?.goodsName
|
||||||
setBackgroundResource(
|
|
||||||
if (item?.isClicked == true) R.drawable.shape_green_stroke
|
|
||||||
else R.drawable.shape_white_12_corners
|
|
||||||
)
|
|
||||||
setTextColor(
|
setTextColor(
|
||||||
ContextCompat.getColor(
|
ContextCompat.getColor(
|
||||||
context,
|
context,
|
||||||
@@ -35,6 +31,10 @@ class SeasoningSearchAdapter(private var list: MutableList<GoodsItem>) :
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
holder.binding.root.setBackgroundResource(
|
||||||
|
if (item?.isClicked == true) R.drawable.shape_green_stroke
|
||||||
|
else R.drawable.shape_white_12_corners
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onCreateViewHolder(
|
override fun onCreateViewHolder(
|
||||||
@@ -43,10 +43,10 @@ class SeasoningSearchAdapter(private var list: MutableList<GoodsItem>) :
|
|||||||
viewType: Int
|
viewType: Int
|
||||||
): VH {
|
): VH {
|
||||||
val binding =
|
val binding =
|
||||||
ListItemFoodBinding.inflate(LayoutInflater.from(context), parent, false)
|
ListItemSeasoningBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||||
return VH(binding)
|
return VH(binding)
|
||||||
}
|
}
|
||||||
|
|
||||||
inner class VH(var binding: ListItemFoodBinding) : QuickViewHolder(binding.root)
|
inner class VH(var binding: ListItemSeasoningBinding) : 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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
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.R
|
||||||
|
import com.shuwei.dish.match.databinding.ListItemTaskBinding
|
||||||
|
import com.shuwei.dish.match.model.NutComboTaskVO
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 组配任务列表适配器
|
||||||
|
*/
|
||||||
|
class TaskAdapter(list: MutableList<NutComboTaskVO>) :
|
||||||
|
BaseQuickAdapter<NutComboTaskVO, TaskAdapter.VH>(list) {
|
||||||
|
|
||||||
|
inner class VH(var binding: ListItemTaskBinding) : QuickViewHolder(binding.root)
|
||||||
|
|
||||||
|
override fun onBindViewHolder(
|
||||||
|
holder: VH,
|
||||||
|
position: Int,
|
||||||
|
item: NutComboTaskVO?
|
||||||
|
) {
|
||||||
|
holder.binding.apply {
|
||||||
|
tvTaskNo.text = "任务编号:${item?.taskNo}"
|
||||||
|
tvTargetDish.text = item?.targetDish
|
||||||
|
tvSpec.text = item?.spec
|
||||||
|
tvPlanDate.text = "计划日期:${item?.planDate}"
|
||||||
|
tvPortions.text = "总份数:${item?.portions}"
|
||||||
|
tvOwnerName.text = "负责人:${item?.ownerName}"
|
||||||
|
|
||||||
|
// 状态文本映射
|
||||||
|
val statusText = when (item?.comboStatus) {
|
||||||
|
0 -> "待组配"
|
||||||
|
1 -> "组配中"
|
||||||
|
2 -> "已完成"
|
||||||
|
else -> "未知"
|
||||||
|
}
|
||||||
|
tvStatus.text = statusText
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreateViewHolder(
|
||||||
|
context: Context,
|
||||||
|
parent: ViewGroup,
|
||||||
|
viewType: Int
|
||||||
|
): VH {
|
||||||
|
val inflater = LayoutInflater.from(context)
|
||||||
|
val binding = ListItemTaskBinding.inflate(inflater, parent, false)
|
||||||
|
return VH(binding)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
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.graphics.toColorInt
|
||||||
|
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.ListItemTaskDetailBinding
|
||||||
|
import com.shuwei.dish.match.model.NutComboTaskItemDetail
|
||||||
|
import com.shuwei.dish.match.ui.MaterialTypeTool
|
||||||
|
import com.shuwei.dish.match.utils.ext.formatDecimal
|
||||||
|
import com.shuwei.dish.match.utils.ext.gone
|
||||||
|
import com.shuwei.dish.match.utils.ext.visible
|
||||||
|
import java.math.BigDecimal
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 组配任务详情食材列表适配器
|
||||||
|
* Adapter for displaying ingredient list in task details
|
||||||
|
*/
|
||||||
|
class TaskDetailAdapter(list: MutableList<NutComboTaskItemDetail>) :
|
||||||
|
BaseQuickAdapter<NutComboTaskItemDetail, TaskDetailAdapter.VH>(list) {
|
||||||
|
|
||||||
|
// ViewHolder class for holding the view bindings
|
||||||
|
inner class VH(var binding: ListItemTaskDetailBinding) : QuickViewHolder(binding.root)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called by RecyclerView to display the item at the specified position.
|
||||||
|
* This method updates the ViewHolder's contents with the item's data.
|
||||||
|
*
|
||||||
|
* @param holder The ViewHolder to be updated
|
||||||
|
* @param position The position of the item in the adapter
|
||||||
|
* @param item The NutComboTaskItemDetail to be displayed
|
||||||
|
*/
|
||||||
|
override fun onBindViewHolder(
|
||||||
|
holder: VH,
|
||||||
|
position: Int,
|
||||||
|
item: NutComboTaskItemDetail?
|
||||||
|
) {
|
||||||
|
item ?: return
|
||||||
|
holder.binding.apply {
|
||||||
|
// Set ingredient name
|
||||||
|
tvIngredientName.text = item.ingredientName
|
||||||
|
|
||||||
|
// 食材类别
|
||||||
|
// val classText = when (item.ingredientClass) {
|
||||||
|
// 1 -> "主材"
|
||||||
|
// 2 -> "辅材"
|
||||||
|
// 3 -> "调料"
|
||||||
|
// else -> "-"
|
||||||
|
// }
|
||||||
|
tvIngredientClass.text = MaterialTypeTool.getMaterialText(item.ingredientClass ?: 0)
|
||||||
|
|
||||||
|
val unit = item.unit ?: "g"
|
||||||
|
tvPerPortionQty.text = "每份用量:${item.perPortionQty.formatDecimal()}${unit}"
|
||||||
|
tvActualQty.run {
|
||||||
|
if (item.actualQty.isNullOrBlank()) {
|
||||||
|
setTextColor("#999999".toColorInt())
|
||||||
|
text = "-"
|
||||||
|
} else {
|
||||||
|
setTextColor("#00BC71".toColorInt())
|
||||||
|
text = item.actualQty.formatDecimal() + unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// tvTotalQty.text = "合计用量:${item?.totalQty.formatDecimal()}${unit}"
|
||||||
|
|
||||||
|
tvTraceCode.visible()
|
||||||
|
tvTraceCode.text = "溯源码:${(item.traceCode ?: "").ifBlank { "-" }}"
|
||||||
|
|
||||||
|
// val hasWeight = item.actualQty.isNullOrBlank().not()
|
||||||
|
// ivClearIcon.imageTintList = if (hasWeight) null else ColorStateList.valueOf("#BFBFBF".toColorInt())
|
||||||
|
|
||||||
|
ivOperateIcon.setImageResource(
|
||||||
|
if (item.isSetFinished == true) R.drawable.ic_dish_selected
|
||||||
|
else R.drawable.ic_dish_unselected
|
||||||
|
)
|
||||||
|
|
||||||
|
root.setBackgroundResource(
|
||||||
|
if (item.isClicked == true) R.drawable.shape_item_cook_dish
|
||||||
|
else R.drawable.shape_white_fb_15_corners
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreateViewHolder(
|
||||||
|
context: Context,
|
||||||
|
parent: ViewGroup,
|
||||||
|
viewType: Int
|
||||||
|
): VH {
|
||||||
|
val inflater = LayoutInflater.from(context)
|
||||||
|
val binding = ListItemTaskDetailBinding.inflate(inflater, parent, false)
|
||||||
|
return VH(binding)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,7 +9,7 @@ import com.chad.library.adapter4.BaseQuickAdapter
|
|||||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||||
import com.shuwei.dish.match.R
|
import com.shuwei.dish.match.R
|
||||||
import com.shuwei.dish.match.databinding.ListItemVectorCollectionBinding
|
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
|
import com.shuwei.dish.match.utils.ext.load
|
||||||
|
|
||||||
class VectorCollectionAdapter (var list: MutableList<FoodCollectionBean>) :
|
class VectorCollectionAdapter (var list: MutableList<FoodCollectionBean>) :
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import android.content.pm.ActivityInfo
|
|||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.os.Handler
|
import android.os.Handler
|
||||||
import android.os.Looper
|
import android.os.Looper
|
||||||
|
import android.util.Log
|
||||||
import android.view.View
|
import android.view.View
|
||||||
import android.widget.FrameLayout
|
import android.widget.FrameLayout
|
||||||
import android.widget.ImageView
|
import android.widget.ImageView
|
||||||
@@ -37,6 +38,7 @@ import kotlin.getValue
|
|||||||
open class BaseActivity : AppCompatActivity() {
|
open class BaseActivity : AppCompatActivity() {
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
const val TAG = "BaseActivity"
|
||||||
/** 日期时间格式化器,复用避免每秒重复创建 */
|
/** 日期时间格式化器,复用避免每秒重复创建 */
|
||||||
private val DATE_FORMATTER =
|
private val DATE_FORMATTER =
|
||||||
DateTimeFormatter.ofPattern("yyyy年MM月dd日 EEEE***HH:mm:ss", Locale.CHINA)
|
DateTimeFormatter.ofPattern("yyyy年MM月dd日 EEEE***HH:mm:ss", Locale.CHINA)
|
||||||
@@ -49,10 +51,10 @@ open class BaseActivity : AppCompatActivity() {
|
|||||||
// 提前隐藏系统栏,避免窗口创建时导航栏闪烁
|
// 提前隐藏系统栏,避免窗口创建时导航栏闪烁
|
||||||
hideSystemBars()
|
hideSystemBars()
|
||||||
// 主设备竖屏,子设备横屏
|
// 主设备竖屏,子设备横屏
|
||||||
requestedOrientation = if (GlobalData.deviceRole == DeviceRole.MASTER)
|
// requestedOrientation = if (GlobalData.deviceRole == DeviceRole.MASTER)
|
||||||
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
|
// ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
|
||||||
else
|
// else
|
||||||
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
|
// ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
|
||||||
ActivityManager.addActivity(this)
|
ActivityManager.addActivity(this)
|
||||||
binding = ActivityBaseBinding.inflate(layoutInflater)
|
binding = ActivityBaseBinding.inflate(layoutInflater)
|
||||||
if (this !is InitActivity || GlobalData.deviceRole == DeviceRole.SLAVE) {
|
if (this !is InitActivity || GlobalData.deviceRole == DeviceRole.SLAVE) {
|
||||||
@@ -71,7 +73,8 @@ open class BaseActivity : AppCompatActivity() {
|
|||||||
|
|
||||||
override fun onDestroy() {
|
override fun onDestroy() {
|
||||||
handler.removeCallbacksAndMessages(null)
|
handler.removeCallbacksAndMessages(null)
|
||||||
dismissLoading()
|
// 只关闭自己弹出的 Loading,防止误关其他 Activity 的 Loading
|
||||||
|
Loading.dismissIfOwnedBy(this)
|
||||||
super.onDestroy()
|
super.onDestroy()
|
||||||
ActivityManager.removeActivity(this)
|
ActivityManager.removeActivity(this)
|
||||||
}
|
}
|
||||||
@@ -92,13 +95,13 @@ open class BaseActivity : AppCompatActivity() {
|
|||||||
titleBarAction: ((FrameLayout) -> Unit)? = null,
|
titleBarAction: ((FrameLayout) -> Unit)? = null,
|
||||||
backAction: ((ImageView) -> Unit)? = null,
|
backAction: ((ImageView) -> Unit)? = null,
|
||||||
titleAction: ((TextView) -> Unit)? = null,
|
titleAction: ((TextView) -> Unit)? = null,
|
||||||
rightIconActon: ((ImageView) -> Unit)? = null
|
rightIconAction: ((ImageView) -> Unit)? = null
|
||||||
) {
|
) {
|
||||||
binding.llTitleBar.visible()
|
binding.llTitleBar.visible()
|
||||||
titleBarAction?.invoke(binding.llTitleBar)
|
titleBarAction?.invoke(binding.llTitleBar)
|
||||||
backAction?.invoke(binding.ivBack)
|
backAction?.invoke(binding.ivBack)
|
||||||
titleAction?.invoke(binding.tvTitle)
|
titleAction?.invoke(binding.tvTitle)
|
||||||
rightIconActon?.invoke(binding.ivRightIcon)
|
rightIconAction?.invoke(binding.ivRightIcon)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setHeaderBgVisible(show: Boolean) {
|
fun setHeaderBgVisible(show: Boolean) {
|
||||||
@@ -150,22 +153,25 @@ open class BaseActivity : AppCompatActivity() {
|
|||||||
handler.removeCallbacks(updateTask)
|
handler.removeCallbacks(updateTask)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun showLoading(msg: String = "加载中……") {
|
fun showLoading(msg: String = "加载中……", timeoutMs: Long = Loading.DEFAULT_TIMEOUT_MS) {
|
||||||
handler.post {
|
handler.post {
|
||||||
Loading.show(
|
Loading.show(
|
||||||
context = this,
|
context = this,
|
||||||
message = msg
|
message = msg,
|
||||||
|
timeoutMs = timeoutMs
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun dismissLoading() {
|
fun dismissLoading() {
|
||||||
|
Log.d(TAG, "dismissLoading, ${this.javaClass.simpleName}")
|
||||||
handler.post {
|
handler.post {
|
||||||
Loading.dismiss()
|
Loading.dismiss()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun delayDismissLoading() {
|
fun delayDismissLoading() {
|
||||||
|
Log.d(TAG, "delayDismissLoading, ${this.javaClass.simpleName}")
|
||||||
handler.postDelayed({
|
handler.postDelayed({
|
||||||
Loading.dismiss()
|
Loading.dismiss()
|
||||||
}, 500)
|
}, 500)
|
||||||
@@ -182,7 +188,7 @@ open class BaseActivity : AppCompatActivity() {
|
|||||||
|
|
||||||
|
|
||||||
val netViewModel: NetViewModel by viewModels()
|
val netViewModel: NetViewModel by viewModels()
|
||||||
val appViewModel: DbViewModel by viewModels()
|
val dbViewModel: DbViewModel by viewModels()
|
||||||
|
|
||||||
private var singlePermissionCallback: ((isGranted: Boolean) -> Unit)? = null
|
private var singlePermissionCallback: ((isGranted: Boolean) -> Unit)? = null
|
||||||
private var multiplePermissionsCallback: ((isGranted: Boolean) -> Unit)? = null
|
private var multiplePermissionsCallback: ((isGranted: Boolean) -> Unit)? = null
|
||||||
|
|||||||
@@ -1,82 +1,100 @@
|
|||||||
package com.shuwei.dish.match.base
|
package com.shuwei.dish.match.base
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
import android.app.Application
|
import android.app.Application
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.content.IntentFilter
|
import android.content.IntentFilter
|
||||||
import android.content.SharedPreferences
|
import android.content.SharedPreferences
|
||||||
|
import android.os.Bundle
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
|
import com.shuwei.dish.match.BuildConfig
|
||||||
import com.shuwei.dish.match.R
|
import com.shuwei.dish.match.R
|
||||||
import com.shuwei.dish.match.db.DatabaseProvider
|
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.ScaleDeviceConfig
|
||||||
import com.shuwei.dish.match.scale.ScaleServiceManager
|
|
||||||
import com.shuwei.dish.match.utils.AppUtil
|
import com.shuwei.dish.match.utils.AppUtil
|
||||||
import com.shuwei.dish.match.utils.BootReceiver
|
import com.shuwei.dish.match.utils.BootReceiver
|
||||||
import com.shuwei.dish.match.utils.CrashHandler
|
import com.shuwei.dish.match.utils.CrashHandler
|
||||||
import com.shuwei.dish.match.utils.Weigher2
|
import com.shuwei.dish.match.utils.SpTool
|
||||||
|
import com.shuwei.dish.match.utils.WeightUtil
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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() {
|
class BaseApp : Application() {
|
||||||
|
|
||||||
// Lazy initialization of the database instance
|
|
||||||
val database by lazy { DatabaseProvider(this).instance }
|
val database by lazy { DatabaseProvider(this).instance }
|
||||||
|
|
||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
// Set the application instance
|
|
||||||
instance = this
|
instance = this
|
||||||
// Initialize crash handler for error tracking
|
// 读取本地保存的环境地址,覆盖默认值
|
||||||
CrashHandler.init(this)
|
val savedBaseUrl = SpTool.baseUrl
|
||||||
// Get and store the unique device ID
|
if (savedBaseUrl.isNotEmpty()) {
|
||||||
val deviceId = AppUtil.getUDID(this)
|
GlobalData.appBaseUrl = savedBaseUrl
|
||||||
Log.d(TAG, "onCreate: deviceId=$deviceId")
|
|
||||||
GlobalData.deviceId = deviceId
|
|
||||||
|
|
||||||
// 根据设备 ID 判断角色:指定 ID 为主设备,其余为子设备
|
|
||||||
// 主设备是/dev/ttyS7,子设备是/dev/ttyS4
|
|
||||||
if (deviceId == ScaleDeviceConfig.DEVICE_ID_2) {
|
|
||||||
GlobalData.deviceRole = DeviceRole.MASTER
|
|
||||||
Weigher2.setDevicePort("/dev/ttyS7")
|
|
||||||
} else {
|
|
||||||
GlobalData.deviceRole = DeviceRole.SLAVE
|
|
||||||
Weigher2.setDevicePort("/dev/ttyS4")
|
|
||||||
}
|
}
|
||||||
Log.d(TAG, "设备角色: ${GlobalData.deviceRole}")
|
CrashHandler.init(this)
|
||||||
|
|
||||||
|
GlobalData.deviceId = AppUtil.getUDID(this)
|
||||||
|
|
||||||
|
// 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 为主设备,其余为子设备
|
||||||
|
// // 主设备是/dev/ttyS7,子设备是/dev/ttyS4
|
||||||
|
// if (deviceId == ScaleDeviceConfig.DEVICE_ID_2) {
|
||||||
|
// GlobalData.deviceRole = DeviceRole.MASTER
|
||||||
|
// Weigher2.setDevicePort("/dev/ttyS7")
|
||||||
|
// } else {
|
||||||
|
// GlobalData.deviceRole = DeviceRole.SLAVE
|
||||||
|
// Weigher2.setDevicePort("/dev/ttyS4")
|
||||||
|
// }
|
||||||
|
// Log.d(TAG, "设备角色: ${GlobalData.deviceRole}")
|
||||||
|
//
|
||||||
|
// // 启动秤服务(主设备多启动发现+聚合,子设备只启动服务端+注册)
|
||||||
|
// 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) {}
|
||||||
|
})
|
||||||
|
|
||||||
// 启动秤服务(主设备多启动发现+聚合,子设备只启动服务端+注册)
|
|
||||||
ScaleServiceManager.start(this)
|
|
||||||
// GlobalData.deviceId = "39a7abdd06b3c7ab"
|
// GlobalData.deviceId = "39a7abdd06b3c7ab"
|
||||||
val filter = IntentFilter(Intent.ACTION_BOOT_COMPLETED)
|
val filter = IntentFilter(Intent.ACTION_BOOT_COMPLETED)
|
||||||
registerReceiver(BootReceiver(), filter)
|
registerReceiver(BootReceiver(), filter)
|
||||||
ObjectBox.init(this)
|
// ObjectBox.init(this)
|
||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
private val TAG = "BaseApp"
|
private val TAG = "BaseApp"
|
||||||
// const val canteenId = "1678234139391512577"
|
|
||||||
var canteenId = "0"
|
var canteenId = "0"
|
||||||
// var configUrl = ""
|
|
||||||
|
|
||||||
// var token: String? = null
|
|
||||||
// var deviceId: String? = null
|
|
||||||
var appVersion: String = "1"
|
var appVersion: String = "1"
|
||||||
|
|
||||||
@Volatile
|
@Volatile
|
||||||
private var sharedPref: SharedPreferences? = null
|
private var sharedPref: SharedPreferences? = null
|
||||||
|
|
||||||
public var instance: BaseApp? = null
|
lateinit var instance: BaseApp
|
||||||
fun getSharedPref(): SharedPreferences? {
|
|
||||||
if (sharedPref != null) {
|
/** 双重检查锁,保证多线程下只初始化一次 */
|
||||||
return sharedPref
|
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,13 +8,16 @@ package com.shuwei.dish.match.base
|
|||||||
enum class DeviceRole { MASTER, SLAVE }
|
enum class DeviceRole { MASTER, SLAVE }
|
||||||
|
|
||||||
object GlobalData {
|
object GlobalData {
|
||||||
var appBaseUrl: String = TEST_BASE_URL
|
var appBaseUrl: String = LOCAL_BASE_URL
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 具体业务 BaseUrl
|
* 具体业务 BaseUrl
|
||||||
*/
|
*/
|
||||||
const val TEST_BASE_URL = "http://192.168.1.201:14801"
|
// const val LOCAL_BASE_URL = "http://192.168.1.201:14801"
|
||||||
const val UAT_BASE_URL = "https://dev.yixiong-tech.com:8081"
|
const val LOCAL_BASE_URL = "http://192.168.10.101:24801"
|
||||||
|
|
||||||
|
const val TEST_BASE_URL = "https://dev.yixiong-tech.com:8081"
|
||||||
|
// const val TEST_BASE_URL = "https://dev.yixiong-tech.com:8083"
|
||||||
const val PROD_BASE_URL = "https://api.dm.yixiong-tech.com:8443"
|
const val PROD_BASE_URL = "https://api.dm.yixiong-tech.com:8443"
|
||||||
/**
|
/**
|
||||||
* 设备id
|
* 设备id
|
||||||
@@ -25,8 +28,8 @@ object GlobalData {
|
|||||||
* 当前设备角色,启动时从 SpTool 读取,默认为 SLAVE
|
* 当前设备角色,启动时从 SpTool 读取,默认为 SLAVE
|
||||||
*/
|
*/
|
||||||
var deviceRole: DeviceRole = DeviceRole.SLAVE
|
var deviceRole: DeviceRole = DeviceRole.SLAVE
|
||||||
var appId = "Hkz1rBk6PZXbS8KwKr67K2eZtsz8bRoMHLg64bUdgCZj"
|
|
||||||
var sdkKey = "AabXs3sHM8UhhE7oCGf4LVMLrdkGb1nJNksbjjTdVt7k"
|
var userName = "张三"
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -37,4 +40,5 @@ object GlobalKey {
|
|||||||
const val KEY_TOKEN = "tokenKey"
|
const val KEY_TOKEN = "tokenKey"
|
||||||
const val KEY_USER_INFO = "userInfoKey"
|
const val KEY_USER_INFO = "userInfoKey"
|
||||||
const val KEY_USER_NAME = "userNameKey"
|
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.CookFoodGoodsDao
|
||||||
import com.shuwei.dish.match.db.dao.SeasoningDao
|
import com.shuwei.dish.match.db.dao.SeasoningDao
|
||||||
import com.shuwei.dish.match.db.dao.SeasoningSlotDao
|
import com.shuwei.dish.match.db.dao.SeasoningSlotDao
|
||||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
import com.shuwei.dish.match.db.entity.CookFoodEntity
|
||||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
import com.shuwei.dish.match.db.entity.SeasoningEntity
|
||||||
import com.shuwei.dish.match.entity.SeasoningSlotEntity
|
import com.shuwei.dish.match.db.entity.SeasoningSlotEntity
|
||||||
|
|
||||||
|
|
||||||
// 步骤1:更新版本号
|
// 步骤1:更新版本号
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
package com.shuwei.dish.match.db
|
package com.shuwei.dish.match.db
|
||||||
|
|
||||||
import com.shuwei.dish.match.base.BaseApp
|
import com.shuwei.dish.match.base.BaseApp
|
||||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
import com.shuwei.dish.match.db.entity.CookFoodEntity
|
||||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
import com.shuwei.dish.match.db.entity.SeasoningEntity
|
||||||
import com.shuwei.dish.match.entity.SeasoningSlotEntity
|
import com.shuwei.dish.match.db.entity.SeasoningSlotEntity
|
||||||
|
import androidx.sqlite.db.SupportSQLiteQuery
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
@@ -233,6 +234,40 @@ class DbRepository {
|
|||||||
db.seasoningSlotDao().countSlotAll()
|
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 张表的测试数据
|
* 物理清空全部 4 张表的测试数据
|
||||||
* 清除顺序:先删子表(食材),再删主表(菜品),最后删配置表(调料、槽位)
|
* 清除顺序:先删子表(食材),再删主表(菜品),最后删配置表(调料、槽位)
|
||||||
|
|||||||
@@ -2,12 +2,13 @@ package com.shuwei.dish.match.db
|
|||||||
|
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.shuwei.dish.match.entity.CollectedFoodItem
|
import androidx.sqlite.db.SimpleSQLiteQuery
|
||||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
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.objbox.ObjectBox
|
||||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
import com.shuwei.dish.match.db.entity.SeasoningEntity
|
||||||
import com.shuwei.dish.match.entity.SeasoningSlotEntity
|
import com.shuwei.dish.match.db.entity.SeasoningSlotEntity
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
@@ -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 {
|
suspend fun countCookFood(cookMode: Int): Int {
|
||||||
return rep.countCookFood(cookMode)
|
return rep.countCookFood(cookMode)
|
||||||
}
|
}
|
||||||
@@ -73,6 +98,8 @@ class DbViewModel : ViewModel() {
|
|||||||
// 首次保存:主表 + 主辅材 + 调料 全量 insert
|
// 首次保存:主表 + 主辅材 + 调料 全量 insert
|
||||||
rep.insertCookFood(entity)
|
rep.insertCookFood(entity)
|
||||||
val newData = rep.getCookFoodById(entity.foodId, cookMode, entity.dinnerType ?: "0")
|
val newData = rep.getCookFoodById(entity.foodId, cookMode, entity.dinnerType ?: "0")
|
||||||
|
// 回填 id,防止下次调用时 getCookFoodById 查不到而重复插入主辅材
|
||||||
|
newData?.let { entity.id = it.id }
|
||||||
list?.let {
|
list?.let {
|
||||||
it.forEach { goods ->
|
it.forEach { goods ->
|
||||||
goods.id = 0
|
goods.id = 0
|
||||||
@@ -103,6 +130,17 @@ class DbViewModel : ViewModel() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 接口提交成功后删除本地菜品草稿(异步版本,绑定 viewModelScope)
|
||||||
|
* 与 [markSubmittedAndDelete] 的区别:不是 suspend,内部用 viewModelScope 启动协程,
|
||||||
|
* 不受调用方 Activity 生命周期影响,适合 singleTask 跳转前触发删除的场景
|
||||||
|
*/
|
||||||
|
fun markSubmittedAndDeleteAsync(cookMode: Int, foodId: String, dinnerType: String) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
markSubmittedAndDelete(cookMode, foodId, dinnerType)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 接口提交成功后删除本地菜品草稿
|
* 接口提交成功后删除本地菜品草稿
|
||||||
* 与 [deleteCookFoodAndGoods] 的区别:主表 submitState 会被置 1,便于审计区分手动删除与接口删除
|
* 与 [deleteCookFoodAndGoods] 的区别:主表 submitState 会被置 1,便于审计区分手动删除与接口删除
|
||||||
@@ -295,71 +333,89 @@ class DbViewModel : ViewModel() {
|
|||||||
* @param totalCount 当前过滤条件下的总记录数
|
* @param totalCount 当前过滤条件下的总记录数
|
||||||
* @param hasMore 是否还有更多数据可加载
|
* @param hasMore 是否还有更多数据可加载
|
||||||
* @param isLoading 是否正在加载(首次加载或加载更多)
|
* @param isLoading 是否正在加载(首次加载或加载更多)
|
||||||
|
* @param filter 当前生效的筛选条件,供"加载更多"复用
|
||||||
*/
|
*/
|
||||||
data class DbInspectUiState(
|
data class DbInspectUiState(
|
||||||
val items: List<DbRecord> = emptyList(),
|
val items: List<DbRecord> = emptyList(),
|
||||||
val totalCount: Int = 0,
|
val totalCount: Int = 0,
|
||||||
val hasMore: Boolean = false,
|
val hasMore: Boolean = false,
|
||||||
val isLoading: 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())
|
private val _dbInspectState = MutableStateFlow(DbInspectUiState())
|
||||||
val dbInspectState: StateFlow<DbInspectUiState> = _dbInspectState.asStateFlow()
|
val dbInspectState: StateFlow<DbInspectUiState> = _dbInspectState.asStateFlow()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 加载指定表的第一页数据(切换 Tab / 切换 isDel 过滤时调用)
|
* 加载指定表的第一页数据(切换 Tab / 修改筛选条件时调用)
|
||||||
* @param tableIndex 0=菜品 1=食材 2=调料 3=槽位
|
* @param tableIndex 0=菜品 1=食材 2=调料 3=槽位
|
||||||
* @param showDel true=包含已删除记录,false=只看有效记录
|
* @param filter 筛选条件,包含 showDel 和各字段过滤值
|
||||||
*/
|
*/
|
||||||
fun loadDbInspect(tableIndex: Int, showDel: Boolean) {
|
fun loadDbInspect(tableIndex: Int, filter: DbInspectFilter) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
// 立即清空旧数据并显示加载状态,避免切换 Tab 时旧数据闪现
|
// 立即清空旧数据并显示加载状态,避免切换 Tab 时旧数据闪现
|
||||||
_dbInspectState.value = DbInspectUiState(isLoading = true)
|
_dbInspectState.value = DbInspectUiState(isLoading = true, filter = filter)
|
||||||
val (items, total) = queryPage(tableIndex, showDel, offset = 0)
|
val (items, total) = queryPage(tableIndex, filter, offset = 0)
|
||||||
_dbInspectState.value = DbInspectUiState(
|
_dbInspectState.value = DbInspectUiState(
|
||||||
items = items,
|
items = items,
|
||||||
totalCount = total,
|
totalCount = total,
|
||||||
hasMore = items.size < total,
|
hasMore = items.size < total,
|
||||||
isLoading = false
|
isLoading = false,
|
||||||
|
filter = filter
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 追加加载下一页数据(点击"加载更多"时调用)
|
* 追加加载下一页数据(点击"加载更多"时调用)
|
||||||
|
* 筛选条件从当前 state 中复用,无需重新传入
|
||||||
* @param tableIndex 0=菜品 1=食材 2=调料 3=槽位
|
* @param tableIndex 0=菜品 1=食材 2=调料 3=槽位
|
||||||
* @param showDel true=包含已删除记录
|
|
||||||
*/
|
*/
|
||||||
fun loadMoreDbInspect(tableIndex: Int, showDel: Boolean) {
|
fun loadMoreDbInspect(tableIndex: Int) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
val current = _dbInspectState.value
|
val current = _dbInspectState.value
|
||||||
// 已在加载中或无更多数据时直接返回,防止重复请求
|
// 已在加载中或无更多数据时直接返回,防止重复请求
|
||||||
if (!current.hasMore || current.isLoading) return@launch
|
if (!current.hasMore || current.isLoading) return@launch
|
||||||
_dbInspectState.value = current.copy(isLoading = true)
|
_dbInspectState.value = current.copy(isLoading = true)
|
||||||
val (newItems, total) = queryPage(tableIndex, showDel, offset = current.items.size)
|
val (newItems, total) = queryPage(tableIndex, current.filter, offset = current.items.size)
|
||||||
val merged = current.items + newItems
|
val merged = current.items + newItems
|
||||||
_dbInspectState.value = DbInspectUiState(
|
_dbInspectState.value = DbInspectUiState(
|
||||||
items = merged,
|
items = merged,
|
||||||
totalCount = total,
|
totalCount = total,
|
||||||
hasMore = merged.size < total,
|
hasMore = merged.size < total,
|
||||||
isLoading = false
|
isLoading = false,
|
||||||
|
filter = current.filter
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 执行分页查询,返回 DbRecord 列表和总记录数
|
* 执行分页查询,返回 DbRecord 列表和总记录数
|
||||||
|
* 通过 buildQueries 将 filter 转换为动态 SQL
|
||||||
*/
|
*/
|
||||||
private suspend fun queryPage(
|
private suspend fun queryPage(
|
||||||
tableIndex: Int,
|
tableIndex: Int,
|
||||||
showDel: Boolean,
|
filter: DbInspectFilter,
|
||||||
offset: Int
|
offset: Int
|
||||||
): Pair<List<DbRecord>, Int> {
|
): Pair<List<DbRecord>, Int> {
|
||||||
val limit = DB_INSPECT_PAGE_SIZE
|
val limit = DB_INSPECT_PAGE_SIZE
|
||||||
return when (tableIndex) {
|
return when (tableIndex) {
|
||||||
0 -> {
|
0 -> {
|
||||||
val total = rep.countCookFoodAll(showDel)
|
val (pageQ, countQ) = buildQueries("dm_cook_food", "createTime DESC", true, filter, limit, offset)
|
||||||
val rows = rep.getCookFoodPaged(showDel, limit, offset).map { e ->
|
val total = rep.countCookFoodFiltered(countQ)
|
||||||
|
val rows = rep.getCookFoodPagedFiltered(pageQ).map { e ->
|
||||||
DbRecord(
|
DbRecord(
|
||||||
isDel = e.isDel == 1,
|
isDel = e.isDel == 1,
|
||||||
fields = listOf(
|
fields = listOf(
|
||||||
@@ -373,8 +429,9 @@ class DbViewModel : ViewModel() {
|
|||||||
rows to total
|
rows to total
|
||||||
}
|
}
|
||||||
1 -> {
|
1 -> {
|
||||||
val total = rep.countCookFoodGoodsAll(showDel)
|
val (pageQ, countQ) = buildQueries("dm_cook_food_goods", "createTime DESC", true, filter, limit, offset)
|
||||||
val rows = rep.getCookFoodGoodsPaged(showDel, limit, offset).map { e ->
|
val total = rep.countCookFoodGoodsFiltered(countQ)
|
||||||
|
val rows = rep.getCookFoodGoodsPagedFiltered(pageQ).map { e ->
|
||||||
DbRecord(
|
DbRecord(
|
||||||
isDel = e.isDel == 1,
|
isDel = e.isDel == 1,
|
||||||
fields = listOf(
|
fields = listOf(
|
||||||
@@ -389,8 +446,9 @@ class DbViewModel : ViewModel() {
|
|||||||
rows to total
|
rows to total
|
||||||
}
|
}
|
||||||
2 -> {
|
2 -> {
|
||||||
val total = rep.countSeasoningAll(showDel)
|
val (pageQ, countQ) = buildQueries("dm_seasoning", "sort ASC", true, filter, limit, offset)
|
||||||
val rows = rep.getSeasoningPaged(showDel, limit, offset).map { e ->
|
val total = rep.countSeasoningFiltered(countQ)
|
||||||
|
val rows = rep.getSeasoningPagedFiltered(pageQ).map { e ->
|
||||||
DbRecord(
|
DbRecord(
|
||||||
isDel = e.isDel == 1,
|
isDel = e.isDel == 1,
|
||||||
fields = listOf(
|
fields = listOf(
|
||||||
@@ -404,15 +462,16 @@ class DbViewModel : ViewModel() {
|
|||||||
rows to total
|
rows to total
|
||||||
}
|
}
|
||||||
3 -> {
|
3 -> {
|
||||||
val total = rep.countSlotAll()
|
val (pageQ, countQ) = buildQueries("dm_seasoning_slot", "deviceId ASC, address ASC", false, filter, limit, offset)
|
||||||
val rows = rep.getSlotPaged(limit, offset).map { e ->
|
val total = rep.countSlotFiltered(countQ)
|
||||||
|
val rows = rep.getSlotPagedFiltered(pageQ).map { e ->
|
||||||
DbRecord(
|
DbRecord(
|
||||||
isDel = false,
|
isDel = false,
|
||||||
fields = listOf(
|
fields = listOf(
|
||||||
"deviceId" to e.deviceId, "address" to "${e.address}",
|
"deviceId" to e.deviceId, "address" to "${e.address}",
|
||||||
"goodsId" to e.goodsId, "goodsName" to e.goodsName
|
"goodsId" to e.goodsId, "goodsName" to e.goodsName
|
||||||
),
|
),
|
||||||
columnsPerRow = 1 // 槽位表字段少,保持单列显示
|
columnsPerRow = 1
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
rows to total
|
rows to total
|
||||||
@@ -421,6 +480,55 @@ class DbViewModel : ViewModel() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据筛选条件动态构建分页查询和计数查询的 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 {
|
// viewModelScope.launch {
|
||||||
@@ -500,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.Insert
|
||||||
import androidx.room.OnConflictStrategy
|
import androidx.room.OnConflictStrategy
|
||||||
import androidx.room.Query
|
import androidx.room.Query
|
||||||
|
import androidx.room.RawQuery
|
||||||
import androidx.room.Update
|
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
|
@Dao
|
||||||
interface CookFoodDao {
|
interface CookFoodDao {
|
||||||
@@ -48,4 +50,12 @@ interface CookFoodDao {
|
|||||||
/** 物理清空全表,用于清除测试数据 */
|
/** 物理清空全表,用于清除测试数据 */
|
||||||
@Query("DELETE FROM dm_cook_food")
|
@Query("DELETE FROM dm_cook_food")
|
||||||
suspend fun deleteAll()
|
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.Insert
|
||||||
import androidx.room.OnConflictStrategy
|
import androidx.room.OnConflictStrategy
|
||||||
import androidx.room.Query
|
import androidx.room.Query
|
||||||
|
import androidx.room.RawQuery
|
||||||
import androidx.room.Update
|
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
|
@Dao
|
||||||
interface CookFoodGoodsDao {
|
interface CookFoodGoodsDao {
|
||||||
@@ -48,4 +50,12 @@ interface CookFoodGoodsDao {
|
|||||||
/** 物理清空全表,用于清除测试数据 */
|
/** 物理清空全表,用于清除测试数据 */
|
||||||
@Query("DELETE FROM dm_cook_food_goods")
|
@Query("DELETE FROM dm_cook_food_goods")
|
||||||
suspend fun deleteAll()
|
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.Insert
|
||||||
import androidx.room.OnConflictStrategy
|
import androidx.room.OnConflictStrategy
|
||||||
import androidx.room.Query
|
import androidx.room.Query
|
||||||
|
import androidx.room.RawQuery
|
||||||
import androidx.room.Update
|
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
|
@Dao
|
||||||
interface SeasoningDao {
|
interface SeasoningDao {
|
||||||
@@ -57,4 +59,12 @@ interface SeasoningDao {
|
|||||||
/** 物理清空全表,用于清除测试数据(比 clearAllSeasoning 的逻辑删除更彻底) */
|
/** 物理清空全表,用于清除测试数据(比 clearAllSeasoning 的逻辑删除更彻底) */
|
||||||
@Query("DELETE FROM dm_seasoning")
|
@Query("DELETE FROM dm_seasoning")
|
||||||
suspend fun deleteAll()
|
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.Insert
|
||||||
import androidx.room.OnConflictStrategy
|
import androidx.room.OnConflictStrategy
|
||||||
import androidx.room.Query
|
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
|
* 调料槽位配置 DAO
|
||||||
@@ -64,4 +66,12 @@ interface SeasoningSlotDao {
|
|||||||
/** 物理清空全表,用于清除测试数据 */
|
/** 物理清空全表,用于清除测试数据 */
|
||||||
@Query("DELETE FROM dm_seasoning_slot")
|
@Query("DELETE FROM dm_seasoning_slot")
|
||||||
suspend fun deleteAll()
|
suspend fun deleteAll()
|
||||||
|
|
||||||
|
/** 动态条件分页查询槽位记录,由 ViewModel 构建 SQL */
|
||||||
|
@RawQuery
|
||||||
|
suspend fun queryPagedFiltered(query: SupportSQLiteQuery): List<SeasoningSlotEntity>
|
||||||
|
|
||||||
|
/** 动态条件统计槽位记录总数,由 ViewModel 构建 SQL */
|
||||||
|
@RawQuery
|
||||||
|
suspend fun countFiltered(query: SupportSQLiteQuery): Int
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -1,4 +1,4 @@
|
|||||||
package com.shuwei.dish.match.entity
|
package com.shuwei.dish.match.db.entity
|
||||||
|
|
||||||
import androidx.room.Entity
|
import androidx.room.Entity
|
||||||
import androidx.room.Ignore
|
import androidx.room.Ignore
|
||||||
@@ -31,4 +31,4 @@ data class CookFoodEntity(
|
|||||||
var foodConstituteList: MutableList<CookFoodGoodsEntity>? = null
|
var foodConstituteList: MutableList<CookFoodGoodsEntity>? = null
|
||||||
|
|
||||||
constructor() : this(foodId = "") // 必需的空构造
|
constructor() : this(foodId = "") // 必需的空构造
|
||||||
}
|
}
|
||||||
+3
-2
@@ -1,8 +1,9 @@
|
|||||||
package com.shuwei.dish.match.entity
|
package com.shuwei.dish.match.db.entity
|
||||||
|
|
||||||
import androidx.room.Entity
|
import androidx.room.Entity
|
||||||
import androidx.room.PrimaryKey
|
import androidx.room.PrimaryKey
|
||||||
import com.shuwei.dish.match.db.BaseEntity
|
import com.shuwei.dish.match.db.BaseEntity
|
||||||
|
import com.shuwei.dish.match.model.GoodsItem
|
||||||
import com.shuwei.dish.match.utils.DateTimeUtil
|
import com.shuwei.dish.match.utils.DateTimeUtil
|
||||||
import java.io.Serializable
|
import java.io.Serializable
|
||||||
import java.time.LocalDateTime
|
import java.time.LocalDateTime
|
||||||
@@ -94,4 +95,4 @@ class CookFoodGoodsEntity(
|
|||||||
goodsOrRelationCode = goodsOrRelationCode,
|
goodsOrRelationCode = goodsOrRelationCode,
|
||||||
rawMaterialsType = rawMaterialsType
|
rawMaterialsType = rawMaterialsType
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
+2
-2
@@ -1,4 +1,4 @@
|
|||||||
package com.shuwei.dish.match.entity
|
package com.shuwei.dish.match.db.entity
|
||||||
|
|
||||||
import androidx.room.Entity
|
import androidx.room.Entity
|
||||||
import androidx.room.PrimaryKey
|
import androidx.room.PrimaryKey
|
||||||
@@ -72,4 +72,4 @@ var isDel: Int = 0,
|
|||||||
var createTime: String = DateTimeUtil.formatDateTime(LocalDateTime.now())
|
var createTime: String = DateTimeUtil.formatDateTime(LocalDateTime.now())
|
||||||
) : BaseEntity {
|
) : BaseEntity {
|
||||||
constructor() : this(goodsId = "") // 必需的空构造
|
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
|
import androidx.room.Entity
|
||||||
|
|
||||||
@@ -26,10 +26,12 @@ open class CommonDialog(
|
|||||||
private var negativeText = "取消"
|
private var negativeText = "取消"
|
||||||
private var positiveText = "确认"
|
private var positiveText = "确认"
|
||||||
private var neutralText: String? = null
|
private var neutralText: String? = null
|
||||||
|
private var singleText: String? = null
|
||||||
private var negativeClick: (() -> Unit)? = null
|
private var negativeClick: (() -> Unit)? = null
|
||||||
// 返回 true 时关闭弹窗,返回 false 时保持弹窗显示(用于校验不通过的场景)
|
// 返回 true 时关闭弹窗,返回 false 时保持弹窗显示(用于校验不通过的场景)
|
||||||
private var positiveClick: (() -> Boolean)? = null
|
private var positiveClick: (() -> Boolean)? = null
|
||||||
private var neutralClick: (() -> Unit)? = null
|
private var neutralClick: (() -> Unit)? = null
|
||||||
|
private var singleClick: (() -> Unit)? = null
|
||||||
private var dismissCallback: (() -> Unit)? = null
|
private var dismissCallback: (() -> Unit)? = null
|
||||||
// 待添加到 llContent 的自定义 View,在 onCreate 后挂载
|
// 待添加到 llContent 的自定义 View,在 onCreate 后挂载
|
||||||
private var pendingContentView: View? = null
|
private var pendingContentView: View? = null
|
||||||
@@ -51,7 +53,7 @@ open class CommonDialog(
|
|||||||
/** 设置右侧确认按钮文字及点击回调(3按钮模式下对应底部按钮),点击后自动关闭弹窗 */
|
/** 设置右侧确认按钮文字及点击回调(3按钮模式下对应底部按钮),点击后自动关闭弹窗 */
|
||||||
fun setPositiveButton(text: String, onClick: (() -> Unit)? = null): CommonDialog = apply {
|
fun setPositiveButton(text: String, onClick: (() -> Unit)? = null): CommonDialog = apply {
|
||||||
positiveText = text
|
positiveText = text
|
||||||
positiveClick = onClick?.let { { it(); true } }
|
positiveClick = onClick?.let { cb -> { cb(); true } }
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -69,6 +71,12 @@ open class CommonDialog(
|
|||||||
neutralClick = onClick
|
neutralClick = onClick
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 设置单按钮文字及点击回调,调用后自动切换为单按钮布局(优先级最高) */
|
||||||
|
fun setSingleButton(text: String, onClick: (() -> Unit)? = null): CommonDialog = apply {
|
||||||
|
singleText = text
|
||||||
|
singleClick = onClick
|
||||||
|
}
|
||||||
|
|
||||||
/** 设置弹窗消失回调 */
|
/** 设置弹窗消失回调 */
|
||||||
fun setOnDismissCallback(callback: () -> Unit): CommonDialog = apply {
|
fun setOnDismissCallback(callback: () -> Unit): CommonDialog = apply {
|
||||||
dismissCallback = callback
|
dismissCallback = callback
|
||||||
@@ -91,9 +99,9 @@ open class CommonDialog(
|
|||||||
setContentView(binding.root)
|
setContentView(binding.root)
|
||||||
// 弹窗不允许点击外部关闭
|
// 弹窗不允许点击外部关闭
|
||||||
setCancelable(false)
|
setCancelable(false)
|
||||||
|
val isMaster = GlobalData.deviceRole == DeviceRole.MASTER
|
||||||
window?.run {
|
window?.run {
|
||||||
val screenWidth = context.resources.displayMetrics.widthPixels
|
val screenWidth = context.resources.displayMetrics.widthPixels
|
||||||
val isMaster = GlobalData.deviceRole == DeviceRole.MASTER
|
|
||||||
attributes = attributes.apply {
|
attributes = attributes.apply {
|
||||||
width = if (isMaster) (screenWidth * 0.72f).toInt() else (screenWidth * 0.60f).toInt()
|
width = if (isMaster) (screenWidth * 0.72f).toInt() else (screenWidth * 0.60f).toInt()
|
||||||
}
|
}
|
||||||
@@ -103,7 +111,7 @@ open class CommonDialog(
|
|||||||
setWindowAnimations(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.tvTitle.updateLayoutParams<LinearLayout.LayoutParams> { topMargin = verticalMargin }
|
||||||
binding.tvContent.updateLayoutParams<LinearLayout.LayoutParams> { bottomMargin = verticalMargin }
|
binding.tvContent.updateLayoutParams<LinearLayout.LayoutParams> { bottomMargin = verticalMargin }
|
||||||
|
|
||||||
@@ -130,10 +138,17 @@ open class CommonDialog(
|
|||||||
if (positiveClick?.invoke() != false) dismiss()
|
if (positiveClick?.invoke() != false) dismiss()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 单按钮点击事件
|
||||||
|
binding.btnSingle.setOnClickListener {
|
||||||
|
singleClick?.invoke()
|
||||||
|
dismiss()
|
||||||
|
}
|
||||||
|
|
||||||
setOnDismissListener { dismissCallback?.invoke() }
|
setOnDismissListener { dismissCallback?.invoke() }
|
||||||
|
|
||||||
// 挂载自定义内容 View,并执行 tvContent 的灵活控制回调
|
// 挂载自定义内容 View,并执行 tvContent 的灵活控制回调
|
||||||
pendingContentView?.let {
|
pendingContentView?.let {
|
||||||
|
binding.llContent.removeAllViews()
|
||||||
binding.llContent.addView(it)
|
binding.llContent.addView(it)
|
||||||
binding.llContent.visibility = View.VISIBLE
|
binding.llContent.visibility = View.VISIBLE
|
||||||
tvContentConfigurator?.invoke(binding.tvContent)
|
tvContentConfigurator?.invoke(binding.tvContent)
|
||||||
@@ -148,10 +163,15 @@ open class CommonDialog(
|
|||||||
binding.tvContent.visibility = if (contentText.isNullOrEmpty()) View.GONE else View.VISIBLE
|
binding.tvContent.visibility = if (contentText.isNullOrEmpty()) View.GONE else View.VISIBLE
|
||||||
|
|
||||||
val hasThreeButtons = !neutralText.isNullOrEmpty()
|
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
|
binding.layoutButtonsVertical.visibility = if (hasThreeButtons) View.VISIBLE else View.GONE
|
||||||
|
|
||||||
if (hasThreeButtons) {
|
if (hasSingleButton) {
|
||||||
|
// 单按钮模式
|
||||||
|
binding.btnSingle.text = singleText
|
||||||
|
} else if (hasThreeButtons) {
|
||||||
// 3按钮模式:顶部=取消,中间=中立,底部=确认
|
// 3按钮模式:顶部=取消,中间=中立,底部=确认
|
||||||
binding.btnTop.text = negativeText
|
binding.btnTop.text = negativeText
|
||||||
binding.btnMiddle.text = neutralText
|
binding.btnMiddle.text = neutralText
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
package com.shuwei.dish.match.dialog
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.widget.ImageView
|
||||||
|
import android.widget.PopupWindow
|
||||||
|
import androidx.core.graphics.drawable.toDrawable
|
||||||
|
import androidx.core.view.updateLayoutParams
|
||||||
|
import androidx.recyclerview.widget.LinearLayoutManager
|
||||||
|
import androidx.recyclerview.widget.RecyclerView
|
||||||
|
import com.shuwei.dish.match.R
|
||||||
|
import com.shuwei.dish.match.adapter.DropdownAdapter
|
||||||
|
import com.shuwei.dish.match.databinding.LayoutPopupDropdownBinding
|
||||||
|
import com.shuwei.dish.match.model.DictType
|
||||||
|
import com.shuwei.dish.match.utils.ext.dp
|
||||||
|
|
||||||
|
class DropdownPopup(
|
||||||
|
var context: Context,
|
||||||
|
var list: MutableList<DictType>,
|
||||||
|
var popWidth: Int = 280.dp,
|
||||||
|
var popHeight: Int = 284.dp,
|
||||||
|
var onPopupItemClick: (DictType) -> Unit
|
||||||
|
) : PopupWindow() {
|
||||||
|
|
||||||
|
init {
|
||||||
|
// 初始化PopupWindow
|
||||||
|
// val popupView = LayoutInflater.from(context).inflate(R.layout.layout_popup_dropdown, null)
|
||||||
|
val binding = LayoutPopupDropdownBinding.inflate(LayoutInflater.from(context))
|
||||||
|
contentView = binding.root
|
||||||
|
width = ViewGroup.LayoutParams.WRAP_CONTENT
|
||||||
|
height = ViewGroup.LayoutParams.WRAP_CONTENT
|
||||||
|
// 设置透明背景,避免覆盖圆角
|
||||||
|
setBackgroundDrawable(Color.TRANSPARENT.toDrawable())
|
||||||
|
isOutsideTouchable = true
|
||||||
|
isFocusable = true
|
||||||
|
|
||||||
|
// 设置动画样式
|
||||||
|
// animationStyle = R.style.PopupAnimation
|
||||||
|
|
||||||
|
// 初始化视图和事件
|
||||||
|
initViews(binding.rvWarehouse)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun initViews(rv: RecyclerView) {
|
||||||
|
// 获取关闭按钮并设置点击事件
|
||||||
|
rv.updateLayoutParams {
|
||||||
|
width = popWidth
|
||||||
|
height = popHeight
|
||||||
|
}
|
||||||
|
rv.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
|
||||||
|
rv.adapter = DropdownAdapter(list).setOnItemClickListener { adapter, view, position ->
|
||||||
|
onPopupItemClick(list[position])
|
||||||
|
dismiss()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var arrowImage: ImageView? = null
|
||||||
|
|
||||||
|
var bgLayout: ViewGroup? = null
|
||||||
|
|
||||||
|
var defLayoutBgResId = R.drawable.bg_white_radius10_stroke2
|
||||||
|
|
||||||
|
override fun showAsDropDown(anchor: View?) {
|
||||||
|
super.showAsDropDown(anchor)
|
||||||
|
bgLayout?.setBackgroundResource(R.drawable.shape_green_stroke)
|
||||||
|
arrowImage?.setImageResource(R.mipmap.ic_triangle_up)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun dismiss() {
|
||||||
|
super.dismiss()
|
||||||
|
bgLayout?.setBackgroundResource(defLayoutBgResId)
|
||||||
|
arrowImage?.setImageResource(R.mipmap.ic_triangle_down)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -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.LOCAL_BASE_URL
|
||||||
|
contentBinding.rbUat.id -> GlobalData.TEST_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.LOCAL_BASE_URL -> contentBinding.rbTest.isChecked = true
|
||||||
|
GlobalData.TEST_BASE_URL -> contentBinding.rbUat.isChecked = true
|
||||||
|
GlobalData.PROD_BASE_URL -> contentBinding.rbProd.isChecked = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 显示弹窗 */
|
||||||
|
fun show() = dialog.show()
|
||||||
|
|
||||||
|
/** 关闭弹窗 */
|
||||||
|
fun dismiss() = dialog.dismiss()
|
||||||
|
}
|
||||||
@@ -10,14 +10,12 @@ import android.view.MotionEvent
|
|||||||
import android.view.View
|
import android.view.View
|
||||||
import android.view.Window
|
import android.view.Window
|
||||||
import android.widget.FrameLayout
|
import android.widget.FrameLayout
|
||||||
import androidx.core.view.isEmpty
|
|
||||||
import androidx.core.widget.addTextChangedListener
|
import androidx.core.widget.addTextChangedListener
|
||||||
import androidx.lifecycle.Lifecycle
|
import androidx.lifecycle.Lifecycle
|
||||||
import androidx.lifecycle.lifecycleScope
|
import androidx.lifecycle.lifecycleScope
|
||||||
import androidx.lifecycle.repeatOnLifecycle
|
import androidx.lifecycle.repeatOnLifecycle
|
||||||
import androidx.recyclerview.widget.GridLayoutManager
|
import androidx.recyclerview.widget.GridLayoutManager
|
||||||
import androidx.recyclerview.widget.LinearLayoutManager
|
import androidx.recyclerview.widget.LinearLayoutManager
|
||||||
import androidx.recyclerview.widget.RecyclerView
|
|
||||||
import com.chad.library.adapter4.util.setOnDebouncedItemClick
|
import com.chad.library.adapter4.util.setOnDebouncedItemClick
|
||||||
import com.google.android.material.bottomsheet.BottomSheetDialog
|
import com.google.android.material.bottomsheet.BottomSheetDialog
|
||||||
import com.shuwei.dish.match.R
|
import com.shuwei.dish.match.R
|
||||||
@@ -25,11 +23,9 @@ import com.shuwei.dish.match.adapter.FoodAdapter
|
|||||||
import com.shuwei.dish.match.base.BaseActivity
|
import com.shuwei.dish.match.base.BaseActivity
|
||||||
import com.shuwei.dish.match.databinding.DialogFoodSearchBinding
|
import com.shuwei.dish.match.databinding.DialogFoodSearchBinding
|
||||||
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
||||||
import com.shuwei.dish.match.dialog.SeasoningSelectDialog.Companion.PAGE_SIZE
|
import com.shuwei.dish.match.model.GoodsItem
|
||||||
import com.shuwei.dish.match.entity.GoodsItem
|
|
||||||
import com.shuwei.dish.match.net.UiState
|
import com.shuwei.dish.match.net.UiState
|
||||||
import com.shuwei.dish.match.utils.KeyboardUtil
|
import com.shuwei.dish.match.utils.KeyboardUtil
|
||||||
import com.shuwei.dish.match.utils.buildMockGoodsList
|
|
||||||
import com.shuwei.dish.match.utils.showRawMaterialsDialog
|
import com.shuwei.dish.match.utils.showRawMaterialsDialog
|
||||||
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
||||||
import com.shuwei.dish.match.utils.ext.toast
|
import com.shuwei.dish.match.utils.ext.toast
|
||||||
@@ -57,7 +53,7 @@ class FoodSearchDialog(
|
|||||||
private val adapter = FoodAdapter(list).apply {
|
private val adapter = FoodAdapter(list).apply {
|
||||||
isStateViewEnable = true
|
isStateViewEnable = true
|
||||||
setOnDebouncedItemClick { _, _, position ->
|
setOnDebouncedItemClick { _, _, position ->
|
||||||
val item = list[position]
|
val item = list.getOrNull(position) ?: return@setOnDebouncedItemClick
|
||||||
// 弹出净材种类单选弹窗,确认后再回调并关闭弹窗
|
// 弹出净材种类单选弹窗,确认后再回调并关闭弹窗
|
||||||
showRawMaterialsDialog(
|
showRawMaterialsDialog(
|
||||||
context = activity,
|
context = activity,
|
||||||
@@ -232,12 +228,19 @@ class FoodSearchDialog(
|
|||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
binding.recyclerView.layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
// 仅当当前不是 GridLayoutManager 时才重新赋值(空态切回网格时)
|
||||||
|
binding.recyclerView.run {
|
||||||
|
if (layoutManager !is GridLayoutManager) {
|
||||||
|
layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
||||||
|
}
|
||||||
|
}
|
||||||
if (pageNo == 1) list.clear()
|
if (pageNo == 1) list.clear()
|
||||||
// 将接口返回的 rawMaterialsType(全部种类)移存到 rawMaterialsTypes,供弹窗使用
|
// 将接口返回的 rawMaterialsType(全部种类)移存到 rawMaterialsTypes,供弹窗使用
|
||||||
records.forEach {
|
records.forEach {
|
||||||
it.rawMaterialsTypes = it.rawMaterialsType
|
it.rawMaterialsTypes = it.rawMaterialsType
|
||||||
it.rawMaterialsType = null
|
it.rawMaterialsType = null
|
||||||
|
it.oldGoodsId = it.goodsId
|
||||||
|
it.goodsId = it.materId ?: ""
|
||||||
}
|
}
|
||||||
list.addAll(records)
|
list.addAll(records)
|
||||||
adapter.notifyDataSetChanged()
|
adapter.notifyDataSetChanged()
|
||||||
@@ -270,7 +273,7 @@ class FoodSearchDialog(
|
|||||||
emptyViewBinding?.let {
|
emptyViewBinding?.let {
|
||||||
it.tvContent.text = "暂无数据"
|
it.tvContent.text = "暂无数据"
|
||||||
it.tvSubContent.text = "未查询到食材信息,请联系管理员添加"
|
it.tvSubContent.text = "未查询到食材信息,请联系管理员添加"
|
||||||
it.root.setOnClickListener { loadGoodsList(buildMockGoodsList().toMutableList()) }
|
// it.root.setOnClickListener { loadGoodsList(buildMockGoodsList().toMutableList()) }
|
||||||
it.root.layoutParams = FrameLayout.LayoutParams(
|
it.root.layoutParams = FrameLayout.LayoutParams(
|
||||||
FrameLayout.LayoutParams.MATCH_PARENT,
|
FrameLayout.LayoutParams.MATCH_PARENT,
|
||||||
FrameLayout.LayoutParams.MATCH_PARENT
|
FrameLayout.LayoutParams.MATCH_PARENT
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,214 @@
|
|||||||
|
package com.shuwei.dish.match.dialog
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
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 android.view.Window
|
||||||
|
import android.widget.FrameLayout
|
||||||
|
import androidx.core.widget.addTextChangedListener
|
||||||
|
import androidx.recyclerview.widget.GridLayoutManager
|
||||||
|
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.InboundIngredientAdapter
|
||||||
|
import com.shuwei.dish.match.base.BaseActivity
|
||||||
|
import com.shuwei.dish.match.databinding.DialogInboundIngredientSearchBinding
|
||||||
|
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
||||||
|
import com.shuwei.dish.match.model.NutCleanInboundIngredientVO
|
||||||
|
import com.shuwei.dish.match.net.NetViewModelV2
|
||||||
|
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
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 已入库净菜食材搜索弹窗
|
||||||
|
* @param activity 宿主 Activity
|
||||||
|
* @param defIngredientName 默认填充的食材名称(可选)
|
||||||
|
* @param onItemSelected 用户点击某项食材时的回调
|
||||||
|
*/
|
||||||
|
class InboundIngredientSearchDialog(
|
||||||
|
private val activity: BaseActivity,
|
||||||
|
private val viewModelV2: NetViewModelV2,
|
||||||
|
private val defIngredientName: String? = null,
|
||||||
|
private val onItemSelected: (item: NutCleanInboundIngredientVO) -> Unit
|
||||||
|
) : BottomSheetDialog(activity, R.style.BottomSheet) {
|
||||||
|
|
||||||
|
private val binding = DialogInboundIngredientSearchBinding.inflate(LayoutInflater.from(activity))
|
||||||
|
private val list = mutableListOf<NutCleanInboundIngredientVO>()
|
||||||
|
private val adapter = InboundIngredientAdapter(list).apply {
|
||||||
|
isStateViewEnable = true
|
||||||
|
setOnDebouncedItemClick { _, _, position ->
|
||||||
|
val item = list.getOrNull(position) ?: return@setOnDebouncedItemClick
|
||||||
|
onItemSelected(item)
|
||||||
|
dismiss()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var keyword: String? = null
|
||||||
|
|
||||||
|
init {
|
||||||
|
setContentView(binding.root)
|
||||||
|
setCancelable(true)
|
||||||
|
behavior.skipCollapsed = false
|
||||||
|
setOnDismissListener { activity.hideStatusBar() }
|
||||||
|
|
||||||
|
binding.tvSheetName.text = "已入库净菜检索"
|
||||||
|
|
||||||
|
// 输入框:清空时重置列表
|
||||||
|
binding.etSheetInput.run {
|
||||||
|
hint = "输入食材名称"
|
||||||
|
addTextChangedListener(
|
||||||
|
onTextChanged = { text, _, _, _ -> keyword = text.toString() },
|
||||||
|
afterTextChanged = { it: Editable? ->
|
||||||
|
if (it.isNullOrBlank()) {
|
||||||
|
list.clear()
|
||||||
|
adapter.notifyDataSetChanged()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
addOnActionSearchListener { searchIngredient(this) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// RecyclerView 初始化
|
||||||
|
binding.recyclerView.run {
|
||||||
|
layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
||||||
|
adapter = this@InboundIngredientSearchDialog.adapter
|
||||||
|
}
|
||||||
|
|
||||||
|
binding.refreshLayout.run {
|
||||||
|
setEnableRefresh(true)
|
||||||
|
setEnableLoadMore(false)
|
||||||
|
setOnRefreshListener { getIngredientList() }
|
||||||
|
}
|
||||||
|
|
||||||
|
binding.ivSearch.setOnClickListener { searchIngredient(it) }
|
||||||
|
binding.root.setOnClickListener { KeyboardUtil.hideKeyboard(it) }
|
||||||
|
|
||||||
|
// 若有默认食材名称,自动填充并触发搜索
|
||||||
|
if (!defIngredientName.isNullOrBlank()) {
|
||||||
|
binding.etSheetInput.setText(defIngredientName)
|
||||||
|
getIngredientList()
|
||||||
|
KeyboardUtil.hideKeyboard(binding.root)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 弹窗显示时在 Window.Callback 层提前拦截触摸,解决 BottomSheet 拖拽与列表滑动的手势冲突 */
|
||||||
|
override fun show() {
|
||||||
|
super.show()
|
||||||
|
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)
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 触发搜索:校验输入、隐藏键盘、发起请求
|
||||||
|
*/
|
||||||
|
private fun searchIngredient(v: View) {
|
||||||
|
if (keyword.isNullOrBlank()) {
|
||||||
|
activity.toast("请输入食材名称")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
getIngredientList()
|
||||||
|
KeyboardUtil.hideKeyboard(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 请求食材列表,使用回调方式发起
|
||||||
|
*/
|
||||||
|
private fun getIngredientList() {
|
||||||
|
viewModelV2.getInboundIngredientOptionsWithCallback(
|
||||||
|
keyword = keyword.takeUnless { it.isNullOrBlank() },
|
||||||
|
onLoading = {},
|
||||||
|
onResult = { state ->
|
||||||
|
when (state) {
|
||||||
|
is UiState.Success -> loadIngredientList(state.data)
|
||||||
|
is UiState.Error -> {
|
||||||
|
activity.toast(state.msg)
|
||||||
|
binding.refreshLayout.finishRefresh()
|
||||||
|
}
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将返回数据填充到列表
|
||||||
|
*/
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
private fun loadIngredientList(records: List<NutCleanInboundIngredientVO>?) {
|
||||||
|
binding.refreshLayout.finishRefresh()
|
||||||
|
if (records.isNullOrEmpty()) {
|
||||||
|
loadEmptyView()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
binding.recyclerView.layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
||||||
|
list.clear()
|
||||||
|
list.addAll(records)
|
||||||
|
adapter.notifyDataSetChanged()
|
||||||
|
}
|
||||||
|
|
||||||
|
private var emptyViewBinding: LayoutEmptyViewBinding? = null
|
||||||
|
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
private fun loadEmptyView() {
|
||||||
|
try {
|
||||||
|
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.layoutParams = FrameLayout.LayoutParams(
|
||||||
|
FrameLayout.LayoutParams.MATCH_PARENT,
|
||||||
|
FrameLayout.LayoutParams.MATCH_PARENT
|
||||||
|
)
|
||||||
|
binding.recyclerView.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
|
||||||
|
binding.recyclerView.post {
|
||||||
|
it.root.minimumHeight = binding.recyclerView.height
|
||||||
|
adapter.stateView = it.root
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,17 +1,28 @@
|
|||||||
package com.shuwei.dish.match.dialog
|
package com.shuwei.dish.match.dialog
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
import android.app.Dialog
|
import android.app.Dialog
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.graphics.Color
|
import android.graphics.Color
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
import android.view.LayoutInflater
|
import android.view.LayoutInflater
|
||||||
import android.view.WindowManager
|
import android.view.WindowManager
|
||||||
import androidx.core.graphics.drawable.toDrawable
|
import androidx.core.graphics.drawable.toDrawable
|
||||||
import com.shuwei.dish.match.R
|
import com.shuwei.dish.match.R
|
||||||
import com.shuwei.dish.match.databinding.DialogLoadingBinding
|
import com.shuwei.dish.match.databinding.DialogLoadingBinding
|
||||||
|
|
||||||
|
@SuppressLint("StaticFieldLeak")
|
||||||
object Loading {
|
object Loading {
|
||||||
|
|
||||||
|
/** 默认超时兜底时长(毫秒):业务方未传值时使用 */
|
||||||
|
const val DEFAULT_TIMEOUT_MS = 15_000L
|
||||||
|
|
||||||
private var dialog: LoadingDialog? = null
|
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 {
|
fun isShowing(): Boolean {
|
||||||
return dialog != null && dialog!!.isShowing
|
return dialog != null && dialog!!.isShowing
|
||||||
@@ -22,30 +33,71 @@ object Loading {
|
|||||||
dialog!!.updateContent(content)
|
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 {
|
try {
|
||||||
|
// 节流:已显示中只更新文案 + 重置超时,不重新 attach 窗口
|
||||||
|
// 避免反复触发 FocusEvent 在主线程繁忙时引发 ANR
|
||||||
if (dialog?.isShowing == true) {
|
if (dialog?.isShowing == true) {
|
||||||
dialog?.dismiss()
|
dialog?.updateContent(message)
|
||||||
}
|
owner = context // 同一弹窗最后一次 show 决定 owner
|
||||||
if (dialog == null) {
|
resetTimeout(timeoutMs)
|
||||||
dialog = LoadingDialog(context = context, message = message, onDismiss = onDismiss)
|
return
|
||||||
}
|
}
|
||||||
|
dialog = LoadingDialog(context = context, message = message, onDismiss = onDismiss)
|
||||||
|
owner = context
|
||||||
dialog?.show()
|
dialog?.show()
|
||||||
|
resetTimeout(timeoutMs)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
e.printStackTrace()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun dismiss() {
|
fun dismiss() {
|
||||||
|
timeoutHandler.removeCallbacks(timeoutRunnable)
|
||||||
try {
|
try {
|
||||||
dialog?.let {
|
dialog?.let {
|
||||||
if (it.isShowing) {
|
if (it.isShowing) {
|
||||||
it.dismiss()
|
it.dismiss()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
dialog = null
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ import com.shuwei.dish.match.adapter.SeasoningSearchAdapter
|
|||||||
import com.shuwei.dish.match.base.BaseActivity
|
import com.shuwei.dish.match.base.BaseActivity
|
||||||
import com.shuwei.dish.match.databinding.DialogSeasoningSelectBinding
|
import com.shuwei.dish.match.databinding.DialogSeasoningSelectBinding
|
||||||
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
||||||
import com.shuwei.dish.match.entity.GoodsItem
|
import com.shuwei.dish.match.model.GoodsItem
|
||||||
import com.shuwei.dish.match.net.UiState
|
import com.shuwei.dish.match.net.UiState
|
||||||
import com.shuwei.dish.match.utils.KeyboardUtil
|
import com.shuwei.dish.match.utils.KeyboardUtil
|
||||||
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
||||||
@@ -52,10 +52,11 @@ class SeasoningSelectDialog(
|
|||||||
private val adapter = SeasoningSearchAdapter(list).apply {
|
private val adapter = SeasoningSearchAdapter(list).apply {
|
||||||
isStateViewEnable = true
|
isStateViewEnable = true
|
||||||
setOnItemClickListener { _, v, position ->
|
setOnItemClickListener { _, v, position ->
|
||||||
list[position].isClicked = true
|
val item = list.getOrNull(position) ?: return@setOnItemClickListener
|
||||||
|
item.isClicked = true
|
||||||
notifyItemChanged(position)
|
notifyItemChanged(position)
|
||||||
v.postDelayed({
|
v.postDelayed({
|
||||||
onItemSelected(list[position])
|
onItemSelected(item)
|
||||||
dismiss()
|
dismiss()
|
||||||
}, 300)
|
}, 300)
|
||||||
}
|
}
|
||||||
@@ -227,6 +228,11 @@ class SeasoningSelectDialog(
|
|||||||
binding.recyclerView.layoutManager = GridLayoutManager(activity, 3, GridLayoutManager.VERTICAL, false)
|
binding.recyclerView.layoutManager = GridLayoutManager(activity, 3, GridLayoutManager.VERTICAL, false)
|
||||||
if (pageNo == 1) list.clear()
|
if (pageNo == 1) list.clear()
|
||||||
list.addAll(records)
|
list.addAll(records)
|
||||||
|
list.forEach {
|
||||||
|
it.oldGoodsId = it.goodsId
|
||||||
|
//materId才是提交数据需要的goodsId数据
|
||||||
|
it.goodsId = it.materId ?:""
|
||||||
|
}
|
||||||
adapter.notifyDataSetChanged()
|
adapter.notifyDataSetChanged()
|
||||||
val isLoadMoreEnable = records.size >= PAGE_SIZE
|
val isLoadMoreEnable = records.size >= PAGE_SIZE
|
||||||
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
|
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
|
||||||
@@ -259,7 +265,7 @@ class SeasoningSelectDialog(
|
|||||||
it.tvContent.text = "暂无数据"
|
it.tvContent.text = "暂无数据"
|
||||||
it.tvSubContent.text = "未查询到调料信息,请联系管理员添加"
|
it.tvSubContent.text = "未查询到调料信息,请联系管理员添加"
|
||||||
// 点击空布局加载本地模拟数据,方便联调时验证 UI
|
// 点击空布局加载本地模拟数据,方便联调时验证 UI
|
||||||
it.root.setOnClickListener { loadMockData() }
|
//it.root.setOnClickListener { loadMockData() }
|
||||||
it.root.layoutParams = FrameLayout.LayoutParams(
|
it.root.layoutParams = FrameLayout.LayoutParams(
|
||||||
FrameLayout.LayoutParams.MATCH_PARENT,
|
FrameLayout.LayoutParams.MATCH_PARENT,
|
||||||
FrameLayout.LayoutParams.MATCH_PARENT
|
FrameLayout.LayoutParams.MATCH_PARENT
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package com.shuwei.dish.match.entity
|
package com.shuwei.dish.match.model
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 已采集食材列表项数据模型
|
* 已采集食材列表项数据模型
|
||||||
+3
-1
@@ -1,5 +1,7 @@
|
|||||||
package com.shuwei.dish.match.entity
|
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
|
import java.io.Serializable
|
||||||
|
|
||||||
/**
|
/**
|
||||||
+3
-1
@@ -1,5 +1,7 @@
|
|||||||
package com.shuwei.dish.match.entity
|
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
|
import java.io.Serializable
|
||||||
|
|
||||||
/**
|
/**
|
||||||
+1
-3
@@ -1,4 +1,4 @@
|
|||||||
package com.shuwei.dish.match.entity
|
package com.shuwei.dish.match.model
|
||||||
|
|
||||||
import android.graphics.Bitmap
|
import android.graphics.Bitmap
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
@@ -50,5 +50,3 @@ data class FoodCollectionBean(
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package com.shuwei.dish.match.model
|
||||||
|
|
||||||
|
import android.os.Parcelable
|
||||||
|
import kotlinx.parcelize.Parcelize
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 字典类型 如仓库列表 物品类型 存储方式等
|
||||||
|
*/
|
||||||
|
@Parcelize
|
||||||
|
data class DictType(
|
||||||
|
val id: String? = null,
|
||||||
|
val value: String? = null,
|
||||||
|
val type: String = "",
|
||||||
|
var position: Int = 0
|
||||||
|
) : Parcelable {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按字段名取值,供 extraApiKeys 映射直接使用
|
||||||
|
*/
|
||||||
|
operator fun get(fieldName: String): String = when (fieldName) {
|
||||||
|
"id" -> id ?: ""
|
||||||
|
"value" -> value ?: ""
|
||||||
|
else -> type
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-2
@@ -1,4 +1,4 @@
|
|||||||
package com.shuwei.dish.match.entity
|
package com.shuwei.dish.match.model
|
||||||
|
|
||||||
import java.io.Serializable
|
import java.io.Serializable
|
||||||
|
|
||||||
@@ -17,4 +17,3 @@ data class FoodRecord(
|
|||||||
var isOriginalData: Boolean = true,
|
var isOriginalData: Boolean = true,
|
||||||
var sort: Int = 0
|
var sort: Int = 0
|
||||||
) : Serializable
|
) : Serializable
|
||||||
|
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package com.shuwei.dish.match.model
|
||||||
|
|
||||||
|
/** 表单字段类型枚举 */
|
||||||
|
enum class FieldType {
|
||||||
|
/** 普通文本输入 */
|
||||||
|
TEXT,
|
||||||
|
/** 整数输入 */
|
||||||
|
INTEGER,
|
||||||
|
/** 小数输入 */
|
||||||
|
DECIMAL,
|
||||||
|
/** 下拉选择 */
|
||||||
|
DROPDOWN,
|
||||||
|
/** 日期选择弹窗 */
|
||||||
|
DATE_PICKER,
|
||||||
|
/** 固定值,不可编辑 */
|
||||||
|
FIXED,
|
||||||
|
/** 子列表容器,用于动态增减行(如"包含食材") */
|
||||||
|
CHILDREN
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 动态表单字段数据模型
|
||||||
|
* @param label 字段标签名称
|
||||||
|
* @param type 字段类型,决定渲染哪种输入控件
|
||||||
|
* @param apiKey 非下拉字段对应的接口参数名,空字符串表示不提交
|
||||||
|
* @param extraApiKeys 下拉字段的多接口参数映射,key=接口参数名,value=DictType 字段名(id/value/type)
|
||||||
|
* @param required 是否必填,提交时校验
|
||||||
|
* @param hidden 是否隐藏,hidden=true 时不渲染该字段
|
||||||
|
* @param hint 校验失败提示文案,同时作为输入框 hint
|
||||||
|
* @param options 下拉框选项列表(DROPDOWN 类型使用)
|
||||||
|
* @param value 当前显示值/输入值;DATE_PICKER 存 yyyy-MM-dd 显示格式
|
||||||
|
* @param extraValues 下拉选中后按 extraApiKeys 映射存储的提交值,key=接口参数名
|
||||||
|
* @param children 子字段模板(CHILDREN 类型使用),每行按此模板创建一组字段
|
||||||
|
* @param childAddLabel 添加按钮文案(CHILDREN 类型使用),如 "+ 添加食材"
|
||||||
|
* @param childrenRows 子列表实际数据(CHILDREN 类型使用),每行是一个 List<FormField>
|
||||||
|
*/
|
||||||
|
data class FormField(
|
||||||
|
val label: String,
|
||||||
|
val type: FieldType,
|
||||||
|
val apiKey: String = "",
|
||||||
|
val extraApiKeys: Map<String, String> = emptyMap(),
|
||||||
|
val required: Boolean = false,
|
||||||
|
val hidden: Boolean = false,
|
||||||
|
val hint: String = "",
|
||||||
|
var options: MutableList<DictType> = mutableListOf(),
|
||||||
|
var value: String = "",
|
||||||
|
val extraValues: MutableMap<String, String> = mutableMapOf(),
|
||||||
|
val children: List<FormField>? = null,
|
||||||
|
val childAddLabel: String? = null,
|
||||||
|
val childrenRows: MutableList<MutableList<FormField>> = mutableListOf(),
|
||||||
|
var onDropdownSelected: ((DictType) -> Unit)? = null
|
||||||
|
)
|
||||||
+9
-6
@@ -1,5 +1,7 @@
|
|||||||
package com.shuwei.dish.match.entity
|
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
|
import java.io.Serializable
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -8,12 +10,12 @@ import java.io.Serializable
|
|||||||
*/
|
*/
|
||||||
data class GoodsItem(
|
data class GoodsItem(
|
||||||
// 接口返回字段
|
// 接口返回字段
|
||||||
val goodsId: String = "",
|
var goodsId: String = "",
|
||||||
val goodsName: String? = null,
|
var goodsName: String? = null,
|
||||||
val popularName: String? = null,
|
val popularName: String? = null,
|
||||||
val zjmCode: String? = null,
|
val zjmCode: String? = null,
|
||||||
val materId: String? = null,
|
var materId: String? = null,
|
||||||
val materCode: String? = null,
|
var materCode: String? = null,
|
||||||
|
|
||||||
// 从 CookFoodGoodsEntity 迁移的数据字段(DishPartAdapter 显示及转换用)
|
// 从 CookFoodGoodsEntity 迁移的数据字段(DishPartAdapter 显示及转换用)
|
||||||
var materialType: Int = 0,
|
var materialType: Int = 0,
|
||||||
@@ -35,7 +37,8 @@ data class GoodsItem(
|
|||||||
// 净材种类(当前选中值)
|
// 净材种类(当前选中值)
|
||||||
var rawMaterialsType: String? = null,
|
var rawMaterialsType: String? = null,
|
||||||
// 净材种类候选列表(临时字段,逗号分隔,不持久化)
|
// 净材种类候选列表(临时字段,逗号分隔,不持久化)
|
||||||
var rawMaterialsTypes: String? = null
|
var rawMaterialsTypes: String? = null,
|
||||||
|
var oldGoodsId: String? = null
|
||||||
) : Serializable {
|
) : Serializable {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package com.shuwei.dish.match.entity
|
package com.shuwei.dish.match.model
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 物品名称批量查询入参 DTO
|
* 物品名称批量查询入参 DTO
|
||||||
@@ -0,0 +1,264 @@
|
|||||||
|
package com.shuwei.dish.match.model
|
||||||
|
|
||||||
|
import android.os.Parcelable
|
||||||
|
import kotlinx.parcelize.Parcelize
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 食堂VO - 食堂下拉列表响应
|
||||||
|
*/
|
||||||
|
@Parcelize
|
||||||
|
data class NutCanteenVO(
|
||||||
|
val id: Long?,
|
||||||
|
val canteenCode: String?,
|
||||||
|
val canteenName: String?,
|
||||||
|
val orgCode: String?,
|
||||||
|
val orgName: String?,
|
||||||
|
val leader: String?,
|
||||||
|
val leaderPhone: String?,
|
||||||
|
val useTerminal: Short?,
|
||||||
|
val address: String?,
|
||||||
|
val longitude: String?,
|
||||||
|
val latitude: String?,
|
||||||
|
val status: Short?
|
||||||
|
) : Parcelable
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 字典项VO - 字典项下拉响应
|
||||||
|
*/
|
||||||
|
@Parcelize
|
||||||
|
data class NutDictItemVO(
|
||||||
|
val id: Long?,
|
||||||
|
val dictType: String?,
|
||||||
|
val dictCode: String?,
|
||||||
|
val dictLabel: String?,
|
||||||
|
val sortOrder: Int?,
|
||||||
|
val isBuiltin: Short?,
|
||||||
|
val status: Short?,
|
||||||
|
val remark: String?
|
||||||
|
) : Parcelable
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 食材选项VO - 食材下拉响应
|
||||||
|
*/
|
||||||
|
@Parcelize
|
||||||
|
data class NutMaterOptionVO(
|
||||||
|
val id: Long?,
|
||||||
|
val materClassName: String?
|
||||||
|
) : Parcelable
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 包装设备VO - 包装设备下拉响应
|
||||||
|
*/
|
||||||
|
@Parcelize
|
||||||
|
data class NutSupPkgDeviceVO(
|
||||||
|
val id: Long?,
|
||||||
|
val deviceNo: String?,
|
||||||
|
val deviceName: String?
|
||||||
|
) : Parcelable
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 餐品选项VO - 餐品下拉搜索响应
|
||||||
|
*/
|
||||||
|
@Parcelize
|
||||||
|
data class NutFoodOptionVO(
|
||||||
|
val foodId: Long?,
|
||||||
|
val foodCode: String?,
|
||||||
|
val foodName: String?,
|
||||||
|
val compositions: List<NutFoodComposition>?
|
||||||
|
) : Parcelable
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 餐品食材构成
|
||||||
|
*/
|
||||||
|
@Parcelize
|
||||||
|
data class NutFoodComposition(
|
||||||
|
var materId: Long?,
|
||||||
|
var ingredientName: String?,
|
||||||
|
var traceCode: String?,
|
||||||
|
var amount: Double?,
|
||||||
|
var isMain: Int?,
|
||||||
|
//1-主材、2-辅材、3-调料
|
||||||
|
var mainText: String?=null
|
||||||
|
) : Parcelable
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 溯源码查食材信息VO
|
||||||
|
*/
|
||||||
|
@Parcelize
|
||||||
|
data class NutSupHygieneIngredientOptionVO(
|
||||||
|
val traceCode: String?,
|
||||||
|
val materId: Long?,
|
||||||
|
val materName: String?,
|
||||||
|
val vegTypes: String?,
|
||||||
|
val materClassId: Long?,
|
||||||
|
val materClassName: String?,
|
||||||
|
val testNo: String?
|
||||||
|
) : Parcelable
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 组配任务视频监控VO
|
||||||
|
*/
|
||||||
|
@Parcelize
|
||||||
|
data class NutProdComboVideoVO(
|
||||||
|
val cameraCode: String?,
|
||||||
|
val streamUrl: String?,
|
||||||
|
val snapshotUrl: String?,
|
||||||
|
val onlineStatus: Int?,
|
||||||
|
val recordType: Int?,
|
||||||
|
val startTime: String?,
|
||||||
|
val endTime: String?
|
||||||
|
) : Parcelable
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 组配任务DTO - 上报组配任务请求体
|
||||||
|
*/
|
||||||
|
data class NutProdComboTaskDTO(
|
||||||
|
val planDate: String,
|
||||||
|
val canteenId: Long,
|
||||||
|
val mealType: Short?,
|
||||||
|
val foodId: Long?,
|
||||||
|
val targetDish: String,
|
||||||
|
val spec: String,
|
||||||
|
val portions: Int,
|
||||||
|
val taskDeadline: String?,
|
||||||
|
val taskSource: Short?,
|
||||||
|
val ownerName: String?,
|
||||||
|
val items: List<NutProdComboTaskItem>?
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 组配任务食材明细
|
||||||
|
*/
|
||||||
|
data class NutProdComboTaskItem(
|
||||||
|
val ingredientCode: String?,
|
||||||
|
val ingredientName: String,
|
||||||
|
val perPortionQty: String,
|
||||||
|
val unit: String? = "g",
|
||||||
|
val sortOrder: Int?
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 单品净菜包装DTO - 上报单品净菜包装记录请求体
|
||||||
|
*/
|
||||||
|
data class NutSupCleanPackageDTO(
|
||||||
|
val traceCode: String,
|
||||||
|
val cleanInboundId: Long?,
|
||||||
|
val cleanName: String,
|
||||||
|
val packageMethod: String,
|
||||||
|
val spec: String,
|
||||||
|
val quantity: Int,
|
||||||
|
val packageDate: String,
|
||||||
|
val expiryDate: String,
|
||||||
|
val storageTemp: String?,
|
||||||
|
val relatedOrderNo: String?,
|
||||||
|
val operator: String?,
|
||||||
|
val deviceId: Long?,
|
||||||
|
val cameraCode: String?,
|
||||||
|
val videoUrl: String?
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 餐品净菜包装DTO - 上报餐品净菜包装记录请求体
|
||||||
|
*/
|
||||||
|
data class NutSupMealPackageDTO(
|
||||||
|
val foodId: Long,
|
||||||
|
val mealName: String,
|
||||||
|
val spec: String,
|
||||||
|
val packageMethod: String,
|
||||||
|
val quantity: Int,
|
||||||
|
val packageDate: String,
|
||||||
|
val expiryDate: String,
|
||||||
|
val storageTemp: String?,
|
||||||
|
val relatedOrderNo: String?,
|
||||||
|
val operator: String?,
|
||||||
|
val deviceId: Long?,
|
||||||
|
val cameraCode: String?,
|
||||||
|
val videoUrl: String?,
|
||||||
|
val ingredients: List<NutSupMealPackageIngredient>
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 餐品净菜包装食材明细
|
||||||
|
*/
|
||||||
|
data class NutSupMealPackageIngredient(
|
||||||
|
val materId: Long,
|
||||||
|
val ingredientName: String,
|
||||||
|
val amount: String?,
|
||||||
|
val traceCode: String
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 组配任务VO - 未完成组配任务列表响应
|
||||||
|
*/
|
||||||
|
@Parcelize
|
||||||
|
data class NutComboTaskVO(
|
||||||
|
val id: Long?,
|
||||||
|
val taskNo: String?,
|
||||||
|
val planDate: String?,
|
||||||
|
val canteenId: Long?,
|
||||||
|
val mealType: Int?,
|
||||||
|
val foodId: Long?,
|
||||||
|
val targetDish: String?,
|
||||||
|
val spec: String?,
|
||||||
|
val portions: Int?,
|
||||||
|
var comboStatus: Int?,
|
||||||
|
val ownerName: String?,
|
||||||
|
val createTime: String?
|
||||||
|
) : Parcelable
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 组配任务详情VO - 组配任务详情响应
|
||||||
|
*/
|
||||||
|
@Parcelize
|
||||||
|
data class NutComboTaskDetailVO(
|
||||||
|
var id: Long? = null,
|
||||||
|
var taskNo: String? = null,
|
||||||
|
var planDate: String? = null,
|
||||||
|
var canteenId: Long? = null,
|
||||||
|
var mealType: Int? = null,
|
||||||
|
var foodId: Long? = null,
|
||||||
|
var targetDish: String? = null,
|
||||||
|
var spec: String? = null,
|
||||||
|
var portions: Int? = null,
|
||||||
|
var comboStatus: Int? = null,
|
||||||
|
var ownerName: String? = null,
|
||||||
|
var deviceCode: String? = null,
|
||||||
|
var items: List<NutComboTaskItemDetail>? = null,
|
||||||
|
) : Parcelable
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 组配任务食材明细
|
||||||
|
*/
|
||||||
|
@Parcelize
|
||||||
|
data class NutComboTaskItemDetail(
|
||||||
|
val id: Long?,
|
||||||
|
val ingredientCode: String?,
|
||||||
|
val ingredientName: String?,
|
||||||
|
val ingredientClass: Int?,
|
||||||
|
var traceCode: String?,
|
||||||
|
val perPortionQty: String?,
|
||||||
|
var actualQty: String?,
|
||||||
|
val totalQty: String?,
|
||||||
|
val unit: String?,
|
||||||
|
var isClicked: Boolean? = false,
|
||||||
|
var isSetFinished: Boolean? = false,
|
||||||
|
) : Parcelable
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 已入库净菜食材VO - 按食材名称查询已入库有库存的净菜记录
|
||||||
|
*/
|
||||||
|
@Parcelize
|
||||||
|
data class NutCleanInboundIngredientVO(
|
||||||
|
val id: Long?,
|
||||||
|
val materId: Long?,
|
||||||
|
val ingredientName: String?,
|
||||||
|
val traceCode: String?,
|
||||||
|
val currentStock: String?
|
||||||
|
) : Parcelable
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ID通用DTO - 用于开始/完成组配等需要id参数的接口
|
||||||
|
*/
|
||||||
|
data class IdDTO(
|
||||||
|
val id: Long
|
||||||
|
)
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
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 = type.label,
|
||||||
|
val subtitle: String? = null,
|
||||||
|
val isHidden: Boolean = false,
|
||||||
|
val onClick: () -> Unit
|
||||||
|
) {
|
||||||
|
/** 设置菜单项类型枚举 */
|
||||||
|
enum class Type(val label: String) {
|
||||||
|
COOK_MODE("菜品模式"),
|
||||||
|
SEASONING_CONFIG("调料区设置"),
|
||||||
|
FOOD_COLLECT("食材采集"),
|
||||||
|
WEIGHT_CONFIG("减重配置"),
|
||||||
|
CLEAN_PACKAGE("净菜包"),
|
||||||
|
MEAL_PACKAGE("餐品净菜包"),
|
||||||
|
GROUP_TASK("组配任务"),
|
||||||
|
// MEAL_PACKAGE_TEST("餐品净菜包-测试"),
|
||||||
|
DB_INSPECT("数据库查看"),
|
||||||
|
SCALE_OBSERVE("秤数据监控"),
|
||||||
|
ENV_SWITCH("切换环境"),
|
||||||
|
CLEAR_DATA("数据清除"),
|
||||||
|
TEST_SEASONING("测试调料拿取"),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
package com.shuwei.dish.match.net
|
package com.shuwei.dish.match.net
|
||||||
|
|
||||||
import com.shuwei.dish.match.base.GlobalData
|
import com.shuwei.dish.match.base.GlobalData
|
||||||
import com.shuwei.dish.match.entity.CookFoodDTO
|
import com.shuwei.dish.match.model.CookFoodDTO
|
||||||
import com.shuwei.dish.match.entity.FoodRecord
|
import com.shuwei.dish.match.model.FoodRecord
|
||||||
import com.shuwei.dish.match.entity.GoodsItem
|
import com.shuwei.dish.match.model.GoodsItem
|
||||||
import okhttp3.MultipartBody
|
import okhttp3.MultipartBody
|
||||||
import okhttp3.RequestBody
|
import okhttp3.RequestBody
|
||||||
import retrofit2.http.Body
|
import retrofit2.http.Body
|
||||||
|
|||||||
@@ -0,0 +1,173 @@
|
|||||||
|
package com.shuwei.dish.match.net
|
||||||
|
|
||||||
|
import com.shuwei.dish.match.base.GlobalData
|
||||||
|
import com.shuwei.dish.match.model.NutSupPkgDeviceVO
|
||||||
|
import com.shuwei.dish.match.model.NutCanteenVO
|
||||||
|
import com.shuwei.dish.match.model.NutDictItemVO
|
||||||
|
import com.shuwei.dish.match.model.NutMaterOptionVO
|
||||||
|
import com.shuwei.dish.match.model.NutFoodOptionVO
|
||||||
|
import com.shuwei.dish.match.model.NutSupHygieneIngredientOptionVO
|
||||||
|
import com.shuwei.dish.match.model.NutProdComboVideoVO
|
||||||
|
import com.shuwei.dish.match.model.NutProdComboTaskDTO
|
||||||
|
import com.shuwei.dish.match.model.IdDTO
|
||||||
|
import com.shuwei.dish.match.model.NutCleanInboundIngredientVO
|
||||||
|
import com.shuwei.dish.match.model.NutComboTaskDetailVO
|
||||||
|
import com.shuwei.dish.match.model.NutComboTaskVO
|
||||||
|
import retrofit2.http.Body
|
||||||
|
import retrofit2.http.GET
|
||||||
|
import retrofit2.http.POST
|
||||||
|
import retrofit2.http.Query
|
||||||
|
import retrofit2.http.Url
|
||||||
|
|
||||||
|
interface ApiServiceV2 {
|
||||||
|
|
||||||
|
// ========== 一、下拉选项接口 ==========
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 食堂下拉列表,返回启用状态的食堂列表,支持关键字模糊搜索
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
suspend fun getCanteenOptions(
|
||||||
|
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/canteen-options",
|
||||||
|
@Query("keyword") keyword: String? = null
|
||||||
|
): ApiResponse<List<NutCanteenVO>>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 字典项下拉,按 dictType 查询字典项
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
suspend fun getDictItems(
|
||||||
|
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/dict-items",
|
||||||
|
@Query("dictType") dictType: String
|
||||||
|
): ApiResponse<List<NutDictItemVO>>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 食材下拉列表,支持关键字模糊搜索
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
suspend fun getMaterOptions(
|
||||||
|
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/mater-options",
|
||||||
|
@Query("keyword") keyword: String? = null
|
||||||
|
): ApiResponse<List<NutMaterOptionVO>>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 包装设备下拉(仅在线),返回在线设备的 id、编号、名称
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
suspend fun getDeviceOptions(
|
||||||
|
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/device-options"
|
||||||
|
): ApiResponse<List<NutSupPkgDeviceVO>>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 餐品下拉搜索(含食材构成),按名称模糊搜索,分页返回
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
suspend fun getFoodOptions(
|
||||||
|
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/food-options",
|
||||||
|
@Query("keyword") keyword: String? = null,
|
||||||
|
@Query("pageNum") pageNum: Int = 1,
|
||||||
|
@Query("pageSize") pageSize: Int = 10
|
||||||
|
): ApiResponse<Page<NutFoodOptionVO>>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按溯源码查食材信息
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
suspend fun getIngredientByTrace(
|
||||||
|
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/ingredient-by-trace",
|
||||||
|
@Query("traceCode") traceCode: String
|
||||||
|
): ApiResponse<List<NutSupHygieneIngredientOptionVO>>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按食材名称查询已入库有库存的净菜记录
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
suspend fun getInboundIngredientOptions(
|
||||||
|
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/inbound-ingredient-options",
|
||||||
|
@Query("keyword") keyword: String? = null
|
||||||
|
): ApiResponse<List<NutCleanInboundIngredientVO>>
|
||||||
|
|
||||||
|
// ========== 二、净菜组配接口 ==========
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 上报组配任务(含食材明细)
|
||||||
|
*/
|
||||||
|
@POST
|
||||||
|
suspend fun addComboTask(
|
||||||
|
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/combo-task/add",
|
||||||
|
@Body param: NutComboTaskDetailVO
|
||||||
|
): ApiResponse<Unit>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 开始组配,组配状态 0 -> 1
|
||||||
|
*/
|
||||||
|
@POST
|
||||||
|
suspend fun startComboTask(
|
||||||
|
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/combo-task/start",
|
||||||
|
@Body param: IdDTO
|
||||||
|
): ApiResponse<Unit>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 完成组配,组配状态 1 -> 2
|
||||||
|
*/
|
||||||
|
@POST
|
||||||
|
suspend fun finishComboTask(
|
||||||
|
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/combo-task/finish",
|
||||||
|
@Body param: IdDTO
|
||||||
|
): ApiResponse<Unit>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取组配任务视频监控地址
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
suspend fun getComboTaskVideo(
|
||||||
|
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/combo-task/video",
|
||||||
|
@Query("taskNo") taskNo: String
|
||||||
|
): ApiResponse<NutProdComboVideoVO>
|
||||||
|
|
||||||
|
// ========== 三、单品净菜包装接口 ==========
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 上报单品净菜包装记录
|
||||||
|
*/
|
||||||
|
@POST
|
||||||
|
suspend fun addCleanPackage(
|
||||||
|
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/clean-package/add",
|
||||||
|
@Body param: Map<String, @JvmSuppressWildcards Any?>
|
||||||
|
): ApiResponse<Unit>
|
||||||
|
|
||||||
|
// ========== 四、餐品净菜包装接口 ==========
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 上报餐品净菜包装记录
|
||||||
|
*/
|
||||||
|
@POST
|
||||||
|
suspend fun addMealPackage(
|
||||||
|
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/meal-package/add",
|
||||||
|
@Body param: Map<String, @JvmSuppressWildcards Any?>
|
||||||
|
): ApiResponse<Unit>
|
||||||
|
|
||||||
|
// ========== 五、组配任务接口 ==========
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询未完成组配任务(分页)
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
suspend fun getIncompleteComboTasks(
|
||||||
|
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/combo-task/incomplete",
|
||||||
|
@Query("deviceCode") deviceCode: String? = null,
|
||||||
|
@Query("keyword") keyword: String? = null,
|
||||||
|
@Query("pageNum") pageNum: Int = 1,
|
||||||
|
@Query("pageSize") pageSize: Int = 10
|
||||||
|
): ApiResponse<Page<NutComboTaskVO>>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取组配任务详情
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
suspend fun getComboTaskDetail(
|
||||||
|
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/combo-task/detail",
|
||||||
|
@Query("id") id: Long
|
||||||
|
): ApiResponse<NutComboTaskDetailVO>
|
||||||
|
|
||||||
|
}
|
||||||
@@ -3,13 +3,16 @@ package com.shuwei.dish.match.net
|
|||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.shuwei.dish.match.base.BaseApp
|
import com.shuwei.dish.match.base.BaseApp
|
||||||
import com.shuwei.dish.match.entity.CookFoodDTO
|
import com.shuwei.dish.match.model.CookFoodDTO
|
||||||
import com.shuwei.dish.match.entity.FoodRecord
|
import com.shuwei.dish.match.model.FoodRecord
|
||||||
import com.shuwei.dish.match.entity.GoodsItem
|
import com.shuwei.dish.match.model.GoodsItem
|
||||||
import com.shuwei.dish.match.entity.GoodsNameQueryDTO
|
import com.shuwei.dish.match.model.GoodsNameQueryDTO
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.SharedFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.flow.asSharedFlow
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||||
import okhttp3.MultipartBody
|
import okhttp3.MultipartBody
|
||||||
@@ -62,23 +65,46 @@ class NetViewModel(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 搜索菜品列表的 UI 状态流,UI 层通过 collect 监听
|
* 搜索菜品列表的 UI 状态流。
|
||||||
|
* 使用 replay=1 保证 Fragment 重建后能收到最近一次结果;
|
||||||
|
* emit 时包一层 Event wrapper 打破 equals 去重,确保相同数据也能触发 collect。
|
||||||
*/
|
*/
|
||||||
private val _searchFoodState = MutableStateFlow<UiState<MutableList<FoodRecord>?>>(UiState.Idle)
|
private val _searchFoodState = MutableSharedFlow<UiState<MutableList<FoodRecord>?>>(
|
||||||
val searchFoodState: StateFlow<UiState<MutableList<FoodRecord>?>> = _searchFoodState.asStateFlow()
|
replay = 1,
|
||||||
|
extraBufferCapacity = 1
|
||||||
|
)
|
||||||
|
val searchFoodState: SharedFlow<UiState<MutableList<FoodRecord>?>> = _searchFoodState.asSharedFlow()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 搜索菜品列表
|
* 搜索菜品列表
|
||||||
*/
|
*/
|
||||||
fun searchFoodList(param: MutableMap<String, Any>) {
|
fun searchFoodList(param: MutableMap<String, Any>) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
_searchFoodState.value = UiState.Loading
|
// pageNum=1 时先 emit Idle 重置 replay 缓存,防止相同数据导致 SharedFlow 去重不触发
|
||||||
_searchFoodState.value = repository.searchFoodList(param)
|
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 监听
|
|
||||||
*/
|
*/
|
||||||
private val _samplingListState = MutableStateFlow<UiState<MutableList<FoodRecord>?>>(UiState.Idle)
|
private val _samplingListState = MutableStateFlow<UiState<MutableList<FoodRecord>?>>(UiState.Idle)
|
||||||
val samplingListState: StateFlow<UiState<MutableList<FoodRecord>?>> = _samplingListState.asStateFlow()
|
val samplingListState: StateFlow<UiState<MutableList<FoodRecord>?>> = _samplingListState.asStateFlow()
|
||||||
@@ -96,6 +122,21 @@ class NetViewModel(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询采样数据列表(回调版本),结果通过 onResult 直接回调,不经过 StateFlow
|
||||||
|
* 适合不需要跨生命周期持续监听的一次性查询场景
|
||||||
|
*/
|
||||||
|
fun getSamplingListWithCallback(
|
||||||
|
param: MutableMap<String, Any>,
|
||||||
|
onLoading: () -> Unit = {},
|
||||||
|
onResult: (UiState<MutableList<FoodRecord>?>) -> Unit
|
||||||
|
) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
onLoading()
|
||||||
|
onResult(repository.getSamplingList(param))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 查询物品信息列表的 UI 状态流(食材/调料共用),UI 层通过 collect 监听
|
* 查询物品信息列表的 UI 状态流(食材/调料共用),UI 层通过 collect 监听
|
||||||
*/
|
*/
|
||||||
@@ -108,6 +149,10 @@ class NetViewModel(
|
|||||||
private val _foodSearchGoodsListState = MutableStateFlow<UiState<MutableList<GoodsItem>?>>(UiState.Idle)
|
private val _foodSearchGoodsListState = MutableStateFlow<UiState<MutableList<GoodsItem>?>>(UiState.Idle)
|
||||||
val foodSearchGoodsListState: StateFlow<UiState<MutableList<GoodsItem>?>> = _foodSearchGoodsListState.asStateFlow()
|
val foodSearchGoodsListState: StateFlow<UiState<MutableList<GoodsItem>?>> = _foodSearchGoodsListState.asStateFlow()
|
||||||
|
|
||||||
|
fun resetGoodsListState() {
|
||||||
|
_goodsListState.value = UiState.Idle
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 查询物品信息列表(食材 goodsType=0,调料 goodsType=1 共用)
|
* 查询物品信息列表(食材 goodsType=0,调料 goodsType=1 共用)
|
||||||
* @param goodsType 物品类型:0=食材,1=调料
|
* @param goodsType 物品类型:0=食材,1=调料
|
||||||
@@ -184,7 +229,7 @@ class NetViewModel(
|
|||||||
params: MutableMap<String, RequestBody>
|
params: MutableMap<String, RequestBody>
|
||||||
) {
|
) {
|
||||||
val fileParts = fileList.map { file ->
|
val fileParts = fileList.map { file ->
|
||||||
file.asRequestBody("image/jpeg".toMediaTypeOrNull())
|
file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
|
||||||
.let { MultipartBody.Part.createFormData("foodPics", file.name, it) }
|
.let { MultipartBody.Part.createFormData("foodPics", file.name, it) }
|
||||||
}
|
}
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
|
|||||||
@@ -0,0 +1,327 @@
|
|||||||
|
package com.shuwei.dish.match.net
|
||||||
|
|
||||||
|
import androidx.lifecycle.ViewModel
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import com.shuwei.dish.match.model.NutCanteenVO
|
||||||
|
import com.shuwei.dish.match.model.NutCleanInboundIngredientVO
|
||||||
|
import com.shuwei.dish.match.model.NutComboTaskDetailVO
|
||||||
|
import com.shuwei.dish.match.model.NutComboTaskVO
|
||||||
|
import com.shuwei.dish.match.model.NutDictItemVO
|
||||||
|
import com.shuwei.dish.match.model.NutFoodOptionVO
|
||||||
|
import com.shuwei.dish.match.model.NutMaterOptionVO
|
||||||
|
import com.shuwei.dish.match.model.NutProdComboTaskDTO
|
||||||
|
import com.shuwei.dish.match.model.NutProdComboVideoVO
|
||||||
|
import com.shuwei.dish.match.model.NutSupHygieneIngredientOptionVO
|
||||||
|
import com.shuwei.dish.match.model.NutSupPkgDeviceVO
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 网络请求 ViewModel V2,所有网络操作通过 RemoteRepositoryV2 发起
|
||||||
|
*/
|
||||||
|
class NetViewModelV2(
|
||||||
|
private val repository: RemoteRepositoryV2 = RemoteRepositoryV2()
|
||||||
|
) : ViewModel() {
|
||||||
|
|
||||||
|
// ========== 下拉选项接口 ==========
|
||||||
|
|
||||||
|
// 食堂下拉列表
|
||||||
|
private val _canteenOptionsState = MutableStateFlow<UiState<List<NutCanteenVO>?>>(UiState.Idle)
|
||||||
|
val canteenOptionsState: StateFlow<UiState<List<NutCanteenVO>?>> =
|
||||||
|
_canteenOptionsState.asStateFlow()
|
||||||
|
|
||||||
|
fun getCanteenOptions(keyword: String? = null) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_canteenOptionsState.value = UiState.Loading
|
||||||
|
_canteenOptionsState.value = repository.getCanteenOptions(keyword)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 字典项下拉
|
||||||
|
private val _dictItemsState = MutableStateFlow<UiState<List<NutDictItemVO>?>>(UiState.Idle)
|
||||||
|
val dictItemsState: StateFlow<UiState<List<NutDictItemVO>?>> = _dictItemsState.asStateFlow()
|
||||||
|
|
||||||
|
// fun getDictItems(dictType: String) {
|
||||||
|
// viewModelScope.launch {
|
||||||
|
// _dictItemsState.value = UiState.Loading
|
||||||
|
// _dictItemsState.value = repository.getDictItems(dictType)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// 食材下拉列表
|
||||||
|
private val _materOptionsState =
|
||||||
|
MutableStateFlow<UiState<List<NutMaterOptionVO>?>>(UiState.Idle)
|
||||||
|
val materOptionsState: StateFlow<UiState<List<NutMaterOptionVO>?>> =
|
||||||
|
_materOptionsState.asStateFlow()
|
||||||
|
|
||||||
|
fun getMaterOptions(keyword: String? = null) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_materOptionsState.value = UiState.Loading
|
||||||
|
_materOptionsState.value = repository.getMaterOptions(keyword)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 包装设备下拉
|
||||||
|
private val _deviceOptionsState =
|
||||||
|
MutableStateFlow<UiState<List<NutSupPkgDeviceVO>?>>(UiState.Idle)
|
||||||
|
val deviceOptionsState: StateFlow<UiState<List<NutSupPkgDeviceVO>?>> =
|
||||||
|
_deviceOptionsState.asStateFlow()
|
||||||
|
|
||||||
|
fun getDeviceOptions() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_deviceOptionsState.value = UiState.Loading
|
||||||
|
_deviceOptionsState.value = repository.getDeviceOptions()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 餐品下拉搜索
|
||||||
|
private val _foodOptionsState = MutableStateFlow<UiState<Page<NutFoodOptionVO>?>>(UiState.Idle)
|
||||||
|
val foodOptionsState: StateFlow<UiState<Page<NutFoodOptionVO>?>> =
|
||||||
|
_foodOptionsState.asStateFlow()
|
||||||
|
|
||||||
|
// fun getFoodOptions(keyword: String? = null, pageNum: Int = 1, pageSize: Int = 10) {
|
||||||
|
// viewModelScope.launch {
|
||||||
|
// _foodOptionsState.value = UiState.Loading
|
||||||
|
// _foodOptionsState.value = repository.getFoodOptions(keyword, pageNum, pageSize)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 字典项下拉(回调版本),不依赖 StateFlow,适合多次不同 dictType 的场景
|
||||||
|
*/
|
||||||
|
fun getDictItemsWithCallback(
|
||||||
|
dictType: String,
|
||||||
|
onLoading: () -> Unit = {},
|
||||||
|
onResult: (UiState<List<NutDictItemVO>?>) -> Unit
|
||||||
|
) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
onLoading()
|
||||||
|
onResult(repository.getDictItems(dictType))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 餐品下拉(回调版本),不依赖 StateFlow,适合多次调用的场景
|
||||||
|
*/
|
||||||
|
fun getFoodOptionsWithCallback(
|
||||||
|
keyword: String? = null,
|
||||||
|
pageNum: Int = 1,
|
||||||
|
pageSize: Int = 10,
|
||||||
|
onLoading: () -> Unit = {},
|
||||||
|
onResult: (UiState<Page<NutFoodOptionVO>?>) -> Unit
|
||||||
|
) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
onLoading()
|
||||||
|
val state = repository.getFoodOptions(keyword, pageNum, pageSize)
|
||||||
|
onResult(state)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设备下拉(回调版本),不依赖 StateFlow,适合多次调用的场景
|
||||||
|
*/
|
||||||
|
fun getDeviceOptionsWithCallback(
|
||||||
|
onLoading: () -> Unit = {},
|
||||||
|
onResult: (UiState<List<NutSupPkgDeviceVO>?>) -> Unit
|
||||||
|
) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
onLoading()
|
||||||
|
onResult(repository.getDeviceOptions())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 按溯源码查食材信息
|
||||||
|
private val _ingredientByTraceState =
|
||||||
|
MutableStateFlow<UiState<List<NutSupHygieneIngredientOptionVO>?>>(UiState.Idle)
|
||||||
|
val ingredientByTraceState: StateFlow<UiState<List<NutSupHygieneIngredientOptionVO>?>> =
|
||||||
|
_ingredientByTraceState.asStateFlow()
|
||||||
|
|
||||||
|
fun getIngredientByTrace(traceCode: String) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_ingredientByTraceState.value = UiState.Loading
|
||||||
|
_ingredientByTraceState.value = repository.getIngredientByTrace(traceCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 净菜组配接口 ==========
|
||||||
|
|
||||||
|
// 上报组配任务
|
||||||
|
private val _addComboTaskState = MutableStateFlow<UiState<Unit?>>(UiState.Idle)
|
||||||
|
val addComboTaskState: StateFlow<UiState<Unit?>> = _addComboTaskState.asStateFlow()
|
||||||
|
|
||||||
|
fun addComboTask(param: NutComboTaskDetailVO, block: (Boolean, String) -> Unit) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
val uiState = repository.addComboTask(param)
|
||||||
|
when (uiState) {
|
||||||
|
is UiState.Success -> {
|
||||||
|
block(true, "")
|
||||||
|
}
|
||||||
|
is UiState.Error -> {
|
||||||
|
block(false, uiState.msg)
|
||||||
|
}
|
||||||
|
is UiState.Loading -> {}
|
||||||
|
is UiState.Idle -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// fun addComboTask(param: NutProdComboTaskDTO) {
|
||||||
|
// viewModelScope.launch {
|
||||||
|
// _addComboTaskState.value = UiState.Loading
|
||||||
|
// _addComboTaskState.value = repository.addComboTask(param)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// 开始组配
|
||||||
|
private val _startComboTaskState = MutableStateFlow<UiState<Unit?>>(UiState.Idle)
|
||||||
|
val startComboTaskState: StateFlow<UiState<Unit?>> = _startComboTaskState.asStateFlow()
|
||||||
|
|
||||||
|
fun startComboTask(id: Long) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_startComboTaskState.value = UiState.Loading
|
||||||
|
_startComboTaskState.value = repository.startComboTask(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 完成组配
|
||||||
|
private val _finishComboTaskState = MutableStateFlow<UiState<Unit?>>(UiState.Idle)
|
||||||
|
val finishComboTaskState: StateFlow<UiState<Unit?>> = _finishComboTaskState.asStateFlow()
|
||||||
|
|
||||||
|
fun finishComboTask(id: Long) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_finishComboTaskState.value = UiState.Loading
|
||||||
|
_finishComboTaskState.value = repository.finishComboTask(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取组配任务视频监控地址
|
||||||
|
private val _comboTaskVideoState = MutableStateFlow<UiState<NutProdComboVideoVO?>>(UiState.Idle)
|
||||||
|
val comboTaskVideoState: StateFlow<UiState<NutProdComboVideoVO?>> =
|
||||||
|
_comboTaskVideoState.asStateFlow()
|
||||||
|
|
||||||
|
fun getComboTaskVideo(taskNo: String) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_comboTaskVideoState.value = UiState.Loading
|
||||||
|
_comboTaskVideoState.value = repository.getComboTaskVideo(taskNo)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 单品净菜包装接口 ==========
|
||||||
|
|
||||||
|
private val _addCleanPackageState = MutableStateFlow<UiState<Unit?>>(UiState.Idle)
|
||||||
|
val addCleanPackageState: StateFlow<UiState<Unit?>> = _addCleanPackageState.asStateFlow()
|
||||||
|
|
||||||
|
fun addCleanPackage(param: Map<String, Any?>, callback: (Boolean, String) -> Unit) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
val uiState = repository.addCleanPackage(param)
|
||||||
|
when (uiState) {
|
||||||
|
is UiState.Success -> {
|
||||||
|
callback(true, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
is UiState.Error -> {
|
||||||
|
callback(false, uiState.msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
is UiState.Loading -> {}
|
||||||
|
is UiState.Idle -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fun addCleanPackage(param: Map<String, Any?>) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_addCleanPackageState.value = UiState.Loading
|
||||||
|
_addCleanPackageState.value = repository.addCleanPackage(param)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 餐品净菜包装接口 ==========
|
||||||
|
|
||||||
|
private val _addMealPackageState = MutableStateFlow<UiState<Unit?>>(UiState.Idle)
|
||||||
|
val addMealPackageState: StateFlow<UiState<Unit?>> = _addMealPackageState.asStateFlow()
|
||||||
|
|
||||||
|
fun addMealPackage(param: Map<String, Any?>, callback: (Boolean, String) -> Unit) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
val uiState = repository.addMealPackage(param)
|
||||||
|
when (uiState) {
|
||||||
|
is UiState.Success -> {
|
||||||
|
callback(true, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
is UiState.Error -> {
|
||||||
|
callback(false, uiState.msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
is UiState.Loading -> {}
|
||||||
|
is UiState.Idle -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun addMealPackage(param: Map<String, Any>) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_addMealPackageState.value = UiState.Loading
|
||||||
|
_addMealPackageState.value = repository.addMealPackage(param)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 组配任务接口 ==========
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询未完成组配任务(回调版本)
|
||||||
|
*/
|
||||||
|
fun getIncompleteComboTasksWithCallback(
|
||||||
|
deviceCode: String? = null,
|
||||||
|
keyword: String? = null,
|
||||||
|
pageNum: Int = 1,
|
||||||
|
pageSize: Int = 10,
|
||||||
|
onLoading: () -> Unit = {},
|
||||||
|
onResult: (UiState<Page<NutComboTaskVO>?>) -> Unit
|
||||||
|
) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
onLoading()
|
||||||
|
onResult(
|
||||||
|
repository.getIncompleteComboTasks(
|
||||||
|
deviceCode = deviceCode,
|
||||||
|
keyword = keyword,
|
||||||
|
pageNum = pageNum,
|
||||||
|
pageSize = pageSize
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取组配任务详情(回调版本)
|
||||||
|
*/
|
||||||
|
fun getComboTaskDetailWithCallback(
|
||||||
|
id: Long,
|
||||||
|
onLoading: () -> Unit = {},
|
||||||
|
onResult: (UiState<NutComboTaskDetailVO?>) -> Unit
|
||||||
|
) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
onLoading()
|
||||||
|
onResult(repository.getComboTaskDetail(id))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 已入库净菜食材接口 ==========
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按食材名称查询已入库有库存的净菜记录(回调版本)
|
||||||
|
*/
|
||||||
|
fun getInboundIngredientOptionsWithCallback(
|
||||||
|
keyword: String? = null,
|
||||||
|
pageNum: Int = 1,
|
||||||
|
pageSize: Int = 20,
|
||||||
|
onLoading: () -> Unit = {},
|
||||||
|
onResult: (UiState<List<NutCleanInboundIngredientVO>?>) -> Unit
|
||||||
|
) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
onLoading()
|
||||||
|
onResult(repository.getInboundIngredientOptions(keyword))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.shuwei.dish.match.net
|
||||||
|
|
||||||
|
/** 通用分页响应包装 */
|
||||||
|
data class Page<T>(
|
||||||
|
val records: List<T>?,
|
||||||
|
val total: Long?,
|
||||||
|
val size: Int?,
|
||||||
|
val current: Int?,
|
||||||
|
val pages: Int?
|
||||||
|
)
|
||||||
@@ -1,11 +1,10 @@
|
|||||||
package com.shuwei.dish.match.net
|
package com.shuwei.dish.match.net
|
||||||
|
|
||||||
import com.shuwei.dish.match.entity.CookFoodDTO
|
import com.shuwei.dish.match.model.CookFoodDTO
|
||||||
import com.shuwei.dish.match.entity.FoodRecord
|
import com.shuwei.dish.match.model.FoodRecord
|
||||||
import com.shuwei.dish.match.entity.GoodsItem
|
import com.shuwei.dish.match.model.GoodsItem
|
||||||
import okhttp3.MultipartBody
|
import okhttp3.MultipartBody
|
||||||
import okhttp3.RequestBody
|
import okhttp3.RequestBody
|
||||||
import java.io.File
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 网络数据仓库,封装所有 ApiService 调用
|
* 网络数据仓库,封装所有 ApiService 调用
|
||||||
@@ -13,104 +12,42 @@ import java.io.File
|
|||||||
*/
|
*/
|
||||||
class RemoteRepository {
|
class RemoteRepository {
|
||||||
|
|
||||||
/**
|
/** 统一封装 API 调用:处理响应映射和异常转换,返回 UiState */
|
||||||
* 提交制作菜品
|
private suspend fun <T> safeApiCall(call: suspend () -> ApiResponse<T>): UiState<T?> {
|
||||||
* @param entity 菜品实体
|
|
||||||
* @return UiState 包装的结果,Success 表示提交成功,Error 携带错误信息
|
|
||||||
*/
|
|
||||||
suspend fun submitCookFood(entity: CookFoodDTO): UiState<Any?> {
|
|
||||||
return try {
|
return try {
|
||||||
val resp = apiService.submitCookFood(param = entity)
|
val resp = call()
|
||||||
if (resp.isSuccess()) UiState.Success(resp.data)
|
if (resp.isSuccess()) UiState.Success(resp.data)
|
||||||
else UiState.Error(resp.code, resp.msg ?: "")
|
else UiState.Error(resp.code, resp.msg ?: "")
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
val ex = getApiException(e)
|
UiState.Error("-1", getApiException(e).errorMsg)
|
||||||
UiState.Error("-1", ex.errorMsg)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** 提交制作菜品 */
|
||||||
* 查询菜品详情
|
suspend fun submitCookFood(entity: CookFoodDTO): UiState<Any?> =
|
||||||
* @param foodId 菜品 ID
|
safeApiCall { apiService.submitCookFood(param = entity) }
|
||||||
* @return UiState 包装的结果,Success 携带详情数据,Error 携带错误信息
|
|
||||||
*/
|
|
||||||
suspend fun getFoodDetail(foodId: String): UiState<CookFoodDTO?> {
|
|
||||||
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 getFoodDetail(foodId: String): UiState<CookFoodDTO?> =
|
||||||
* @param param 查询参数
|
safeApiCall { apiService.getFoodDetail(foodId = foodId) }
|
||||||
* @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 searchFoodList(param: MutableMap<String, Any>): UiState<MutableList<FoodRecord>?> =
|
||||||
* @param param 查询参数
|
safeApiCall { apiService.searchFoodList(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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/** 查询采样数据列表 */
|
||||||
* 查询物品信息列表(食材 goodsType=0,调料 goodsType=1 共用)
|
suspend fun getSamplingList(param: MutableMap<String, Any>): UiState<MutableList<FoodRecord>?> =
|
||||||
* @param param 查询参数
|
safeApiCall { apiService.getSamplingList(param = param) }
|
||||||
* @return UiState 包装的结果,Success 携带列表数据,Error 携带错误信息
|
|
||||||
*/
|
|
||||||
suspend fun queryGoodsList(param: MutableMap<String, Any>): UiState<MutableList<GoodsItem>?> {
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/** 查询物品信息列表(食材 goodsType=0,调料 goodsType=1 共用) */
|
||||||
* 上次采集数据
|
suspend fun queryGoodsList(param: MutableMap<String, Any>): UiState<MutableList<GoodsItem>?> =
|
||||||
* @param params 参数
|
safeApiCall { apiService.queryGoodsList(param = param) }
|
||||||
* @param foodPics 图片
|
|
||||||
* @return UiState 包装的结果,Success 携带列表数据,Error 携带错误信息
|
/** 上传采集数据 */
|
||||||
*/
|
|
||||||
suspend fun uploadFoodVectorData(
|
suspend fun uploadFoodVectorData(
|
||||||
params: MutableMap<String, RequestBody>,
|
params: MutableMap<String, RequestBody>,
|
||||||
foodPics: List<MultipartBody.Part>
|
foodPics: List<MultipartBody.Part>
|
||||||
): UiState<List<String>?> {
|
): UiState<List<String>?> =
|
||||||
return try {
|
safeApiCall { apiService.uploadFoodVectorData(params = params, foodPics = foodPics) }
|
||||||
val resp = apiService.uploadFoodVectorData(params = params, foodPics = foodPics)
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
package com.shuwei.dish.match.net
|
||||||
|
|
||||||
|
import com.shuwei.dish.match.model.IdDTO
|
||||||
|
import com.shuwei.dish.match.model.NutCanteenVO
|
||||||
|
import com.shuwei.dish.match.model.NutCleanInboundIngredientVO
|
||||||
|
import com.shuwei.dish.match.model.NutComboTaskDetailVO
|
||||||
|
import com.shuwei.dish.match.model.NutComboTaskVO
|
||||||
|
import com.shuwei.dish.match.model.NutDictItemVO
|
||||||
|
import com.shuwei.dish.match.model.NutFoodOptionVO
|
||||||
|
import com.shuwei.dish.match.model.NutMaterOptionVO
|
||||||
|
import com.shuwei.dish.match.model.NutProdComboTaskDTO
|
||||||
|
import com.shuwei.dish.match.model.NutProdComboVideoVO
|
||||||
|
import com.shuwei.dish.match.model.NutSupHygieneIngredientOptionVO
|
||||||
|
import com.shuwei.dish.match.model.NutSupPkgDeviceVO
|
||||||
|
import com.shuwei.dish.match.base.GlobalData
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import retrofit2.Retrofit
|
||||||
|
import retrofit2.converter.gson.GsonConverterFactory
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 网络数据仓库 V2,封装所有 ApiServiceV2 调用
|
||||||
|
*/
|
||||||
|
class RemoteRepositoryV2 {
|
||||||
|
|
||||||
|
private val apiService: ApiServiceV2 by lazy {
|
||||||
|
Retrofit.Builder()
|
||||||
|
.baseUrl(GlobalData.appBaseUrl)
|
||||||
|
.client(HttpManager.instance.client)
|
||||||
|
.addConverterFactory(GsonConverterFactory.create())
|
||||||
|
.build()
|
||||||
|
.create(ApiServiceV2::class.java)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 统一封装 API 调用:处理响应映射和异常转换,返回 UiState */
|
||||||
|
private suspend fun <T> safeApiCall(call: suspend () -> ApiResponse<T>): UiState<T?> {
|
||||||
|
return try {
|
||||||
|
val resp = call()
|
||||||
|
if (resp.isSuccess()) UiState.Success(resp.data)
|
||||||
|
else UiState.Error(resp.code, resp.msg ?: "")
|
||||||
|
} catch (e: Exception) {
|
||||||
|
UiState.Error("-1", getApiException(e).errorMsg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 下拉选项接口 ==========
|
||||||
|
|
||||||
|
suspend fun getCanteenOptions(keyword: String? = null): UiState<List<NutCanteenVO>?> =
|
||||||
|
safeApiCall { apiService.getCanteenOptions(keyword = keyword) }
|
||||||
|
|
||||||
|
suspend fun getDictItems(dictType: String): UiState<List<NutDictItemVO>?> =
|
||||||
|
safeApiCall { apiService.getDictItems(dictType = dictType) }
|
||||||
|
|
||||||
|
suspend fun getMaterOptions(keyword: String? = null): UiState<List<NutMaterOptionVO>?> =
|
||||||
|
safeApiCall { apiService.getMaterOptions(keyword = keyword) }
|
||||||
|
|
||||||
|
suspend fun getDeviceOptions(): UiState<List<NutSupPkgDeviceVO>?> =
|
||||||
|
safeApiCall { apiService.getDeviceOptions() }
|
||||||
|
|
||||||
|
suspend fun getFoodOptions(
|
||||||
|
keyword: String? = null,
|
||||||
|
pageNum: Int = 1,
|
||||||
|
pageSize: Int = 10
|
||||||
|
): UiState<Page<NutFoodOptionVO>?> =
|
||||||
|
safeApiCall { apiService.getFoodOptions(keyword = keyword, pageNum = pageNum, pageSize = pageSize) }
|
||||||
|
|
||||||
|
suspend fun getIngredientByTrace(traceCode: String): UiState<List<NutSupHygieneIngredientOptionVO>?> =
|
||||||
|
safeApiCall { apiService.getIngredientByTrace(traceCode = traceCode) }
|
||||||
|
|
||||||
|
suspend fun getInboundIngredientOptions(keyword: String? = null): UiState<List<NutCleanInboundIngredientVO>?> =
|
||||||
|
safeApiCall { apiService.getInboundIngredientOptions(keyword = keyword) }
|
||||||
|
|
||||||
|
// ========== 净菜组配接口 ==========
|
||||||
|
|
||||||
|
suspend fun addComboTask(param: NutComboTaskDetailVO): UiState<Unit?> =
|
||||||
|
safeApiCall { apiService.addComboTask(param = param) }
|
||||||
|
|
||||||
|
suspend fun startComboTask(id: Long): UiState<Unit?> =
|
||||||
|
safeApiCall { apiService.startComboTask(param = IdDTO(id)) }
|
||||||
|
|
||||||
|
suspend fun finishComboTask(id: Long): UiState<Unit?> =
|
||||||
|
safeApiCall { apiService.finishComboTask(param = IdDTO(id)) }
|
||||||
|
|
||||||
|
suspend fun getComboTaskVideo(taskNo: String): UiState<NutProdComboVideoVO?> =
|
||||||
|
safeApiCall { apiService.getComboTaskVideo(taskNo = taskNo) }
|
||||||
|
|
||||||
|
// ========== 单品净菜包装接口 ==========
|
||||||
|
|
||||||
|
suspend fun addCleanPackage(param: Map<String, Any?>): UiState<Unit?> =
|
||||||
|
safeApiCall { apiService.addCleanPackage(param = param) }
|
||||||
|
|
||||||
|
// ========== 餐品净菜包装接口 ==========
|
||||||
|
|
||||||
|
suspend fun addMealPackage(param: Map<String, Any?>): UiState<Unit?> =
|
||||||
|
safeApiCall { apiService.addMealPackage(param = param) }
|
||||||
|
|
||||||
|
// ========== 组配任务接口 ==========
|
||||||
|
|
||||||
|
suspend fun getIncompleteComboTasks(
|
||||||
|
deviceCode: String? = null,
|
||||||
|
keyword: String? = null,
|
||||||
|
pageNum: Int = 1,
|
||||||
|
pageSize: Int = 10
|
||||||
|
): UiState<Page<NutComboTaskVO>?> =
|
||||||
|
safeApiCall { apiService.getIncompleteComboTasks(deviceCode = deviceCode, keyword = keyword, pageNum = pageNum, pageSize = pageSize) }
|
||||||
|
|
||||||
|
suspend fun getComboTaskDetail(id: Long): UiState<NutComboTaskDetailVO?> =
|
||||||
|
safeApiCall { apiService.getComboTaskDetail(id = id) }
|
||||||
|
|
||||||
|
}
|
||||||
@@ -213,6 +213,11 @@ object ObjectBox {
|
|||||||
getBox<Food>()?.query(Food_.name.equal(name))?.build()?.remove()
|
getBox<Food>()?.query(Food_.name.equal(name))?.build()?.remove()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 清除所有向量采集数据
|
||||||
|
suspend fun removeAll() = safeDbOp {
|
||||||
|
getBox<Food>()?.removeAll()
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 按名称分组统计采集数量
|
* 按名称分组统计采集数量
|
||||||
* 使用属性查询只加载 name 字段,不加载 foodVector,节省大量内存
|
* 使用属性查询只加载 name 字段,不加载 foodVector,节省大量内存
|
||||||
|
|||||||
@@ -28,7 +28,6 @@ class MdnsDiscoveryManager(private val context: Context) {
|
|||||||
|
|
||||||
/** 待解析队列,串行处理避免并发解析失败 */
|
/** 待解析队列,串行处理避免并发解析失败 */
|
||||||
private val resolveQueue = LinkedList<NsdServiceInfo>()
|
private val resolveQueue = LinkedList<NsdServiceInfo>()
|
||||||
@Volatile
|
|
||||||
private var isResolving = false
|
private var isResolving = false
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import com.shuwei.dish.match.utils.NetworkUtil
|
|||||||
import com.shuwei.dish.match.utils.WeightUtil
|
import com.shuwei.dish.match.utils.WeightUtil
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.cancel
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
@@ -34,6 +36,9 @@ object ScaleServiceManager {
|
|||||||
|
|
||||||
private const val TAG = "ScaleServiceManager"
|
private const val TAG = "ScaleServiceManager"
|
||||||
|
|
||||||
|
@Volatile private var isStarted = false
|
||||||
|
private var serviceScope: CoroutineScope? = null
|
||||||
|
|
||||||
private var mdnsRegister: MdnsRegisterManager? = null
|
private var mdnsRegister: MdnsRegisterManager? = null
|
||||||
private var wsServer: ScaleWebSocketServer? = null
|
private var wsServer: ScaleWebSocketServer? = null
|
||||||
private var udpSender: UdpBroadcastSender? = null
|
private var udpSender: UdpBroadcastSender? = null
|
||||||
@@ -135,6 +140,9 @@ object ScaleServiceManager {
|
|||||||
* 启动所有秤服务,在 Application.onCreate() 中调用
|
* 启动所有秤服务,在 Application.onCreate() 中调用
|
||||||
*/
|
*/
|
||||||
fun start(context: Context) {
|
fun start(context: Context) {
|
||||||
|
if (isStarted) return
|
||||||
|
isStarted = true
|
||||||
|
serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||||
val deviceId = GlobalData.deviceId
|
val deviceId = GlobalData.deviceId
|
||||||
val role = GlobalData.deviceRole
|
val role = GlobalData.deviceRole
|
||||||
Log.d(TAG, "启动秤服务, deviceId=$deviceId, role=$role")
|
Log.d(TAG, "启动秤服务, deviceId=$deviceId, role=$role")
|
||||||
@@ -180,14 +188,14 @@ object ScaleServiceManager {
|
|||||||
}
|
}
|
||||||
it.onDeviceConnected = { remoteId ->
|
it.onDeviceConnected = { remoteId ->
|
||||||
// 子设备连接成功时,从 Room 读取全量配置并单独推送给该设备
|
// 子设备连接成功时,从 Room 读取全量配置并单独推送给该设备
|
||||||
CoroutineScope(Dispatchers.IO).launch {
|
serviceScope?.launch {
|
||||||
val slots = BaseApp.instance!!.database.seasoningSlotDao()
|
val slots = BaseApp.instance?.database?.seasoningSlotDao()
|
||||||
.queryAll()
|
?.queryAll()
|
||||||
.map { slot ->
|
?.map { slot ->
|
||||||
ScaleEvent.SlotConfig(
|
ScaleEvent.SlotConfig(
|
||||||
slot.deviceId, slot.address, slot.goodsId, slot.goodsName
|
slot.deviceId, slot.address, slot.goodsId, slot.goodsName
|
||||||
)
|
)
|
||||||
}
|
} ?: return@launch
|
||||||
if (slots.isNotEmpty()) sendSeasoningConfigTo(remoteId, slots)
|
if (slots.isNotEmpty()) sendSeasoningConfigTo(remoteId, slots)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -246,6 +254,9 @@ object ScaleServiceManager {
|
|||||||
* 停止所有秤服务,在 Application.onTerminate() 或退出时调用
|
* 停止所有秤服务,在 Application.onTerminate() 或退出时调用
|
||||||
*/
|
*/
|
||||||
fun stop() {
|
fun stop() {
|
||||||
|
serviceScope?.cancel()
|
||||||
|
serviceScope = null
|
||||||
|
isStarted = false
|
||||||
mdnsDiscovery?.stopDiscovery()
|
mdnsDiscovery?.stopDiscovery()
|
||||||
udpReceiver?.stop()
|
udpReceiver?.stop()
|
||||||
udpSender?.stop()
|
udpSender?.stop()
|
||||||
|
|||||||
@@ -138,7 +138,8 @@ class ScaleWebSocketClient {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
connections[deviceId] = ws
|
// 写入新连接前先关闭旧连接,避免 IP 变化时旧 ws 对象悬空造成 TCP 资源泄漏
|
||||||
|
connections.put(deviceId, ws)?.close(1000, "新连接替换")
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -9,9 +9,11 @@ import org.java_websocket.WebSocket
|
|||||||
import org.java_websocket.handshake.ClientHandshake
|
import org.java_websocket.handshake.ClientHandshake
|
||||||
import org.java_websocket.server.WebSocketServer
|
import org.java_websocket.server.WebSocketServer
|
||||||
import java.net.InetSocketAddress
|
import java.net.InetSocketAddress
|
||||||
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
import java.util.concurrent.Executors
|
import java.util.concurrent.Executors
|
||||||
import java.util.concurrent.ScheduledFuture
|
import java.util.concurrent.ScheduledFuture
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 秤数据 WebSocket 服务端(主设备和子设备均运行)
|
* 秤数据 WebSocket 服务端(主设备和子设备均运行)
|
||||||
@@ -46,13 +48,13 @@ class ScaleWebSocketServer(private val deviceId: String, private val context: Co
|
|||||||
get() = server?.connections?.isNotEmpty() == true
|
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;保证窗口结束时最新数据被推送 */
|
/** 节流窗口内的延迟推送任务,key=address;保证窗口结束时最新数据被推送 */
|
||||||
private val pendingPushTasks = mutableMapOf<Int, ScheduledFuture<*>>()
|
private val pendingPushTasks = ConcurrentHashMap<Int, ScheduledFuture<*>>()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 启动 WebSocket 服务器,并注册 WeightUtil 回调
|
* 启动 WebSocket 服务器,并注册 WeightUtil 回调
|
||||||
@@ -67,7 +69,7 @@ class ScaleWebSocketServer(private val deviceId: String, private val context: Co
|
|||||||
WeightUtil.addWeightListener(TAG) { address, state, weight ->
|
WeightUtil.addWeightListener(TAG) { address, state, weight ->
|
||||||
Log.d(TAG, "WebSocket 设备${deviceId}推送数据, address=$address, state=$state, weight=$weight")
|
Log.d(TAG, "WebSocket 设备${deviceId}推送数据, address=$address, state=$state, weight=$weight")
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
// 方案三:数据未变化时直接跳过,避免无效推送
|
// 数据未变化时直接跳过,避免无效推送
|
||||||
val last = latestData[address]
|
val last = latestData[address]
|
||||||
if (last?.weight == weight && last.state == state) return@addWeightListener
|
if (last?.weight == weight && last.state == state) return@addWeightListener
|
||||||
|
|
||||||
@@ -89,7 +91,7 @@ class ScaleWebSocketServer(private val deviceId: String, private val context: Co
|
|||||||
pendingPushTasks.remove(address)?.cancel(false)
|
pendingPushTasks.remove(address)?.cancel(false)
|
||||||
broadcast(gson.toJson(data))
|
broadcast(gson.toJson(data))
|
||||||
} else if (pendingPushTasks[address] == null) {
|
} else if (pendingPushTasks[address] == null) {
|
||||||
// 方案一:窗口内首次触发时安排一个 trailing 推送,保证窗口末尾推最新值
|
// 窗口内首次触发:安排 trailing 推送,保证窗口末尾推最新值
|
||||||
val delay = THROTTLE_MS - (now - lastPush)
|
val delay = THROTTLE_MS - (now - lastPush)
|
||||||
if (!scheduler.isShutdown) {
|
if (!scheduler.isShutdown) {
|
||||||
pendingPushTasks[address] = scheduler.schedule({
|
pendingPushTasks[address] = scheduler.schedule({
|
||||||
@@ -156,10 +158,10 @@ class ScaleWebSocketServer(private val deviceId: String, private val context: Co
|
|||||||
WebSocketServer(InetSocketAddress(port)) {
|
WebSocketServer(InetSocketAddress(port)) {
|
||||||
|
|
||||||
/** 当前活跃连接计数,用于替代 connections.isNullOrEmpty() 避免竞态 */
|
/** 当前活跃连接计数,用于替代 connections.isNullOrEmpty() 避免竞态 */
|
||||||
private var connectionCount = 0
|
private val connectionCount = AtomicInteger(0)
|
||||||
|
|
||||||
override fun onOpen(conn: WebSocket, handshake: ClientHandshake) {
|
override fun onOpen(conn: WebSocket, handshake: ClientHandshake) {
|
||||||
connectionCount++
|
connectionCount.incrementAndGet()
|
||||||
Log.d(TAG, "主设备已连接: ${conn.remoteSocketAddress}")
|
Log.d(TAG, "主设备已连接: ${conn.remoteSocketAddress}")
|
||||||
onConnectionChanged?.invoke(true)
|
onConnectionChanged?.invoke(true)
|
||||||
|
|
||||||
@@ -194,8 +196,8 @@ class ScaleWebSocketServer(private val deviceId: String, private val context: Co
|
|||||||
override fun onClose(conn: WebSocket, code: Int, reason: String, remote: Boolean) {
|
override fun onClose(conn: WebSocket, code: Int, reason: String, remote: Boolean) {
|
||||||
Log.d(TAG, "主设备已断开: ${conn.remoteSocketAddress}, reason=$reason")
|
Log.d(TAG, "主设备已断开: ${conn.remoteSocketAddress}, reason=$reason")
|
||||||
// 用计数器判断是否还有活跃连接,避免依赖 connections 集合的移除时机导致竞态
|
// 用计数器判断是否还有活跃连接,避免依赖 connections 集合的移除时机导致竞态
|
||||||
if (--connectionCount <= 0) {
|
if (connectionCount.decrementAndGet() <= 0) {
|
||||||
connectionCount = 0
|
connectionCount.set(0)
|
||||||
onConnectionChanged?.invoke(false)
|
onConnectionChanged?.invoke(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,716 @@
|
|||||||
|
package com.shuwei.dish.match.ui
|
||||||
|
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Bundle
|
||||||
|
import androidx.core.content.IntentCompat
|
||||||
|
import androidx.recyclerview.widget.GridLayoutManager
|
||||||
|
import com.shuwei.dish.match.adapter.FormFieldAdapter
|
||||||
|
import com.shuwei.dish.match.base.BaseActivity
|
||||||
|
import com.shuwei.dish.match.base.GlobalData
|
||||||
|
import com.shuwei.dish.match.databinding.ActivityCleanPackBinding
|
||||||
|
import com.shuwei.dish.match.model.DictType
|
||||||
|
import com.shuwei.dish.match.model.FieldType
|
||||||
|
import com.shuwei.dish.match.model.FormField
|
||||||
|
import com.shuwei.dish.match.model.NutCleanInboundIngredientVO
|
||||||
|
import com.shuwei.dish.match.model.NutFoodOptionVO
|
||||||
|
import com.shuwei.dish.match.net.NetViewModelV2
|
||||||
|
import com.shuwei.dish.match.net.UiState
|
||||||
|
import com.shuwei.dish.match.utils.AddressUtil
|
||||||
|
import com.shuwei.dish.match.utils.SpTool
|
||||||
|
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.roundedOneDecimalPlace
|
||||||
|
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 kotlinx.coroutines.Job
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 净菜包装表单页面,根据类型显示不同的表单字段
|
||||||
|
*/
|
||||||
|
class CleanPackActivity : BaseActivity() {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val TAG = "CleanPackActivity"
|
||||||
|
|
||||||
|
/** 单品净菜包装 */
|
||||||
|
const val TYPE_CLEAN = 1
|
||||||
|
|
||||||
|
/** 餐品净菜包装 */
|
||||||
|
const val TYPE_MEAL = 2
|
||||||
|
|
||||||
|
const val EXTRA_TYPE = "extra_type"
|
||||||
|
}
|
||||||
|
|
||||||
|
private lateinit var binding: ActivityCleanPackBinding
|
||||||
|
private val fields = mutableListOf<FormField>()
|
||||||
|
private val formAdapter by lazy { FormFieldAdapter(fields) }
|
||||||
|
private val viewModelV2 by lazy { NetViewModelV2() }
|
||||||
|
private var packType: Int = TYPE_CLEAN
|
||||||
|
|
||||||
|
// 字段引用,用于跨方法访问
|
||||||
|
private var traceCodeField: FormField? = null
|
||||||
|
private var cleanNameField: FormField? = null
|
||||||
|
private var packageMethodField: FormField? = null
|
||||||
|
private var deviceField: FormField? = null
|
||||||
|
private var foodOptionsField: FormField? = null
|
||||||
|
|
||||||
|
// private var packagingSpecField: FormField? = null
|
||||||
|
private var ingredientsField: FormField? = null
|
||||||
|
private var traceCodeJob: Job? = null
|
||||||
|
|
||||||
|
// 缓存餐品选项完整数据,用于选择后获取 compositions
|
||||||
|
private val foodOptionsData = mutableListOf<NutFoodOptionVO>()
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
statusBarDarkFont(enable = true)
|
||||||
|
|
||||||
|
binding = ActivityCleanPackBinding.inflate(layoutInflater)
|
||||||
|
setContentView(binding.root)
|
||||||
|
setHeaderBackground()
|
||||||
|
packType = intent.getIntExtra(EXTRA_TYPE, TYPE_CLEAN)
|
||||||
|
|
||||||
|
// 根据类型设置标题
|
||||||
|
val title = when (packType) {
|
||||||
|
TYPE_CLEAN -> "净菜包"
|
||||||
|
TYPE_MEAL -> "餐品净菜包"
|
||||||
|
else -> return
|
||||||
|
}
|
||||||
|
|
||||||
|
setTitleBar(titleBarAction = {
|
||||||
|
it.visible()
|
||||||
|
it.setOnClickListener { v ->
|
||||||
|
hideKeyboard()
|
||||||
|
}
|
||||||
|
}, titleAction = {
|
||||||
|
it.text = title
|
||||||
|
}, rightIconAction = {
|
||||||
|
it.gone()
|
||||||
|
}, backAction = {
|
||||||
|
it.visible()
|
||||||
|
it.setOnClickListener {
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
addWeightListener()
|
||||||
|
|
||||||
|
// 初始化 RecyclerView
|
||||||
|
// val flexboxLayoutManager = FlexboxLayoutManager(this).apply {
|
||||||
|
// flexDirection = FlexDirection.ROW
|
||||||
|
// flexWrap = FlexWrap.WRAP
|
||||||
|
// alignItems = AlignItems.STRETCH
|
||||||
|
// }
|
||||||
|
val layoutManager = GridLayoutManager(this, 2)
|
||||||
|
binding.rvForm.layoutManager = layoutManager
|
||||||
|
binding.rvForm.adapter = formAdapter
|
||||||
|
|
||||||
|
// 根据类型初始化表单数据
|
||||||
|
when (packType) {
|
||||||
|
TYPE_CLEAN -> initCleanPackFields()
|
||||||
|
TYPE_MEAL -> initMealPackFields()
|
||||||
|
}
|
||||||
|
|
||||||
|
binding.btnSubmit.setOnClickListener {
|
||||||
|
hideKeyboard()
|
||||||
|
if (!validateFields()) return@setOnClickListener
|
||||||
|
|
||||||
|
// when (packType) {
|
||||||
|
// TYPE_CLEAN -> submitCleanPackage()
|
||||||
|
// TYPE_MEAL -> submitMealPackage()
|
||||||
|
// }
|
||||||
|
|
||||||
|
submitCleanPackage()
|
||||||
|
}
|
||||||
|
|
||||||
|
binding.ivClearWeight.clickWithDebounce {
|
||||||
|
initialWeight = 0.0
|
||||||
|
SpTool.configWeight = 0
|
||||||
|
WeightUtil.tareTwo(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
binding.flSearchBar.clickWithDebounce {
|
||||||
|
val launchIntent = Intent(this, FoodSearchV2Activity::class.java)
|
||||||
|
startActivity(launchIntent) { data ->
|
||||||
|
data?:return@startActivity
|
||||||
|
IntentCompat.getParcelableExtra<NutCleanInboundIngredientVO>(
|
||||||
|
data,
|
||||||
|
FoodSearchV2Activity.INGREDIENT_ITEM,
|
||||||
|
NutCleanInboundIngredientVO::class.java
|
||||||
|
)?.let { food ->
|
||||||
|
this@CleanPackActivity.currentFood = food
|
||||||
|
binding.tvFoodName.text = food.ingredientName
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var currentFood: NutCleanInboundIngredientVO? = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化单品净菜包装表单字段
|
||||||
|
* 对应接口 NutSupCleanPackageDTO
|
||||||
|
*/
|
||||||
|
private fun initCleanPackFields() {
|
||||||
|
fields.clear()
|
||||||
|
|
||||||
|
// // 溯源码
|
||||||
|
// traceCodeField = FormField(
|
||||||
|
// label = "溯源码",
|
||||||
|
// type = FieldType.TEXT,
|
||||||
|
// apiKey = "traceCode",
|
||||||
|
// required = true
|
||||||
|
// )
|
||||||
|
// fields.add(traceCodeField!!)
|
||||||
|
|
||||||
|
// 净菜名称
|
||||||
|
// cleanNameField = FormField(
|
||||||
|
// label = "净菜名称",
|
||||||
|
// type = FieldType.DROPDOWN,
|
||||||
|
//// apiKey = "cleanName",
|
||||||
|
// extraApiKeys = mapOf("cleanName" to "value", "traceCode" to "type"),
|
||||||
|
// required = true
|
||||||
|
// )
|
||||||
|
// fields.add(cleanNameField!!)
|
||||||
|
// 包装方式(下拉)
|
||||||
|
packageMethodField = FormField(
|
||||||
|
label = "包装方式",
|
||||||
|
type = FieldType.DROPDOWN,
|
||||||
|
// extraApiKeys = mapOf("packageMethodId" to "id", "packageMethod" to "value"),
|
||||||
|
extraApiKeys = mapOf("packageMethod" to "type"),
|
||||||
|
required = true
|
||||||
|
)
|
||||||
|
fields.add(packageMethodField!!)
|
||||||
|
|
||||||
|
fields.add(
|
||||||
|
FormField(label = "包装规格", type = FieldType.TEXT, apiKey = "spec", required = false)
|
||||||
|
)
|
||||||
|
|
||||||
|
fields.add(
|
||||||
|
FormField(
|
||||||
|
label = "包装份数",
|
||||||
|
type = FieldType.INTEGER,
|
||||||
|
apiKey = "quantity",
|
||||||
|
required = true,
|
||||||
|
hint = "请输入整数"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
fields.add(
|
||||||
|
FormField(
|
||||||
|
label = "包装日期",
|
||||||
|
type = FieldType.DATE_PICKER,
|
||||||
|
apiKey = "packageDate",
|
||||||
|
required = true
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
fields.add(
|
||||||
|
FormField(
|
||||||
|
label = "保质期至",
|
||||||
|
type = FieldType.DATE_PICKER,
|
||||||
|
apiKey = "expiryDate",
|
||||||
|
required = true
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
fields.add(
|
||||||
|
FormField(
|
||||||
|
label = "存放温度(℃)",
|
||||||
|
type = FieldType.DECIMAL,
|
||||||
|
apiKey = "storageTemp",
|
||||||
|
required = false,
|
||||||
|
hint = "请输入小数"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
fields.add(
|
||||||
|
FormField(
|
||||||
|
label = "包装人",
|
||||||
|
type = FieldType.TEXT,
|
||||||
|
apiKey = "operator",
|
||||||
|
required = false
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
// 终端设备(下拉)
|
||||||
|
deviceField = FormField(
|
||||||
|
label = "终端设备",
|
||||||
|
type = FieldType.DROPDOWN,
|
||||||
|
extraApiKeys = mapOf("deviceId" to "id"),
|
||||||
|
required = false
|
||||||
|
)
|
||||||
|
fields.add(deviceField!!)
|
||||||
|
|
||||||
|
formAdapter.submitList(fields.filter { !it.hidden })
|
||||||
|
|
||||||
|
// 监听溯源码输入,自动填充净菜名称
|
||||||
|
// setupTraceCodeQuery()
|
||||||
|
// 加载下拉选项
|
||||||
|
// loadDictItems("sup_package_method", packageMethodField!!)
|
||||||
|
loadDictItemsWithCallback("sup_package_method", packageMethodField!!)
|
||||||
|
loadDeviceOptionsWithCallback(deviceField)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化餐品净菜包装表单字段
|
||||||
|
* 对应接口 NutSupMealPackageDTO
|
||||||
|
*/
|
||||||
|
private fun initMealPackFields() {
|
||||||
|
fields.clear()
|
||||||
|
|
||||||
|
// 包装餐品(下拉)
|
||||||
|
foodOptionsField = FormField(
|
||||||
|
label = "包装餐品", type = FieldType.DROPDOWN,
|
||||||
|
extraApiKeys = mapOf("foodId" to "id"),
|
||||||
|
required = true
|
||||||
|
)
|
||||||
|
fields.add(foodOptionsField!!)
|
||||||
|
|
||||||
|
// 包装规格(下拉)
|
||||||
|
// packagingSpecField = FormField(
|
||||||
|
// label = "包装规格", type = FieldType.DROPDOWN,
|
||||||
|
// extraApiKeys = mapOf("spec" to "value"),
|
||||||
|
// required = true
|
||||||
|
// )
|
||||||
|
// fields.add(packagingSpecField!!)
|
||||||
|
|
||||||
|
// 包装方式(下拉)
|
||||||
|
packageMethodField =
|
||||||
|
FormField(
|
||||||
|
label = "包装方式", type = FieldType.DROPDOWN,
|
||||||
|
// extraApiKeys = mapOf("packageMethodId" to "id", "packageMethod" to "value"),
|
||||||
|
extraApiKeys = mapOf("packageMethod" to "type"),
|
||||||
|
required = true
|
||||||
|
)
|
||||||
|
fields.add(packageMethodField!!)
|
||||||
|
|
||||||
|
// 包装份数
|
||||||
|
fields.add(
|
||||||
|
FormField(
|
||||||
|
label = "包装份数", type = FieldType.INTEGER,
|
||||||
|
apiKey = "quantity", required = true, hint = "请输入份数"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
// 包含食材(子列表容器)
|
||||||
|
val ingredientTemplate = listOf(
|
||||||
|
FormField(
|
||||||
|
label = "食材溯源码",
|
||||||
|
type = FieldType.TEXT,
|
||||||
|
apiKey = "traceCode",
|
||||||
|
required = true,
|
||||||
|
hint = "溯源码"
|
||||||
|
),
|
||||||
|
FormField(
|
||||||
|
label = "食材名称",
|
||||||
|
type = FieldType.FIXED,
|
||||||
|
extraApiKeys = mapOf("materId" to "id", "ingredientName" to "value"),
|
||||||
|
required = true
|
||||||
|
),
|
||||||
|
FormField(
|
||||||
|
label = "分类", type = FieldType.FIXED,
|
||||||
|
// extraApiKeys = mapOf("classify" to "value"),
|
||||||
|
apiKey = "classify",
|
||||||
|
required = true,
|
||||||
|
// options = mutableListOf(
|
||||||
|
// DictType(id = "1", value = "蔬菜类", type = "蔬菜类"),
|
||||||
|
// DictType(id = "2", value = "肉禽类", type = "肉禽类"),
|
||||||
|
// DictType(id = "3", value = "水产类", type = "水产类"),
|
||||||
|
// )
|
||||||
|
),
|
||||||
|
FormField(
|
||||||
|
label = "每份用量",
|
||||||
|
type = FieldType.TEXT,
|
||||||
|
apiKey = "amount",
|
||||||
|
required = true,
|
||||||
|
hint = "如 120g"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
ingredientsField = FormField(
|
||||||
|
label = "包含食材", type = FieldType.CHILDREN,
|
||||||
|
required = true,
|
||||||
|
children = ingredientTemplate,
|
||||||
|
childAddLabel = "+ 添加食材"
|
||||||
|
)
|
||||||
|
fields.add(ingredientsField!!)
|
||||||
|
|
||||||
|
// 餐品选中后,根据 position 从 compositions 加载包含食材
|
||||||
|
foodOptionsField!!.onDropdownSelected = { dictType ->
|
||||||
|
val position = dictType.position
|
||||||
|
if (position >= 0 && position < foodOptionsData.size) {
|
||||||
|
val compositions = foodOptionsData[position].compositions ?: emptyList()
|
||||||
|
val ingredients = ingredientsField!!
|
||||||
|
ingredients.childrenRows.clear()
|
||||||
|
for (comp in compositions) {
|
||||||
|
// 每行复制模板的4个字段,将 composition 数据填充进去
|
||||||
|
val newRow = ingredients.children?.map { template ->
|
||||||
|
// 根据 extraApiKeys 判断是否为食材名称字段
|
||||||
|
val hasMaterId = template.extraApiKeys.containsKey("materId")
|
||||||
|
val hasIngredientName = template.extraApiKeys.containsKey("ingredientName")
|
||||||
|
val fieldValue = if (hasIngredientName) comp.ingredientName ?: "" else ""
|
||||||
|
val fieldExtraValues = mutableMapOf<String, String>()
|
||||||
|
template.extraApiKeys.forEach { (apiKey, dictField) ->
|
||||||
|
fieldExtraValues[apiKey] = when (dictField) {
|
||||||
|
"id" -> comp.materId?.toString() ?: ""
|
||||||
|
"value" -> comp.ingredientName ?: ""
|
||||||
|
else -> ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
FormField(
|
||||||
|
label = template.label,
|
||||||
|
type = template.type,
|
||||||
|
apiKey = template.apiKey,
|
||||||
|
extraApiKeys = template.extraApiKeys,
|
||||||
|
required = template.required,
|
||||||
|
hint = template.hint,
|
||||||
|
options = template.options,
|
||||||
|
value = fieldValue,
|
||||||
|
extraValues = fieldExtraValues
|
||||||
|
)
|
||||||
|
}?.toMutableList() ?: mutableListOf()
|
||||||
|
ingredients.childrenRows.add(newRow)
|
||||||
|
}
|
||||||
|
val idx = fields.indexOf(ingredients)
|
||||||
|
if (idx >= 0) formAdapter.notifyItemChanged(idx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 包装日期
|
||||||
|
fields.add(
|
||||||
|
FormField(
|
||||||
|
label = "包装日期", type = FieldType.DATE_PICKER,
|
||||||
|
apiKey = "packageDate", required = true
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
// 保质期至
|
||||||
|
fields.add(
|
||||||
|
FormField(
|
||||||
|
label = "保质期至", type = FieldType.DATE_PICKER,
|
||||||
|
apiKey = "expiryDate", required = true
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
// 存放温度
|
||||||
|
fields.add(
|
||||||
|
FormField(
|
||||||
|
label = "存放温度(℃)", type = FieldType.DECIMAL,
|
||||||
|
apiKey = "storageTemp", required = false, hint = "如 3.8"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
// 包装人
|
||||||
|
fields.add(
|
||||||
|
FormField(
|
||||||
|
label = "包装人",
|
||||||
|
type = FieldType.FIXED,
|
||||||
|
apiKey = "operator",
|
||||||
|
required = false,
|
||||||
|
hint = "请输入包装人",
|
||||||
|
value = GlobalData.userName
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
// 终端设备(下拉)
|
||||||
|
deviceField = FormField(
|
||||||
|
label = "终端设备", type = FieldType.DROPDOWN,
|
||||||
|
extraApiKeys = mapOf("deviceId" to "id"),
|
||||||
|
required = false
|
||||||
|
)
|
||||||
|
fields.add(deviceField!!)
|
||||||
|
|
||||||
|
// 操作类型(暂时固定)
|
||||||
|
fields.add(
|
||||||
|
FormField(
|
||||||
|
label = "操作类型", type = FieldType.FIXED,
|
||||||
|
apiKey = "opType",
|
||||||
|
required = true,
|
||||||
|
value = "设备自动"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
formAdapter.submitList(fields.filter { !it.hidden })
|
||||||
|
|
||||||
|
// 加载下拉选项
|
||||||
|
loadFoodOptionsWithKeyword()
|
||||||
|
loadDictItemsWithCallback("sup_package_method", packageMethodField!!)
|
||||||
|
// loadDictItemsWithCallback("sup_package_spec", packagingSpecField!!)
|
||||||
|
loadDeviceOptionsWithCallback(deviceField)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 监听溯源码字段变化,输入后 800ms 无变化则触发查询
|
||||||
|
*/
|
||||||
|
private fun setupTraceCodeQuery() {
|
||||||
|
// val field = traceCodeField ?: return
|
||||||
|
// val cleanField = cleanNameField ?: return
|
||||||
|
//
|
||||||
|
// traceCodeJob = lifecycleScope.launch {
|
||||||
|
// var lastValue = ""
|
||||||
|
// while (true) {
|
||||||
|
// val current = field.value.trim()
|
||||||
|
// if (current != lastValue && current.isNotBlank()) {
|
||||||
|
// lastValue = current
|
||||||
|
// viewModelV2.getIngredientByTrace(current)
|
||||||
|
// }
|
||||||
|
// delay(800)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// lifecycleScope.launch {
|
||||||
|
// viewModelV2.ingredientByTraceState.collect { state ->
|
||||||
|
// when (state) {
|
||||||
|
// is UiState.Success -> {
|
||||||
|
// val data = state.data
|
||||||
|
// if (!data.isNullOrEmpty()) {
|
||||||
|
// val info = data[0]
|
||||||
|
// cleanField.value = info.materName ?: ""
|
||||||
|
// // 通知 adapter 刷新净菜名称字段(索引为 1)
|
||||||
|
// val idx = fields.indexOf(cleanField)
|
||||||
|
// if (idx >= 0) formAdapter.notifyItemChanged(idx)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// is UiState.Error -> {
|
||||||
|
// toast(state.msg)
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// else -> {}
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
super.onDestroy()
|
||||||
|
traceCodeJob?.cancel()
|
||||||
|
WeightUtil.removeWeightListener(TAG)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 加载餐品下拉选项(回调版本)
|
||||||
|
*/
|
||||||
|
private fun loadFoodOptionsWithKeyword() {
|
||||||
|
val field = foodOptionsField ?: return
|
||||||
|
viewModelV2.getFoodOptionsWithCallback(
|
||||||
|
onLoading = {},
|
||||||
|
onResult = { state ->
|
||||||
|
when (state) {
|
||||||
|
is UiState.Success -> {
|
||||||
|
val records = state.data?.records ?: emptyList()
|
||||||
|
foodOptionsData.clear()
|
||||||
|
foodOptionsData.addAll(records)
|
||||||
|
val options = records.mapIndexed { index, vo ->
|
||||||
|
DictType(
|
||||||
|
id = vo.foodId?.toString() ?: "",
|
||||||
|
value = vo.foodName ?: "",
|
||||||
|
type = vo.foodCode ?: "",
|
||||||
|
position = index
|
||||||
|
)
|
||||||
|
}
|
||||||
|
field.options.clear()
|
||||||
|
field.options.addAll(options)
|
||||||
|
val index = fields.indexOf(field)
|
||||||
|
if (index >= 0) formAdapter.notifyItemChanged(index)
|
||||||
|
}
|
||||||
|
|
||||||
|
is UiState.Error -> {
|
||||||
|
toast("加载餐品列表失败:${state.msg}")
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 加载字典项下拉(回调版本),适合多次不同 dictType 的场景
|
||||||
|
*/
|
||||||
|
private fun loadDictItemsWithCallback(dictType: String, targetField: FormField) {
|
||||||
|
viewModelV2.getDictItemsWithCallback(
|
||||||
|
dictType = dictType,
|
||||||
|
onLoading = {},
|
||||||
|
onResult = { state ->
|
||||||
|
when (state) {
|
||||||
|
is UiState.Success -> {
|
||||||
|
val options = state.data?.map { vo ->
|
||||||
|
DictType(
|
||||||
|
id = vo.id?.toString() ?: "",
|
||||||
|
value = vo.dictLabel ?: "",
|
||||||
|
type = vo.dictCode ?: ""
|
||||||
|
)
|
||||||
|
} ?: emptyList()
|
||||||
|
targetField.options.clear()
|
||||||
|
targetField.options.addAll(options)
|
||||||
|
val index = fields.indexOf(targetField)
|
||||||
|
if (index >= 0) formAdapter.notifyItemChanged(index)
|
||||||
|
}
|
||||||
|
|
||||||
|
is UiState.Error -> {
|
||||||
|
toast("加载字典项失败:${state.msg}")
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 加载设备下拉(回调版本),用于餐品净菜包装
|
||||||
|
*/
|
||||||
|
private fun loadDeviceOptionsWithCallback(deviceField: FormField? = null) {
|
||||||
|
val field = deviceField ?: return
|
||||||
|
viewModelV2.getDeviceOptionsWithCallback(
|
||||||
|
onLoading = {},
|
||||||
|
onResult = { state ->
|
||||||
|
when (state) {
|
||||||
|
is UiState.Success -> {
|
||||||
|
val options = state.data?.map { vo ->
|
||||||
|
DictType(
|
||||||
|
id = vo.id?.toString() ?: "",
|
||||||
|
value = vo.deviceName ?: "",
|
||||||
|
type = vo.deviceNo ?: ""
|
||||||
|
)
|
||||||
|
} ?: emptyList()
|
||||||
|
field.options.clear()
|
||||||
|
field.options.addAll(options)
|
||||||
|
val index = fields.indexOf(field)
|
||||||
|
if (index >= 0) formAdapter.notifyItemChanged(index)
|
||||||
|
}
|
||||||
|
|
||||||
|
is UiState.Error -> {
|
||||||
|
toast("加载设备列表失败:${state.msg}")
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验必填字段
|
||||||
|
*/
|
||||||
|
private fun validateFields(): Boolean {
|
||||||
|
for (field in fields) {
|
||||||
|
if (field.hidden) continue
|
||||||
|
if (field.required) {
|
||||||
|
if (field.type == FieldType.CHILDREN) {
|
||||||
|
if (field.childrenRows.isEmpty()) {
|
||||||
|
toast("请至少添加一条${field.label}")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
// 校验子行必填
|
||||||
|
for ((rowIdx, row) in field.childrenRows.withIndex()) {
|
||||||
|
for (child in row) {
|
||||||
|
if (child.required && child.value.isBlank()) {
|
||||||
|
toast("第${rowIdx + 1}行${child.label}不能为空")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (field.value.isBlank()) {
|
||||||
|
toast("${field.label}不能为空")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 收集字段提交值,根据 apiKey / extraApiKeys 规则汇总
|
||||||
|
* @return 提交参数 Map,key 为接口参数名,value 为提交值
|
||||||
|
*/
|
||||||
|
private fun collectSubmitValues(): MutableMap<String, String?> {
|
||||||
|
val params = mutableMapOf<String, String?>()
|
||||||
|
for (field in fields) {
|
||||||
|
if (field.hidden) continue
|
||||||
|
// 跳过 CHILDREN 类型,暂不处理
|
||||||
|
if (field.type == FieldType.CHILDREN) continue
|
||||||
|
|
||||||
|
if (field.extraApiKeys.isNotEmpty()) {
|
||||||
|
// 下拉字段:直接读取 bindDropdown 已解析好的 extraValues
|
||||||
|
field.extraValues.forEach { (apiKey, value) ->
|
||||||
|
params[apiKey] = value
|
||||||
|
}
|
||||||
|
} else if (field.apiKey.isNotBlank()) {
|
||||||
|
// 普通字段
|
||||||
|
params[field.apiKey] = field.value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return params
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提交单品净菜包装
|
||||||
|
*/
|
||||||
|
private fun submitCleanPackage() {
|
||||||
|
val params = collectSubmitValues()
|
||||||
|
if (currentWeight <= 0.0) {
|
||||||
|
toast("未识别到重量")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (currentFood == null || currentFood!!.ingredientName.isNullOrBlank() || currentFood!!.traceCode.isNullOrBlank()) {
|
||||||
|
toast("食材信息错误")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val food = currentFood!!
|
||||||
|
params["traceCode"] = food.traceCode
|
||||||
|
params["cleanInboundId"] = food.id.toString()
|
||||||
|
params["cleanName"] = food.ingredientName
|
||||||
|
|
||||||
|
params["weightPerUnit"] = currentWeight.toString()
|
||||||
|
viewModelV2.addCleanPackage(params) { state, msg ->
|
||||||
|
if (state.not()) {
|
||||||
|
toast("提交失败:$msg")
|
||||||
|
return@addCleanPackage
|
||||||
|
}
|
||||||
|
toast("提交成功")
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提交餐品净菜包装
|
||||||
|
*/
|
||||||
|
private fun submitMealPackage() {
|
||||||
|
val params = collectSubmitValues()
|
||||||
|
viewModelV2.addMealPackage(params) { state, msg ->
|
||||||
|
if (state.not()) {
|
||||||
|
toast("提交失败:$msg")
|
||||||
|
return@addMealPackage
|
||||||
|
}
|
||||||
|
toast("提交成功")
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var initialWeight = SpTool.configWeight.toDouble()
|
||||||
|
private var currentWeight = 0.0
|
||||||
|
|
||||||
|
private fun addWeightListener() {
|
||||||
|
WeightUtil.addWeightListener(
|
||||||
|
weightKey = TAG,
|
||||||
|
getWeight = { address, state, weight ->
|
||||||
|
if (address == AddressUtil.ONE && state == WeightUtil.STATE_STABLE) {
|
||||||
|
runOnUiThread {
|
||||||
|
currentWeight = weight - initialWeight
|
||||||
|
binding.tvShowWeight.run {
|
||||||
|
if (tag != currentWeight) {
|
||||||
|
val weightText = "${currentWeight.roundedOneDecimalPlace()}g"
|
||||||
|
text = weightText
|
||||||
|
tag = currentWeight
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -19,14 +19,16 @@ import com.shuwei.dish.match.base.BaseActivity
|
|||||||
import com.shuwei.dish.match.databinding.ActivityCollectedFoodBinding
|
import com.shuwei.dish.match.databinding.ActivityCollectedFoodBinding
|
||||||
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
||||||
import com.shuwei.dish.match.dialog.CommonDialog
|
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.KeyboardUtil
|
||||||
import com.shuwei.dish.match.utils.ext.appendText
|
import com.shuwei.dish.match.utils.ext.appendText
|
||||||
import com.shuwei.dish.match.utils.ext.buildSpannableString
|
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.gone
|
||||||
import com.shuwei.dish.match.utils.ext.toast
|
import com.shuwei.dish.match.utils.ext.toast
|
||||||
import com.shuwei.dish.match.utils.ext.visible
|
import com.shuwei.dish.match.utils.ext.visible
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlin.collections.getOrNull
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 已采集食材列表页面
|
* 已采集食材列表页面
|
||||||
@@ -45,7 +47,8 @@ class CollectedFoodActivity : BaseActivity() {
|
|||||||
isStateViewEnable = true
|
isStateViewEnable = true
|
||||||
// 点击删除按钮,移除对应食材
|
// 点击删除按钮,移除对应食材
|
||||||
addOnItemChildClickListener(R.id.ivDelete) { _, _, position ->
|
addOnItemChildClickListener(R.id.ivDelete) { _, _, position ->
|
||||||
showDeleteDialog(foodList[position].foodName)
|
val item = foodList.getOrNull(position) ?: return@addOnItemChildClickListener
|
||||||
|
showDeleteDialog(item.foodName)
|
||||||
}
|
}
|
||||||
setOnItemClickListener { _, _, _ ->
|
setOnItemClickListener { _, _, _ ->
|
||||||
hideKeyboard()
|
hideKeyboard()
|
||||||
@@ -53,6 +56,22 @@ class CollectedFoodActivity : BaseActivity() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除所有采集数据确认弹窗
|
||||||
|
*/
|
||||||
|
private fun showClearAllDialog() {
|
||||||
|
CommonDialog(this)
|
||||||
|
.setTitle("清除提示")
|
||||||
|
.setContent("清除后无法恢复,确认要清除所有采集数据吗?")
|
||||||
|
.setNegativeButton("取消")
|
||||||
|
.setPositiveButton("确认") {
|
||||||
|
dbViewModel.clearAllCollectedFood {
|
||||||
|
toast("已清除所有采集数据")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 删除弹窗
|
* 删除弹窗
|
||||||
*/
|
*/
|
||||||
@@ -69,7 +88,7 @@ class CollectedFoodActivity : BaseActivity() {
|
|||||||
.setContent(content)
|
.setContent(content)
|
||||||
.setNegativeButton("取消")
|
.setNegativeButton("取消")
|
||||||
.setPositiveButton("确认") {
|
.setPositiveButton("确认") {
|
||||||
appViewModel.removeCollectedFood(
|
dbViewModel.removeCollectedFood(
|
||||||
foodName = foodName,
|
foodName = foodName,
|
||||||
nameFilter = binding.editSearch.text.toString()
|
nameFilter = binding.editSearch.text.toString()
|
||||||
)
|
)
|
||||||
@@ -93,8 +112,13 @@ class CollectedFoodActivity : BaseActivity() {
|
|||||||
}
|
}
|
||||||
}, titleAction = {
|
}, titleAction = {
|
||||||
it.text = "已采集食材"
|
it.text = "已采集食材"
|
||||||
}, rightIconActon = {
|
}, rightIconAction = {
|
||||||
it.gone()
|
it.visible()
|
||||||
|
it.setPaddingRelative(25.dp ,0 ,25.dp ,0)
|
||||||
|
it.setImageResource(R.drawable.ic_trash_white)
|
||||||
|
it.setOnClickListener {
|
||||||
|
showClearAllDialog()
|
||||||
|
}
|
||||||
}, backAction = {
|
}, backAction = {
|
||||||
it.visible()
|
it.visible()
|
||||||
it.setOnClickListener {
|
it.setOnClickListener {
|
||||||
@@ -108,7 +132,7 @@ class CollectedFoodActivity : BaseActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun loadCollectedFoodList(name: String = "") {
|
private fun loadCollectedFoodList(name: String = "") {
|
||||||
appViewModel.loadCollectedFoodList(nameFilter = name)
|
dbViewModel.loadCollectedFoodList(nameFilter = name)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -118,7 +142,7 @@ class CollectedFoodActivity : BaseActivity() {
|
|||||||
private fun initObserver() {
|
private fun initObserver() {
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||||
appViewModel.collectedFoodListState.collect { items ->
|
dbViewModel.collectedFoodListState.collect { items ->
|
||||||
foodList.clear()
|
foodList.clear()
|
||||||
foodList.addAll(items)
|
foodList.addAll(items)
|
||||||
adapter.notifyDataSetChanged()
|
adapter.notifyDataSetChanged()
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.shuwei.dish.match.ui
|
|||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import androidx.activity.addCallback
|
import androidx.activity.addCallback
|
||||||
|
import androidx.core.widget.addTextChangedListener
|
||||||
import androidx.lifecycle.lifecycleScope
|
import androidx.lifecycle.lifecycleScope
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import com.shuwei.dish.match.R
|
import com.shuwei.dish.match.R
|
||||||
@@ -46,7 +47,7 @@ class CookingModeActivity : BaseActivity() {
|
|||||||
it.visible()
|
it.visible()
|
||||||
}, titleAction = {
|
}, titleAction = {
|
||||||
it.text = "选择菜品"
|
it.text = "选择菜品"
|
||||||
}, rightIconActon = {
|
}, rightIconAction = {
|
||||||
it.visible()
|
it.visible()
|
||||||
it.setImageResource(R.drawable.ic_setting)
|
it.setImageResource(R.drawable.ic_setting)
|
||||||
it.setOnClickListener {
|
it.setOnClickListener {
|
||||||
@@ -62,7 +63,7 @@ class CookingModeActivity : BaseActivity() {
|
|||||||
|
|
||||||
|
|
||||||
fun getCookFoodList() {
|
fun getCookFoodList() {
|
||||||
appViewModel.getCookFoodList(cookMode = 0, dinnerType = dinnerType)
|
dbViewModel.getCookFoodList(cookMode = 0, dinnerType = dinnerType)
|
||||||
}
|
}
|
||||||
|
|
||||||
private var configFinished = false
|
private var configFinished = false
|
||||||
@@ -72,7 +73,7 @@ class CookingModeActivity : BaseActivity() {
|
|||||||
// block()
|
// block()
|
||||||
// return
|
// return
|
||||||
// }
|
// }
|
||||||
// appViewModel.loadSeasoning {
|
// dbViewModel.loadSeasoning {
|
||||||
// if (it.isEmpty()) {
|
// if (it.isEmpty()) {
|
||||||
// showDeviceConfigDialog()
|
// showDeviceConfigDialog()
|
||||||
// return@loadSeasoning
|
// return@loadSeasoning
|
||||||
@@ -92,22 +93,44 @@ class CookingModeActivity : BaseActivity() {
|
|||||||
.show()
|
.show()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun addViewListener() {
|
/** 切换餐次时清空输入框,用此标志跳过 afterTextChanged 的查询触发 */
|
||||||
binding.dishRadioGroup.setOnCheckedChangeListener { _, checkedId ->
|
private var isClearingByTabSwitch = false
|
||||||
dinnerType = when (checkedId) {
|
|
||||||
R.id.rbBreakfast -> "1"
|
private fun addViewListener() {
|
||||||
R.id.rbLunch -> "2"
|
binding.tvBreakfast.setOnClickListener { selectTab("1") }
|
||||||
R.id.rbDinner -> "3"
|
binding.tvLunch.setOnClickListener { selectTab("2") }
|
||||||
else -> "1"
|
binding.tvDinner.setOnClickListener { selectTab("3") }
|
||||||
}
|
|
||||||
loadFragment()
|
|
||||||
}
|
|
||||||
binding.etInputDish.addOnActionSearchListener {
|
binding.etInputDish.addOnActionSearchListener {
|
||||||
jumpSearch()
|
jumpSearch()
|
||||||
}
|
}
|
||||||
binding.ivDishSearch.setOnClickListener {
|
binding.ivDishSearch.setOnClickListener {
|
||||||
jumpSearch()
|
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() {
|
private fun jumpSearch() {
|
||||||
@@ -116,24 +139,22 @@ class CookingModeActivity : BaseActivity() {
|
|||||||
toast(binding.etInputDish.hint.toString())
|
toast(binding.etInputDish.hint.toString())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
startActivity<FoodSearchActivity> {
|
currentFragment()?.getDishList(pageNo = 1, dinnerType = dinnerType, foodName = searchText)
|
||||||
putExtra(FoodSearchActivity.DINNER_TYPE, dinnerType)
|
|
||||||
putExtra(FoodSearchActivity.FOOD_NAME, searchText)
|
|
||||||
}
|
|
||||||
hideKeyboard()
|
hideKeyboard()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun loadFragment() {
|
private fun loadFragment() {
|
||||||
runCatching {
|
runCatching {
|
||||||
fragmentList[dinnerType.toInt() - 1].let {
|
val target = fragmentList[dinnerType.toInt() - 1]
|
||||||
supportFragmentManager.beginTransaction().apply {
|
supportFragmentManager.beginTransaction().apply {
|
||||||
if (fragmentList.contains(it)) {
|
fragmentList.forEach { fragment ->
|
||||||
replace(R.id.flSubPage, it)
|
if (fragment.isAdded) {
|
||||||
|
if (fragment == target) show(fragment) else hide(fragment)
|
||||||
} else {
|
} else {
|
||||||
add(R.id.flSubPage, it)
|
if (fragment == target) add(R.id.flSubPage, fragment)
|
||||||
}
|
}
|
||||||
commit()
|
|
||||||
}
|
}
|
||||||
|
commit()
|
||||||
}
|
}
|
||||||
}.onFailure {
|
}.onFailure {
|
||||||
it.printStackTrace()
|
it.printStackTrace()
|
||||||
@@ -142,7 +163,7 @@ class CookingModeActivity : BaseActivity() {
|
|||||||
|
|
||||||
fun deleteCookFoodAndGoods(foodId: String, dinnerType: String, action: () -> Unit) {
|
fun deleteCookFoodAndGoods(foodId: String, dinnerType: String, action: () -> Unit) {
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
appViewModel.deleteCookFoodAndGoods(cookMode = 0, foodId = foodId, dinnerType = dinnerType)
|
dbViewModel.deleteCookFoodAndGoods(cookMode = 0, foodId = foodId, dinnerType = dinnerType)
|
||||||
action()
|
action()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -150,19 +171,19 @@ class CookingModeActivity : BaseActivity() {
|
|||||||
override fun onNewIntent(intent: Intent) {
|
override fun onNewIntent(intent: Intent) {
|
||||||
super.onNewIntent(intent)
|
super.onNewIntent(intent)
|
||||||
runCatching {
|
runCatching {
|
||||||
val isConfigPage = intent?.getBooleanExtra(IS_CONFIG_PAGE, false) ?: false
|
val isConfigPage = intent.getBooleanExtra(IS_CONFIG_PAGE, false)
|
||||||
if (isConfigPage) {
|
if (isConfigPage) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
val isCooking = intent?.getBooleanExtra(IS_COOKING, false) ?: false
|
val lastDinnerType = intent.getStringExtra(DINNER_TYPE) ?: "0"
|
||||||
val lastDinnerType = intent?.getStringExtra(DINNER_TYPE) ?: "0"
|
if (lastDinnerType !in listOf("1", "2", "3")) return
|
||||||
if (lastDinnerType == "1" || lastDinnerType == "2" || lastDinnerType == "3") {
|
if (lastDinnerType == dinnerType) {
|
||||||
fragmentList[lastDinnerType.toInt() - 1].getDishList(1, lastDinnerType)
|
// 同一 Tab:onHiddenChanged 不会触发,直接刷新
|
||||||
}
|
clearSearchText()
|
||||||
when (lastDinnerType) {
|
currentFragment()?.getDishList(1, lastDinnerType)
|
||||||
"1" -> binding.dishRadioGroup.check(R.id.rbBreakfast)
|
} else {
|
||||||
"2" -> binding.dishRadioGroup.check(R.id.rbLunch)
|
// 不同 Tab:selectTab → loadFragment → show → onHiddenChanged 负责刷新,无需直接调用
|
||||||
"3" -> binding.dishRadioGroup.check(R.id.rbDinner)
|
selectTab(lastDinnerType)
|
||||||
}
|
}
|
||||||
}.onFailure {
|
}.onFailure {
|
||||||
it.printStackTrace()
|
it.printStackTrace()
|
||||||
@@ -180,8 +201,10 @@ class CookingModeActivity : BaseActivity() {
|
|||||||
isVisible = false
|
isVisible = false
|
||||||
}
|
}
|
||||||
|
|
||||||
public fun getFoodList(param: MutableMap<String, Any>) {
|
fun clearSearchText() {
|
||||||
netViewModel.searchFoodList(param = param)
|
isClearingByTabSwitch = true
|
||||||
|
binding.etInputDish.text?.clear()
|
||||||
|
isClearingByTabSwitch = false
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -77,7 +77,7 @@
|
|||||||
// it.visible()
|
// it.visible()
|
||||||
// }, titleAction = {
|
// }, titleAction = {
|
||||||
// it.text = "设备配置"
|
// it.text = "设备配置"
|
||||||
// }, rightIconActon = {
|
// }, rightIconAction = {
|
||||||
// it.gone()
|
// it.gone()
|
||||||
//// it.alpha = 0.0F
|
//// it.alpha = 0.0F
|
||||||
//// it.setImageResource(R.drawable.ic_setting)
|
//// it.setImageResource(R.drawable.ic_setting)
|
||||||
|
|||||||
@@ -10,10 +10,12 @@ import androidx.recyclerview.widget.RecyclerView
|
|||||||
import com.shuwei.dish.match.adapter.FoodAdapter
|
import com.shuwei.dish.match.adapter.FoodAdapter
|
||||||
import com.shuwei.dish.match.base.BaseActivity
|
import com.shuwei.dish.match.base.BaseActivity
|
||||||
import com.shuwei.dish.match.databinding.ActivityFoodRecognizeBinding
|
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.dialog.FoodSearchDialog
|
||||||
import com.shuwei.dish.match.entity.GoodsItem
|
import com.shuwei.dish.match.model.GoodsItem
|
||||||
import com.shuwei.dish.match.entity.GoodsNameQueryDTO
|
import com.shuwei.dish.match.model.GoodsNameQueryDTO
|
||||||
import com.shuwei.dish.match.utils.ActivityManager
|
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.WeightUtil
|
||||||
import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
||||||
import com.shuwei.dish.match.utils.ext.gone
|
import com.shuwei.dish.match.utils.ext.gone
|
||||||
@@ -38,6 +40,7 @@ class FoodRecognizeActivity : BaseActivity() {
|
|||||||
private const val TAG = "FoodRecognizeActivity"
|
private const val TAG = "FoodRecognizeActivity"
|
||||||
private const val EXTRA_IMAGE_URI = "extra_image_uri"
|
private const val EXTRA_IMAGE_URI = "extra_image_uri"
|
||||||
private const val EXTRA_CURRENT_WEIGHT = "extra_current_weight"
|
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 EXTRA_SELECTED_ITEM = "extra_selected_item"
|
||||||
const val IS_MANUAL_CANCEL = "isManualCancel"
|
const val IS_MANUAL_CANCEL = "isManualCancel"
|
||||||
|
|
||||||
@@ -54,6 +57,7 @@ class FoodRecognizeActivity : BaseActivity() {
|
|||||||
activity: BaseActivity,
|
activity: BaseActivity,
|
||||||
imageUri: String? = null,
|
imageUri: String? = null,
|
||||||
currentWeight: Double = 0.0,
|
currentWeight: Double = 0.0,
|
||||||
|
initialWeight: Double = 0.0,
|
||||||
nameScoreList: ArrayList<FoodModule.IdNameScore> = arrayListOf(),
|
nameScoreList: ArrayList<FoodModule.IdNameScore> = arrayListOf(),
|
||||||
finishCallback: (Boolean, GoodsItem?) -> Unit = { _, _ -> }
|
finishCallback: (Boolean, GoodsItem?) -> Unit = { _, _ -> }
|
||||||
) {
|
) {
|
||||||
@@ -61,6 +65,7 @@ class FoodRecognizeActivity : BaseActivity() {
|
|||||||
val launchIntent = Intent(activity, FoodRecognizeActivity::class.java).apply {
|
val launchIntent = Intent(activity, FoodRecognizeActivity::class.java).apply {
|
||||||
putExtra(EXTRA_IMAGE_URI, imageUri)
|
putExtra(EXTRA_IMAGE_URI, imageUri)
|
||||||
putExtra(EXTRA_CURRENT_WEIGHT, currentWeight)
|
putExtra(EXTRA_CURRENT_WEIGHT, currentWeight)
|
||||||
|
putExtra(EXTRA_INITIAL_WEIGHT, initialWeight)
|
||||||
}
|
}
|
||||||
activity.startActivity(launchIntent) { resultIntent ->
|
activity.startActivity(launchIntent) { resultIntent ->
|
||||||
val isManualCancel = resultIntent?.getBooleanExtra(IS_MANUAL_CANCEL, false) ?: false
|
val isManualCancel = resultIntent?.getBooleanExtra(IS_MANUAL_CANCEL, false) ?: false
|
||||||
@@ -94,14 +99,17 @@ class FoodRecognizeActivity : BaseActivity() {
|
|||||||
/** 当前选中的列表位置,-1 表示无选中 */
|
/** 当前选中的列表位置,-1 表示无选中 */
|
||||||
private var selectedPosition = -1
|
private var selectedPosition = -1
|
||||||
|
|
||||||
/** 秤1当前实时重量 */
|
/** 秤1当前实时净重(已减去初始读数) */
|
||||||
private var currentWeight = 0.0
|
private var currentWeight = 0.0
|
||||||
|
|
||||||
/** 重量减少时延迟更新的任务,页面关闭前取消可防止用错误重量 */
|
/** 初始秤读数,净重 = 秤读数 - initialWeight */
|
||||||
private var pendingWeightRunnable: Runnable? = null
|
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() }
|
private val scrollIndicatorMinHeightPx by lazy { (24 * resources.displayMetrics.density).toInt() }
|
||||||
@@ -109,6 +117,9 @@ class FoodRecognizeActivity : BaseActivity() {
|
|||||||
/** 食材搜索弹窗,持有引用防止重复打开 */
|
/** 食材搜索弹窗,持有引用防止重复打开 */
|
||||||
private var foodSearchDialog: FoodSearchDialog? = null
|
private var foodSearchDialog: FoodSearchDialog? = null
|
||||||
|
|
||||||
|
/** 数据不稳定提示弹窗,持有引用通过 isShowing 防止重复弹出 */
|
||||||
|
private var unstableDialog: CommonDialog? = null
|
||||||
|
|
||||||
/** 通过name查询IdNameScore */
|
/** 通过name查询IdNameScore */
|
||||||
private val nameScoreMap = mutableMapOf<String, FoodModule.IdNameScore>()
|
private val nameScoreMap = mutableMapOf<String, FoodModule.IdNameScore>()
|
||||||
|
|
||||||
@@ -124,7 +135,7 @@ class FoodRecognizeActivity : BaseActivity() {
|
|||||||
private val adapter = FoodAdapter(list).apply {
|
private val adapter = FoodAdapter(list).apply {
|
||||||
setOnItemClickListener { _, _, position ->
|
setOnItemClickListener { _, _, position ->
|
||||||
// rawMaterialsRemind(position)
|
// rawMaterialsRemind(position)
|
||||||
val item = list[position]
|
val item = list.getOrNull(position) ?: return@setOnItemClickListener
|
||||||
list.forEachIndexed { i, it -> it.isClicked = (i == position) }
|
list.forEachIndexed { i, it -> it.isClicked = (i == position) }
|
||||||
// 点击选择时记录当前秤重量
|
// 点击选择时记录当前秤重量
|
||||||
item.useWeight = currentWeight
|
item.useWeight = currentWeight
|
||||||
@@ -135,7 +146,7 @@ class FoodRecognizeActivity : BaseActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun rawMaterialsRemind(position: Int) {
|
private fun rawMaterialsRemind(position: Int) {
|
||||||
val item = list[position]
|
val item = list.getOrNull(position) ?: return
|
||||||
// 弹出净材种类单选弹窗,确认后再选中该食材
|
// 弹出净材种类单选弹窗,确认后再选中该食材
|
||||||
showRawMaterialsDialog(
|
showRawMaterialsDialog(
|
||||||
context = this@FoodRecognizeActivity,
|
context = this@FoodRecognizeActivity,
|
||||||
@@ -199,37 +210,23 @@ class FoodRecognizeActivity : BaseActivity() {
|
|||||||
binding.ivFoodPhoto.setImageURI(imageUri.toUri())
|
binding.ivFoodPhoto.setImageURI(imageUri.toUri())
|
||||||
}
|
}
|
||||||
currentWeight = intent.getDoubleExtra(EXTRA_CURRENT_WEIGHT, 0.0)
|
currentWeight = intent.getDoubleExtra(EXTRA_CURRENT_WEIGHT, 0.0)
|
||||||
|
initialWeight = intent.getDoubleExtra(EXTRA_INITIAL_WEIGHT, 0.0)
|
||||||
binding.tvWeight.text = "${currentWeight}g"
|
binding.tvWeight.text = "${currentWeight}g"
|
||||||
// val tempList = arrayListOf<GoodsItem>()
|
|
||||||
// Process recognized name list if available
|
|
||||||
recognizeNameList?.apply {
|
recognizeNameList?.apply {
|
||||||
// Iterate through each recognized item
|
|
||||||
forEach {
|
forEach {
|
||||||
// Extract goods name by splitting "WP" and taking the first part
|
|
||||||
val goodsName = it.name.split("WP").first()
|
val goodsName = it.name.split("WP").first()
|
||||||
val rawMaterialsType = it.rawMaterialsType
|
val rawMaterialsType = it.rawMaterialsType
|
||||||
// Add to goods name list and name-score mapping
|
|
||||||
goodsNameList.add(GoodsNameQueryDTO(goodsName, rawMaterialsType))
|
goodsNameList.add(GoodsNameQueryDTO(goodsName, rawMaterialsType))
|
||||||
nameScoreMap.put(goodsName, it)
|
nameScoreMap.put(goodsName, it)
|
||||||
|
|
||||||
// // TODO: 测试数据,临时使用-------------------------
|
|
||||||
// val testData = buildTestData(it)
|
|
||||||
// tempList.add(testData)
|
|
||||||
// // TODO: 测试数据,临时使用-------------------------
|
|
||||||
}
|
}
|
||||||
// // TODO: 测试数据,临时使用-------------------------
|
|
||||||
// loadRecognizeList(tempList)
|
|
||||||
// // TODO: 测试数据,临时使用-------------------------
|
|
||||||
// Clear the recognize name list after processing
|
|
||||||
recognizeNameList = null
|
recognizeNameList = null
|
||||||
}
|
}
|
||||||
|
|
||||||
// If goods name list is not empty, query goods list from network
|
if (goodsNameList.isNotEmpty()) {
|
||||||
// if (goodsNameList.isNotEmpty()){
|
netViewModel.queryGoodsList(goodsType = "0", goodsNames = goodsNameList)
|
||||||
netViewModel.queryGoodsList(goodsType = "0", goodsNames = goodsNameList)
|
} else {
|
||||||
// } else {
|
loadRecognizeList(emptyList())
|
||||||
// loadRecognizeList(emptyList())
|
}
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun buildTestData(item: FoodModule.IdNameScore): GoodsItem {
|
private fun buildTestData(item: FoodModule.IdNameScore): GoodsItem {
|
||||||
@@ -289,15 +286,16 @@ class FoodRecognizeActivity : BaseActivity() {
|
|||||||
binding.rvRecognizeList.visible()
|
binding.rvRecognizeList.visible()
|
||||||
binding.tvNoData.gone()
|
binding.tvNoData.gone()
|
||||||
list.clear()
|
list.clear()
|
||||||
goodsList.forEach {
|
goodsList.forEach { goods ->
|
||||||
var foodScore = -1
|
var foodScore = -1
|
||||||
nameScoreMap[it.goodsName]?.let { food ->
|
nameScoreMap[goods.goodsName]?.let { food ->
|
||||||
foodScore = ((1 - food.score) * 10000).toInt()
|
foodScore = ((1 - food.score) * 10000).toInt()
|
||||||
}
|
}
|
||||||
// // 将接口返回的 rawMaterialsType(全部种类)移存到 rawMaterialsTypes,供弹窗使用
|
//保存原goodsId
|
||||||
// it.rawMaterialsTypes = it.rawMaterialsType
|
goods.oldGoodsId = goods.goodsId
|
||||||
// it.rawMaterialsType = null
|
//PrepareFoodActivity中的goodsId就是materId
|
||||||
list.add(it.also { it.foodScore = foodScore })
|
goods.goodsId = goods.materId ?: ""
|
||||||
|
list.add(goods.also { it.foodScore = foodScore })
|
||||||
}
|
}
|
||||||
adapter.notifyDataSetChanged()
|
adapter.notifyDataSetChanged()
|
||||||
updateRvParentLayoutHeight()
|
updateRvParentLayoutHeight()
|
||||||
@@ -435,58 +433,87 @@ class FoodRecognizeActivity : BaseActivity() {
|
|||||||
* 低于阈值说明食材已被取走,保留上次有效值等待页面关闭
|
* 低于阈值说明食材已被取走,保留上次有效值等待页面关闭
|
||||||
*/
|
*/
|
||||||
private fun registerWeightListener() {
|
private fun registerWeightListener() {
|
||||||
// WeightUtil.addWeightListener(TAG) { address, state, weight ->
|
WeightUtil.addWeightListener(TAG) { address, state, weight ->
|
||||||
// if (address == AddressUtil.ONE && state == WeightUtil.STATE_STABLE) {
|
if (address == AddressUtil.ONE && state == WeightUtil.STATE_STABLE) {
|
||||||
// runOnUiThread {
|
runOnUiThread {
|
||||||
// currentWeight = weight
|
// 净重 = 秤读数 - 初始读数
|
||||||
// binding.tvWeight.run {
|
val netWeight = weight - initialWeight
|
||||||
// if (tag != weight) {
|
currentWeight = netWeight
|
||||||
// text = "$weight g"
|
binding.tvWeight.run {
|
||||||
// tag = weight
|
if (tag != netWeight) {
|
||||||
// }
|
text = "${netWeight}g"
|
||||||
// }
|
tag = netWeight
|
||||||
// if (weight >= PrepareCookActivity.WEIGHT_RECOGNIZE_VALUE) {
|
}
|
||||||
// adapter.items.firstOrNull { it.isClicked }?.let { item ->
|
}
|
||||||
// if (pendingWeight != weight) {
|
// 入队,超过 10 条移除队头
|
||||||
// // 无论增减,均延迟更新,避免手拿物品时的瞬时增重干扰
|
if (weightWindow.size >= 10) weightWindow.removeFirst()
|
||||||
// cancelPendingWeightUpdate()
|
weightWindow.addLast(netWeight)
|
||||||
// pendingWeight = weight
|
// 实时更新选中食材重量
|
||||||
// pendingWeightRunnable = Runnable {
|
list.getOrNull(selectedPosition)?.useWeight = netWeight
|
||||||
// item.useWeight = weight
|
}
|
||||||
// pendingWeightRunnable = null
|
}
|
||||||
// }.also { handler.postDelayed(it, 3000) }
|
}
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 取消待执行的延迟重量更新任务
|
* 从滑动窗口尾部向前查找连续稳定值:
|
||||||
|
* 跳过尾部不稳定的过渡帧,找到第一段连续相同且大于阈值的序列
|
||||||
|
* 连续条数 >= 3 时返回该值,否则返回 null(数据不稳定)
|
||||||
*/
|
*/
|
||||||
private fun cancelPendingWeightUpdate() {
|
private fun getStableWeightFromWindow(): Double? {
|
||||||
// pendingWeightRunnable?.let { handler.removeCallbacks(it) }
|
val threshold = PrepareFoodActivity.WEIGHT_RECOGNIZE_VALUE
|
||||||
// pendingWeightRunnable = null
|
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) {
|
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 {
|
val intent = Intent().apply {
|
||||||
putExtra(IS_MANUAL_CANCEL, isManualCancel)
|
putExtra(IS_MANUAL_CANCEL, isManualCancel)
|
||||||
if (isManualCancel.not()) {
|
if (!isManualCancel) {
|
||||||
list.getOrNull(selectedPosition)?.let {
|
item?.let { putExtra(EXTRA_SELECTED_ITEM, it) }
|
||||||
// 兜底:若 useWeight 仍为空或0,使用当前实时重量
|
|
||||||
if ((it.useWeight ?: 0.0) <= 0.0) {
|
|
||||||
it.useWeight = currentWeight
|
|
||||||
}
|
|
||||||
putExtra(EXTRA_SELECTED_ITEM, it)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
setResult(RESULT_OK, intent)
|
setResult(RESULT_OK, intent)
|
||||||
@@ -495,7 +522,6 @@ class FoodRecognizeActivity : BaseActivity() {
|
|||||||
|
|
||||||
override fun onDestroy() {
|
override fun onDestroy() {
|
||||||
super.onDestroy()
|
super.onDestroy()
|
||||||
cancelPendingWeightUpdate()
|
|
||||||
WeightUtil.removeWeightListener(TAG)
|
WeightUtil.removeWeightListener(TAG)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import com.shuwei.dish.match.base.BaseActivity
|
|||||||
import com.shuwei.dish.match.base.BaseApp
|
import com.shuwei.dish.match.base.BaseApp
|
||||||
import com.shuwei.dish.match.databinding.ActivityFoodSearchBinding
|
import com.shuwei.dish.match.databinding.ActivityFoodSearchBinding
|
||||||
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
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.net.UiState
|
import com.shuwei.dish.match.net.UiState
|
||||||
import com.shuwei.dish.match.utils.KeyboardUtil
|
import com.shuwei.dish.match.utils.KeyboardUtil
|
||||||
import com.shuwei.dish.match.utils.SpTool
|
import com.shuwei.dish.match.utils.SpTool
|
||||||
@@ -25,6 +25,7 @@ import com.shuwei.dish.match.utils.ext.toast
|
|||||||
import com.shuwei.dish.match.utils.ext.visible
|
import com.shuwei.dish.match.utils.ext.visible
|
||||||
import java.io.Serializable
|
import java.io.Serializable
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlin.collections.getOrNull
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 菜品搜索页面
|
* 菜品搜索页面
|
||||||
@@ -47,15 +48,16 @@ class FoodSearchActivity : BaseActivity() {
|
|||||||
Food2Adapter(list).apply {
|
Food2Adapter(list).apply {
|
||||||
isStateViewEnable = true
|
isStateViewEnable = true
|
||||||
setOnItemClickListener { adapter, view, position ->
|
setOnItemClickListener { adapter, view, position ->
|
||||||
|
var jumpItem = list.getOrNull(position) ?: return@setOnItemClickListener
|
||||||
if (SpTool.cookMode == 0) {
|
if (SpTool.cookMode == 0) {
|
||||||
val jumpItem = list[position].also { it.dinnerType = dinnerType }
|
jumpItem.dinnerType = dinnerType
|
||||||
startActivity<PrepareFoodActivity> {
|
startActivity<PrepareFoodActivity> {
|
||||||
putExtra(PrepareFoodActivity.FOOD_ITEM, jumpItem as Serializable)
|
putExtra(PrepareFoodActivity.FOOD_ITEM, jumpItem as Serializable)
|
||||||
}
|
}
|
||||||
return@setOnItemClickListener
|
return@setOnItemClickListener
|
||||||
}
|
}
|
||||||
setResult(RESULT_OK, Intent().apply {
|
setResult(RESULT_OK, Intent().apply {
|
||||||
putExtra(FOOD_ITEM, list[position] as Serializable)
|
putExtra(FOOD_ITEM, jumpItem as Serializable)
|
||||||
})
|
})
|
||||||
finish()
|
finish()
|
||||||
}
|
}
|
||||||
@@ -76,7 +78,7 @@ class FoodSearchActivity : BaseActivity() {
|
|||||||
it.visible()
|
it.visible()
|
||||||
}, titleAction = {
|
}, titleAction = {
|
||||||
it.text = "菜品搜索"
|
it.text = "菜品搜索"
|
||||||
}, rightIconActon = {
|
}, rightIconAction = {
|
||||||
it.gone()
|
it.gone()
|
||||||
it.setImageResource(R.drawable.ic_setting)
|
it.setImageResource(R.drawable.ic_setting)
|
||||||
it.setOnClickListener {
|
it.setOnClickListener {
|
||||||
|
|||||||
@@ -0,0 +1,204 @@
|
|||||||
|
package com.shuwei.dish.match.ui
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import androidx.core.widget.addTextChangedListener
|
||||||
|
import androidx.lifecycle.lifecycleScope
|
||||||
|
import androidx.recyclerview.widget.GridLayoutManager
|
||||||
|
import androidx.recyclerview.widget.LinearLayoutManager
|
||||||
|
import com.chad.library.adapter4.util.setOnDebouncedItemClick
|
||||||
|
import com.shuwei.dish.match.R
|
||||||
|
import com.shuwei.dish.match.adapter.InboundIngredientV2Adapter
|
||||||
|
import com.shuwei.dish.match.base.BaseActivity
|
||||||
|
import com.shuwei.dish.match.databinding.ActivityFoodSearchV2Binding
|
||||||
|
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
||||||
|
import com.shuwei.dish.match.model.NutCleanInboundIngredientVO
|
||||||
|
import com.shuwei.dish.match.net.NetViewModelV2
|
||||||
|
import com.shuwei.dish.match.net.UiState
|
||||||
|
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 kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 食材搜索页面 V2,使用 NetViewModelV2 的回调接口查询已入库净菜食材
|
||||||
|
*/
|
||||||
|
class FoodSearchV2Activity : BaseActivity() {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val INGREDIENT_ITEM = "ingredientItem"
|
||||||
|
const val INGREDIENT_NAME = "ingredientName"
|
||||||
|
const val PAGE_SIZE = 30
|
||||||
|
}
|
||||||
|
|
||||||
|
private lateinit var binding: ActivityFoodSearchV2Binding
|
||||||
|
private val viewModelV2 by lazy { NetViewModelV2() }
|
||||||
|
|
||||||
|
private val list = mutableListOf<NutCleanInboundIngredientVO>()
|
||||||
|
private val recordAdapter by lazy {
|
||||||
|
InboundIngredientV2Adapter(list).apply {
|
||||||
|
isStateViewEnable = true
|
||||||
|
setOnDebouncedItemClick { _, _, position ->
|
||||||
|
val item = list.getOrNull(position) ?: return@setOnDebouncedItemClick
|
||||||
|
setResult(RESULT_OK, Intent().apply {
|
||||||
|
putExtra(INGREDIENT_ITEM, item)
|
||||||
|
})
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var ingredientName: String? = null
|
||||||
|
private var currentPage = 1
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
binding = ActivityFoodSearchV2Binding.inflate(layoutInflater)
|
||||||
|
setContentView(binding.root)
|
||||||
|
setHeaderBackground()
|
||||||
|
ingredientName = intent.getStringExtra(INGREDIENT_NAME)
|
||||||
|
binding.etInputIngredient.setText(ingredientName)
|
||||||
|
setTitleBar(titleBarAction = {
|
||||||
|
it.visible()
|
||||||
|
}, titleAction = {
|
||||||
|
it.text = "食材搜索"
|
||||||
|
}, rightIconAction = {
|
||||||
|
it.gone()
|
||||||
|
})
|
||||||
|
binding.rvIngredientList.let {
|
||||||
|
it.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
|
||||||
|
it.adapter = recordAdapter
|
||||||
|
}
|
||||||
|
addViewListener()
|
||||||
|
// 若有传入食材名称,自动触发搜索
|
||||||
|
queryIngredientList(ingredientName)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun addViewListener() {
|
||||||
|
binding.ivIngredientSearch.setOnClickListener {
|
||||||
|
getInputAndSearch()
|
||||||
|
}
|
||||||
|
binding.refreshLayout.setEnableRefresh(true)
|
||||||
|
binding.refreshLayout.setEnableLoadMore(false)
|
||||||
|
binding.refreshLayout.run {
|
||||||
|
setOnRefreshListener {
|
||||||
|
currentPage = 1
|
||||||
|
val input = binding.etInputIngredient.text.toString().trim()
|
||||||
|
queryIngredientList(input)
|
||||||
|
}
|
||||||
|
setOnLoadMoreListener {
|
||||||
|
val input = binding.etInputIngredient.text.toString().trim()
|
||||||
|
queryIngredientList(input)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
binding.root.setOnClickListener {
|
||||||
|
hideKeyboard()
|
||||||
|
}
|
||||||
|
binding.etInputIngredient.run {
|
||||||
|
setOnEditorActionListener { _, actionId, _ ->
|
||||||
|
if (actionId == android.view.inputmethod.EditorInfo.IME_ACTION_SEARCH) {
|
||||||
|
getInputAndSearch()
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
addTextChangedListener(onTextChanged = { text, _, _, _ ->
|
||||||
|
if (text.isNullOrBlank()) {
|
||||||
|
currentPage = 1
|
||||||
|
queryIngredientList()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getInputAndSearch() {
|
||||||
|
val input = binding.etInputIngredient.text.toString().trim()
|
||||||
|
if (input.isBlank()) {
|
||||||
|
toast("请输入食材名称")
|
||||||
|
binding.refreshLayout.finishRefresh()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
queryIngredientList(input)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询已入库净菜食材列表
|
||||||
|
*/
|
||||||
|
private fun queryIngredientList(keyword: String? = null) {
|
||||||
|
hideKeyboard()
|
||||||
|
showLoading()
|
||||||
|
viewModelV2.getInboundIngredientOptionsWithCallback(
|
||||||
|
keyword = keyword,
|
||||||
|
pageNum = currentPage,
|
||||||
|
pageSize = PAGE_SIZE,
|
||||||
|
onLoading = {},
|
||||||
|
onResult = { state ->
|
||||||
|
lifecycleScope.launch {
|
||||||
|
when (state) {
|
||||||
|
is UiState.Success -> handleSearchResult(state.data)
|
||||||
|
is UiState.Error -> {
|
||||||
|
delayDismissLoading()
|
||||||
|
if (currentPage == 1) {
|
||||||
|
binding.refreshLayout.finishRefresh()
|
||||||
|
} else {
|
||||||
|
binding.refreshLayout.finishLoadMore()
|
||||||
|
}
|
||||||
|
toast(state.msg)
|
||||||
|
loadEmptyView()
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理搜索结果,填充列表或展示空视图
|
||||||
|
*/
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
private fun handleSearchResult(records: List<NutCleanInboundIngredientVO>?) {
|
||||||
|
delayDismissLoading()
|
||||||
|
if (currentPage == 1 && records.isNullOrEmpty()) {
|
||||||
|
loadEmptyView()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
list.clear()
|
||||||
|
list.addAll(records!!)
|
||||||
|
recordAdapter.notifyDataSetChanged()
|
||||||
|
val isLoadMore = records.size >= PAGE_SIZE
|
||||||
|
binding.refreshLayout.setEnableLoadMore(isLoadMore)
|
||||||
|
if (isLoadMore) {
|
||||||
|
currentPage++
|
||||||
|
binding.refreshLayout.finishLoadMore()
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
binding.refreshLayout.finishLoadMoreWithNoMoreData()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var emptyViewBinding: LayoutEmptyViewBinding? = null
|
||||||
|
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
private fun loadEmptyView() {
|
||||||
|
list.clear()
|
||||||
|
recordAdapter.notifyDataSetChanged()
|
||||||
|
if (emptyViewBinding == null) {
|
||||||
|
emptyViewBinding = LayoutEmptyViewBinding.inflate(
|
||||||
|
LayoutInflater.from(this), binding.rvIngredientList, false
|
||||||
|
)
|
||||||
|
}
|
||||||
|
emptyViewBinding!!.tvContent.text = "暂无数据"
|
||||||
|
emptyViewBinding!!.tvSubContent.text = "可以尝试换个名称重新搜索"
|
||||||
|
recordAdapter.stateView = emptyViewBinding!!.root
|
||||||
|
|
||||||
|
binding.refreshLayout.run {
|
||||||
|
setEnableRefresh(false)
|
||||||
|
setEnableLoadMore(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,11 +10,12 @@ import com.shuwei.dish.match.adapter.HomeModeAdapter
|
|||||||
import com.shuwei.dish.match.base.BaseActivity
|
import com.shuwei.dish.match.base.BaseActivity
|
||||||
import com.shuwei.dish.match.base.BaseApp
|
import com.shuwei.dish.match.base.BaseApp
|
||||||
import com.shuwei.dish.match.databinding.ActivityHomeBinding
|
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.SpTool
|
||||||
import com.shuwei.dish.match.utils.ext.startActivity
|
import com.shuwei.dish.match.utils.ext.startActivity
|
||||||
import com.shuwei.dish.match.utils.ext.toast
|
import com.shuwei.dish.match.utils.ext.toast
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlin.collections.getOrNull
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 主页,包括三种模式:制作模式、采样模式、品控模式
|
* 主页,包括三种模式:制作模式、采样模式、品控模式
|
||||||
@@ -65,18 +66,18 @@ class HomeActivity : BaseActivity() {
|
|||||||
// startActivity<SamplingListActivity>()
|
// startActivity<SamplingListActivity>()
|
||||||
// }
|
// }
|
||||||
|
|
||||||
// appViewModel.deleteSeasoningBySort(12)
|
// dbViewModel.deleteSeasoningBySort(12)
|
||||||
// appViewModel.deleteSeasoningBySort(11)
|
// dbViewModel.deleteSeasoningBySort(11)
|
||||||
// appViewModel.deleteSeasoningBySort(13)
|
// dbViewModel.deleteSeasoningBySort(13)
|
||||||
// appViewModel.deleteSeasoningBySort(14)
|
// dbViewModel.deleteSeasoningBySort(14)
|
||||||
// appViewModel.deleteCookFoodAndGoods(0,"") {}
|
// dbViewModel.deleteCookFoodAndGoods(0,"") {}
|
||||||
// appViewModel.getCookFoodGoodsList("") {goodsList->
|
// dbViewModel.getCookFoodGoodsList("") {goodsList->
|
||||||
// goodsList.forEach {
|
// goodsList.forEach {
|
||||||
// it.foodId = "1594990392084779010"
|
// it.foodId = "1594990392084779010"
|
||||||
// appViewModel.updateGoods(it)
|
// dbViewModel.updateGoods(it)
|
||||||
// }
|
// }
|
||||||
// }
|
// }
|
||||||
// appViewModel.clearAllSeasoning(){}
|
// dbViewModel.clearAllSeasoning(){}
|
||||||
|
|
||||||
|
|
||||||
// binding.btnDeviceConfig.setOnClickListener {
|
// binding.btnDeviceConfig.setOnClickListener {
|
||||||
@@ -97,7 +98,7 @@ class HomeActivity : BaseActivity() {
|
|||||||
private val modeAdapter by lazy {
|
private val modeAdapter by lazy {
|
||||||
HomeModeAdapter(modeList).apply {
|
HomeModeAdapter(modeList).apply {
|
||||||
addOnItemChildClickListener(R.id.layoutCard) { adapter, view, position ->
|
addOnItemChildClickListener(R.id.layoutCard) { adapter, view, position ->
|
||||||
modeList[position].onClick?.invoke()
|
modeList.getOrNull(position)?.onClick?.invoke()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -140,14 +141,14 @@ class HomeActivity : BaseActivity() {
|
|||||||
|
|
||||||
private fun goSampling() {
|
private fun goSampling() {
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
val slots = appViewModel.loadSeasoningSlot()
|
val slots = dbViewModel.loadSeasoningSlot()
|
||||||
if (slots.isEmpty()) {
|
if (slots.isEmpty()) {
|
||||||
// 无调料信息,打开采样历史列表页面,点击设置配置调料信息
|
// 无调料信息,打开采样历史列表页面,点击设置配置调料信息
|
||||||
startActivity<SamplingModeActivity>()
|
startActivity<SamplingModeActivity>()
|
||||||
finish()
|
finish()
|
||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
val count = appViewModel.countCookFood(cookMode = 1)
|
val count = dbViewModel.countCookFood(cookMode = 1)
|
||||||
if (count > 0) {
|
if (count > 0) {
|
||||||
// 有烹饪中数据,打开采样历史列表页面
|
// 有烹饪中数据,打开采样历史列表页面
|
||||||
startActivity<SamplingModeActivity>()
|
startActivity<SamplingModeActivity>()
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package com.shuwei.dish.match.ui
|
||||||
|
|
||||||
|
import android.os.Bundle
|
||||||
|
import com.shuwei.dish.match.base.BaseActivity
|
||||||
|
import com.shuwei.dish.match.databinding.ActivityHomeV2Binding
|
||||||
|
import com.shuwei.dish.match.utils.ext.startActivity
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 主页V2 - 净菜包装页面
|
||||||
|
*/
|
||||||
|
class HomeV2Activity : BaseActivity() {
|
||||||
|
|
||||||
|
private lateinit var binding: ActivityHomeV2Binding
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
statusBarDarkFont(enable = true)
|
||||||
|
|
||||||
|
binding = ActivityHomeV2Binding.inflate(layoutInflater)
|
||||||
|
setContentView(binding.root)
|
||||||
|
|
||||||
|
binding.tvTitle.setOnClickListener {
|
||||||
|
startActivity<SettingActivity> {}
|
||||||
|
}
|
||||||
|
|
||||||
|
binding.btnCleanPack.setOnClickListener {
|
||||||
|
startActivity<CleanPackActivity> {
|
||||||
|
putExtra(CleanPackActivity.EXTRA_TYPE, CleanPackActivity.TYPE_CLEAN)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
binding.btnMealPack.setOnClickListener {
|
||||||
|
startActivity<MealListActivity> {}
|
||||||
|
}
|
||||||
|
|
||||||
|
binding.btnTask.setOnClickListener {
|
||||||
|
startActivity<TaskActivity> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,16 +11,11 @@ import androidx.activity.addCallback
|
|||||||
import androidx.lifecycle.lifecycleScope
|
import androidx.lifecycle.lifecycleScope
|
||||||
import com.shuwei.dish.match.base.BaseActivity
|
import com.shuwei.dish.match.base.BaseActivity
|
||||||
import com.shuwei.dish.match.base.BaseApp
|
import com.shuwei.dish.match.base.BaseApp
|
||||||
import com.shuwei.dish.match.base.DeviceRole
|
|
||||||
import com.shuwei.dish.match.base.GlobalData
|
|
||||||
import com.shuwei.dish.match.databinding.ActivityInitBinding
|
import com.shuwei.dish.match.databinding.ActivityInitBinding
|
||||||
import com.shuwei.dish.match.objbox.FoodModule
|
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.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.SpTool
|
||||||
import com.shuwei.dish.match.utils.WeightUtil
|
|
||||||
import com.shuwei.dish.match.utils.ext.gone
|
import com.shuwei.dish.match.utils.ext.gone
|
||||||
import com.shuwei.dish.match.utils.ext.startActivity
|
import com.shuwei.dish.match.utils.ext.startActivity
|
||||||
import com.shuwei.dish.match.utils.ext.visible
|
import com.shuwei.dish.match.utils.ext.visible
|
||||||
@@ -55,7 +50,7 @@ class InitActivity : BaseActivity() {
|
|||||||
countdownHandler.postDelayed(this, 100)
|
countdownHandler.postDelayed(this, 100)
|
||||||
} else {
|
} else {
|
||||||
// 倒计时结束,最后检测一次网络
|
// 倒计时结束,最后检测一次网络
|
||||||
if (NetworkUtils.isNetworkConnected(this@InitActivity)) {
|
if (NetworkUtil.isNetworkConnected(this@InitActivity)) {
|
||||||
startNextPage()
|
startNextPage()
|
||||||
} else {
|
} else {
|
||||||
// 网络未连接,显示"连接网络"按钮
|
// 网络未连接,显示"连接网络"按钮
|
||||||
@@ -82,12 +77,6 @@ class InitActivity : BaseActivity() {
|
|||||||
|
|
||||||
BaseApp.canteenId = SpTool.canteenId
|
BaseApp.canteenId = SpTool.canteenId
|
||||||
|
|
||||||
WeightUtil.init()
|
|
||||||
WeightUtil.getWeight()
|
|
||||||
WeightUtil.startContinuousRead()
|
|
||||||
//对净材秤1和熟食秤2称进行清零
|
|
||||||
WeightUtil.tareTwo(AddressUtil.ONE)
|
|
||||||
WeightUtil.tareTwo(AddressUtil.TWO)
|
|
||||||
initViews()
|
initViews()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,53 +87,60 @@ class InitActivity : BaseActivity() {
|
|||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
if (withDelay) delay(2000)
|
if (withDelay) delay(2000)
|
||||||
// 子设备:直接进入小屏专属页面,不走原有大屏业务流程
|
// 子设备:直接进入小屏专属页面,不走原有大屏业务流程
|
||||||
if (GlobalData.deviceRole == DeviceRole.SLAVE) {
|
// if (GlobalData.deviceRole == DeviceRole.SLAVE) {
|
||||||
startActivity<SlaveActivity>()
|
// startActivity<SlaveActivity>()
|
||||||
return@launch
|
// // 延迟到下一帧 finish,避免与 LaunchActivityItem 事务竞态导致
|
||||||
}
|
// // "Activity client record must not be null" 偶发崩溃
|
||||||
|
// window.decorView.post { finish() }
|
||||||
|
// return@launch
|
||||||
|
// }
|
||||||
// 主设备:走原有路由逻辑
|
// 主设备:走原有路由逻辑
|
||||||
when (SpTool.cookMode) {
|
// when (SpTool.cookMode) {
|
||||||
0 -> {
|
// 0 -> {
|
||||||
startActivity<CookingModeActivity>()
|
// startActivity<CookingModeActivity>()
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
1 -> {
|
// 1 -> {
|
||||||
goSampling()
|
// goSampling()
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
else -> {
|
// else -> {
|
||||||
startActivity<HomeActivity>()
|
// startActivity<HomeActivity>()
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
startActivity<HomeV2Activity>()
|
||||||
|
// 延迟到下一帧 finish,避免与 LaunchActivityItem 事务竞态导致
|
||||||
|
// "Activity client record must not be null" 偶发崩溃
|
||||||
|
window.decorView.post { finish() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun goSampling() {
|
/**
|
||||||
lifecycleScope.launch {
|
* 采样模式启动路由:根据本地调料配置和烹饪中数据决定跳转目标
|
||||||
val slots = appViewModel.loadSeasoningSlot()
|
* 改为 suspend 后由外层协程串行等待,保证 startActivity 早于 finish() 执行,
|
||||||
if (slots.isEmpty()) {
|
* 避免内部再嵌一层 lifecycleScope.launch 导致 finish 抢跑、跳转失败
|
||||||
// 无调料信息,打开采样历史列表页面,点击设置配置调料信息
|
*/
|
||||||
startActivity<SamplingModeActivity>()
|
private suspend fun goSampling() {
|
||||||
return@launch
|
val slots = dbViewModel.loadSeasoningSlot()
|
||||||
}
|
if (slots.isEmpty()) {
|
||||||
val count = appViewModel.countCookFood(cookMode = 1)
|
// 无调料信息,打开采样历史列表页面,点击设置配置调料信息
|
||||||
if (count > 0) {
|
startActivity<SamplingModeActivity>()
|
||||||
// 有烹饪中数据,打开采样历史列表页面
|
return
|
||||||
startActivity<SamplingModeActivity>()
|
}
|
||||||
return@launch
|
val count = dbViewModel.countCookFood(cookMode = 1)
|
||||||
}
|
if (count > 0) {
|
||||||
// 无烹饪数据,打开新增采样页面
|
// 有烹饪中数据,打开采样历史列表页面
|
||||||
startActivity<PrepareFoodActivity> {
|
startActivity<SamplingModeActivity>()
|
||||||
putExtra(PrepareFoodActivity.PAGE_FROM, PrepareFoodActivity.HOME)
|
return
|
||||||
}
|
}
|
||||||
|
// 无烹饪数据,打开新增采样页面
|
||||||
|
startActivity<PrepareFoodActivity> {
|
||||||
|
putExtra(PrepareFoodActivity.PAGE_FROM, PrepareFoodActivity.HOME)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onDestroy() {
|
override fun onDestroy() {
|
||||||
countdownHandler.removeCallbacksAndMessages(null)
|
countdownHandler.removeCallbacksAndMessages(null)
|
||||||
WeightUtil.stopContinuousRead()
|
|
||||||
// 秤服务伴随进程生命周期,无需在 Activity 销毁时停止;进程退出时 OS 会自动回收所有资源
|
|
||||||
// ScaleServiceManager.stop()
|
|
||||||
super.onDestroy()
|
super.onDestroy()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -177,7 +173,7 @@ class InitActivity : BaseActivity() {
|
|||||||
|
|
||||||
override fun onResume() {
|
override fun onResume() {
|
||||||
super.onResume()
|
super.onResume()
|
||||||
if (NetworkUtils.isNetworkConnected(this)) {
|
if (NetworkUtil.isNetworkConnected(this)) {
|
||||||
// 有网络时隐藏网络检测区域,直接跳转
|
// 有网络时隐藏网络检测区域,直接跳转
|
||||||
binding.llNetwork.gone()
|
binding.llNetwork.gone()
|
||||||
startNextPage(withDelay = false)
|
startNextPage(withDelay = false)
|
||||||
@@ -221,7 +217,7 @@ class InitActivity : BaseActivity() {
|
|||||||
* 检测网络连接
|
* 检测网络连接
|
||||||
*/
|
*/
|
||||||
private fun checkNetworkConnection() {
|
private fun checkNetworkConnection() {
|
||||||
if (NetworkUtils.isNetworkConnected(this)) {
|
if (NetworkUtil.isNetworkConnected(this)) {
|
||||||
// 网络连接成功,停止倒计时并跳转到 HomeActivity
|
// 网络连接成功,停止倒计时并跳转到 HomeActivity
|
||||||
countdownHandler.removeCallbacks(countdownTask)
|
countdownHandler.removeCallbacks(countdownTask)
|
||||||
startNextPage()
|
startNextPage()
|
||||||
@@ -252,4 +248,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.Seasoning18GridAdapter
|
||||||
import com.shuwei.dish.match.adapter.Seasoning22GridAdapter
|
import com.shuwei.dish.match.adapter.Seasoning22GridAdapter
|
||||||
import com.shuwei.dish.match.base.BaseActivity
|
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.dialog.CommonDialog
|
||||||
import com.shuwei.dish.match.databinding.ActivityMasterScaleBinding
|
import com.shuwei.dish.match.databinding.ActivityMasterScaleBinding
|
||||||
import com.shuwei.dish.match.databinding.ListTypeScale1Binding
|
import com.shuwei.dish.match.databinding.ListTypeScale1Binding
|
||||||
@@ -81,7 +82,7 @@ class MasterScaleActivity : BaseActivity() {
|
|||||||
/** 从 Room 加载槽位配置到 slotNameMap,加载完成后启动数据观测 */
|
/** 从 Room 加载槽位配置到 slotNameMap,加载完成后启动数据观测 */
|
||||||
private fun loadSlotNames() {
|
private fun loadSlotNames() {
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
val slots = appViewModel.loadSeasoningSlot()
|
val slots = dbViewModel.loadSeasoningSlot()
|
||||||
slots.forEach { slot ->
|
slots.forEach { slot ->
|
||||||
slotNameMap["${slot.deviceId}#${slot.address}"] = slot.goodsName
|
slotNameMap["${slot.deviceId}#${slot.address}"] = slot.goodsName
|
||||||
}
|
}
|
||||||
@@ -99,7 +100,7 @@ class MasterScaleActivity : BaseActivity() {
|
|||||||
val flow = ScaleServiceManager.allScales ?: return
|
val flow = ScaleServiceManager.allScales ?: return
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
flow.collectLatest { scaleMap ->
|
flow.collectLatest { scaleMap ->
|
||||||
val localId = com.shuwei.dish.match.base.GlobalData.deviceId
|
val localId = GlobalData.deviceId
|
||||||
val localIp = NetworkUtil.getLocalIpAddress(this@MasterScaleActivity)
|
val localIp = NetworkUtil.getLocalIpAddress(this@MasterScaleActivity)
|
||||||
val groups = scaleMap.values
|
val groups = scaleMap.values
|
||||||
.groupBy { it.deviceId }
|
.groupBy { it.deviceId }
|
||||||
@@ -337,7 +338,7 @@ class MasterScaleActivity : BaseActivity() {
|
|||||||
textSize = 22f
|
textSize = 22f
|
||||||
}
|
}
|
||||||
cell.tvState.run {
|
cell.tvState.run {
|
||||||
text = stateStr(scale?.state)
|
text = WeightUtil.getStateStr(scale?.state ?: -1)
|
||||||
textSize = 22f
|
textSize = 22f
|
||||||
}
|
}
|
||||||
cell.root.updateLayoutParams { height = 400.dp }
|
cell.root.updateLayoutParams { height = 400.dp }
|
||||||
@@ -450,20 +451,12 @@ class MasterScaleActivity : BaseActivity() {
|
|||||||
b.tvAddr.text = scale?.let { "秤 ${it.address}" } ?: ""
|
b.tvAddr.text = scale?.let { "秤 ${it.address}" } ?: ""
|
||||||
b.tvName.text = scale?.name?.takeIf { it.isNotBlank() } ?: "-"
|
b.tvName.text = scale?.name?.takeIf { it.isNotBlank() } ?: "-"
|
||||||
b.tvWeight.text = scale?.let { "${it.weight} g" } ?: ""
|
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
|
* @param deviceId 目标设备 ID
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.shuwei.dish.match.ui
|
||||||
|
|
||||||
|
object MaterialTypeTool {
|
||||||
|
|
||||||
|
fun getMaterialText(type: Int) = when (type) {
|
||||||
|
1 -> "主料"
|
||||||
|
2 -> "辅料"
|
||||||
|
3 -> "调料"
|
||||||
|
else -> ""
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
package com.shuwei.dish.match.ui
|
||||||
|
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import androidx.recyclerview.widget.LinearLayoutManager
|
||||||
|
import com.shuwei.dish.match.adapter.MealListAdapter
|
||||||
|
import com.shuwei.dish.match.base.BaseActivity
|
||||||
|
import com.shuwei.dish.match.databinding.ActivityMealListBinding
|
||||||
|
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
||||||
|
import com.shuwei.dish.match.model.NutFoodOptionVO
|
||||||
|
import com.shuwei.dish.match.net.NetViewModelV2
|
||||||
|
import com.shuwei.dish.match.net.UiState
|
||||||
|
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
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 餐品列表页面
|
||||||
|
*/
|
||||||
|
class MealListActivity : BaseActivity() {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val MEAL_ITEM = "mealItem"
|
||||||
|
const val PAGE_SIZE = 30
|
||||||
|
}
|
||||||
|
|
||||||
|
private val binding by lazy { ActivityMealListBinding.inflate(layoutInflater) }
|
||||||
|
private val viewModelV2 by lazy { NetViewModelV2() }
|
||||||
|
|
||||||
|
private val mealList = mutableListOf<NutFoodOptionVO>()
|
||||||
|
private val mealAdapter by lazy { MealListAdapter(mealList).apply {
|
||||||
|
isStateViewEnable = true
|
||||||
|
setOnItemClickListener { _, _, position ->
|
||||||
|
val item = mealList.getOrNull(position) ?: return@setOnItemClickListener
|
||||||
|
startActivity<PackActivity>{
|
||||||
|
putExtra(PackActivity.MEAL_ITEM, item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} }
|
||||||
|
private var emptyViewBinding: LayoutEmptyViewBinding? = null
|
||||||
|
private var currentPage = 1
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
setContentView(binding.root)
|
||||||
|
setHeaderBackground()
|
||||||
|
setTitleBar(titleBarAction = {
|
||||||
|
it.visible()
|
||||||
|
}, titleAction = {
|
||||||
|
it.text = "餐品列表"
|
||||||
|
}, rightIconAction = {
|
||||||
|
it.gone()
|
||||||
|
}, backAction = {
|
||||||
|
it.setOnClickListener {
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
initRecyclerView()
|
||||||
|
loadMealList()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化 RecyclerView
|
||||||
|
*/
|
||||||
|
private fun initRecyclerView() {
|
||||||
|
binding.rvMealList.layoutManager = LinearLayoutManager(this)
|
||||||
|
binding.rvMealList.adapter = mealAdapter
|
||||||
|
binding.refreshLayout.setEnableRefresh(true)
|
||||||
|
binding.refreshLayout.setEnableLoadMore(true)
|
||||||
|
binding.refreshLayout.setOnRefreshListener {
|
||||||
|
currentPage = 1
|
||||||
|
loadMealList()
|
||||||
|
}
|
||||||
|
binding.refreshLayout.setOnLoadMoreListener {
|
||||||
|
currentPage++
|
||||||
|
loadMealList()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 加载餐品列表
|
||||||
|
*/
|
||||||
|
private fun loadMealList() {
|
||||||
|
showLoading("加载中……")
|
||||||
|
viewModelV2.getFoodOptionsWithCallback(
|
||||||
|
keyword = null,
|
||||||
|
pageNum = currentPage,
|
||||||
|
pageSize = PAGE_SIZE,
|
||||||
|
onLoading = {},
|
||||||
|
onResult = { state ->
|
||||||
|
dismissLoading()
|
||||||
|
when (state) {
|
||||||
|
is UiState.Success -> {
|
||||||
|
val records = state.data?.records
|
||||||
|
if (currentPage == 1 && records.isNullOrEmpty()) {
|
||||||
|
binding.refreshLayout.finishRefresh()
|
||||||
|
loadEmptyView()
|
||||||
|
return@getFoodOptionsWithCallback
|
||||||
|
}
|
||||||
|
if (currentPage == 1) {
|
||||||
|
mealList.clear()
|
||||||
|
}
|
||||||
|
mealList.addAll(records!!)
|
||||||
|
mealAdapter.notifyDataSetChanged()
|
||||||
|
val isLoadMore = records.size >= PAGE_SIZE
|
||||||
|
binding.refreshLayout.setEnableLoadMore(isLoadMore)
|
||||||
|
if (isLoadMore) {
|
||||||
|
binding.refreshLayout.finishLoadMore()
|
||||||
|
} else {
|
||||||
|
binding.refreshLayout.finishLoadMoreWithNoMoreData()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
is UiState.Error -> {
|
||||||
|
toast(state.msg)
|
||||||
|
if (currentPage == 1) {
|
||||||
|
binding.refreshLayout.finishRefresh()
|
||||||
|
loadEmptyView()
|
||||||
|
} else {
|
||||||
|
currentPage--
|
||||||
|
binding.refreshLayout.finishLoadMore()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 加载空视图
|
||||||
|
*/
|
||||||
|
private fun loadEmptyView() {
|
||||||
|
mealList.clear()
|
||||||
|
mealAdapter.notifyDataSetChanged()
|
||||||
|
if (emptyViewBinding == null) {
|
||||||
|
emptyViewBinding = LayoutEmptyViewBinding.inflate(
|
||||||
|
LayoutInflater.from(this), binding.rvMealList, false
|
||||||
|
)
|
||||||
|
}
|
||||||
|
emptyViewBinding?.run {
|
||||||
|
tvContent.text = "暂无数据"
|
||||||
|
tvSubContent.text = "暂无餐品数据"
|
||||||
|
mealAdapter.stateView = root
|
||||||
|
}
|
||||||
|
binding.refreshLayout.run {
|
||||||
|
setEnableRefresh(true)
|
||||||
|
setEnableLoadMore(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,868 @@
|
|||||||
|
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.GestureDetector
|
||||||
|
import android.view.MotionEvent
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import androidx.activity.addCallback
|
||||||
|
import androidx.core.content.IntentCompat
|
||||||
|
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.adapter.FoodMaterialAdapter
|
||||||
|
import com.shuwei.dish.match.adapter.FormFieldAdapter
|
||||||
|
import com.shuwei.dish.match.base.BaseActivity
|
||||||
|
import com.shuwei.dish.match.databinding.ActivityPackBinding
|
||||||
|
import com.shuwei.dish.match.databinding.LayoutCameraPreviewBinding
|
||||||
|
import com.shuwei.dish.match.dialog.CommonDialog
|
||||||
|
import com.shuwei.dish.match.model.CookFoodDTO
|
||||||
|
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||||
|
import com.shuwei.dish.match.dialog.InboundIngredientSearchDialog
|
||||||
|
import com.shuwei.dish.match.model.DictType
|
||||||
|
import com.shuwei.dish.match.model.FieldType
|
||||||
|
import com.shuwei.dish.match.model.FoodRecord
|
||||||
|
import com.shuwei.dish.match.model.FormField
|
||||||
|
import com.shuwei.dish.match.model.GoodsItem
|
||||||
|
import com.shuwei.dish.match.model.NutFoodOptionVO
|
||||||
|
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.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.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 com.yanzhenjie.recyclerview.SwipeMenuItem
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.Serializable
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
import kotlin.math.abs
|
||||||
|
import com.shuwei.dish.match.model.NutFoodComposition
|
||||||
|
import com.shuwei.dish.match.net.NetViewModelV2
|
||||||
|
import com.shuwei.dish.match.utils.DateTimeUtil
|
||||||
|
import com.shuwei.dish.match.utils.ext.roundedOneDecimalPlace
|
||||||
|
import java.time.LocalDateTime
|
||||||
|
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
class PackActivity : BaseActivity() {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val TAG = "PackActivity"
|
||||||
|
const val MEAL_ITEM = "mealItem"
|
||||||
|
const val PAGE_FROM = "pageFrom"
|
||||||
|
const val HOME = "home"
|
||||||
|
const val WEIGHT_CHANGE_VALUE = 5
|
||||||
|
const val WEIGHT_RECOGNIZE_VALUE = 10
|
||||||
|
|
||||||
|
/** 主材数量上限 */
|
||||||
|
const val MATERIAL_COUNT = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
private val binding by lazy { ActivityPackBinding.inflate(layoutInflater) }
|
||||||
|
|
||||||
|
private val cameraUtils: CameraUtils by lazy { CameraUtils(this) }
|
||||||
|
|
||||||
|
private var mealItem: NutFoodOptionVO? = null
|
||||||
|
|
||||||
|
/** 来源页面标识,HOME 时返回跳转 SamplingListActivity */
|
||||||
|
private var pageFrom: String? = null
|
||||||
|
|
||||||
|
private var goodsList: MutableList<CookFoodGoodsEntity>? = null
|
||||||
|
private val viewModelV2 by lazy { NetViewModelV2() }
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
setContentView(binding.root)
|
||||||
|
setHeaderBackground()
|
||||||
|
pageFrom = intent.getStringExtra(PAGE_FROM)
|
||||||
|
mealItem = IntentCompat.getParcelableExtra(intent, MEAL_ITEM, NutFoodOptionVO::class.java)
|
||||||
|
|
||||||
|
mealItem?.let {
|
||||||
|
binding.etInputDish.run {
|
||||||
|
setText(it.foodName)
|
||||||
|
tag = it.foodName
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setTitleBar(titleBarAction = {
|
||||||
|
it.visible()
|
||||||
|
}, titleAction = {
|
||||||
|
it.text = "餐品净菜包"
|
||||||
|
}, rightIconAction = {
|
||||||
|
it.gone()
|
||||||
|
}, backAction = {
|
||||||
|
it.setOnClickListener {
|
||||||
|
onBackPressedDispatcher.onBackPressed()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// 不可编辑,仅展示菜名
|
||||||
|
binding.etInputDish.isFocusable = false
|
||||||
|
binding.etInputDish.isFocusableInTouchMode = false
|
||||||
|
binding.ivDishSearch.gone()
|
||||||
|
|
||||||
|
// binding.tvGoodsName.text = "食材名称"
|
||||||
|
|
||||||
|
addViewClickListener()
|
||||||
|
addBackKeyListener()
|
||||||
|
initCamera(binding.flCameraContainer)
|
||||||
|
initRecyclerView()
|
||||||
|
initObserver()
|
||||||
|
|
||||||
|
// 根据传入的餐品数据加载食材列表
|
||||||
|
mealItem?.let {
|
||||||
|
val compositions = it.compositions
|
||||||
|
if (!compositions.isNullOrEmpty()) {
|
||||||
|
loadDishCompositions(compositions)
|
||||||
|
} else {
|
||||||
|
toast("该餐品无食材构成信息")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var currentWeight = 0.0
|
||||||
|
private fun addViewClickListener() {
|
||||||
|
// ========== 重量识别相关功能已注释 ==========
|
||||||
|
WeightUtil.addWeightListener(
|
||||||
|
weightKey = TAG,
|
||||||
|
getWeight = { address, state, weight ->
|
||||||
|
if (address == AddressUtil.ONE && state == WeightUtil.STATE_STABLE) {
|
||||||
|
runOnUiThread {
|
||||||
|
currentWeight = weight - initialWeight
|
||||||
|
binding.tvShowWeight.run {
|
||||||
|
if (tag != currentWeight) {
|
||||||
|
// text = "称重:${netWeight}g"
|
||||||
|
val weightText = "${currentWeight.roundedOneDecimalPlace()}g"
|
||||||
|
text = weightText
|
||||||
|
tag = currentWeight
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//recognizeFood(netWeight)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
if (SpTool.cookMode == 1) {
|
||||||
|
// 采集模式:绑定搜索栏交互
|
||||||
|
binding.ivDishSearch.visible()
|
||||||
|
binding.etInputDish.isFocusable = true
|
||||||
|
binding.etInputDish.isFocusableInTouchMode = true
|
||||||
|
binding.ivDishSearch.setOnClickListener { jumpSearch() }
|
||||||
|
binding.etInputDish.addOnActionSearchListener { jumpSearch() }
|
||||||
|
}
|
||||||
|
|
||||||
|
// binding.btnCook.clickWithDebounce {
|
||||||
|
// if (SpTool.cookMode == 1) {
|
||||||
|
// // 采集模式:从输入框创建 FoodRecord
|
||||||
|
// val showFoodName = binding.etInputDish.text.toString().trim()
|
||||||
|
// if (showFoodName.isBlank()) {
|
||||||
|
// toast("菜品名称为空")
|
||||||
|
// return@clickWithDebounce
|
||||||
|
// }
|
||||||
|
// if (list.isEmpty()) {
|
||||||
|
// toast("菜品构成信息未设置")
|
||||||
|
// return@clickWithDebounce
|
||||||
|
// }
|
||||||
|
// val foodRecord = FoodRecord().apply {
|
||||||
|
// foodId = mealItem?.foodId?.toString()
|
||||||
|
// foodName = showFoodName
|
||||||
|
// cookMode = 1
|
||||||
|
// }
|
||||||
|
// Log.d(TAG, "goToSubmit: goodsList:${list.toJsonString()}")
|
||||||
|
// val submitList = list.map { it.toCookFoodGoodsEntity() }.toMutableList()
|
||||||
|
// startActivity<SubmitFoodActivity> {
|
||||||
|
// putExtra(SubmitFoodActivity.GOODS_LIST, submitList as Serializable)
|
||||||
|
// putExtra(SubmitFoodActivity.FOOD_ITEM, foodRecord as Serializable)
|
||||||
|
// }
|
||||||
|
// } else {
|
||||||
|
// // 包装模式:检查食材是否全部设置完成
|
||||||
|
// val count = list.count { it.isSetFinished.not() }
|
||||||
|
// if (count > 0) {
|
||||||
|
// showRemindDialog()
|
||||||
|
// return@clickWithDebounce
|
||||||
|
// }
|
||||||
|
// openSubmitPage()
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
binding.ivClearWeight.clickWithDebounce {
|
||||||
|
initialWeight = 0.0
|
||||||
|
SpTool.configWeight = 0
|
||||||
|
WeightUtil.tareTwo(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
binding.ivAddWeight.clickWithDebounce {
|
||||||
|
if (currentWeight <= 0.0) {
|
||||||
|
toast("当前秤重量无效")
|
||||||
|
return@clickWithDebounce
|
||||||
|
}
|
||||||
|
list.getOrNull(clickIndex)?.let {
|
||||||
|
it.useWeight = currentWeight
|
||||||
|
it.isSetFinished = true
|
||||||
|
materialAdapter.notifyItemChanged(clickIndex)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
binding.btnGetTraceCode.clickWithDebounce {
|
||||||
|
val item = list.getOrNull(clickIndex) ?: return@clickWithDebounce
|
||||||
|
InboundIngredientSearchDialog(
|
||||||
|
activity = this,
|
||||||
|
viewModelV2 = viewModelV2,
|
||||||
|
defIngredientName = item.goodsName
|
||||||
|
) { vo ->
|
||||||
|
materialAdapter.getItem(clickIndex)?.let {
|
||||||
|
it.materCode = vo.traceCode
|
||||||
|
materialAdapter.notifyItemChanged(clickIndex)
|
||||||
|
}
|
||||||
|
}.show()
|
||||||
|
}
|
||||||
|
binding.btnSubmit.clickWithDebounce {
|
||||||
|
submit()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 收集字段提交值,根据 apiKey / extraApiKeys 规则汇总
|
||||||
|
* @return 提交参数 Map,key 为接口参数名,value 为提交值
|
||||||
|
*/
|
||||||
|
private fun collectSubmitValues(): MutableMap<String, String> {
|
||||||
|
val params = mutableMapOf<String, String>()
|
||||||
|
for (field in fields) {
|
||||||
|
if (field.hidden) continue
|
||||||
|
// 跳过 CHILDREN 类型,暂不处理
|
||||||
|
if (field.type == FieldType.CHILDREN) continue
|
||||||
|
|
||||||
|
if (field.extraApiKeys.isNotEmpty()) {
|
||||||
|
// 下拉字段:直接读取 bindDropdown 已解析好的 extraValues
|
||||||
|
field.extraValues.forEach { (apiKey, value) ->
|
||||||
|
params[apiKey] = value
|
||||||
|
}
|
||||||
|
} else if (field.apiKey.isNotBlank()) {
|
||||||
|
// 普通字段
|
||||||
|
params[field.apiKey] = field.value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return params
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提交餐品净菜包装
|
||||||
|
*/
|
||||||
|
private fun submit() {
|
||||||
|
val food = mealItem ?: return
|
||||||
|
//包装方式、包装份数、保质期至、包装人、存放温度、终端设备
|
||||||
|
val values = collectSubmitValues()
|
||||||
|
val params = mutableMapOf<String, Any?>()
|
||||||
|
values.forEach { (key, value) ->
|
||||||
|
params[key] = value
|
||||||
|
}
|
||||||
|
//关联餐品id
|
||||||
|
params["foodId"] = food.foodId
|
||||||
|
//包装餐品名称
|
||||||
|
params["mealName"] = food.foodName
|
||||||
|
//包装日期
|
||||||
|
params["packageDate"] = DateTimeUtil.formatDateTime(
|
||||||
|
dateTime = LocalDateTime.now(),
|
||||||
|
pattern = DateTimeUtil.YYYY_MM_DD
|
||||||
|
)
|
||||||
|
// //操作类型
|
||||||
|
// params["opType"] = "设备自动"
|
||||||
|
|
||||||
|
//食材明细列表
|
||||||
|
params["ingredients"] = list.map {
|
||||||
|
NutFoodComposition(
|
||||||
|
materId = it.goodsId.toLongOrNull(),
|
||||||
|
ingredientName = it.goodsName,
|
||||||
|
traceCode = it.materCode,
|
||||||
|
amount = it.useWeight,
|
||||||
|
isMain = it.materialType,
|
||||||
|
mainText = MaterialTypeTool.getMaterialText(it.materialType)
|
||||||
|
)
|
||||||
|
}.toMutableList()
|
||||||
|
|
||||||
|
viewModelV2.addMealPackage(params) { state, msg ->
|
||||||
|
if (state.not()) {
|
||||||
|
toast("提交失败:$msg")
|
||||||
|
return@addMealPackage
|
||||||
|
}
|
||||||
|
toast("提交成功")
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// private val isTakingPhoto = AtomicBoolean(false)
|
||||||
|
|
||||||
|
// ========== 重量识别相关变量已注释 ==========
|
||||||
|
// private var showRecognizePage = false
|
||||||
|
// private var pageVisible = true
|
||||||
|
// private var manualCancelFlag = false
|
||||||
|
// private var lastPhotoUri: Uri? = null
|
||||||
|
// private var lastWeight = 0.0
|
||||||
|
// private var currentWeight = 0.0
|
||||||
|
private var initialWeight = SpTool.configWeight.toDouble()
|
||||||
|
|
||||||
|
// private fun recognizeFood(weight: Double) {
|
||||||
|
// // 重量识别逻辑已注释
|
||||||
|
// }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 重新计算 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 }
|
||||||
|
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun openSubmitPage() {
|
||||||
|
getGoodsList()
|
||||||
|
if (goodsList.isNullOrEmpty()) {
|
||||||
|
toast("无菜品构成信息")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
Log.d(TAG, "goToSubmit: goodsList:${goodsList?.toJsonString()}")
|
||||||
|
startActivity<SubmitFoodActivity> {
|
||||||
|
putExtra(SubmitFoodActivity.GOODS_LIST, goodsList as Serializable)
|
||||||
|
putExtra(SubmitFoodActivity.FOOD_ITEM, FoodRecord().apply {
|
||||||
|
foodId = mealItem?.foodId?.toString()
|
||||||
|
foodName = mealItem?.foodName
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getGoodsList() {
|
||||||
|
if (goodsList == null) {
|
||||||
|
goodsList = mutableListOf()
|
||||||
|
} else {
|
||||||
|
goodsList!!.clear()
|
||||||
|
}
|
||||||
|
// 将 Goods Item 转换为 CookFoodGoodsEntity 并补充菜品相关字段
|
||||||
|
list.filter { it.isSetFinished }.forEach {
|
||||||
|
goodsList?.add(it.toCookFoodGoodsEntity().apply {
|
||||||
|
foodId = mealItem?.foodId?.toString()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showRemindDialog() {
|
||||||
|
CommonDialog(this)
|
||||||
|
.setTitle(getString(R.string.food_remind_01))
|
||||||
|
.setContent(getString(R.string.food_remind_02))
|
||||||
|
.setNegativeButton("返回调整")
|
||||||
|
.setPositiveButton("确认无误") { openSubmitPage() }
|
||||||
|
.setOnDismissCallback { hideStatusBar() }
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private fun initObserver() {
|
||||||
|
lifecycleScope.launch {
|
||||||
|
netViewModel.foodDetailState.collect { state ->
|
||||||
|
when (state) {
|
||||||
|
is UiState.Success -> {
|
||||||
|
val detail = state.data
|
||||||
|
if (detail == null) {
|
||||||
|
toast("查询菜品信息为空")
|
||||||
|
return@collect
|
||||||
|
}
|
||||||
|
loadDishDetail(detail)
|
||||||
|
}
|
||||||
|
|
||||||
|
is UiState.Error -> toast(state.msg)
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== getDishDetail 方法已删除,不再通过接口查询 ==========
|
||||||
|
|
||||||
|
private fun loadDishDetail(detail: CookFoodDTO) {
|
||||||
|
val voList = detail.foodConstituteList
|
||||||
|
if (voList.isNullOrEmpty()) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// 筛选出主材和辅材,转换为 Goods Item(useWeight 置零)
|
||||||
|
val tempData = voList.filter { it.materialType == 1 || it.materialType == 2 }
|
||||||
|
.map { it.toGoodsItem().also { item -> item.useWeight = 0.0 } }
|
||||||
|
// 直接替换 adapter.items
|
||||||
|
list.clear()
|
||||||
|
list.addAll(tempData)
|
||||||
|
materialAdapter.items = list
|
||||||
|
materialAdapter.notifyDataSetChanged()
|
||||||
|
firstReqSize = list.size
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 加载餐品食材构成(从 NutFoodOptionVO.compositions 解析)
|
||||||
|
*/
|
||||||
|
private fun loadDishCompositions(compositions: List<NutFoodComposition>) {
|
||||||
|
// 将 NutFoodComposition 转换为 Goods Item
|
||||||
|
val tempData = compositions.map { comp ->
|
||||||
|
GoodsItem().apply {
|
||||||
|
goodsId = comp.materId?.toString() ?: ""
|
||||||
|
goodsName = comp.ingredientName ?: ""
|
||||||
|
materialType = comp.isMain ?: 0
|
||||||
|
useWeight = 0.0
|
||||||
|
isOriginalData = true
|
||||||
|
isSetFinished = false
|
||||||
|
}
|
||||||
|
}.toMutableList()
|
||||||
|
|
||||||
|
list.clear()
|
||||||
|
list.addAll(tempData)
|
||||||
|
materialAdapter.items = list
|
||||||
|
materialAdapter.notifyDataSetChanged()
|
||||||
|
firstReqSize = list.size
|
||||||
|
}
|
||||||
|
|
||||||
|
private var firstReqSize = 0
|
||||||
|
private val list = mutableListOf<GoodsItem>()
|
||||||
|
private var clickIndex = -1
|
||||||
|
|
||||||
|
private val fields = mutableListOf<FormField>()
|
||||||
|
|
||||||
|
private val formAdapter by lazy {
|
||||||
|
FormFieldAdapter(fields)
|
||||||
|
}
|
||||||
|
|
||||||
|
private val materialAdapter by lazy {
|
||||||
|
FoodMaterialAdapter(list).apply {
|
||||||
|
onItemClick = onItemClick@{ positon ->
|
||||||
|
val item = getItem(positon) ?: return@onItemClick
|
||||||
|
this@PackActivity.clickIndex = positon
|
||||||
|
list.forEachIndexed { index, entity ->
|
||||||
|
entity.isClicked = index == positon
|
||||||
|
}
|
||||||
|
notifyDataSetChanged()
|
||||||
|
// binding.tvGoodsName.text = item.goodsName
|
||||||
|
// binding.tvMaterialType.text = when (item.materialType) {
|
||||||
|
// 1 -> "主材"
|
||||||
|
// 2 -> "辅材"
|
||||||
|
// else -> "未知"
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
return@addOnItemChildClickListener
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteRemindDialog("删除确认", "确定删除食材「${item.goodsName}」吗?") {
|
||||||
|
removeFood(position)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private var packageMethodField: FormField? = null
|
||||||
|
private var deviceField: FormField? = null
|
||||||
|
private fun initFormList() {
|
||||||
|
packageMethodField =
|
||||||
|
FormField(
|
||||||
|
label = "包装方式", type = FieldType.DROPDOWN,
|
||||||
|
// extraApiKeys = mapOf("packageMethodId" to "id", "packageMethod" to "value"),
|
||||||
|
extraApiKeys = mapOf("packageMethod" to "type"),
|
||||||
|
required = true
|
||||||
|
)
|
||||||
|
fields.add(packageMethodField!!)
|
||||||
|
fields.add(
|
||||||
|
FormField(
|
||||||
|
label = "包装份数", type = FieldType.INTEGER,
|
||||||
|
apiKey = "quantity", required = true, hint = "请输入份数"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
// fields.add(
|
||||||
|
// FormField(
|
||||||
|
// label = "包装日期",
|
||||||
|
// type = FieldType.DATE_PICKER,
|
||||||
|
// apiKey = "packageDate",
|
||||||
|
// required = true
|
||||||
|
// )
|
||||||
|
// )
|
||||||
|
fields.add(
|
||||||
|
FormField(
|
||||||
|
label = "保质期至",
|
||||||
|
type = FieldType.DATE_PICKER,
|
||||||
|
apiKey = "expiryDate",
|
||||||
|
required = true
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
fields.add(
|
||||||
|
FormField(
|
||||||
|
label = "存放温度(℃)",
|
||||||
|
type = FieldType.DECIMAL,
|
||||||
|
apiKey = "storageTemp",
|
||||||
|
required = false,
|
||||||
|
hint = "请输入小数"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
fields.add(
|
||||||
|
FormField(
|
||||||
|
label = "包装人",
|
||||||
|
type = FieldType.TEXT,
|
||||||
|
apiKey = "operator",
|
||||||
|
required = false
|
||||||
|
)
|
||||||
|
)
|
||||||
|
deviceField = FormField(
|
||||||
|
label = "终端设备",
|
||||||
|
type = FieldType.DROPDOWN,
|
||||||
|
extraApiKeys = mapOf("deviceId" to "id"),
|
||||||
|
required = false
|
||||||
|
)
|
||||||
|
fields.add(deviceField!!)
|
||||||
|
fields.add(
|
||||||
|
FormField(
|
||||||
|
label = "操作类型", type = FieldType.DROPDOWN,
|
||||||
|
apiKey = "opType",
|
||||||
|
extraApiKeys = mapOf("opType" to "id"),
|
||||||
|
required = true,
|
||||||
|
options = listOf(
|
||||||
|
DictType(id = "1", value = "设备自动"),
|
||||||
|
DictType(id = "2", value = "人工录入")
|
||||||
|
).toMutableList()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
loadDictItemsWithCallback("sup_package_method", packageMethodField!!)
|
||||||
|
loadDeviceOptionsWithCallback(deviceField)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 加载字典项下拉(回调版本),适合多次不同 dictType 的场景
|
||||||
|
*/
|
||||||
|
private fun loadDictItemsWithCallback(dictType: String, targetField: FormField) {
|
||||||
|
viewModelV2.getDictItemsWithCallback(
|
||||||
|
dictType = dictType,
|
||||||
|
onLoading = {},
|
||||||
|
onResult = { state ->
|
||||||
|
when (state) {
|
||||||
|
is UiState.Success -> {
|
||||||
|
val options = state.data?.map { vo ->
|
||||||
|
DictType(
|
||||||
|
id = vo.id?.toString() ?: "",
|
||||||
|
value = vo.dictLabel ?: "",
|
||||||
|
type = vo.dictCode ?: ""
|
||||||
|
)
|
||||||
|
} ?: emptyList()
|
||||||
|
targetField.options.clear()
|
||||||
|
targetField.options.addAll(options)
|
||||||
|
val index = fields.indexOf(targetField)
|
||||||
|
if (index >= 0) formAdapter.notifyItemChanged(index)
|
||||||
|
}
|
||||||
|
|
||||||
|
is UiState.Error -> {
|
||||||
|
toast("加载字典项失败:${state.msg}")
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 加载设备下拉(回调版本),用于餐品净菜包装
|
||||||
|
*/
|
||||||
|
private fun loadDeviceOptionsWithCallback(deviceField: FormField? = null) {
|
||||||
|
val field = deviceField ?: return
|
||||||
|
viewModelV2.getDeviceOptionsWithCallback(
|
||||||
|
onLoading = {},
|
||||||
|
onResult = { state ->
|
||||||
|
when (state) {
|
||||||
|
is UiState.Success -> {
|
||||||
|
val options = state.data?.map { vo ->
|
||||||
|
DictType(
|
||||||
|
id = vo.id?.toString() ?: "",
|
||||||
|
value = vo.deviceName ?: "",
|
||||||
|
type = vo.deviceNo ?: ""
|
||||||
|
)
|
||||||
|
} ?: emptyList()
|
||||||
|
field.options.clear()
|
||||||
|
field.options.addAll(options)
|
||||||
|
val index = fields.indexOf(field)
|
||||||
|
if (index >= 0) formAdapter.notifyItemChanged(index)
|
||||||
|
}
|
||||||
|
|
||||||
|
is UiState.Error -> {
|
||||||
|
toast("加载设备列表失败:${state.msg}")
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RecyclerView初始化
|
||||||
|
*/
|
||||||
|
@SuppressLint("ClickableViewAccessibility")
|
||||||
|
private fun initRecyclerView() {
|
||||||
|
initFormList()
|
||||||
|
binding.rvFormList.let {
|
||||||
|
it.layoutManager = GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false)
|
||||||
|
it.adapter = formAdapter
|
||||||
|
}
|
||||||
|
|
||||||
|
binding.rvMaterialList.let {
|
||||||
|
it.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
|
||||||
|
// 仅 isNewDishType=true 的 item 显示侧滑删除菜单(必须在 setAdapter 之前调用)
|
||||||
|
// it.setSwipeMenuCreator { _, rightMenu, position ->
|
||||||
|
// if (list.getOrNull(position)?.isNewDishType == true) {
|
||||||
|
// rightMenu.addMenuItem(buildDeleteMenuItem())
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// // 点击侧滑菜单项:先关闭菜单,再弹窗确认删除
|
||||||
|
// it.setOnItemMenuClickListener { menuBridge, position ->
|
||||||
|
// menuBridge.closeMenu()
|
||||||
|
// val item = list.getOrNull(position) ?: return@setOnItemMenuClickListener
|
||||||
|
// deleteRemindDialog("删除确认", "确定删除食材「${item.goodsName}」吗?") {
|
||||||
|
// removeFood(position)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// // item 点击事件
|
||||||
|
// it.setOnItemClickListener { _, position ->
|
||||||
|
// materialAdapter.onItemClick?.invoke(position)
|
||||||
|
// }
|
||||||
|
handleRvTouchHideKeyboard()
|
||||||
|
it.adapter = materialAdapter
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除提醒
|
||||||
|
*/
|
||||||
|
private fun deleteRemindDialog(title: String, content: String, action: () -> Unit) {
|
||||||
|
CommonDialog(this@PackActivity)
|
||||||
|
.setTitle(title)
|
||||||
|
.setContent(content)
|
||||||
|
.setNegativeButton("取消")
|
||||||
|
.setPositiveButton("确认") {
|
||||||
|
action()
|
||||||
|
}.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 移除菜品
|
||||||
|
*/
|
||||||
|
private fun removeFood(position: Int) {
|
||||||
|
materialAdapter.removeAt(position)
|
||||||
|
toast("已删除")
|
||||||
|
updateMaterialTypes()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建侧滑删除菜单项
|
||||||
|
*/
|
||||||
|
private fun buildDeleteMenuItem(): SwipeMenuItem {
|
||||||
|
return SwipeMenuItem(this).apply {
|
||||||
|
setImage(R.drawable.ic_trash_white)
|
||||||
|
setBackground(R.drawable.bg_swipe_delete)
|
||||||
|
width = 160.dp
|
||||||
|
height = ViewGroup.LayoutParams.MATCH_PARENT
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onResume() {
|
||||||
|
super.onResume()
|
||||||
|
// pageVisible = true
|
||||||
|
// showRecognizePage = false
|
||||||
|
cameraUtils.bind()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onPause() {
|
||||||
|
super.onPause()
|
||||||
|
// pageVisible = false
|
||||||
|
cameraUtils.unbind()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化相机并绑定预览容器
|
||||||
|
* @param container 相机预览容器
|
||||||
|
*/
|
||||||
|
fun initCamera(container: ViewGroup) {
|
||||||
|
cameraUtils.initCamera()
|
||||||
|
val previewBinding = LayoutCameraPreviewBinding.inflate(layoutInflater, container)
|
||||||
|
cameraUtils.setPreviewController(previewBinding.previewView)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册返回键监听,替代已废弃的 onBackPressed()
|
||||||
|
*/
|
||||||
|
private fun addBackKeyListener() {
|
||||||
|
onBackPressedDispatcher.addCallback(this) {
|
||||||
|
if (SpTool.cookMode == 1) {
|
||||||
|
// 采集模式:有新增食材时提示保存
|
||||||
|
if (list.isEmpty().not()) {
|
||||||
|
saveDataRemindDialog()
|
||||||
|
return@addCallback
|
||||||
|
}
|
||||||
|
if (pageFrom == HOME) {
|
||||||
|
startActivity<SamplingModeActivity>()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 包装模式:有未保存数据时提示
|
||||||
|
val count = list.count { !it.isOriginalData }
|
||||||
|
if (count > 0) {
|
||||||
|
saveDataRemindDialog()
|
||||||
|
return@addCallback
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 未保存数据提醒
|
||||||
|
*/
|
||||||
|
private fun saveDataRemindDialog() {
|
||||||
|
CommonDialog(this)
|
||||||
|
.setTitle("返回提示")
|
||||||
|
.setContent("您好,当前页面存在未保存的数据,\n确认返回吗?")
|
||||||
|
.setNegativeButton("取消")
|
||||||
|
.setPositiveButton("确认") {
|
||||||
|
if (SpTool.cookMode == 1 && pageFrom == HOME) {
|
||||||
|
startActivity<SamplingModeActivity>()
|
||||||
|
}
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
.setOnDismissCallback { hideStatusBar() }
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 拍照回调相关功能已注释 ==========
|
||||||
|
// private val cameraSuccessCallback: (Uri) -> Unit = { uri ->
|
||||||
|
// // 拍照成功回调已注释
|
||||||
|
// }
|
||||||
|
// private var notRecognizeDialog: CommonDialog? = null
|
||||||
|
// private fun showNotRecognizeDialog() {
|
||||||
|
// // 未识别弹窗已注释
|
||||||
|
// }
|
||||||
|
// private val cameraFailureCallback: (String) -> Unit = { errMsg ->
|
||||||
|
// // 拍照失败回调已注释
|
||||||
|
// }
|
||||||
|
// private fun loadRecognizeResultPage(nameScoreList: List<FoodModule.IdNameScore>) {
|
||||||
|
// // 识别结果页加载已注释
|
||||||
|
// }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 跳转食物搜索页(采集模式专用)
|
||||||
|
*/
|
||||||
|
private fun jumpSearch() {
|
||||||
|
val searchContent = binding.etInputDish.text.toString().trim()
|
||||||
|
if (searchContent.isBlank()) {
|
||||||
|
toast(binding.etInputDish.hint.toString())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val launchIntent = Intent(this, FoodSearchActivity::class.java).apply {
|
||||||
|
putExtra(FoodSearchActivity.FOOD_NAME, searchContent)
|
||||||
|
}
|
||||||
|
startActivity(launchIntent) { resultIntent ->
|
||||||
|
if (resultIntent == null) return@startActivity
|
||||||
|
val food = IntentCompat.getSerializableExtra(
|
||||||
|
resultIntent,
|
||||||
|
FoodSearchActivity.FOOD_ITEM,
|
||||||
|
FoodRecord::class.java
|
||||||
|
)
|
||||||
|
Log.d(TAG, "jumpSearch: record=$food")
|
||||||
|
if (food == null) return@startActivity
|
||||||
|
binding.etInputDish.run {
|
||||||
|
setText(food.foodName)
|
||||||
|
tag = food.foodName
|
||||||
|
setSelection(text.length)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
hideKeyboard()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleRvTouchHideKeyboard() {
|
||||||
|
val gestureDetector =
|
||||||
|
GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
|
||||||
|
override fun onSingleTapUp(e: MotionEvent): Boolean {
|
||||||
|
hideKeyboard()
|
||||||
|
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
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
super.onDestroy()
|
||||||
|
WeightUtil.removeWeightListener(TAG)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -19,10 +19,10 @@ import com.shuwei.dish.match.base.BaseActivity
|
|||||||
import com.shuwei.dish.match.databinding.ActivityPrepareFoodBinding
|
import com.shuwei.dish.match.databinding.ActivityPrepareFoodBinding
|
||||||
import com.shuwei.dish.match.databinding.LayoutCameraPreviewBinding
|
import com.shuwei.dish.match.databinding.LayoutCameraPreviewBinding
|
||||||
import com.shuwei.dish.match.dialog.CommonDialog
|
import com.shuwei.dish.match.dialog.CommonDialog
|
||||||
import com.shuwei.dish.match.entity.CookFoodDTO
|
import com.shuwei.dish.match.model.CookFoodDTO
|
||||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||||
import com.shuwei.dish.match.entity.FoodRecord
|
import com.shuwei.dish.match.model.FoodRecord
|
||||||
import com.shuwei.dish.match.entity.GoodsItem
|
import com.shuwei.dish.match.model.GoodsItem
|
||||||
import com.shuwei.dish.match.net.UiState
|
import com.shuwei.dish.match.net.UiState
|
||||||
import com.shuwei.dish.match.objbox.FoodModule
|
import com.shuwei.dish.match.objbox.FoodModule
|
||||||
import com.shuwei.dish.match.utils.AddressUtil
|
import com.shuwei.dish.match.utils.AddressUtil
|
||||||
@@ -85,7 +85,7 @@ class PrepareFoodActivity : BaseActivity() {
|
|||||||
it.visible()
|
it.visible()
|
||||||
}, titleAction = {
|
}, titleAction = {
|
||||||
it.text = titleText
|
it.text = titleText
|
||||||
}, rightIconActon = {
|
}, rightIconAction = {
|
||||||
it.gone()
|
it.gone()
|
||||||
}, backAction = {
|
}, backAction = {
|
||||||
it.setOnClickListener {
|
it.setOnClickListener {
|
||||||
@@ -124,34 +124,41 @@ class PrepareFoodActivity : BaseActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun addViewClickListener() {
|
private fun addViewClickListener() {
|
||||||
binding.tvShowWeight.setOnClickListener {
|
// binding.tvShowWeight.setOnClickListener {
|
||||||
showLoading("正在清零……")
|
// showLoading("正在清零……")
|
||||||
WeightUtil.tareTwo(AddressUtil.ONE)
|
// WeightUtil.tareTwo(AddressUtil.ONE)
|
||||||
delayDismissLoading()
|
// delayDismissLoading()
|
||||||
}
|
// }
|
||||||
// TODO: 测试功能-------------------------------
|
// // TODO: 测试功能-------------------------------
|
||||||
binding.btnTestConfirm.clickWithDebounce {
|
// binding.btnTestConfirm.clickWithDebounce {
|
||||||
if (currentWeight <= 0.0) return@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
|
// val (index, item) = list.withIndex().find { (_, it) -> it.isOriginalData && it.isClicked && (it.useWeight?:0.0) <= 0.0 } ?: return@clickWithDebounce
|
||||||
item.useWeight = currentWeight
|
// item.useWeight = currentWeight
|
||||||
item.isSetFinished = true
|
// item.isSetFinished = true
|
||||||
list.forEachIndexed { i, it -> it.isClicked = i == index }
|
// list.forEachIndexed { i, it -> it.isClicked = i == index }
|
||||||
materialAdapter.notifyDataSetChanged()
|
// materialAdapter.notifyDataSetChanged()
|
||||||
}
|
// }
|
||||||
// TODO: 测试功能-------------------------------
|
// // TODO: 测试功能-------------------------------
|
||||||
//binding.root.setOnClickListener { hideKeyboard() }
|
//binding.root.setOnClickListener { hideKeyboard() }
|
||||||
WeightUtil.addWeightListener(
|
WeightUtil.addWeightListener(
|
||||||
weightKey = TAG,
|
weightKey = TAG,
|
||||||
getWeight = { address, state, weight ->
|
getWeight = { address, state, weight ->
|
||||||
if (address == AddressUtil.ONE && state == WeightUtil.STATE_STABLE) {
|
if (address == AddressUtil.ONE && state == WeightUtil.STATE_STABLE) {
|
||||||
runOnUiThread {
|
runOnUiThread {
|
||||||
|
// 首次收到稳定读数时,将其作为初始值(去皮基准)
|
||||||
|
// if (!initialWeightReady) {
|
||||||
|
// initialWeight = weight
|
||||||
|
// initialWeightReady = true
|
||||||
|
// }
|
||||||
|
// 净重 = 秤读数 - 初始读数
|
||||||
|
val netWeight = weight - initialWeight
|
||||||
binding.tvShowWeight.run {
|
binding.tvShowWeight.run {
|
||||||
if (tag != weight) {
|
if (tag != netWeight) {
|
||||||
text = "称重:${weight}g"
|
text = "称重:${netWeight}g"
|
||||||
tag = weight
|
tag = netWeight
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
recognizeFood(weight)
|
recognizeFood(netWeight)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -216,6 +223,12 @@ class PrepareFoodActivity : BaseActivity() {
|
|||||||
private var lastWeight = 0.0
|
private var lastWeight = 0.0
|
||||||
private var currentWeight = 0.0
|
private var currentWeight = 0.0
|
||||||
|
|
||||||
|
/** 初始秤读数,净重 = 秤读数 - initialWeight,从 SpTool.configWeight 读取 */
|
||||||
|
private var initialWeight = SpTool.configWeight.toDouble()
|
||||||
|
|
||||||
|
/** 初始读数是否已从秤获取 */
|
||||||
|
// private var initialWeightReady = false
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 重量稳定时触发菜品识别
|
* 重量稳定时触发菜品识别
|
||||||
* @param weight 当前稳定重量
|
* @param weight 当前稳定重量
|
||||||
@@ -257,11 +270,11 @@ class PrepareFoodActivity : BaseActivity() {
|
|||||||
val filterValue = list.withIndex().find { (_, it) -> it.goodsId == entity.goodsId }
|
val filterValue = list.withIndex().find { (_, it) -> it.goodsId == entity.goodsId }
|
||||||
if (filterValue != null) {
|
if (filterValue != null) {
|
||||||
val index = filterValue.index
|
val index = filterValue.index
|
||||||
val item = filterValue.value
|
val goods = filterValue.value
|
||||||
item.useWeight = (item.useWeight ?: 0.0) + (entity.useWeight ?: 0.0)
|
goods.useWeight = (goods.useWeight ?: 0.0) + (entity.useWeight ?: 0.0)
|
||||||
item.isSetFinished = true
|
goods.isSetFinished = true
|
||||||
list.forEachIndexed { i, it ->
|
list.forEachIndexed { i, it ->
|
||||||
item.isClicked = i == index
|
it.isClicked = i == index
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
list.forEach { it.isClicked = false }
|
list.forEach { it.isClicked = false }
|
||||||
@@ -325,6 +338,8 @@ class PrepareFoodActivity : BaseActivity() {
|
|||||||
private fun getGoodsList() {
|
private fun getGoodsList() {
|
||||||
if (goodsList == null) {
|
if (goodsList == null) {
|
||||||
goodsList = mutableListOf()
|
goodsList = mutableListOf()
|
||||||
|
} else {
|
||||||
|
goodsList!!.clear()
|
||||||
}
|
}
|
||||||
// 将 GoodsItem 转换为 CookFoodGoodsEntity 并补充菜品相关字段
|
// 将 GoodsItem 转换为 CookFoodGoodsEntity 并补充菜品相关字段
|
||||||
list.filter { it.isSetFinished }.forEach {
|
list.filter { it.isSetFinished }.forEach {
|
||||||
@@ -398,8 +413,8 @@ class PrepareFoodActivity : BaseActivity() {
|
|||||||
notifyDataSetChanged()
|
notifyDataSetChanged()
|
||||||
}
|
}
|
||||||
addOnItemChildClickListener(R.id.ivClearIcon) { _, _, position ->
|
addOnItemChildClickListener(R.id.ivClearIcon) { _, _, position ->
|
||||||
Log.d(TAG, "onFoodItemClick: ${list[position].toJsonString()}")
|
val item = list.getOrNull(position) ?:return@addOnItemChildClickListener
|
||||||
val item = list[position]
|
Log.d(TAG, "onFoodItemClick: ${item.toJsonString()}")
|
||||||
if (item.isOriginalData) {
|
if (item.isOriginalData) {
|
||||||
// 无重量信息时转为 item 整体点击(触发选中效果)
|
// 无重量信息时转为 item 整体点击(触发选中效果)
|
||||||
if (item.useWeight == null || item.useWeight == 0.0) {
|
if (item.useWeight == null || item.useWeight == 0.0) {
|
||||||
@@ -595,7 +610,12 @@ class PrepareFoodActivity : BaseActivity() {
|
|||||||
notRecognizeDialog = CommonDialog(this)
|
notRecognizeDialog = CommonDialog(this)
|
||||||
.setTitle("提示")
|
.setTitle("提示")
|
||||||
.setContent("未识别到食材,请稍后重试")
|
.setContent("未识别到食材,请稍后重试")
|
||||||
.setNegativeButton("取消")
|
.setNegativeButton("取消") {
|
||||||
|
manualCancelFlag = true
|
||||||
|
}
|
||||||
|
.setNeutralButton("重新识别") {
|
||||||
|
recognizeFood(currentWeight)
|
||||||
|
}
|
||||||
.setPositiveButton("手动设置"){
|
.setPositiveButton("手动设置"){
|
||||||
loadRecognizeResultPage(emptyList())
|
loadRecognizeResultPage(emptyList())
|
||||||
}
|
}
|
||||||
@@ -629,6 +649,7 @@ class PrepareFoodActivity : BaseActivity() {
|
|||||||
activity = this,
|
activity = this,
|
||||||
imageUri = lastPhotoUri?.toString(),
|
imageUri = lastPhotoUri?.toString(),
|
||||||
currentWeight = currentWeight,
|
currentWeight = currentWeight,
|
||||||
|
initialWeight = initialWeight,
|
||||||
nameScoreList = ArrayList(nameScoreList),
|
nameScoreList = ArrayList(nameScoreList),
|
||||||
finishCallback = { isManualCancel, entity ->
|
finishCallback = { isManualCancel, entity ->
|
||||||
Log.d(
|
Log.d(
|
||||||
|
|||||||
@@ -3,13 +3,12 @@ package com.shuwei.dish.match.ui
|
|||||||
import android.annotation.SuppressLint
|
import android.annotation.SuppressLint
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
|
import android.util.Log
|
||||||
import android.view.LayoutInflater
|
import android.view.LayoutInflater
|
||||||
import android.view.ViewGroup
|
import android.view.ViewGroup
|
||||||
import android.widget.FrameLayout
|
import android.widget.FrameLayout
|
||||||
import androidx.activity.addCallback
|
import androidx.activity.addCallback
|
||||||
import androidx.lifecycle.Lifecycle
|
|
||||||
import androidx.lifecycle.lifecycleScope
|
import androidx.lifecycle.lifecycleScope
|
||||||
import androidx.lifecycle.repeatOnLifecycle
|
|
||||||
import androidx.recyclerview.widget.LinearLayoutManager
|
import androidx.recyclerview.widget.LinearLayoutManager
|
||||||
import com.shuwei.dish.match.R
|
import com.shuwei.dish.match.R
|
||||||
import com.shuwei.dish.match.adapter.FoodListAdapter
|
import com.shuwei.dish.match.adapter.FoodListAdapter
|
||||||
@@ -18,7 +17,7 @@ import com.shuwei.dish.match.base.BaseApp
|
|||||||
import com.shuwei.dish.match.databinding.ActivitySamplingModeBinding
|
import com.shuwei.dish.match.databinding.ActivitySamplingModeBinding
|
||||||
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
||||||
import com.shuwei.dish.match.dialog.CommonDialog
|
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.net.UiState
|
import com.shuwei.dish.match.net.UiState
|
||||||
import com.shuwei.dish.match.utils.DateTimeUtil
|
import com.shuwei.dish.match.utils.DateTimeUtil
|
||||||
import com.shuwei.dish.match.utils.ext.dp
|
import com.shuwei.dish.match.utils.ext.dp
|
||||||
@@ -49,83 +48,16 @@ class SamplingModeActivity : BaseActivity() {
|
|||||||
setHeaderBackground()
|
setHeaderBackground()
|
||||||
initRecyclerView()
|
initRecyclerView()
|
||||||
addViewListener()
|
addViewListener()
|
||||||
initObserver()
|
|
||||||
requestData(true)
|
requestData(true)
|
||||||
onBackPressedDispatcher.addCallback(this) { }
|
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
|
|
||||||
dinnerType = entity.dinnerType ?: "0"
|
|
||||||
})
|
|
||||||
}
|
|
||||||
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() {
|
private fun setTitleBar() {
|
||||||
setTitleBar(titleBarAction = {
|
setTitleBar(titleBarAction = {
|
||||||
it.visible()
|
it.visible()
|
||||||
}, titleAction = {
|
}, titleAction = {
|
||||||
it.text = "采样历史"
|
it.text = "采样历史"
|
||||||
}, rightIconActon = {
|
}, rightIconAction = {
|
||||||
it.visible()
|
it.visible()
|
||||||
it.setImageResource(R.drawable.ic_setting)
|
it.setImageResource(R.drawable.ic_setting)
|
||||||
it.setOnClickListener {
|
it.setOnClickListener {
|
||||||
@@ -134,22 +66,44 @@ class SamplingModeActivity : BaseActivity() {
|
|||||||
}, backAction = {
|
}, backAction = {
|
||||||
it.gone()
|
it.gone()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
|
||||||
fun getCookFoodList() {
|
fun getCookFoodList() {
|
||||||
val checkedId = binding.dishRadioGroup.checkedRadioButtonId
|
dbViewModel.getCookFoodListWithCallback(cookMode = 1) { cookFoodEntities ->
|
||||||
if (checkedId == R.id.rbSamplingCooking) {
|
// 回调期间用户可能已切换 Tab,需再次校验
|
||||||
appViewModel.getCookFoodList(cookMode = 1)
|
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, dinnerType: String, action: () -> Unit) {
|
fun deleteCookFoodAndGoods(foodId: String, dinnerType: String, action: () -> Unit) {
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
appViewModel.deleteCookFoodAndGoods(cookMode = 1, foodId = foodId, dinnerType = dinnerType)
|
dbViewModel.deleteCookFoodAndGoods(cookMode = 1, foodId = foodId, dinnerType = dinnerType)
|
||||||
action()
|
action()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -157,11 +111,13 @@ class SamplingModeActivity : BaseActivity() {
|
|||||||
override fun onNewIntent(intent: Intent) {
|
override fun onNewIntent(intent: Intent) {
|
||||||
super.onNewIntent(intent)
|
super.onNewIntent(intent)
|
||||||
val isConfigPage = intent?.getBooleanExtra(IS_CONFIG_PAGE, false) ?: false
|
val isConfigPage = intent?.getBooleanExtra(IS_CONFIG_PAGE, false) ?: false
|
||||||
|
Log.d(TAG, "onNewIntent, isConfigPage=$isConfigPage")
|
||||||
if (isConfigPage) {
|
if (isConfigPage) {
|
||||||
getCookFoodList()
|
getCookFoodList()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
val isCooking = intent?.getBooleanExtra(IS_COOKING, false) ?: false
|
val isCooking = intent?.getBooleanExtra(IS_COOKING, false) ?: false
|
||||||
|
Log.d(TAG, "onNewIntent, isCooking=$isCooking")
|
||||||
//toast("isCooking=$isCooking")
|
//toast("isCooking=$isCooking")
|
||||||
refreshPage(isCooking)
|
refreshPage(isCooking)
|
||||||
}
|
}
|
||||||
@@ -252,7 +208,7 @@ class SamplingModeActivity : BaseActivity() {
|
|||||||
}
|
}
|
||||||
binding.refreshLayout.setOnRefreshListener {
|
binding.refreshLayout.setOnRefreshListener {
|
||||||
pageNo = 1
|
pageNo = 1
|
||||||
if (binding.dishRadioGroup.checkedRadioButtonId == R.id.rbSamplingFinished) {
|
if (binding.rbSamplingFinished.isChecked) {
|
||||||
getSamplingList()
|
getSamplingList()
|
||||||
} else {
|
} else {
|
||||||
finishRefresh()
|
finishRefresh()
|
||||||
@@ -260,30 +216,33 @@ class SamplingModeActivity : BaseActivity() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
binding.refreshLayout.setOnLoadMoreListener {
|
binding.refreshLayout.setOnLoadMoreListener {
|
||||||
if (binding.dishRadioGroup.checkedRadioButtonId == R.id.rbSamplingFinished) {
|
if (binding.rbSamplingFinished.isChecked) {
|
||||||
getSamplingList()
|
getSamplingList()
|
||||||
} else {
|
} else {
|
||||||
finishRefresh()
|
finishRefresh()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
binding.rbSamplingCooking.setOnClickListener {
|
binding.rbSamplingCooking.let {
|
||||||
// Log.d(TAG, "addViewListener: cooking:${binding.rbSamplingCooking.isChecked}")
|
it.setOnClickListener { _ ->
|
||||||
if (it.tag == true) {
|
if (it.isChecked) {
|
||||||
return@setOnClickListener
|
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}")
|
// Log.d(TAG, "addViewListener: finish:${binding.rbSamplingFinished.isChecked}")
|
||||||
if (it.tag == true) {
|
if (it.isChecked) {
|
||||||
return@setOnClickListener
|
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
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -292,13 +251,37 @@ class SamplingModeActivity : BaseActivity() {
|
|||||||
|
|
||||||
@SuppressLint("NotifyDataSetChanged")
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
fun getSamplingList() {
|
fun getSamplingList() {
|
||||||
netViewModel.getSamplingList(
|
netViewModel.getSamplingListWithCallback(
|
||||||
param = mutableMapOf(
|
param = mutableMapOf(
|
||||||
"pageNum" to pageNo,
|
"pageNum" to pageNo,
|
||||||
"pageSize" to pageSize,
|
"pageSize" to pageSize,
|
||||||
"placeId" to BaseApp.canteenId
|
"placeId" to BaseApp.canteenId
|
||||||
)
|
),
|
||||||
)
|
onLoading = { showLoading() }
|
||||||
|
) { state ->
|
||||||
|
when (state) {
|
||||||
|
is UiState.Success -> {
|
||||||
|
// 回调期间用户可能已切换 Tab,需再次校验
|
||||||
|
if (binding.rbSamplingFinished.isChecked.not()) {
|
||||||
|
delayDismissLoading()
|
||||||
|
return@getSamplingListWithCallback
|
||||||
|
}
|
||||||
|
loadDishList(state.data)
|
||||||
|
}
|
||||||
|
is UiState.Error -> {
|
||||||
|
if (binding.rbSamplingFinished.isChecked.not()) {
|
||||||
|
delayDismissLoading()
|
||||||
|
return@getSamplingListWithCallback
|
||||||
|
}
|
||||||
|
binding.refreshLayout.setEnableRefresh(true)
|
||||||
|
toast(state.msg)
|
||||||
|
finishRefresh()
|
||||||
|
delayDismissLoading()
|
||||||
|
if (pageNo == 1) loadEmptyView()
|
||||||
|
}
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun finishRefresh() {
|
private fun finishRefresh() {
|
||||||
@@ -336,18 +319,18 @@ class SamplingModeActivity : BaseActivity() {
|
|||||||
//dishAdapter.setStateViewLayout(requireContext(), R.layout-sw800dp.layout_empty_view)
|
//dishAdapter.setStateViewLayout(requireContext(), R.layout-sw800dp.layout_empty_view)
|
||||||
|
|
||||||
binding.refreshLayout.run {
|
binding.refreshLayout.run {
|
||||||
setEnableRefresh(binding.dishRadioGroup.checkedRadioButtonId == R.id.rbSamplingFinished)
|
setEnableRefresh(binding.rbSamplingFinished.isChecked)
|
||||||
setEnableLoadMore(false)
|
setEnableLoadMore(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun refreshPage(isCooking: Boolean) {
|
fun refreshPage(isCooking: Boolean) {
|
||||||
val checkedId = binding.dishRadioGroup.checkedRadioButtonId
|
if (binding.rbSamplingFinished.isChecked) {
|
||||||
if (checkedId == R.id.rbSamplingFinished) {
|
|
||||||
//当前是已采样
|
//当前是已采样
|
||||||
if (isCooking) {
|
if (isCooking) {
|
||||||
//需要切换到烹饪中
|
//需要切换到烹饪中
|
||||||
binding.dishRadioGroup.check(R.id.rbSamplingCooking)
|
binding.rbSamplingCooking.isChecked = true
|
||||||
|
binding.rbSamplingFinished.isChecked = false
|
||||||
requestData(true)
|
requestData(true)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -358,7 +341,8 @@ class SamplingModeActivity : BaseActivity() {
|
|||||||
//当前是烹饪中
|
//当前是烹饪中
|
||||||
if (isCooking.not()) {
|
if (isCooking.not()) {
|
||||||
//需要切换到已采样
|
//需要切换到已采样
|
||||||
binding.dishRadioGroup.check(R.id.rbSamplingFinished)
|
binding.rbSamplingCooking.isChecked = false
|
||||||
|
binding.rbSamplingFinished.isChecked = true
|
||||||
requestData(false)
|
requestData(false)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -366,21 +350,17 @@ class SamplingModeActivity : BaseActivity() {
|
|||||||
requestData(true)
|
requestData(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressLint("NotifyDataSetChanged")
|
|
||||||
fun refreshLocalData() {
|
fun refreshLocalData() {
|
||||||
showLoading()
|
showLoading()
|
||||||
appViewModel.resetCookFoodList()
|
|
||||||
getCookFoodList()
|
getCookFoodList()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun requestData(isCooking: Boolean) {
|
private fun requestData(isCooking: Boolean) {
|
||||||
|
list.clear()
|
||||||
|
dishAdapter.notifyDataSetChanged()
|
||||||
if (isCooking) {
|
if (isCooking) {
|
||||||
// 清除上次网络请求的残留状态
|
|
||||||
netViewModel.resetSamplingListState()
|
|
||||||
refreshLocalData()
|
refreshLocalData()
|
||||||
} else {
|
} else {
|
||||||
// 同理,清除本地数据残留状态
|
|
||||||
appViewModel.resetCookFoodList()
|
|
||||||
pageNo = 1
|
pageNo = 1
|
||||||
getSamplingList()
|
getSamplingList()
|
||||||
}
|
}
|
||||||
@@ -419,7 +399,7 @@ class SamplingModeActivity : BaseActivity() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
val slots = appViewModel.loadSeasoningSlot()
|
val slots = dbViewModel.loadSeasoningSlot()
|
||||||
if (slots.isEmpty()) {
|
if (slots.isEmpty()) {
|
||||||
showDeviceConfigDialog()
|
showDeviceConfigDialog()
|
||||||
return@launch
|
return@launch
|
||||||
|
|||||||
@@ -9,19 +9,23 @@ import android.os.Build
|
|||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.provider.Settings
|
import android.provider.Settings
|
||||||
import androidx.core.content.ContextCompat
|
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.base.BaseActivity
|
||||||
import com.shuwei.dish.match.databinding.ActivitySettingBinding
|
import com.shuwei.dish.match.databinding.ActivitySettingBinding
|
||||||
import com.shuwei.dish.match.dialog.CommonDialog
|
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.scale.ScaleServiceManager
|
||||||
import com.shuwei.dish.match.utils.SpTool
|
import com.shuwei.dish.match.utils.SpTool
|
||||||
import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
||||||
import com.shuwei.dish.match.utils.ext.startActivity
|
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 com.shuwei.dish.match.utils.ext.visible
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 设置Activity
|
* 设置页面
|
||||||
* 功能:管理多个设置相关的Fragment,支持Fragment切换
|
* 使用 RecyclerView 展示设置菜单项,点击逻辑内聚在各 SettingItem 的 onClick 中
|
||||||
*/
|
*/
|
||||||
class SettingActivity : BaseActivity() {
|
class SettingActivity : BaseActivity() {
|
||||||
|
|
||||||
@@ -30,10 +34,15 @@ class SettingActivity : BaseActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private lateinit var binding: ActivitySettingBinding
|
private lateinit var binding: ActivitySettingBinding
|
||||||
// private val cameraUtils: CameraUtils by lazy {
|
|
||||||
// CameraUtils(this)
|
/** 包含全部菜单项的完整列表(含隐藏项) */
|
||||||
// }
|
private val allItems: List<SettingItem> by lazy { buildAllItems() }
|
||||||
// private lateinit var previewView: PreviewView
|
|
||||||
|
private val adapter = SettingAdapter().apply {
|
||||||
|
setOnDebouncedItemClick { _, _, position ->
|
||||||
|
getItem(position)?.onClick()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
@@ -43,53 +52,113 @@ class SettingActivity : BaseActivity() {
|
|||||||
setTitleBar(titleBarAction = {
|
setTitleBar(titleBarAction = {
|
||||||
it.visible()
|
it.visible()
|
||||||
}, titleAction = {
|
}, titleAction = {
|
||||||
it.text = "设备设置"
|
it.text = "设置"
|
||||||
}, rightIconActon = {
|
}, rightIconAction = {
|
||||||
it.visible()
|
it.visible()
|
||||||
|
// 点击右上角图标,展示全部隐藏的开发者选项
|
||||||
it.clickWithDebounce {
|
it.clickWithDebounce {
|
||||||
binding.llDbInspect.visible()
|
adapter.submitList(allItems.toList())
|
||||||
binding.llScaleObserve.visible()
|
|
||||||
binding.llClearData.visible()
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
initView()
|
initView()
|
||||||
|
|
||||||
// // 默认显示设备配置Fragment
|
|
||||||
// if (savedInstanceState == null) {
|
|
||||||
// showDeviceConfigFragment()
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// initUI()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private fun initView() {
|
private fun initView() {
|
||||||
binding.tvCurrentMode.text = when (SpTool.cookMode) {
|
binding.rvSettings.layoutManager = LinearLayoutManager(this)
|
||||||
0 -> "当前:制作模式"
|
binding.rvSettings.adapter = adapter
|
||||||
1 -> "当前:采样模式"
|
// 默认只展示非隐藏项
|
||||||
else -> "当前:未知模式"
|
adapter.submitList(allItems.filter { !it.isHidden })
|
||||||
}
|
|
||||||
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.llDbInspect.clickWithDebounce {
|
|
||||||
SingleFragmentActivity.start(this, SingleFragmentActivity.PageType.DB_INSPECT)
|
|
||||||
}
|
|
||||||
binding.llScaleObserve.clickWithDebounce {
|
|
||||||
startActivity<MasterScaleActivity>()
|
|
||||||
}
|
|
||||||
binding.llClearData.clickWithDebounce {
|
|
||||||
showClearDataDialog()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建完整的设置菜单列表,每项的 onClick 直接注入对应业务逻辑
|
||||||
|
*/
|
||||||
|
private fun buildAllItems(): List<SettingItem> = listOf(
|
||||||
|
SettingItem(
|
||||||
|
type = SettingItem.Type.COOK_MODE,
|
||||||
|
subtitle = when (SpTool.cookMode) {
|
||||||
|
0 -> "当前:制作模式"
|
||||||
|
1 -> "当前:采样模式"
|
||||||
|
else -> "当前:未知模式"
|
||||||
|
},
|
||||||
|
onClick = {
|
||||||
|
SingleFragmentActivity.start(this, SingleFragmentActivity.PageType.COOK_MODE)
|
||||||
|
}
|
||||||
|
),
|
||||||
|
SettingItem(
|
||||||
|
type = SettingItem.Type.SEASONING_CONFIG,
|
||||||
|
onClick = {
|
||||||
|
SingleFragmentActivity.start(this, SingleFragmentActivity.PageType.SEASONING_CONFIG)
|
||||||
|
}
|
||||||
|
),
|
||||||
|
SettingItem(
|
||||||
|
type = SettingItem.Type.FOOD_COLLECT,
|
||||||
|
onClick = { checkCameraPermission() }
|
||||||
|
),
|
||||||
|
SettingItem(
|
||||||
|
type = SettingItem.Type.WEIGHT_CONFIG,
|
||||||
|
onClick = {
|
||||||
|
SingleFragmentActivity.start(this, SingleFragmentActivity.PageType.WEIGHT_CONFIG)
|
||||||
|
}
|
||||||
|
),
|
||||||
|
SettingItem(
|
||||||
|
type = SettingItem.Type.CLEAN_PACKAGE,
|
||||||
|
onClick = {
|
||||||
|
startActivity<CleanPackActivity> {
|
||||||
|
putExtra(CleanPackActivity.EXTRA_TYPE, CleanPackActivity.TYPE_CLEAN)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
),
|
||||||
|
SettingItem(
|
||||||
|
type = SettingItem.Type.MEAL_PACKAGE,
|
||||||
|
onClick = {
|
||||||
|
startActivity<MealListActivity> { }
|
||||||
|
}
|
||||||
|
),
|
||||||
|
SettingItem(
|
||||||
|
type = SettingItem.Type.GROUP_TASK,
|
||||||
|
onClick = {
|
||||||
|
startActivity<TaskActivity> { }
|
||||||
|
}
|
||||||
|
),
|
||||||
|
// SettingItem(
|
||||||
|
// type = SettingItem.Type.MEAL_PACKAGE_TEST,
|
||||||
|
// onClick = {
|
||||||
|
// startActivity<CleanPackActivity> {
|
||||||
|
// putExtra(CleanPackActivity.EXTRA_TYPE, CleanPackActivity.TYPE_MEAL)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// ),
|
||||||
|
SettingItem(
|
||||||
|
type = SettingItem.Type.DB_INSPECT,
|
||||||
|
isHidden = true,
|
||||||
|
onClick = {
|
||||||
|
SingleFragmentActivity.start(this, SingleFragmentActivity.PageType.DB_INSPECT)
|
||||||
|
}
|
||||||
|
),
|
||||||
|
SettingItem(
|
||||||
|
type = SettingItem.Type.SCALE_OBSERVE,
|
||||||
|
isHidden = true,
|
||||||
|
onClick = { startActivity<MasterScaleActivity>() }
|
||||||
|
),
|
||||||
|
SettingItem(
|
||||||
|
type = SettingItem.Type.ENV_SWITCH,
|
||||||
|
isHidden = true,
|
||||||
|
onClick = { EnvSwitchDialog(this).show() }
|
||||||
|
),
|
||||||
|
SettingItem(
|
||||||
|
type = SettingItem.Type.CLEAR_DATA,
|
||||||
|
isHidden = true,
|
||||||
|
onClick = { showClearDataDialog() }
|
||||||
|
),
|
||||||
|
SettingItem(
|
||||||
|
type = SettingItem.Type.TEST_SEASONING,
|
||||||
|
isHidden = true,
|
||||||
|
onClick = { startActivity<SubmitFoodActivity> { } }
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 弹出清除测试数据的二次确认弹窗
|
* 弹出清除测试数据的二次确认弹窗
|
||||||
*/
|
*/
|
||||||
@@ -99,14 +168,12 @@ class SettingActivity : BaseActivity() {
|
|||||||
.setContent("将物理删除全部 4 张表数据(菜品、食材、调料、槽位),此操作不可恢复,同时重置菜品模式和食堂id,确认继续?")
|
.setContent("将物理删除全部 4 张表数据(菜品、食材、调料、槽位),此操作不可恢复,同时重置菜品模式和食堂id,确认继续?")
|
||||||
.setNegativeButton("取消")
|
.setNegativeButton("取消")
|
||||||
.setPositiveButton("确认") {
|
.setPositiveButton("确认") {
|
||||||
appViewModel.clearAllData {
|
dbViewModel.clearAllData {
|
||||||
SpTool.cookMode = -1
|
SpTool.cookMode = -1
|
||||||
SpTool.canteenId = "0"
|
SpTool.canteenId = "0"
|
||||||
// 通知所有已连接子设备同步清除数据
|
// 通知所有已连接子设备同步清除数据
|
||||||
ScaleServiceManager.sendClearData()
|
ScaleServiceManager.sendClearData()
|
||||||
startActivity<HomeActivity> {
|
startActivity<InitActivity>()
|
||||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.show()
|
.show()
|
||||||
@@ -117,12 +184,11 @@ class SettingActivity : BaseActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 检查相机权限并显示 CollectFragment
|
* 检查相机权限,有权限则直接打开采集页,否则发起授权请求
|
||||||
*/
|
*/
|
||||||
@SuppressLint("ObsoleteSdkInt")
|
@SuppressLint("ObsoleteSdkInt")
|
||||||
private fun checkCameraPermission() {
|
private fun checkCameraPermission() {
|
||||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
|
||||||
// Android 6.0 以下,直接打开
|
|
||||||
openCollectPage()
|
openCollectPage()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -131,16 +197,12 @@ class SettingActivity : BaseActivity() {
|
|||||||
Manifest.permission.CAMERA
|
Manifest.permission.CAMERA
|
||||||
) == PackageManager.PERMISSION_GRANTED
|
) == PackageManager.PERMISSION_GRANTED
|
||||||
) {
|
) {
|
||||||
// 权限已授予,直接打开
|
|
||||||
openCollectPage()
|
openCollectPage()
|
||||||
} else {
|
} else {
|
||||||
// 权限未授予,申请权限
|
|
||||||
requestPermission(Manifest.permission.CAMERA) { isGranted ->
|
requestPermission(Manifest.permission.CAMERA) { isGranted ->
|
||||||
if (isGranted) {
|
if (isGranted) {
|
||||||
// 权限已授予,直接打开
|
|
||||||
openCollectPage()
|
openCollectPage()
|
||||||
} else {
|
} else {
|
||||||
// 权限被拒绝
|
|
||||||
showNotGrantedCameraPermissionDialog()
|
showNotGrantedCameraPermissionDialog()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -162,197 +224,4 @@ class SettingActivity : BaseActivity() {
|
|||||||
}
|
}
|
||||||
.show()
|
.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()
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import com.shuwei.dish.match.ui.fragment.DbInspectFragment
|
|||||||
import com.shuwei.dish.match.ui.fragment.VectorCollectionFragment
|
import com.shuwei.dish.match.ui.fragment.VectorCollectionFragment
|
||||||
import com.shuwei.dish.match.ui.fragment.DeviceConfigFragment
|
import com.shuwei.dish.match.ui.fragment.DeviceConfigFragment
|
||||||
import com.shuwei.dish.match.ui.fragment.SeasoningConfigFragment
|
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.gone
|
||||||
import com.shuwei.dish.match.utils.ext.visible
|
import com.shuwei.dish.match.utils.ext.visible
|
||||||
|
|
||||||
@@ -39,6 +40,9 @@ class SingleFragmentActivity : BaseActivity() {
|
|||||||
|
|
||||||
/** 数据库调试查看页 */
|
/** 数据库调试查看页 */
|
||||||
DB_INSPECT,
|
DB_INSPECT,
|
||||||
|
|
||||||
|
/** 默认减重配置页 */
|
||||||
|
WEIGHT_CONFIG,
|
||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
@@ -81,7 +85,7 @@ class SingleFragmentActivity : BaseActivity() {
|
|||||||
setTitleBar(
|
setTitleBar(
|
||||||
titleBarAction = { it.visible() },
|
titleBarAction = { it.visible() },
|
||||||
titleAction = { it.text = getTitleForPage(pageType) },
|
titleAction = { it.text = getTitleForPage(pageType) },
|
||||||
rightIconActon = { it.gone() }
|
rightIconAction = { it.gone() }
|
||||||
)
|
)
|
||||||
|
|
||||||
// 首次创建时加载 Fragment,避免屏幕旋转重复添加
|
// 首次创建时加载 Fragment,避免屏幕旋转重复添加
|
||||||
@@ -101,6 +105,7 @@ class SingleFragmentActivity : BaseActivity() {
|
|||||||
PageType.COOK_MODE -> "菜品模式"
|
PageType.COOK_MODE -> "菜品模式"
|
||||||
PageType.SEASONING_CONFIG -> "调料区设置"
|
PageType.SEASONING_CONFIG -> "调料区设置"
|
||||||
PageType.DB_INSPECT -> "数据库查看"
|
PageType.DB_INSPECT -> "数据库查看"
|
||||||
|
PageType.WEIGHT_CONFIG -> "减重配置"
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -111,6 +116,7 @@ class SingleFragmentActivity : BaseActivity() {
|
|||||||
PageType.COOK_MODE -> DeviceConfigFragment()
|
PageType.COOK_MODE -> DeviceConfigFragment()
|
||||||
PageType.SEASONING_CONFIG -> SeasoningConfigFragment()
|
PageType.SEASONING_CONFIG -> SeasoningConfigFragment()
|
||||||
PageType.DB_INSPECT -> DbInspectFragment()
|
PageType.DB_INSPECT -> DbInspectFragment()
|
||||||
|
PageType.WEIGHT_CONFIG -> WeightConfigFragment()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onResume() {
|
override fun onResume() {
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ import com.shuwei.dish.match.base.BaseActivity
|
|||||||
import com.shuwei.dish.match.base.GlobalData
|
import com.shuwei.dish.match.base.GlobalData
|
||||||
import com.shuwei.dish.match.databinding.ActivitySlaveBinding
|
import com.shuwei.dish.match.databinding.ActivitySlaveBinding
|
||||||
import com.shuwei.dish.match.dialog.CommonDialog
|
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.ScaleData
|
||||||
import com.shuwei.dish.match.scale.ScaleDeviceConfig
|
import com.shuwei.dish.match.scale.ScaleDeviceConfig
|
||||||
import com.shuwei.dish.match.scale.ScaleServiceManager
|
import com.shuwei.dish.match.scale.ScaleServiceManager
|
||||||
@@ -162,7 +162,7 @@ class SlaveActivity : BaseActivity() {
|
|||||||
*/
|
*/
|
||||||
private fun loadSlotsFromDb() {
|
private fun loadSlotsFromDb() {
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
val slots = appViewModel.getSeasoningSlotsByDeviceId(GlobalData.deviceId)
|
val slots = dbViewModel.getSeasoningSlotsByDeviceId(GlobalData.deviceId)
|
||||||
applySlots(slots)
|
applySlots(slots)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -179,8 +179,8 @@ class SlaveActivity : BaseActivity() {
|
|||||||
?: return@onSeasoningConfig
|
?: return@onSeasoningConfig
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
// 全量替换:先删除本机所有旧槽位,再写入最新配置
|
// 全量替换:先删除本机所有旧槽位,再写入最新配置
|
||||||
appViewModel.deleteAllSlotsByDeviceId(GlobalData.deviceId)
|
dbViewModel.deleteAllSlotsByDeviceId(GlobalData.deviceId)
|
||||||
appViewModel.upsertAllSeasoningSlots(mySlots)
|
dbViewModel.upsertAllSeasoningSlots(mySlots)
|
||||||
applySlots(mySlots)
|
applySlots(mySlots)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -194,7 +194,7 @@ class SlaveActivity : BaseActivity() {
|
|||||||
private fun listenClearData() {
|
private fun listenClearData() {
|
||||||
ScaleServiceManager.onClearData = {
|
ScaleServiceManager.onClearData = {
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
appViewModel.clearAllData {
|
dbViewModel.clearAllData {
|
||||||
SpTool.cookMode = -1
|
SpTool.cookMode = -1
|
||||||
SpTool.canteenId = "0"
|
SpTool.canteenId = "0"
|
||||||
runOnUiThread { applySlots(emptyList()) }
|
runOnUiThread { applySlots(emptyList()) }
|
||||||
|
|||||||
@@ -12,15 +12,17 @@ import androidx.lifecycle.Lifecycle
|
|||||||
import androidx.lifecycle.lifecycleScope
|
import androidx.lifecycle.lifecycleScope
|
||||||
import androidx.lifecycle.repeatOnLifecycle
|
import androidx.lifecycle.repeatOnLifecycle
|
||||||
import androidx.recyclerview.widget.GridLayoutManager
|
import androidx.recyclerview.widget.GridLayoutManager
|
||||||
|
import com.shuwei.dish.match.R
|
||||||
import com.shuwei.dish.match.adapter.SeasoningWeightAdapter
|
import com.shuwei.dish.match.adapter.SeasoningWeightAdapter
|
||||||
import com.shuwei.dish.match.base.BaseActivity
|
import com.shuwei.dish.match.base.BaseActivity
|
||||||
import com.shuwei.dish.match.base.BaseApp
|
import com.shuwei.dish.match.base.BaseApp
|
||||||
import com.shuwei.dish.match.databinding.ActivitySubmitFoodBinding
|
import com.shuwei.dish.match.databinding.ActivitySubmitFoodBinding
|
||||||
import com.shuwei.dish.match.dialog.CommonDialog
|
import com.shuwei.dish.match.dialog.CommonDialog
|
||||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
import com.shuwei.dish.match.dialog.GoodsPreviewDialog
|
||||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
import com.shuwei.dish.match.db.entity.CookFoodEntity
|
||||||
import com.shuwei.dish.match.entity.FoodRecord
|
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||||
import com.shuwei.dish.match.entity.toDTO
|
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.net.UiState
|
||||||
import com.shuwei.dish.match.scale.ScaleDeviceConfig
|
import com.shuwei.dish.match.scale.ScaleDeviceConfig
|
||||||
import com.shuwei.dish.match.scale.ScaleServiceManager
|
import com.shuwei.dish.match.scale.ScaleServiceManager
|
||||||
@@ -29,14 +31,12 @@ import com.shuwei.dish.match.utils.WeightUtil
|
|||||||
import com.shuwei.dish.match.utils.ext.appendText
|
import com.shuwei.dish.match.utils.ext.appendText
|
||||||
import com.shuwei.dish.match.utils.ext.buildSpannableString
|
import com.shuwei.dish.match.utils.ext.buildSpannableString
|
||||||
import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
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.roundedDecimalPlace
|
||||||
import com.shuwei.dish.match.utils.ext.roundedOneDecimalPlace
|
import com.shuwei.dish.match.utils.ext.roundedOneDecimalPlace
|
||||||
import com.shuwei.dish.match.utils.ext.startActivity
|
import com.shuwei.dish.match.utils.ext.startActivity
|
||||||
import com.shuwei.dish.match.utils.ext.toJsonString
|
import com.shuwei.dish.match.utils.ext.toJsonString
|
||||||
import com.shuwei.dish.match.utils.ext.toast
|
import com.shuwei.dish.match.utils.ext.toast
|
||||||
import com.shuwei.dish.match.utils.ext.visible
|
import com.shuwei.dish.match.utils.ext.visible
|
||||||
import kotlinx.coroutines.flow.collectLatest
|
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
@SuppressLint("UseSparseArrays")
|
@SuppressLint("UseSparseArrays")
|
||||||
@@ -49,6 +49,8 @@ class SubmitFoodActivity : BaseActivity() {
|
|||||||
|
|
||||||
/** 本地临时 foodId 前缀;以此开头说明菜品尚未在服务器登记,提交时需清空让服务器分配真实 ID */
|
/** 本地临时 foodId 前缀;以此开头说明菜品尚未在服务器登记,提交时需清空让服务器分配真实 ID */
|
||||||
const val LOCAL_ID_PREFIX = "localId_"
|
const val LOCAL_ID_PREFIX = "localId_"
|
||||||
|
|
||||||
|
const val WEIGHT_THRESHOLD = 0.01
|
||||||
}
|
}
|
||||||
|
|
||||||
private lateinit var binding: ActivitySubmitFoodBinding
|
private lateinit var binding: ActivitySubmitFoodBinding
|
||||||
@@ -100,6 +102,12 @@ class SubmitFoodActivity : BaseActivity() {
|
|||||||
*/
|
*/
|
||||||
private val lastTsMap = mutableMapOf<String, Long>()
|
private val lastTsMap = mutableMapOf<String, Long>()
|
||||||
|
|
||||||
|
/** 主设备 2格秤的初始重量,首次收到数据时赋值;调用清零后重置为 0.0 */
|
||||||
|
private var initWeight: Double = 0.0
|
||||||
|
|
||||||
|
/** initWeight 是否已完成初始化 */
|
||||||
|
// private var initWeightSet: Boolean = false
|
||||||
|
|
||||||
@Suppress("unchecked_cast", "DEPRECATION")
|
@Suppress("unchecked_cast", "DEPRECATION")
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
@@ -119,8 +127,15 @@ class SubmitFoodActivity : BaseActivity() {
|
|||||||
it.visible()
|
it.visible()
|
||||||
}, titleAction = {
|
}, titleAction = {
|
||||||
it.text = food?.foodName
|
it.text = food?.foodName
|
||||||
}, rightIconActon = {
|
}, rightIconAction = {
|
||||||
it.gone()
|
it.visible()
|
||||||
|
it.setImageResource(R.drawable.ic_list_view)
|
||||||
|
it.setOnClickListener {
|
||||||
|
lifecycleScope.launch {
|
||||||
|
val list = buildPreviewGoodsList()
|
||||||
|
GoodsPreviewDialog(this@SubmitFoodActivity, list).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
}, backAction = {
|
}, backAction = {
|
||||||
it.setOnClickListener {
|
it.setOnClickListener {
|
||||||
remindSaveDataDialog()
|
remindSaveDataDialog()
|
||||||
@@ -172,7 +187,7 @@ class SubmitFoodActivity : BaseActivity() {
|
|||||||
*/
|
*/
|
||||||
private fun loadSlotsThenObserveScales() {
|
private fun loadSlotsThenObserveScales() {
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
val slots = appViewModel.loadSeasoningSlot()
|
val slots = dbViewModel.loadSeasoningSlot()
|
||||||
slots.forEach { slot ->
|
slots.forEach { slot ->
|
||||||
slotMap["${slot.deviceId}#${slot.address}"] = slot.goodsId to slot.goodsName
|
slotMap["${slot.deviceId}#${slot.address}"] = slot.goodsId to slot.goodsName
|
||||||
}
|
}
|
||||||
@@ -181,7 +196,7 @@ class SubmitFoodActivity : BaseActivity() {
|
|||||||
val foodId = food?.foodId ?: return@launch
|
val foodId = food?.foodId ?: return@launch
|
||||||
val cookMode = food?.cookMode ?: return@launch
|
val cookMode = food?.cookMode ?: return@launch
|
||||||
val list =
|
val list =
|
||||||
appViewModel.getCookFoodGoodsList(foodId, cookMode, food?.dinnerType ?: "0")
|
dbViewModel.getCookFoodGoodsList(foodId, cookMode, food?.dinnerType ?: "0")
|
||||||
goodsList = list
|
goodsList = list
|
||||||
prefillSeasoningFromGoodsList(list)
|
prefillSeasoningFromGoodsList(list)
|
||||||
} else {
|
} else {
|
||||||
@@ -218,7 +233,7 @@ class SubmitFoodActivity : BaseActivity() {
|
|||||||
private fun observeScaleData() {
|
private fun observeScaleData() {
|
||||||
val flow = ScaleServiceManager.allScales ?: return
|
val flow = ScaleServiceManager.allScales ?: return
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
flow.collectLatest { scaleMap ->
|
flow.collect { scaleMap ->
|
||||||
//Log.d(TAG, "observeScaleData,scaleMap=${scaleMap.toJsonString()}")
|
//Log.d(TAG, "observeScaleData,scaleMap=${scaleMap.toJsonString()}")
|
||||||
scaleMap.forEach { (key, data) ->
|
scaleMap.forEach { (key, data) ->
|
||||||
// ts 未变化说明是其他秤更新触发的 StateFlow 重发,跳过
|
// ts 未变化说明是其他秤更新触发的 StateFlow 重发,跳过
|
||||||
@@ -247,7 +262,7 @@ class SubmitFoodActivity : BaseActivity() {
|
|||||||
.coerceAtLeast(0.0)
|
.coerceAtLeast(0.0)
|
||||||
.roundedOneDecimalPlace()
|
.roundedOneDecimalPlace()
|
||||||
|
|
||||||
if (useWeight < 0.5) {
|
if (useWeight < WEIGHT_THRESHOLD) {
|
||||||
// 放回场景:必须稳定后才移除,避免拿取过程中误删
|
// 放回场景:必须稳定后才移除,避免拿取过程中误删
|
||||||
if (data.state != WeightUtil.STATE_STABLE) return@forEach
|
if (data.state != WeightUtil.STATE_STABLE) return@forEach
|
||||||
if (rawWeightMap.remove(key) != null) {
|
if (rawWeightMap.remove(key) != null) {
|
||||||
@@ -279,8 +294,8 @@ class SubmitFoodActivity : BaseActivity() {
|
|||||||
val (baseGoodsId, baseWeight) = baseSeasoningMap[goodsName] ?: ("" to 0.0)
|
val (baseGoodsId, baseWeight) = baseSeasoningMap[goodsName] ?: ("" to 0.0)
|
||||||
val totalWeight = (newWeight + baseWeight).roundedOneDecimalPlace()
|
val totalWeight = (newWeight + baseWeight).roundedOneDecimalPlace()
|
||||||
Log.d(TAG, "refreshAdapterByName, goodsName=$goodsName, newWeight=$newWeight, baseWeight=$baseWeight, totalWeight=$totalWeight, isCooking=${food?.isCooking}")
|
Log.d(TAG, "refreshAdapterByName, goodsName=$goodsName, newWeight=$newWeight, baseWeight=$baseWeight, totalWeight=$totalWeight, isCooking=${food?.isCooking}")
|
||||||
if (totalWeight < 0.5) {
|
if (totalWeight < WEIGHT_THRESHOLD) {
|
||||||
Log.d(TAG, "refreshAdapterByName,重量小于0.5g, isCooking=${food?.isCooking}, goodsName=$goodsName, totalWeight=$totalWeight")
|
Log.d(TAG, "refreshAdapterByName,重量小于${WEIGHT_THRESHOLD}g, isCooking=${food?.isCooking}, goodsName=$goodsName, totalWeight=$totalWeight")
|
||||||
// 仅保护 baseSeasoningMap 中的历史调料;本次会话新加的调料可以移除
|
// 仅保护 baseSeasoningMap 中的历史调料;本次会话新加的调料可以移除
|
||||||
if (!baseSeasoningMap.containsKey(goodsName)) {
|
if (!baseSeasoningMap.containsKey(goodsName)) {
|
||||||
// 只有 item 确实存在时才调用 remove,避免无效遍历
|
// 只有 item 确实存在时才调用 remove,避免无效遍历
|
||||||
@@ -303,18 +318,25 @@ class SubmitFoodActivity : BaseActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun addViewListener() {
|
private fun addViewListener() {
|
||||||
// 切换调料列表布局:4 列卡片 ↔ 2 列水平
|
// 切换调料列表布局:4 列卡片 ↔ 2 列水平,图标始终显示"目标布局"样式
|
||||||
binding.ivSeasoningLayoutToggle.setOnClickListener {
|
binding.ivSeasoningLayoutToggle.clickWithDebounce {
|
||||||
seasoningAdapter.isListMode = !seasoningAdapter.isListMode
|
seasoningAdapter.isListMode = !seasoningAdapter.isListMode
|
||||||
val spanCount = if (seasoningAdapter.isListMode) 2 else 4
|
val spanCount = if (seasoningAdapter.isListMode) 2 else 4
|
||||||
(binding.rvSeasoning.layoutManager as? GridLayoutManager)?.spanCount = spanCount
|
(binding.rvSeasoning.layoutManager as? GridLayoutManager)?.spanCount = spanCount
|
||||||
seasoningAdapter.notifyDataSetChanged()
|
seasoningAdapter.notifyDataSetChanged()
|
||||||
|
binding.ivSeasoningLayoutToggle.setImageResource(
|
||||||
|
if (seasoningAdapter.isListMode) R.drawable.ic_layout_grid else R.drawable.ic_layout_list
|
||||||
|
)
|
||||||
}
|
}
|
||||||
binding.btnCook.clickWithDebounce {
|
binding.btnCook.clickWithDebounce {
|
||||||
val content = getRemindSpannable("开始制作")
|
val content = getRemindSpannable("开始制作")
|
||||||
showRemindDialog(content) { cook() }
|
showRemindDialog(content) { cook() }
|
||||||
}
|
}
|
||||||
binding.btnWeightClear.clickWithDebounce { WeightUtil.tareTwo(2) }
|
binding.btnWeightClear.clickWithDebounce {
|
||||||
|
WeightUtil.tareTwo(2)
|
||||||
|
// 清零后将初始重量重置为 0,后续以秤读数直接作为净重
|
||||||
|
initWeight = 0.0
|
||||||
|
}
|
||||||
binding.btnSubmit.clickWithDebounce {
|
binding.btnSubmit.clickWithDebounce {
|
||||||
if (cookFoodEntity.foodWeight <= 0.toDouble()) {
|
if (cookFoodEntity.foodWeight <= 0.toDouble()) {
|
||||||
toast("未识别到菜品熟重")
|
toast("未识别到菜品熟重")
|
||||||
@@ -327,12 +349,19 @@ class SubmitFoodActivity : BaseActivity() {
|
|||||||
// 监听主设备 2格秤的熟重
|
// 监听主设备 2格秤的熟重
|
||||||
WeightUtil.addWeightListener(TAG) { address, _, weight ->
|
WeightUtil.addWeightListener(TAG) { address, _, weight ->
|
||||||
if (address == AddressUtil.TWO) {
|
if (address == AddressUtil.TWO) {
|
||||||
cookFoodEntity.foodWeight = weight
|
// 首次收到数据时记录初始重量
|
||||||
if (weight > 1000) {
|
// if (!initWeightSet) {
|
||||||
binding.tvTotalWeight.text = "${(weight / 1000f).roundedDecimalPlace(3)}"
|
// initWeight = weight
|
||||||
|
// initWeightSet = true
|
||||||
|
// }
|
||||||
|
// 实际净重 = 秤读数 - 初始重量
|
||||||
|
val netWeight = weight - initWeight
|
||||||
|
cookFoodEntity.foodWeight = netWeight
|
||||||
|
if (netWeight > 1000) {
|
||||||
|
binding.tvTotalWeight.text = "${(netWeight / 1000f).roundedDecimalPlace(3)}"
|
||||||
binding.tvWeightUnit.text = "千克"
|
binding.tvWeightUnit.text = "千克"
|
||||||
} else {
|
} else {
|
||||||
binding.tvTotalWeight.text = "$weight"
|
binding.tvTotalWeight.text = "$netWeight"
|
||||||
binding.tvWeightUnit.text = "克"
|
binding.tvWeightUnit.text = "克"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -369,7 +398,7 @@ class SubmitFoodActivity : BaseActivity() {
|
|||||||
seasoningAdapter.items
|
seasoningAdapter.items
|
||||||
.filter { it.useWeight > 0.0 }
|
.filter { it.useWeight > 0.0 }
|
||||||
.forEach { goodsList?.add(buildSeasoningEntity(it)) }
|
.forEach { goodsList?.add(buildSeasoningEntity(it)) }
|
||||||
appViewModel.saveCookFoodAndGoods(
|
dbViewModel.saveCookFoodAndGoods(
|
||||||
cookMode = food!!.cookMode,
|
cookMode = food!!.cookMode,
|
||||||
entity = cookFoodEntity,
|
entity = cookFoodEntity,
|
||||||
list = goodsList
|
list = goodsList
|
||||||
@@ -422,7 +451,7 @@ class SubmitFoodActivity : BaseActivity() {
|
|||||||
* 从本地 dm_seasoning 表补充完整字段(popularName、zjmCode、materId、goodsCode 等)
|
* 从本地 dm_seasoning 表补充完整字段(popularName、zjmCode、materId、goodsCode 等)
|
||||||
*/
|
*/
|
||||||
private suspend fun buildSeasoningEntity(item: SeasoningWeightAdapter.Item): CookFoodGoodsEntity {
|
private suspend fun buildSeasoningEntity(item: SeasoningWeightAdapter.Item): CookFoodGoodsEntity {
|
||||||
val seasoning = appViewModel.getSeasoningByGoodsId(item.goodsId)
|
val seasoning = dbViewModel.getSeasoningByGoodsId(item.goodsId)
|
||||||
return CookFoodGoodsEntity().also { entity ->
|
return CookFoodGoodsEntity().also { entity ->
|
||||||
entity.foodId = cookFoodEntity.foodId
|
entity.foodId = cookFoodEntity.foodId
|
||||||
entity.goodsId = item.goodsId
|
entity.goodsId = item.goodsId
|
||||||
@@ -445,15 +474,15 @@ class SubmitFoodActivity : BaseActivity() {
|
|||||||
jumpPage(isSamplingData, false)
|
jumpPage(isSamplingData, false)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
lifecycleScope.launch {
|
// 用 viewModelScope 执行删除,不受当前 Activity 生命周期影响
|
||||||
appViewModel.markSubmittedAndDelete(
|
// singleTask 跳转会销毁本 Activity 并取消 lifecycleScope,导致删除被中断
|
||||||
cookMode = food!!.cookMode,
|
dbViewModel.markSubmittedAndDeleteAsync(
|
||||||
foodId = food!!.foodId!!,
|
cookMode = food!!.cookMode,
|
||||||
dinnerType = food!!.dinnerType
|
foodId = food!!.foodId!!,
|
||||||
)
|
dinnerType = food!!.dinnerType
|
||||||
dismissLoading()
|
)
|
||||||
jumpPage(isSamplingData, false)
|
dismissLoading()
|
||||||
}
|
jumpPage(isSamplingData, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun jumpPage(isSampling: Boolean, isCooking: Boolean) {
|
private fun jumpPage(isSampling: Boolean, isCooking: Boolean) {
|
||||||
@@ -470,6 +499,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() {
|
override fun onDestroy() {
|
||||||
WeightUtil.removeWeightListener(TAG)
|
WeightUtil.removeWeightListener(TAG)
|
||||||
super.onDestroy()
|
super.onDestroy()
|
||||||
|
|||||||
@@ -0,0 +1,212 @@
|
|||||||
|
package com.shuwei.dish.match.ui
|
||||||
|
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Bundle
|
||||||
|
import androidx.recyclerview.widget.LinearLayoutManager
|
||||||
|
import com.shuwei.dish.match.adapter.TaskAdapter
|
||||||
|
import com.shuwei.dish.match.base.BaseActivity
|
||||||
|
import com.shuwei.dish.match.base.GlobalData
|
||||||
|
import com.shuwei.dish.match.databinding.ActivityTaskBinding
|
||||||
|
import com.shuwei.dish.match.model.NutComboTaskVO
|
||||||
|
import com.shuwei.dish.match.net.NetViewModelV2
|
||||||
|
import com.shuwei.dish.match.net.UiState
|
||||||
|
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
||||||
|
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.toast
|
||||||
|
import com.shuwei.dish.match.utils.ext.visible
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 组配任务列表页面
|
||||||
|
*/
|
||||||
|
class TaskActivity : BaseActivity() {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val TAG = "TaskActivity"
|
||||||
|
const val TASK_ITEM = "taskItem"
|
||||||
|
}
|
||||||
|
|
||||||
|
private val binding by lazy { ActivityTaskBinding.inflate(layoutInflater) }
|
||||||
|
private val viewModelV2 by lazy { NetViewModelV2() }
|
||||||
|
|
||||||
|
private val taskList = mutableListOf<NutComboTaskVO>()
|
||||||
|
private val taskAdapter by lazy {
|
||||||
|
TaskAdapter(taskList).apply {
|
||||||
|
setOnItemClickListener { adapter, view, position ->
|
||||||
|
startActivity<TaskDetailActivity> {
|
||||||
|
putExtra(TaskDetailActivity.TASK_ITEM, taskList[position])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var currentPage = 1
|
||||||
|
private var keyword: String? = null
|
||||||
|
private var isLoading = false
|
||||||
|
private var hasMore = true
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
setContentView(binding.root)
|
||||||
|
setHeaderBackground()
|
||||||
|
setTitleBar(titleBarAction = {
|
||||||
|
it.visible()
|
||||||
|
}, titleAction = {
|
||||||
|
it.text = "组配任务"
|
||||||
|
}, rightIconAction = {
|
||||||
|
it.gone()
|
||||||
|
}, backAction = {
|
||||||
|
it.setOnClickListener {
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
initRecyclerView()
|
||||||
|
initRefreshLayout()
|
||||||
|
initSearchListener()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onResume() {
|
||||||
|
super.onResume()
|
||||||
|
currentPage = 1
|
||||||
|
loadTaskList()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化 RecyclerView
|
||||||
|
*/
|
||||||
|
private fun initRecyclerView() {
|
||||||
|
binding.rvTaskList.layoutManager = LinearLayoutManager(this)
|
||||||
|
binding.rvTaskList.adapter = taskAdapter
|
||||||
|
taskAdapter.setOnItemClickListener { _, _, position ->
|
||||||
|
val item = taskList.getOrNull(position) ?: return@setOnItemClickListener
|
||||||
|
val intent = Intent(this, TaskDetailActivity::class.java).apply {
|
||||||
|
putExtra(TASK_ITEM, item)
|
||||||
|
}
|
||||||
|
startActivity(intent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化 SmartRefreshLayout 下拉刷新和上拉加载
|
||||||
|
*/
|
||||||
|
private fun initRefreshLayout() {
|
||||||
|
binding.refreshLayout.apply {
|
||||||
|
// 下拉刷新
|
||||||
|
setOnRefreshListener {
|
||||||
|
currentPage = 1
|
||||||
|
hasMore = true
|
||||||
|
loadTaskList()
|
||||||
|
}
|
||||||
|
// 上拉加载
|
||||||
|
setOnLoadMoreListener { refreshLayout ->
|
||||||
|
if (isLoading || !hasMore) {
|
||||||
|
refreshLayout.finishLoadMoreWithNoMoreData()
|
||||||
|
return@setOnLoadMoreListener
|
||||||
|
}
|
||||||
|
currentPage++
|
||||||
|
loadTaskList()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 搜索栏交互
|
||||||
|
*/
|
||||||
|
private fun initSearchListener() {
|
||||||
|
binding.ivSearch.clickWithDebounce {
|
||||||
|
performSearch()
|
||||||
|
}
|
||||||
|
binding.etInputKeyword.addOnActionSearchListener {
|
||||||
|
performSearch()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 执行搜索
|
||||||
|
*/
|
||||||
|
private fun performSearch() {
|
||||||
|
keyword = binding.etInputKeyword.text.toString().trim()
|
||||||
|
if (keyword.isNullOrBlank()) {
|
||||||
|
toast("请输入搜索关键字")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
currentPage = 1
|
||||||
|
hasMore = true
|
||||||
|
taskList.clear()
|
||||||
|
taskAdapter.notifyDataSetChanged()
|
||||||
|
binding.rvTaskList.visible()
|
||||||
|
binding.tvEmpty.gone()
|
||||||
|
loadTaskList()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 加载组配任务列表
|
||||||
|
*/
|
||||||
|
private fun loadTaskList() {
|
||||||
|
isLoading = true
|
||||||
|
viewModelV2.getIncompleteComboTasksWithCallback(
|
||||||
|
deviceCode = GlobalData.deviceId,
|
||||||
|
keyword = keyword,
|
||||||
|
pageNum = currentPage,
|
||||||
|
pageSize = 10,
|
||||||
|
onLoading = {
|
||||||
|
if (currentPage == 1) {
|
||||||
|
showLoading("加载中……")
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onResult = onResult@{ state ->
|
||||||
|
dismissLoading()
|
||||||
|
isLoading = false
|
||||||
|
when (state) {
|
||||||
|
is UiState.Success -> {
|
||||||
|
val records = state.data?.records
|
||||||
|
if (currentPage == 1 && records.isNullOrEmpty()) {
|
||||||
|
binding.rvTaskList.gone()
|
||||||
|
binding.tvEmpty.visible()
|
||||||
|
binding.refreshLayout.finishRefresh()
|
||||||
|
binding.refreshLayout.finishLoadMoreWithNoMoreData()
|
||||||
|
return@onResult
|
||||||
|
}
|
||||||
|
if (!records.isNullOrEmpty()) {
|
||||||
|
binding.rvTaskList.visible()
|
||||||
|
binding.tvEmpty.gone()
|
||||||
|
if (currentPage == 1) {
|
||||||
|
taskList.clear()
|
||||||
|
}
|
||||||
|
taskList.addAll(records)
|
||||||
|
taskAdapter.notifyDataSetChanged()
|
||||||
|
|
||||||
|
// 判断是否还有更多数据
|
||||||
|
if (records.size < 10) {
|
||||||
|
hasMore = false
|
||||||
|
binding.refreshLayout.finishLoadMoreWithNoMoreData()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
hasMore = false
|
||||||
|
binding.refreshLayout.finishLoadMoreWithNoMoreData()
|
||||||
|
}
|
||||||
|
binding.refreshLayout.finishRefresh()
|
||||||
|
binding.refreshLayout.finishLoadMore()
|
||||||
|
}
|
||||||
|
|
||||||
|
is UiState.Error -> {
|
||||||
|
toast(state.msg)
|
||||||
|
if (currentPage > 1) {
|
||||||
|
currentPage--
|
||||||
|
}
|
||||||
|
if (currentPage == 1 && taskList.isEmpty()) {
|
||||||
|
binding.rvTaskList.gone()
|
||||||
|
binding.tvEmpty.visible()
|
||||||
|
}
|
||||||
|
binding.refreshLayout.finishRefresh()
|
||||||
|
binding.refreshLayout.finishLoadMore(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,319 @@
|
|||||||
|
package com.shuwei.dish.match.ui
|
||||||
|
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.util.Log
|
||||||
|
import androidx.core.content.IntentCompat
|
||||||
|
import androidx.lifecycle.lifecycleScope
|
||||||
|
import androidx.recyclerview.widget.LinearLayoutManager
|
||||||
|
import com.shuwei.dish.match.R
|
||||||
|
import com.shuwei.dish.match.adapter.TaskDetailAdapter
|
||||||
|
import com.shuwei.dish.match.base.BaseActivity
|
||||||
|
import com.shuwei.dish.match.base.GlobalData
|
||||||
|
import com.shuwei.dish.match.databinding.ActivityTaskDetailBinding
|
||||||
|
import com.shuwei.dish.match.dialog.CommonDialog
|
||||||
|
import com.shuwei.dish.match.dialog.InboundIngredientSearchDialog
|
||||||
|
import com.shuwei.dish.match.model.NutComboTaskDetailVO
|
||||||
|
import com.shuwei.dish.match.model.NutComboTaskItemDetail
|
||||||
|
import com.shuwei.dish.match.model.NutComboTaskVO
|
||||||
|
import com.shuwei.dish.match.net.NetViewModelV2
|
||||||
|
import com.shuwei.dish.match.net.UiState
|
||||||
|
import com.shuwei.dish.match.utils.AddressUtil
|
||||||
|
import com.shuwei.dish.match.utils.SpTool
|
||||||
|
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.roundedOneDecimalPlace
|
||||||
|
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.launch
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 组配任务详情页面
|
||||||
|
*/
|
||||||
|
class TaskDetailActivity : BaseActivity() {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val TAG = "TaskDetailActivity"
|
||||||
|
const val TASK_ITEM = "taskItem"
|
||||||
|
}
|
||||||
|
|
||||||
|
private var taskDetailVO: NutComboTaskDetailVO? = null
|
||||||
|
private val binding by lazy { ActivityTaskDetailBinding.inflate(layoutInflater) }
|
||||||
|
private val viewModelV2 by lazy { NetViewModelV2() }
|
||||||
|
|
||||||
|
private var taskItem: NutComboTaskVO? = null
|
||||||
|
private var clickIndex = -1
|
||||||
|
private val comboTaskList = mutableListOf<NutComboTaskItemDetail>()
|
||||||
|
private val itemAdapter by lazy {
|
||||||
|
TaskDetailAdapter(comboTaskList).apply {
|
||||||
|
setOnItemClickListener { adapter, view, position ->
|
||||||
|
clickItem(this, position)
|
||||||
|
}
|
||||||
|
addOnItemChildClickListener(R.id.ivClearIcon) { _, _, position ->
|
||||||
|
val item = getItem(position) ?: return@addOnItemChildClickListener
|
||||||
|
Log.d(PrepareFoodActivity.Companion.TAG, "onFoodItemClick: ${item.toJsonString()}")
|
||||||
|
// 无重量信息时转为 item 整体点击(触发选中效果)
|
||||||
|
if (item.actualQty.isNullOrBlank()) {
|
||||||
|
clickItem(this, position)
|
||||||
|
return@addOnItemChildClickListener
|
||||||
|
}
|
||||||
|
deleteRemindDialog("清除确认", "确定清除食材「${item.ingredientName}」添加的溯源码和重量吗?") {
|
||||||
|
item.run {
|
||||||
|
actualQty = null
|
||||||
|
traceCode = null
|
||||||
|
isSetFinished = false
|
||||||
|
}
|
||||||
|
notifyItemChanged(position)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除提醒
|
||||||
|
*/
|
||||||
|
private fun deleteRemindDialog(title: String, content: String, action: () -> Unit) {
|
||||||
|
CommonDialog(this)
|
||||||
|
.setTitle(title)
|
||||||
|
.setContent(content)
|
||||||
|
.setNegativeButton("取消")
|
||||||
|
.setPositiveButton("确认") {
|
||||||
|
action()
|
||||||
|
}.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun clickItem(adapter: TaskDetailAdapter, position: Int) {
|
||||||
|
adapter.getItem(position) ?: return
|
||||||
|
comboTaskList.forEachIndexed { index, detail ->
|
||||||
|
detail.isClicked = index == position
|
||||||
|
}
|
||||||
|
adapter.notifyDataSetChanged()
|
||||||
|
this@TaskDetailActivity.clickIndex = position
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
setContentView(binding.root)
|
||||||
|
setHeaderBackground()
|
||||||
|
|
||||||
|
taskItem = IntentCompat.getParcelableExtra(intent, TASK_ITEM, NutComboTaskVO::class.java)
|
||||||
|
|
||||||
|
setTitleBar(titleBarAction = {
|
||||||
|
it.visible()
|
||||||
|
}, titleAction = {
|
||||||
|
it.text = "任务详情"
|
||||||
|
}, rightIconAction = {
|
||||||
|
it.gone()
|
||||||
|
}, backAction = {
|
||||||
|
it.setOnClickListener {
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
initRecyclerView()
|
||||||
|
addWeightListener()
|
||||||
|
initView()
|
||||||
|
loadDetail()
|
||||||
|
|
||||||
|
lifecycleScope.launch {
|
||||||
|
viewModelV2.startComboTaskState.collect { state ->
|
||||||
|
when (state) {
|
||||||
|
is UiState.Success -> {
|
||||||
|
dismissLoading()
|
||||||
|
toast("已开始组配")
|
||||||
|
// 刷新详情
|
||||||
|
loadDetail()
|
||||||
|
// 更新本地状态
|
||||||
|
taskItem?.comboStatus = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
is UiState.Error -> {
|
||||||
|
dismissLoading()
|
||||||
|
toast(state.msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化任务概要信息
|
||||||
|
*/
|
||||||
|
private fun initView() {
|
||||||
|
taskItem?.let {
|
||||||
|
binding.tvTaskNo.text = "任务编号:${it.taskNo}"
|
||||||
|
binding.tvTargetDish.text = it.targetDish
|
||||||
|
binding.tvSpec.text = it.spec
|
||||||
|
binding.tvPlanDate.text = "计划日期:${it.planDate}"
|
||||||
|
binding.tvPortions.text = "总份数:${it.portions}"
|
||||||
|
binding.tvOwnerName.text = "负责人:${it.ownerName}"
|
||||||
|
binding.tvStatus.text = getStatusText(it.comboStatus)
|
||||||
|
|
||||||
|
// 仅待组配状态显示"开始组配"按钮
|
||||||
|
// if (it.comboStatus == 0) {
|
||||||
|
// binding.btnStart.visible()
|
||||||
|
binding.btnStart.clickWithDebounce {
|
||||||
|
//val taskId = it.id ?: return@clickWithDebounce
|
||||||
|
startComboTask()
|
||||||
|
}
|
||||||
|
// } else {
|
||||||
|
// binding.btnStart.gone()
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
binding.btnGetTraceCode.clickWithDebounce {
|
||||||
|
val item = itemAdapter.getItem(clickIndex) ?: return@clickWithDebounce
|
||||||
|
InboundIngredientSearchDialog(
|
||||||
|
activity = this,
|
||||||
|
viewModelV2 = viewModelV2,
|
||||||
|
defIngredientName = item.ingredientName
|
||||||
|
) { vo ->
|
||||||
|
itemAdapter.getItem(clickIndex)?.let {
|
||||||
|
it.traceCode = vo.traceCode
|
||||||
|
itemAdapter.notifyItemChanged(clickIndex)
|
||||||
|
}
|
||||||
|
}.show()
|
||||||
|
}
|
||||||
|
binding.ivAddWeight.clickWithDebounce {
|
||||||
|
if (currentWeight <= 0.0) {
|
||||||
|
toast("当前秤重量无效")
|
||||||
|
return@clickWithDebounce
|
||||||
|
}
|
||||||
|
itemAdapter.getItem(clickIndex)?.let {
|
||||||
|
it.actualQty = currentWeight.toString()
|
||||||
|
it.isSetFinished = true
|
||||||
|
itemAdapter.notifyItemChanged(clickIndex)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
binding.ivClearWeight.clickWithDebounce {
|
||||||
|
initialWeight = 0.0
|
||||||
|
SpTool.configWeight = 0
|
||||||
|
WeightUtil.tareTwo(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var currentWeight: Double = 0.0
|
||||||
|
|
||||||
|
/** 初始秤读数,净重 = 秤读数 - initialWeight,从 SpTool.configWeight 读取 */
|
||||||
|
private var initialWeight = SpTool.configWeight.toDouble()
|
||||||
|
|
||||||
|
private fun addWeightListener() {
|
||||||
|
WeightUtil.addWeightListener(
|
||||||
|
weightKey = TAG,
|
||||||
|
getWeight = { address, state, weight ->
|
||||||
|
if (address == AddressUtil.ONE && state == WeightUtil.STATE_STABLE) {
|
||||||
|
runOnUiThread {
|
||||||
|
currentWeight = weight - initialWeight
|
||||||
|
binding.tvShowWeight.run {
|
||||||
|
if (tag != currentWeight) {
|
||||||
|
// text = "称重:${netWeight}g"
|
||||||
|
val weightText = "${currentWeight.roundedOneDecimalPlace()}g"
|
||||||
|
text = weightText
|
||||||
|
tag = currentWeight
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//recognizeFood(netWeight)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化 RecyclerView
|
||||||
|
*/
|
||||||
|
private fun initRecyclerView() {
|
||||||
|
binding.rvItemList.layoutManager = LinearLayoutManager(this)
|
||||||
|
binding.rvItemList.adapter = itemAdapter
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 加载任务详情(食材清单)
|
||||||
|
*/
|
||||||
|
private fun loadDetail() {
|
||||||
|
val taskId = taskItem?.id ?: return
|
||||||
|
viewModelV2.getComboTaskDetailWithCallback(
|
||||||
|
id = taskId,
|
||||||
|
onLoading = {
|
||||||
|
showLoading("加载中……")
|
||||||
|
},
|
||||||
|
onResult = onResult@{ state ->
|
||||||
|
dismissLoading()
|
||||||
|
when (state) {
|
||||||
|
is UiState.Success -> {
|
||||||
|
taskDetailVO = state.data
|
||||||
|
if (taskDetailVO == null) {
|
||||||
|
toast("详情为空")
|
||||||
|
return@onResult
|
||||||
|
}
|
||||||
|
// 更新状态(可能已被其他设备修改)
|
||||||
|
binding.tvStatus.text = getStatusText(taskDetailVO!!.comboStatus)
|
||||||
|
if (taskDetailVO!!.comboStatus != 0) {
|
||||||
|
binding.btnStart.gone()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 加载食材列表
|
||||||
|
val items = taskDetailVO!!.items
|
||||||
|
if (!items.isNullOrEmpty()) {
|
||||||
|
comboTaskList.clear()
|
||||||
|
comboTaskList.addAll(items)
|
||||||
|
itemAdapter.notifyDataSetChanged()
|
||||||
|
} else {
|
||||||
|
toast("该任务无食材信息")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
is UiState.Error -> toast(state.msg)
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 开始组配
|
||||||
|
*/
|
||||||
|
private fun startComboTask() {
|
||||||
|
val task = taskDetailVO ?: return
|
||||||
|
val count = comboTaskList.count { it.traceCode.isNullOrBlank() }
|
||||||
|
if (count > 0) {
|
||||||
|
toast("存在未设置的溯源码")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
task.deviceCode = GlobalData.deviceId
|
||||||
|
task.portions = 1
|
||||||
|
showLoading("正在开始组配……")
|
||||||
|
lifecycleScope.launch {
|
||||||
|
//viewModelV2.startComboTask(taskId)
|
||||||
|
task.items = comboTaskList
|
||||||
|
viewModelV2.addComboTask(param = task) { state, msg ->
|
||||||
|
dismissLoading()
|
||||||
|
if (state.not()) {
|
||||||
|
toast(msg)
|
||||||
|
return@addComboTask
|
||||||
|
}
|
||||||
|
toast("组配成功")
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 状态文本映射
|
||||||
|
*/
|
||||||
|
private fun getStatusText(status: Int?): String {
|
||||||
|
return when (status) {
|
||||||
|
0 -> "待组配"
|
||||||
|
1 -> "组配中"
|
||||||
|
2 -> "已完成"
|
||||||
|
else -> "未知"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
super.onDestroy()
|
||||||
|
WeightUtil.removeWeightListener(TAG)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -2,9 +2,13 @@ package com.shuwei.dish.match.ui.fragment
|
|||||||
|
|
||||||
import android.graphics.Color
|
import android.graphics.Color
|
||||||
import android.graphics.Typeface
|
import android.graphics.Typeface
|
||||||
|
import android.text.InputType
|
||||||
|
import android.view.Gravity
|
||||||
import android.view.LayoutInflater
|
import android.view.LayoutInflater
|
||||||
import android.view.View
|
import android.view.View
|
||||||
import android.view.ViewGroup
|
import android.view.ViewGroup
|
||||||
|
import android.widget.EditText
|
||||||
|
import android.widget.LinearLayout
|
||||||
import android.widget.RadioButton
|
import android.widget.RadioButton
|
||||||
import android.widget.TextView
|
import android.widget.TextView
|
||||||
import androidx.cardview.widget.CardView
|
import androidx.cardview.widget.CardView
|
||||||
@@ -20,12 +24,11 @@ import com.shuwei.dish.match.ui.SingleFragmentActivity
|
|||||||
import com.shuwei.dish.match.utils.ext.gone
|
import com.shuwei.dish.match.utils.ext.gone
|
||||||
import com.shuwei.dish.match.utils.ext.visible
|
import com.shuwei.dish.match.utils.ext.visible
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import androidx.core.graphics.toColorInt
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 数据库调试查看页面
|
* 数据库调试查看页面
|
||||||
* 支持按表切换、isDel 过滤开关、分页加载(每页 50 条)
|
* 支持按表切换、isDel 过滤开关、多字段筛选、分页加载
|
||||||
* 菜品/食材/调料表每行 3 列等宽显示字段,槽位表保持单列
|
|
||||||
* 已逻辑删除(isDel=1)的记录以灰色文字 + 半透明卡片区分
|
|
||||||
*/
|
*/
|
||||||
class DbInspectFragment : BaseFragment<FragmentDbInspectBinding>() {
|
class DbInspectFragment : BaseFragment<FragmentDbInspectBinding>() {
|
||||||
|
|
||||||
@@ -45,6 +48,55 @@ class DbInspectFragment : BaseFragment<FragmentDbInspectBinding>() {
|
|||||||
/** Tab RadioButton 列表,用于统一更新选中样式 */
|
/** Tab RadioButton 列表,用于统一更新选中样式 */
|
||||||
private val tabButtons = mutableListOf<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(
|
override fun inflateBinding(
|
||||||
inflater: LayoutInflater,
|
inflater: LayoutInflater,
|
||||||
container: ViewGroup?
|
container: ViewGroup?
|
||||||
@@ -60,18 +112,19 @@ class DbInspectFragment : BaseFragment<FragmentDbInspectBinding>() {
|
|||||||
listOf(binding.rbCookFood, binding.rbGoods, binding.rbSeasoning, binding.rbSlot)
|
listOf(binding.rbCookFood, binding.rbGoods, binding.rbSeasoning, binding.rbSlot)
|
||||||
)
|
)
|
||||||
|
|
||||||
// Tab 切换:重置到第一页
|
// Tab 切换:重置筛选框并加载第一页
|
||||||
binding.rgTabs.setOnCheckedChangeListener { _, checkedId ->
|
binding.rgTabs.setOnCheckedChangeListener { _, checkedId ->
|
||||||
currentTableIndex = when (checkedId) {
|
currentTableIndex = when (checkedId) {
|
||||||
R.id.rbCookFood -> 0
|
R.id.rbCookFood -> 0
|
||||||
R.id.rbGoods -> 1
|
R.id.rbGoods -> 1
|
||||||
R.id.rbSeasoning -> 2
|
R.id.rbSeasoning -> 2
|
||||||
R.id.rbSlot -> 3
|
R.id.rbSlot -> 3
|
||||||
else -> 0
|
else -> 0
|
||||||
}
|
}
|
||||||
updateTabStyles()
|
updateTabStyles()
|
||||||
moveIndicator(currentTableIndex)
|
moveIndicator(currentTableIndex)
|
||||||
updateDelControlsVisibility()
|
updateDelControlsVisibility()
|
||||||
|
rebuildFilterUI()
|
||||||
loadFirstPage()
|
loadFirstPage()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,17 +135,17 @@ class DbInspectFragment : BaseFragment<FragmentDbInspectBinding>() {
|
|||||||
loadFirstPage()
|
loadFirstPage()
|
||||||
}
|
}
|
||||||
|
|
||||||
// 刷新按钮
|
// 查询按钮:收集筛选条件并加载第一页
|
||||||
binding.tvRefresh.setOnClickListener { loadFirstPage() }
|
binding.tvRefresh.setOnClickListener { loadFirstPage() }
|
||||||
|
|
||||||
// 加载更多按钮
|
// 加载更多按钮:筛选条件从 state 中复用,无需重新传入
|
||||||
binding.tvLoadMore.setOnClickListener {
|
binding.tvLoadMore.setOnClickListener {
|
||||||
currentActivity.appViewModel.loadMoreDbInspect(currentTableIndex, showDel)
|
currentActivity.dbViewModel.loadMoreDbInspect(currentTableIndex)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 订阅 UI 状态
|
// 订阅 UI 状态
|
||||||
viewLifecycleOwner.lifecycleScope.launch {
|
viewLifecycleOwner.lifecycleScope.launch {
|
||||||
currentActivity.appViewModel.dbInspectState.collect { state ->
|
currentActivity.dbViewModel.dbInspectState.collect { state ->
|
||||||
renderState(state)
|
renderState(state)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -100,12 +153,89 @@ class DbInspectFragment : BaseFragment<FragmentDbInspectBinding>() {
|
|||||||
// 初始化样式并加载
|
// 初始化样式并加载
|
||||||
updateTabStyles()
|
updateTabStyles()
|
||||||
updateDelControlsVisibility()
|
updateDelControlsVisibility()
|
||||||
|
rebuildFilterUI()
|
||||||
binding.vTabIndicator.post { moveIndicator(currentTableIndex) }
|
binding.vTabIndicator.post { moveIndicator(currentTableIndex) }
|
||||||
loadFirstPage()
|
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() {
|
private fun loadFirstPage() {
|
||||||
currentActivity.appViewModel.loadDbInspect(currentTableIndex, showDel)
|
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) {
|
private fun renderState(state: DbViewModel.DbInspectUiState) {
|
||||||
@@ -168,6 +298,9 @@ class DbInspectFragment : BaseFragment<FragmentDbInspectBinding>() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** dp 转 px 便捷扩展 */
|
||||||
|
private val Int.dp: Int get() = (this * resources.displayMetrics.density + 0.5f).toInt()
|
||||||
|
|
||||||
// ---- 外层 Adapter:每条数据库记录对应一个 CardView ----
|
// ---- 外层 Adapter:每条数据库记录对应一个 CardView ----
|
||||||
|
|
||||||
/** 外层列表适配器,每个 item 内嵌一个 GridLayoutManager 的 RecyclerView 展示字段 */
|
/** 外层列表适配器,每个 item 内嵌一个 GridLayoutManager 的 RecyclerView 展示字段 */
|
||||||
@@ -191,17 +324,14 @@ class DbInspectFragment : BaseFragment<FragmentDbInspectBinding>() {
|
|||||||
val record = data[position]
|
val record = data[position]
|
||||||
|
|
||||||
if (record.isDel) {
|
if (record.isDel) {
|
||||||
// 已删除:浅红背景 + 左侧红色标记条 + 文字颜色正常(深色可读)
|
|
||||||
holder.card.setCardBackgroundColor(Color.parseColor("#FFF3F3"))
|
holder.card.setCardBackgroundColor(Color.parseColor("#FFF3F3"))
|
||||||
holder.vDelMark.visibility = View.VISIBLE
|
holder.vDelMark.visibility = View.VISIBLE
|
||||||
} else {
|
} else {
|
||||||
// 正常记录:白色背景,隐藏标记条
|
|
||||||
holder.card.setCardBackgroundColor(Color.WHITE)
|
holder.card.setCardBackgroundColor(Color.WHITE)
|
||||||
holder.vDelMark.visibility = View.GONE
|
holder.vDelMark.visibility = View.GONE
|
||||||
}
|
}
|
||||||
val textColor = if (record.isDel) Color.parseColor("#C62828") else Color.parseColor("#333333")
|
val textColor = if (record.isDel) Color.parseColor("#C62828") else Color.parseColor("#333333")
|
||||||
|
|
||||||
// 每次绑定时重新设置 GridLayoutManager 列数(槽位表为 1,其余为 3)
|
|
||||||
holder.rvFields.layoutManager = GridLayoutManager(holder.rvFields.context, record.columnsPerRow)
|
holder.rvFields.layoutManager = GridLayoutManager(holder.rvFields.context, record.columnsPerRow)
|
||||||
holder.rvFields.adapter = DbFieldAdapter(record.fields, textColor)
|
holder.rvFields.adapter = DbFieldAdapter(record.fields, textColor)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,12 +3,11 @@ package com.shuwei.dish.match.ui.fragment
|
|||||||
import android.annotation.SuppressLint
|
import android.annotation.SuppressLint
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
|
import android.util.Log
|
||||||
import android.view.LayoutInflater
|
import android.view.LayoutInflater
|
||||||
import android.view.ViewGroup
|
import android.view.ViewGroup
|
||||||
import android.widget.FrameLayout
|
import android.widget.FrameLayout
|
||||||
import androidx.lifecycle.Lifecycle
|
|
||||||
import androidx.lifecycle.lifecycleScope
|
import androidx.lifecycle.lifecycleScope
|
||||||
import androidx.lifecycle.repeatOnLifecycle
|
|
||||||
import androidx.recyclerview.widget.LinearLayoutManager
|
import androidx.recyclerview.widget.LinearLayoutManager
|
||||||
import com.shuwei.dish.match.R
|
import com.shuwei.dish.match.R
|
||||||
import com.shuwei.dish.match.adapter.FoodListAdapter
|
import com.shuwei.dish.match.adapter.FoodListAdapter
|
||||||
@@ -17,19 +16,23 @@ import com.shuwei.dish.match.base.BaseFragment
|
|||||||
import com.shuwei.dish.match.databinding.FragmentFoodListBinding
|
import com.shuwei.dish.match.databinding.FragmentFoodListBinding
|
||||||
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
||||||
import com.shuwei.dish.match.dialog.CommonDialog
|
import com.shuwei.dish.match.dialog.CommonDialog
|
||||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
import com.shuwei.dish.match.db.entity.CookFoodEntity
|
||||||
import com.shuwei.dish.match.entity.FoodRecord
|
import com.shuwei.dish.match.model.FoodRecord
|
||||||
import com.shuwei.dish.match.net.UiState
|
import com.shuwei.dish.match.net.UiState
|
||||||
import com.shuwei.dish.match.ui.CookingModeActivity
|
import com.shuwei.dish.match.ui.CookingModeActivity
|
||||||
import com.shuwei.dish.match.ui.PrepareFoodActivity
|
import com.shuwei.dish.match.ui.PrepareFoodActivity
|
||||||
import com.shuwei.dish.match.ui.SubmitFoodActivity
|
import com.shuwei.dish.match.ui.SubmitFoodActivity
|
||||||
import com.shuwei.dish.match.utils.ext.dp
|
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.startActivity
|
||||||
import com.shuwei.dish.match.utils.ext.toast
|
import com.shuwei.dish.match.utils.ext.toast
|
||||||
import com.yanzhenjie.recyclerview.SwipeMenuItem
|
import com.yanzhenjie.recyclerview.SwipeMenuItem
|
||||||
|
import androidx.fragment.app.viewModels
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
import java.io.Serializable
|
import java.io.Serializable
|
||||||
import kotlinx.coroutines.flow.combine
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
class FoodListFragment : BaseFragment<FragmentFoodListBinding>() {
|
class FoodListFragment : BaseFragment<FragmentFoodListBinding>() {
|
||||||
|
|
||||||
@@ -46,13 +49,24 @@ class FoodListFragment : BaseFragment<FragmentFoodListBinding>() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val netViewModel: NetViewModel by viewModels()
|
||||||
|
|
||||||
private var pageNo = 1
|
private var pageNo = 1
|
||||||
private val pageSize = 30
|
private val pageSize = 100
|
||||||
|
|
||||||
private var dinnerType = "0"
|
private var dinnerType = "0"
|
||||||
|
|
||||||
|
/** 跟踪当前请求协程,新请求发起前取消旧的,防止并发竞态导致数据错乱 */
|
||||||
|
private var currentJob: Job? = null
|
||||||
|
|
||||||
|
/** 缓存最后一次搜索词,返回二级页面后 onResume 可复用,避免搜索态被重置为全量查询 */
|
||||||
|
private var currentFoodName: String? = null
|
||||||
|
|
||||||
private lateinit var activity: CookingModeActivity
|
private lateinit var activity: CookingModeActivity
|
||||||
|
|
||||||
|
/** 第一页时先查数据库存入此字段,网络结果回来后直接使用,避免时序问题 */
|
||||||
|
private var pendingLocalList: MutableList<CookFoodEntity>? = null
|
||||||
|
|
||||||
private var list: MutableList<FoodRecord> = mutableListOf()
|
private var list: MutableList<FoodRecord> = mutableListOf()
|
||||||
private val dishAdapter by lazy {
|
private val dishAdapter by lazy {
|
||||||
FoodListAdapter(list = list).apply {
|
FoodListAdapter(list = list).apply {
|
||||||
@@ -68,7 +82,7 @@ class FoodListFragment : BaseFragment<FragmentFoodListBinding>() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun onItemClick(position: Int) {
|
private fun onItemClick(position: Int) {
|
||||||
val item = list[position]
|
val item = list.getOrNull(position) ?: return
|
||||||
if (item.isCooking) {
|
if (item.isCooking) {
|
||||||
// 烹饪中,跳到称熟重页面
|
// 烹饪中,跳到称熟重页面
|
||||||
activity.startActivity<SubmitFoodActivity> {
|
activity.startActivity<SubmitFoodActivity> {
|
||||||
@@ -117,23 +131,30 @@ class FoodListFragment : BaseFragment<FragmentFoodListBinding>() {
|
|||||||
}
|
}
|
||||||
.show()
|
.show()
|
||||||
}
|
}
|
||||||
// item 点击
|
// // item 点击
|
||||||
setOnItemClickListener { _, position ->
|
// setOnItemClickListener { _, position ->
|
||||||
if (isAdded && isVisible) {
|
// if (isAdded && isVisible) {
|
||||||
activity.judgeDeviceConfig { onItemClick(position) }
|
// activity.judgeDeviceConfig { onItemClick(position) }
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
adapter = dishAdapter
|
adapter = dishAdapter
|
||||||
}
|
}
|
||||||
addViewListener()
|
addViewListener()
|
||||||
initObserver()
|
|
||||||
|
|
||||||
pageNo = 1
|
|
||||||
activity.showLoading()
|
|
||||||
getDishList()
|
|
||||||
binding.refreshLayout.setEnableRefresh(true)
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 构建统一样式的删除菜单项
|
* 构建统一样式的删除菜单项
|
||||||
*/
|
*/
|
||||||
@@ -146,50 +167,12 @@ class FoodListFragment : BaseFragment<FragmentFoodListBinding>() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 用 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() {
|
private fun addViewListener() {
|
||||||
binding.refreshLayout.run {
|
binding.refreshLayout.run {
|
||||||
setEnableRefresh(true)
|
setEnableRefresh(true)
|
||||||
setEnableLoadMore(false)
|
setEnableLoadMore(false)
|
||||||
setOnRefreshListener {
|
setOnRefreshListener {
|
||||||
|
Log.d("FoodList", "下拉刷新触发, pageNo reset to 1")
|
||||||
pageNo = 1
|
pageNo = 1
|
||||||
getDishList()
|
getDishList()
|
||||||
}
|
}
|
||||||
@@ -199,10 +182,19 @@ class FoodListFragment : BaseFragment<FragmentFoodListBinding>() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun getDishList(pageNo: Int, dinnerType: String) {
|
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.pageNo = pageNo
|
||||||
this.dinnerType = dinnerType
|
this.dinnerType = dinnerType
|
||||||
getDishList()
|
getDishList(foodName)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun getDinnerTypeText(): String {
|
fun getDinnerTypeText(): String {
|
||||||
@@ -216,15 +208,51 @@ class FoodListFragment : BaseFragment<FragmentFoodListBinding>() {
|
|||||||
|
|
||||||
@SuppressLint("NotifyDataSetChanged")
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
@Suppress("unchecked_cast")
|
@Suppress("unchecked_cast")
|
||||||
fun getDishList() {
|
fun getDishList(foodName: String? = null) {
|
||||||
val param = mutableMapOf<String, Any>(
|
currentFoodName = foodName
|
||||||
"pageNum" to pageNo,
|
currentJob?.cancel()
|
||||||
"pageSize" to pageSize,
|
currentJob = viewLifecycleOwner.lifecycleScope.launch {
|
||||||
"placeId" to BaseApp.canteenId,
|
val param = mutableMapOf<String, Any>(
|
||||||
"dinnerType" to getDinnerTypeText()
|
"pageNum" to pageNo,
|
||||||
)
|
"pageSize" to pageSize,
|
||||||
activity.getFoodList(param = param)
|
"placeId" to BaseApp.canteenId,
|
||||||
if (pageNo == 1) activity.getCookFoodList()
|
"dinnerType" to getDinnerTypeText()
|
||||||
|
)
|
||||||
|
foodName?.let { param["foodName"] = it }
|
||||||
|
if (pageNo == 1) {
|
||||||
|
pendingLocalList = activity.dbViewModel.getCookFoodListDirect(
|
||||||
|
cookMode = 0,
|
||||||
|
dinnerType = dinnerType
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val localList = if (pageNo == 1) pendingLocalList else null
|
||||||
|
netViewModel.searchFoodListWithCallback(
|
||||||
|
param = param,
|
||||||
|
onLoading = { activity.showLoading(timeoutMs = 35_000L) }
|
||||||
|
) { result ->
|
||||||
|
when (result) {
|
||||||
|
is UiState.Success -> {
|
||||||
|
if (isAdded.not()) return@searchFoodListWithCallback
|
||||||
|
Log.d(TAG, "getDishList, UiState.Success")
|
||||||
|
activity.delayDismissLoading()
|
||||||
|
finishRefresh()
|
||||||
|
loadAndMergeDishList(result.data, localList)
|
||||||
|
}
|
||||||
|
is UiState.Error -> {
|
||||||
|
if (isAdded.not()) return@searchFoodListWithCallback
|
||||||
|
Log.d(TAG, "getDishList, UiState.Error")
|
||||||
|
toast(result.msg)
|
||||||
|
finishRefresh()
|
||||||
|
activity.delayDismissLoading()
|
||||||
|
if (pageNo == 1) {
|
||||||
|
if (localList.isNullOrEmpty()) loadEmptyView()
|
||||||
|
else loadAndMergeDishList(null, localList)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private var emptyViewBinding: LayoutEmptyViewBinding? = null
|
private var emptyViewBinding: LayoutEmptyViewBinding? = null
|
||||||
@@ -279,49 +307,76 @@ class FoodListFragment : BaseFragment<FragmentFoodListBinding>() {
|
|||||||
val effectiveLocalList = if (pageNo == 1) localList else null
|
val effectiveLocalList = if (pageNo == 1) localList else null
|
||||||
if (records.isNullOrEmpty() && effectiveLocalList.isNullOrEmpty()) {
|
if (records.isNullOrEmpty() && effectiveLocalList.isNullOrEmpty()) {
|
||||||
if (pageNo == 1) loadEmptyView()
|
if (pageNo == 1) loadEmptyView()
|
||||||
|
finishRefresh()
|
||||||
|
binding.refreshLayout.setEnableLoadMore(false)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (pageNo == 1) list.clear()
|
if (pageNo == 1) list.clear()
|
||||||
|
|
||||||
val mergedList = records?.toMutableList() ?: mutableListOf()
|
val mergedList = records?.toMutableList() ?: mutableListOf()
|
||||||
|
mergeCookingItems(mergedList, effectiveLocalList)
|
||||||
if (!effectiveLocalList.isNullOrEmpty()) {
|
deduplicateForPaging(mergedList, localList)
|
||||||
val cookingItems = mutableListOf<FoodRecord>()
|
renderList(mergedList, records)
|
||||||
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) {
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 翻页时从网络结果中剔除第一页已加载的本地烹饪中条目,避免重复出现
|
||||||
|
*/
|
||||||
|
private fun deduplicateForPaging(
|
||||||
|
mergedList: MutableList<FoodRecord>,
|
||||||
|
localList: List<CookFoodEntity>?
|
||||||
|
) {
|
||||||
|
if (pageNo < 2 || localList.isNullOrEmpty()) return
|
||||||
|
val localIds = localList.map { it.foodId }.toHashSet()
|
||||||
|
mergedList.removeAll { it.foodId in localIds }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将合并结果追加到列表并刷新 UI,按网络返回条数决定是否开启加载更多
|
||||||
|
*/
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
private fun renderList(mergedList: List<FoodRecord>, records: List<FoodRecord>?) {
|
||||||
|
list.addAll(mergedList)
|
||||||
|
dishAdapter.notifyDataSetChanged()
|
||||||
|
val isLoadMoreEnable = (records?.size ?: 0) >= pageSize
|
||||||
|
binding.refreshLayout.setEnableRefresh(true)
|
||||||
|
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
|
||||||
|
if (isLoadMoreEnable) pageNo++
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import com.shuwei.dish.match.base.GlobalData
|
|||||||
import com.shuwei.dish.match.databinding.FragmentSeasoningConfigBinding
|
import com.shuwei.dish.match.databinding.FragmentSeasoningConfigBinding
|
||||||
import com.shuwei.dish.match.dialog.CommonDialog
|
import com.shuwei.dish.match.dialog.CommonDialog
|
||||||
import com.shuwei.dish.match.dialog.SeasoningSelectDialog
|
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.ScaleDeviceConfig
|
||||||
import com.shuwei.dish.match.scale.ScaleEvent
|
import com.shuwei.dish.match.scale.ScaleEvent
|
||||||
import com.shuwei.dish.match.scale.ScaleServiceManager
|
import com.shuwei.dish.match.scale.ScaleServiceManager
|
||||||
@@ -50,7 +50,7 @@ class SeasoningConfigFragment : BaseFragment<FragmentSeasoningConfigBinding>() {
|
|||||||
) = FragmentSeasoningConfigBinding.inflate(inflater, container, false)
|
) = FragmentSeasoningConfigBinding.inflate(inflater, container, false)
|
||||||
|
|
||||||
private lateinit var currentActivity: SingleFragmentActivity
|
private lateinit var currentActivity: SingleFragmentActivity
|
||||||
// private lateinit var appViewModel: DbViewModel
|
// private lateinit var dbViewModel: DbViewModel
|
||||||
|
|
||||||
private val adapter22 by lazy { buildAdapter22() }
|
private val adapter22 by lazy { buildAdapter22() }
|
||||||
private val adapter18 by lazy {
|
private val adapter18 by lazy {
|
||||||
@@ -186,7 +186,7 @@ class SeasoningConfigFragment : BaseFragment<FragmentSeasoningConfigBinding>() {
|
|||||||
onUpdateName(name)
|
onUpdateName(name)
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
// 保存槽位配置
|
// 保存槽位配置
|
||||||
currentActivity.appViewModel.upsertSeasoningSlot(
|
currentActivity.dbViewModel.upsertSeasoningSlot(
|
||||||
SeasoningSlotEntity(
|
SeasoningSlotEntity(
|
||||||
deviceId = deviceId,
|
deviceId = deviceId,
|
||||||
address = address,
|
address = address,
|
||||||
@@ -195,7 +195,7 @@ class SeasoningConfigFragment : BaseFragment<FragmentSeasoningConfigBinding>() {
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
// 按 goodsId 去重保存完整调料信息到 dm_seasoning
|
// 按 goodsId 去重保存完整调料信息到 dm_seasoning
|
||||||
currentActivity.appViewModel.upsertSeasoningByGoodsId(item.toSeasoningEntity())
|
currentActivity.dbViewModel.upsertSeasoningByGoodsId(item.toSeasoningEntity())
|
||||||
broadcastAllSlots()
|
broadcastAllSlots()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -205,7 +205,7 @@ class SeasoningConfigFragment : BaseFragment<FragmentSeasoningConfigBinding>() {
|
|||||||
/** 将单个槽位写入 Room,再广播全量配置给子设备 */
|
/** 将单个槽位写入 Room,再广播全量配置给子设备 */
|
||||||
private fun saveSlotAndBroadcast(slot: SeasoningSlotEntity) {
|
private fun saveSlotAndBroadcast(slot: SeasoningSlotEntity) {
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
currentActivity.appViewModel.upsertSeasoningSlot(slot)
|
currentActivity.dbViewModel.upsertSeasoningSlot(slot)
|
||||||
broadcastAllSlots()
|
broadcastAllSlots()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -233,14 +233,14 @@ class SeasoningConfigFragment : BaseFragment<FragmentSeasoningConfigBinding>() {
|
|||||||
/** 从 Room 删除指定槽位,再广播全量配置给子设备 */
|
/** 从 Room 删除指定槽位,再广播全量配置给子设备 */
|
||||||
private fun deleteSlotAndBroadcast(deviceId: String, address: Int) {
|
private fun deleteSlotAndBroadcast(deviceId: String, address: Int) {
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
currentActivity.appViewModel.deleteSeasoningSlot(deviceId, address)
|
currentActivity.dbViewModel.deleteSeasoningSlot(deviceId, address)
|
||||||
broadcastAllSlots()
|
broadcastAllSlots()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 读取全量槽位配置并通过 wsClient 推送给所有已连接子设备 */
|
/** 读取全量槽位配置并通过 wsClient 推送给所有已连接子设备 */
|
||||||
private suspend fun broadcastAllSlots() {
|
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)
|
SlotConfig(it.deviceId, it.address, it.goodsId, it.goodsName)
|
||||||
}
|
}
|
||||||
ScaleServiceManager.sendSeasoningConfig(allSlots)
|
ScaleServiceManager.sendSeasoningConfig(allSlots)
|
||||||
@@ -249,7 +249,7 @@ class SeasoningConfigFragment : BaseFragment<FragmentSeasoningConfigBinding>() {
|
|||||||
// /** 初始化 ViewModel */
|
// /** 初始化 ViewModel */
|
||||||
// private fun initViewModel() {
|
// private fun initViewModel() {
|
||||||
// val factory = AppFactory(DbRepository(BaseApp.instance!!.database.appDao()))
|
// val factory = AppFactory(DbRepository(BaseApp.instance!!.database.appDao()))
|
||||||
// appViewModel = ViewModelProvider(this, factory)[DbViewModel::class.java]
|
// dbViewModel = ViewModelProvider(this, factory)[DbViewModel::class.java]
|
||||||
// }
|
// }
|
||||||
|
|
||||||
|
|
||||||
@@ -292,9 +292,9 @@ class SeasoningConfigFragment : BaseFragment<FragmentSeasoningConfigBinding>() {
|
|||||||
adapter22.update(emptyList())
|
adapter22.update(emptyList())
|
||||||
adapter18.update(emptyList())
|
adapter18.update(emptyList())
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
val slots22 = currentActivity.appViewModel.getSeasoningSlotsByDeviceId(ScaleDeviceConfig.DEVICE_ID_22)
|
val slots22 = currentActivity.dbViewModel.getSeasoningSlotsByDeviceId(ScaleDeviceConfig.DEVICE_ID_22)
|
||||||
val slots18 = currentActivity.appViewModel.getSeasoningSlotsByDeviceId(ScaleDeviceConfig.DEVICE_ID_18)
|
val slots18 = currentActivity.dbViewModel.getSeasoningSlotsByDeviceId(ScaleDeviceConfig.DEVICE_ID_18)
|
||||||
val slotsOil = currentActivity.appViewModel.getSeasoningSlotsByDeviceId(ScaleDeviceConfig.DEVICE_ID_1)
|
val slotsOil = currentActivity.dbViewModel.getSeasoningSlotsByDeviceId(ScaleDeviceConfig.DEVICE_ID_1)
|
||||||
slots22.forEach { slot ->
|
slots22.forEach { slot ->
|
||||||
val pos = ScaleDeviceConfig.SCALE_ORDER_22.indexOf(slot.address)
|
val pos = ScaleDeviceConfig.SCALE_ORDER_22.indexOf(slot.address)
|
||||||
if (pos >= 0) adapter22.updateItemName(pos, slot.goodsName)
|
if (pos >= 0) adapter22.updateItemName(pos, slot.goodsName)
|
||||||
|
|||||||
@@ -32,8 +32,9 @@ import com.shuwei.dish.match.databinding.FragmentVectorCollectionBinding
|
|||||||
import com.shuwei.dish.match.databinding.LayoutCameraPreviewBinding
|
import com.shuwei.dish.match.databinding.LayoutCameraPreviewBinding
|
||||||
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
||||||
import com.shuwei.dish.match.dialog.Loading
|
import com.shuwei.dish.match.dialog.Loading
|
||||||
import com.shuwei.dish.match.entity.FoodCollectionBean
|
import com.shuwei.dish.match.dialog.CommonDialog
|
||||||
import com.shuwei.dish.match.entity.GoodsItem
|
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.net.UiState
|
||||||
import com.shuwei.dish.match.objbox.Food
|
import com.shuwei.dish.match.objbox.Food
|
||||||
import com.shuwei.dish.match.objbox.FoodModule
|
import com.shuwei.dish.match.objbox.FoodModule
|
||||||
@@ -46,12 +47,9 @@ import com.shuwei.dish.match.utils.Debouncer
|
|||||||
import com.shuwei.dish.match.utils.ImageUploader
|
import com.shuwei.dish.match.utils.ImageUploader
|
||||||
import com.shuwei.dish.match.utils.ImageUtil
|
import com.shuwei.dish.match.utils.ImageUtil
|
||||||
import com.shuwei.dish.match.utils.LogSaveUtil
|
import com.shuwei.dish.match.utils.LogSaveUtil
|
||||||
import com.shuwei.dish.match.utils.buildSingleChoiceChipGroup
|
|
||||||
import com.shuwei.dish.match.utils.buildMockGoodsList
|
|
||||||
import com.shuwei.dish.match.utils.showRawMaterialsDialog
|
import com.shuwei.dish.match.utils.showRawMaterialsDialog
|
||||||
import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
||||||
import com.shuwei.dish.match.utils.ext.dp
|
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.toast
|
||||||
import okhttp3.RequestBody
|
import okhttp3.RequestBody
|
||||||
import okhttp3.RequestBody.Companion.toRequestBody
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
@@ -81,7 +79,7 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
|||||||
// 开启空状态视图能力,否则 stateView 赋值不会生效
|
// 开启空状态视图能力,否则 stateView 赋值不会生效
|
||||||
isStateViewEnable = true
|
isStateViewEnable = true
|
||||||
setOnDebouncedItemClick { _, _, position ->
|
setOnDebouncedItemClick { _, _, position ->
|
||||||
val item = searchList[position]
|
val item = searchList.getOrNull(position) ?: return@setOnDebouncedItemClick
|
||||||
// 弹出净材种类单选弹窗
|
// 弹出净材种类单选弹窗
|
||||||
showRawMaterialsDialog(
|
showRawMaterialsDialog(
|
||||||
context = requireContext(),
|
context = requireContext(),
|
||||||
@@ -113,7 +111,7 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
|||||||
private val vectorAdapter: VectorCollectionAdapter by lazy {
|
private val vectorAdapter: VectorCollectionAdapter by lazy {
|
||||||
VectorCollectionAdapter(vectorList).apply {
|
VectorCollectionAdapter(vectorList).apply {
|
||||||
addOnItemChildClickListener(R.id.ivDelete) { _, _, position ->
|
addOnItemChildClickListener(R.id.ivDelete) { _, _, position ->
|
||||||
vectorList[position].let {
|
vectorList.getOrNull(position)?.let {
|
||||||
it.bitmap = null
|
it.bitmap = null
|
||||||
it.imageVector = null
|
it.imageVector = null
|
||||||
it.imageFile = null
|
it.imageFile = null
|
||||||
@@ -121,8 +119,8 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
|||||||
it.isShowCamera = true
|
it.isShowCamera = true
|
||||||
it.isFinish = false
|
it.isFinish = false
|
||||||
it.uploadSuccess = false
|
it.uploadSuccess = false
|
||||||
|
notifyItemChanged(position)
|
||||||
}
|
}
|
||||||
notifyItemChanged(position)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -302,7 +300,14 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
|||||||
}
|
}
|
||||||
takePhoto()
|
takePhoto()
|
||||||
}
|
}
|
||||||
binding.btnClearData.setOnClickListener { clearData() }
|
binding.btnClearData.setOnClickListener {
|
||||||
|
CommonDialog(requireContext())
|
||||||
|
.setTitle("清空确认")
|
||||||
|
.setContent("确认清空所有已采集的图片数据?")
|
||||||
|
.setNegativeButton("取消")
|
||||||
|
.setPositiveButton("确认") { clearData() }
|
||||||
|
.show()
|
||||||
|
}
|
||||||
binding.rvSearchFood.let {
|
binding.rvSearchFood.let {
|
||||||
it.layoutManager = GridLayoutManager(context, 2)
|
it.layoutManager = GridLayoutManager(context, 2)
|
||||||
it.adapter = searchAdapter
|
it.adapter = searchAdapter
|
||||||
@@ -316,6 +321,13 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
|||||||
is UiState.Success -> {
|
is UiState.Success -> {
|
||||||
val list = state.data ?: emptyList()
|
val list = state.data ?: emptyList()
|
||||||
if (list.isEmpty()) loadEmptyView() else fillSearchList(list)
|
if (list.isEmpty()) loadEmptyView() else fillSearchList(list)
|
||||||
|
currentActivity.netViewModel.resetGoodsListState()
|
||||||
|
}
|
||||||
|
|
||||||
|
is UiState.Error -> {
|
||||||
|
toast(state.msg)
|
||||||
|
loadEmptyView()
|
||||||
|
currentActivity.netViewModel.resetGoodsListState()
|
||||||
}
|
}
|
||||||
|
|
||||||
else -> Unit
|
else -> Unit
|
||||||
@@ -330,7 +342,9 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
|||||||
private fun upload() {
|
private fun upload() {
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
val totalFileCount = vectorList.count { it.imageFile != null }
|
val totalFileCount = vectorList.count { it.imageFile != null }
|
||||||
showWaitingDialog("图片上传中0/$totalFileCount")
|
// 上传场景单批可能耗时较长(含图片传输 + 网络往返),用 60s 超时兜底
|
||||||
|
// 每次 onProgress 都会重新调用 showWaitingDialog,会重置定时器,正常进度不会触发兜底
|
||||||
|
showWaitingDialog("图片上传中0/$totalFileCount", timeoutMs = 60_000L)
|
||||||
val params = mutableMapOf<String, RequestBody>()
|
val params = mutableMapOf<String, RequestBody>()
|
||||||
params["goodsId"] = checkedItem!!.goodsId.toRequestBody()
|
params["goodsId"] = checkedItem!!.goodsId.toRequestBody()
|
||||||
params["goodsName"] = checkedItem!!.goodsName!!.toRequestBody()
|
params["goodsName"] = checkedItem!!.goodsName!!.toRequestBody()
|
||||||
@@ -352,9 +366,10 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
|||||||
// 直接 await 单批上传结果,成功返回 id 列表,失败返回 null 触发 onError
|
// 直接 await 单批上传结果,成功返回 id 列表,失败返回 null 触发 onError
|
||||||
val result = currentActivity.netViewModel.uploadFoodVectorDataBatch(files, params)
|
val result = currentActivity.netViewModel.uploadFoodVectorDataBatch(files, params)
|
||||||
log("uploadImage返回:result=${result.toJsonString()}")
|
log("uploadImage返回:result=${result.toJsonString()}")
|
||||||
if (result is UiState.Success) result.data else null
|
if (result is UiState.Success) result.data to null
|
||||||
|
else null to (result as? UiState.Error)?.msg
|
||||||
}, onProgress = { count, batch, idList ->
|
}, onProgress = { count, batch, idList ->
|
||||||
showWaitingDialog("图片上传中$count/$totalFileCount")
|
showWaitingDialog("图片上传中$count/$totalFileCount", timeoutMs = 60_000L)
|
||||||
val foodList = batch.mapIndexed { index, it ->
|
val foodList = batch.mapIndexed { index, it ->
|
||||||
val name = checkedItem!!.goodsName + "&&" + checkedItem!!.rawMaterialsType
|
val name = checkedItem!!.goodsName + "&&" + checkedItem!!.rawMaterialsType
|
||||||
Food(
|
Food(
|
||||||
@@ -365,10 +380,10 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
|||||||
ObjectBox.putAll(foodList)
|
ObjectBox.putAll(foodList)
|
||||||
batch.forEach { it.isFinish = true }
|
batch.forEach { it.isFinish = true }
|
||||||
vectorAdapter.notifyDataSetChanged()
|
vectorAdapter.notifyDataSetChanged()
|
||||||
}, onError = {
|
}, onError = { _, errorMsg ->
|
||||||
binding.root.postDelayed({
|
binding.root.postDelayed({
|
||||||
hideWaitingDialog()
|
hideWaitingDialog()
|
||||||
toast("上传失败,请稍后重试")
|
toast("上传失败:${(errorMsg ?: "").ifBlank { "请稍后重试" }}")
|
||||||
}, 1000)
|
}, 1000)
|
||||||
}, onComplete = {
|
}, onComplete = {
|
||||||
binding.root.postDelayed({
|
binding.root.postDelayed({
|
||||||
@@ -381,9 +396,11 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
|||||||
|
|
||||||
@SuppressLint("NotifyDataSetChanged")
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
fun searchFood() {
|
fun searchFood() {
|
||||||
|
log("searchFood")
|
||||||
|
// 立即重置,防止 StateFlow 向新订阅者重播旧的错误状态
|
||||||
|
currentActivity.netViewModel.resetGoodsListState()
|
||||||
debouncer.debounce {
|
debouncer.debounce {
|
||||||
val keyword = binding.editFoodName.text.toString().trim()
|
val keyword = binding.editFoodName.text.toString().trim()
|
||||||
// 通过 NetViewModel 查询净材数据(goodsType=0 食材),结果由 initialize() 中的 observer 统一处理
|
|
||||||
currentActivity.netViewModel.queryGoodsList(
|
currentActivity.netViewModel.queryGoodsList(
|
||||||
goodsType = "0",
|
goodsType = "0",
|
||||||
goodsName = keyword.ifEmpty { null }
|
goodsName = keyword.ifEmpty { null }
|
||||||
@@ -398,9 +415,11 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
|||||||
@SuppressLint("NotifyDataSetChanged")
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
private fun fillSearchList(list: List<GoodsItem>) {
|
private fun fillSearchList(list: List<GoodsItem>) {
|
||||||
// 将 rawMaterialsType 转存到 rawMaterialsTypes,并清空 rawMaterialsType
|
// 将 rawMaterialsType 转存到 rawMaterialsTypes,并清空 rawMaterialsType
|
||||||
list.forEach { item ->
|
list.forEach {
|
||||||
item.rawMaterialsTypes = item.rawMaterialsType
|
it.rawMaterialsTypes = it.rawMaterialsType
|
||||||
item.rawMaterialsType = null
|
it.rawMaterialsType = null
|
||||||
|
it.oldGoodsId = it.goodsId
|
||||||
|
it.goodsId = it.materId ?: ""
|
||||||
}
|
}
|
||||||
// 空布局切过 LinearLayoutManager,此处恢复为 2 列 GridLayoutManager
|
// 空布局切过 LinearLayoutManager,此处恢复为 2 列 GridLayoutManager
|
||||||
if (binding.rvSearchFood.layoutManager !is GridLayoutManager) {
|
if (binding.rvSearchFood.layoutManager !is GridLayoutManager) {
|
||||||
@@ -437,13 +456,13 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
|||||||
}
|
}
|
||||||
emptyViewBinding?.let {
|
emptyViewBinding?.let {
|
||||||
it.tvContent.text = "暂无数据"
|
it.tvContent.text = "暂无数据"
|
||||||
it.tvSubContent.text = "点击此处重新查询"
|
it.tvSubContent.text = "未查询到食材信息,请稍后重试"
|
||||||
// 点击空布局填充本地假数据,便于 UI 效果测试
|
|
||||||
it.root.setOnClickListener {
|
|
||||||
fillSearchList(buildMockGoodsList())
|
|
||||||
}
|
|
||||||
binding.rvSearchFood.post {
|
binding.rvSearchFood.post {
|
||||||
it.root.minimumHeight = binding.rvSearchFood.height
|
it.root.minimumHeight = binding.rvSearchFood.height
|
||||||
|
// 在 stateView 挂载完成后再设置点击监听,避免 adapter 重置 view 状态时丢失监听器
|
||||||
|
it.root.setOnClickListener {
|
||||||
|
searchFood()
|
||||||
|
}
|
||||||
searchAdapter.stateView = it.root
|
searchAdapter.stateView = it.root
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -468,8 +487,8 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
|||||||
vectorAdapter.notifyDataSetChanged()
|
vectorAdapter.notifyDataSetChanged()
|
||||||
|
|
||||||
clickIndex = -1
|
clickIndex = -1
|
||||||
|
// setText("") 会触发 addTextChangedListener → searchFood(),无需再次直接调用
|
||||||
binding.editFoodName.setText("")
|
binding.editFoodName.setText("")
|
||||||
searchFood()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private var isFirstOpen = true
|
private var isFirstOpen = true
|
||||||
@@ -499,12 +518,14 @@ class VectorCollectionFragment : BaseFragment<FragmentVectorCollectionBinding>()
|
|||||||
currentActivity.dismissLoading()
|
currentActivity.dismissLoading()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun showWaitingDialog(msg: String) {
|
/**
|
||||||
if (Loading.isShowing()) {
|
* 显示等待弹窗
|
||||||
Loading.updateContent(msg)
|
* @param msg 提示文案
|
||||||
return
|
* @param timeoutMs 超时兜底时长(毫秒):到期自动关闭,传 0 关闭兜底
|
||||||
}
|
* Loading 内部已做节流,重复调用只会更新文案 + 重置超时定时器
|
||||||
currentActivity.showLoading(msg)
|
*/
|
||||||
|
private fun showWaitingDialog(msg: String, timeoutMs: Long = Loading.DEFAULT_TIMEOUT_MS) {
|
||||||
|
currentActivity.showLoading(msg, timeoutMs)
|
||||||
}
|
}
|
||||||
|
|
||||||
private lateinit var previewView: PreviewView
|
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.os.Process
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import com.shuwei.dish.match.ui.HomeActivity
|
import com.shuwei.dish.match.ui.HomeActivity
|
||||||
|
import com.shuwei.dish.match.ui.InitActivity
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.FileOutputStream
|
import java.io.FileOutputStream
|
||||||
import java.io.IOException
|
import java.io.IOException
|
||||||
@@ -75,7 +76,7 @@ class CrashHandler private constructor(private val context: Context) :
|
|||||||
private fun restartApp() {
|
private fun restartApp() {
|
||||||
// 延迟1秒后重启应用
|
// 延迟1秒后重启应用
|
||||||
Handler(Looper.getMainLooper()).postDelayed({
|
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)
|
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import java.util.Date
|
|||||||
object DateTimeUtil {
|
object DateTimeUtil {
|
||||||
|
|
||||||
const val YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"
|
const val YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"
|
||||||
|
const val YYYY_MM_DD = "yyyy-MM-dd"
|
||||||
|
|
||||||
fun formatDateTime(dateTime: LocalDateTime, pattern: String = YYYY_MM_DD_HH_MM_SS): String {
|
fun formatDateTime(dateTime: LocalDateTime, pattern: String = YYYY_MM_DD_HH_MM_SS): String {
|
||||||
val formatter = DateTimeFormatter.ofPattern(pattern)
|
val formatter = DateTimeFormatter.ofPattern(pattern)
|
||||||
|
|||||||
@@ -1,26 +1,26 @@
|
|||||||
package com.shuwei.dish.match.utils
|
//package com.shuwei.dish.match.utils
|
||||||
|
//
|
||||||
import com.google.gson.TypeAdapter
|
//import com.google.gson.TypeAdapter
|
||||||
import com.google.gson.stream.JsonReader
|
//import com.google.gson.stream.JsonReader
|
||||||
import com.google.gson.stream.JsonToken
|
//import com.google.gson.stream.JsonToken
|
||||||
import com.google.gson.stream.JsonWriter
|
//import com.google.gson.stream.JsonWriter
|
||||||
|
//
|
||||||
class DecimalAdapter : TypeAdapter<Number>() {
|
//class DecimalAdapter : TypeAdapter<Number>() {
|
||||||
override fun write(out: JsonWriter, value: Number) {
|
// override fun write(out: JsonWriter, value: Number) {
|
||||||
// out.value(value.toString()) // 强制以字符串形式写入
|
//// out.value(value.toString()) // 强制以字符串形式写入
|
||||||
out.value("$value") // 强制以字符串形式写入
|
// out.value("$value") // 强制以字符串形式写入
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
override fun read(reader: JsonReader): Number {
|
// override fun read(reader: JsonReader): Number {
|
||||||
return when (reader.peek()) {
|
// return when (reader.peek()) {
|
||||||
JsonToken.NUMBER -> reader.nextDouble()
|
// JsonToken.NUMBER -> reader.nextDouble()
|
||||||
JsonToken.STRING -> reader.nextString().toDouble()
|
// JsonToken.STRING -> reader.nextString().toDouble()
|
||||||
else -> 0.0
|
// else -> 0.0
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
}
|
//}
|
||||||
|
//
|
||||||
// 使用方式
|
//// 使用方式
|
||||||
//val gson = GsonBuilder()
|
////val gson = GsonBuilder()
|
||||||
// .registerTypeAdapter(Double::class.java, DecimalAdapter())
|
//// .registerTypeAdapter(Double::class.java, DecimalAdapter())
|
||||||
// .create()
|
//// .create()
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
package com.shuwei.dish.match.utils
|
package com.shuwei.dish.match.utils
|
||||||
|
|
||||||
import com.shuwei.dish.match.entity.FoodCollectionBean
|
import com.shuwei.dish.match.model.FoodCollectionBean
|
||||||
import java.util.concurrent.atomic.AtomicInteger
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
|
|
||||||
class ImageUploader(
|
class ImageUploader(
|
||||||
private val totalList: List<FoodCollectionBean>,
|
private val totalList: List<FoodCollectionBean>,
|
||||||
private val uploadImage: suspend (List<FoodCollectionBean>) -> List<String>?,
|
private val uploadImage: suspend (List<FoodCollectionBean>) -> Pair<List<String>?, String?>,
|
||||||
private val onProgress: suspend (Int, List<FoodCollectionBean>, List<String>) -> Unit,
|
private val onProgress: suspend (Int, List<FoodCollectionBean>, List<String>) -> Unit,
|
||||||
private val onError: (List<FoodCollectionBean>) -> Unit,
|
private val onError: (List<FoodCollectionBean>, String?) -> Unit,
|
||||||
private val onComplete: () -> Unit
|
private val onComplete: () -> Unit
|
||||||
) {
|
) {
|
||||||
companion object {
|
companion object {
|
||||||
@@ -19,10 +19,9 @@ class ImageUploader(
|
|||||||
val batches = totalList.filter { it.imageVector!=null }.chunked(BATCH_SIZE)
|
val batches = totalList.filter { it.imageVector!=null }.chunked(BATCH_SIZE)
|
||||||
|
|
||||||
for (batch in batches) {
|
for (batch in batches) {
|
||||||
val idList = uploadImage(batch)
|
val (idList, errorMsg) = uploadImage(batch)
|
||||||
if (idList.isNullOrEmpty()) {
|
if (idList.isNullOrEmpty()) {
|
||||||
//println("上传失败,终止流程")
|
onError(batch, errorMsg)
|
||||||
onError(batch)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
val fileCount = batch.count { it.imageFile!=null }
|
val fileCount = batch.count { it.imageFile!=null }
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user