Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
05c5fe7932 | ||
|
|
b08a77fc9d | ||
|
|
82a9bd15d9 | ||
|
|
8aa5158b41 | ||
|
|
82960b26a0 | ||
|
|
863cd70118 | ||
|
|
e8037b12b7 | ||
|
|
13390f59dc | ||
|
|
335b56eaea | ||
|
|
2d4f7619aa | ||
|
|
e82fffb40a | ||
|
|
30f6c74a99 |
+6
-6
@@ -1,15 +1,15 @@
|
|||||||
*.iml
|
*.iml
|
||||||
.gradle
|
.gradle
|
||||||
/local.properties
|
/local.properties
|
||||||
/.idea/
|
/.idea/caches
|
||||||
|
/.idea/libraries
|
||||||
|
/.idea/modules.xml
|
||||||
|
/.idea/workspace.xml
|
||||||
|
/.idea/navEditor.xml
|
||||||
|
/.idea/assetWizardSettings.xml
|
||||||
.DS_Store
|
.DS_Store
|
||||||
/build
|
/build
|
||||||
/captures
|
/captures
|
||||||
.externalNativeBuild
|
.externalNativeBuild
|
||||||
.cxx
|
.cxx
|
||||||
local.properties
|
local.properties
|
||||||
.claude/
|
|
||||||
app/debug/
|
|
||||||
app/release/
|
|
||||||
# 临时忽略 assets 下的 .pt 模型文件,正式文件就绪后取消此行
|
|
||||||
app/src/main/assets/*.pt
|
|
||||||
|
|||||||
Generated
+3
@@ -0,0 +1,3 @@
|
|||||||
|
# Default ignored files
|
||||||
|
/shelf/
|
||||||
|
/workspace.xml
|
||||||
Generated
+6
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="AndroidProjectSystem">
|
||||||
|
<option name="providerId" value="com.android.tools.idea.GradleProjectSystem" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+6
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="CompilerConfiguration">
|
||||||
|
<bytecodeTargetLevel target="21" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+18
@@ -0,0 +1,18 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="deploymentTargetSelector">
|
||||||
|
<selectionStates>
|
||||||
|
<SelectionState runConfigName="app">
|
||||||
|
<option name="selectionMode" value="DROPDOWN" />
|
||||||
|
<DropdownSelection timestamp="2025-09-10T07:28:30.961571900Z">
|
||||||
|
<Target type="DEFAULT_BOOT">
|
||||||
|
<handle>
|
||||||
|
<DeviceId pluginId="Default" identifier="serial=192.168.1.21:5555;connection=bc7af9a5" />
|
||||||
|
</handle>
|
||||||
|
</Target>
|
||||||
|
</DropdownSelection>
|
||||||
|
<DialogSelection />
|
||||||
|
</SelectionState>
|
||||||
|
</selectionStates>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+13
@@ -0,0 +1,13 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="DeviceTable">
|
||||||
|
<option name="columnSorters">
|
||||||
|
<list>
|
||||||
|
<ColumnSorterState>
|
||||||
|
<option name="column" value="Name" />
|
||||||
|
<option name="order" value="ASCENDING" />
|
||||||
|
</ColumnSorterState>
|
||||||
|
</list>
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+19
@@ -0,0 +1,19 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="GradleMigrationSettings" migrationVersion="1" />
|
||||||
|
<component name="GradleSettings">
|
||||||
|
<option name="linkedExternalProjectsSettings">
|
||||||
|
<GradleProjectSettings>
|
||||||
|
<option name="testRunner" value="CHOOSE_PER_TEST" />
|
||||||
|
<option name="externalProjectPath" value="$PROJECT_DIR$" />
|
||||||
|
<option name="gradleJvm" value="#GRADLE_LOCAL_JAVA_HOME" />
|
||||||
|
<option name="modules">
|
||||||
|
<set>
|
||||||
|
<option value="$PROJECT_DIR$" />
|
||||||
|
<option value="$PROJECT_DIR$/app" />
|
||||||
|
</set>
|
||||||
|
</option>
|
||||||
|
</GradleProjectSettings>
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+10
@@ -0,0 +1,10 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="ProjectMigrations">
|
||||||
|
<option name="MigrateToGradleLocalJavaHome">
|
||||||
|
<set>
|
||||||
|
<option value="$PROJECT_DIR$" />
|
||||||
|
</set>
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+9
@@ -0,0 +1,9 @@
|
|||||||
|
<project version="4">
|
||||||
|
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||||
|
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="jbr-21" project-jdk-type="JavaSDK">
|
||||||
|
<output url="file://$PROJECT_DIR$/build/classes" />
|
||||||
|
</component>
|
||||||
|
<component name="ProjectType">
|
||||||
|
<option name="id" value="Android" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+17
@@ -0,0 +1,17 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="RunConfigurationProducerService">
|
||||||
|
<option name="ignoredProducers">
|
||||||
|
<set>
|
||||||
|
<option value="com.intellij.execution.junit.AbstractAllInDirectoryConfigurationProducer" />
|
||||||
|
<option value="com.intellij.execution.junit.AllInPackageConfigurationProducer" />
|
||||||
|
<option value="com.intellij.execution.junit.PatternConfigurationProducer" />
|
||||||
|
<option value="com.intellij.execution.junit.TestInClassConfigurationProducer" />
|
||||||
|
<option value="com.intellij.execution.junit.UniqueIdConfigurationProducer" />
|
||||||
|
<option value="com.intellij.execution.junit.testDiscovery.JUnitTestDiscoveryConfigurationProducer" />
|
||||||
|
<option value="org.jetbrains.kotlin.idea.junit.KotlinJUnitRunConfigurationProducer" />
|
||||||
|
<option value="org.jetbrains.kotlin.idea.junit.KotlinPatternConfigurationProducer" />
|
||||||
|
</set>
|
||||||
|
</option>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
kotlin version: 2.0.21
|
|
||||||
error message: The daemon has terminated unexpectedly on startup attempt #1 with error code: 0. The daemon process output:
|
|
||||||
1. Kotlin compile daemon is ready
|
|
||||||
|
|
||||||
@@ -1,356 +0,0 @@
|
|||||||
# SwipeRecyclerView
|
|
||||||
|
|
||||||
作者的主页:[https://www.yanzhenjie.com](https://www.yanzhenjie.com)
|
|
||||||
技术交流群:[46505645](https://jq.qq.com/?_wv=1027&k=5wY8UWl)
|
|
||||||
|
|
||||||
----
|
|
||||||
|
|
||||||
本库是基于RecyclerView的封装,提供了Item侧滑菜单、Item滑动删除、Item长按拖拽、添加HeaderView/FooterView、加载更多、Item点击监听等基本功能。
|
|
||||||
|
|
||||||
## 特性
|
|
||||||
1. Item侧滑菜单,支持水平分布、垂直分布
|
|
||||||
2. Item长按拖拽、侧滑删除
|
|
||||||
3. 添加/移除HeaderView/FooterView
|
|
||||||
4. **自动/点击**加载更多的功能
|
|
||||||
5. 支持二级列表,List形式、Grid形式、Staggered形式
|
|
||||||
6. Sticky普通布局黏贴和ReyclerView分组黏贴
|
|
||||||
7. 支持AndroidX
|
|
||||||
|
|
||||||
> 使用本库只需要使用SwipeRecyclerView即可,用法和原生RecyclerView一模一样,本库比原生的RecyclerView多了几个扩展方法。
|
|
||||||
|
|
||||||
## 截图
|
|
||||||
对上面提到的效果基本都有演示,但不是全部,更多效果可以下载Demo查看。
|
|
||||||
|
|
||||||
### Item侧滑菜单
|
|
||||||
<img src="./image/1.gif" width="180px"/> <img src="./image/2.gif" width="180px"/> <img src="./image/3.gif" width="180px"/>
|
|
||||||
|
|
||||||
### Item侧滑删除、拖拽
|
|
||||||
<img src="./image/4.gif" width="180px"/> <img src="./image/5.gif" width="180px"/> <img src="./image/6.gif" width="180px"/>
|
|
||||||
|
|
||||||
### 下拉刷新和加载更多
|
|
||||||
<img src="./image/7.gif" width="180px"/>
|
|
||||||
|
|
||||||
### HeaderView和FooterView
|
|
||||||
<img src="./image/8.gif" width="180px"/>
|
|
||||||
|
|
||||||
### Sticky效果和Item分组
|
|
||||||
<img src="./image/9.gif" width="180px"/> <img src="./image/10.gif" width="180px"/>
|
|
||||||
|
|
||||||
### 和DrawerLayout嵌套
|
|
||||||
<img src="./image/11.gif" width="180px"/>
|
|
||||||
|
|
||||||
## 如何使用
|
|
||||||
如果你使用的是android support库,那么请添加下述依赖:
|
|
||||||
```groovy
|
|
||||||
implementation 'com.yanzhenjie.recyclerview:support:1.3.2'
|
|
||||||
```
|
|
||||||
|
|
||||||
如果你使用的是android x库,那么请添加下述依赖:
|
|
||||||
```groovy
|
|
||||||
implementation 'com.yanzhenjie.recyclerview:x:1.3.2'
|
|
||||||
```
|
|
||||||
|
|
||||||
> **1. SwipeRecyclerView从1.3.0版本开始支持AndroidX和二级列表,因此相对于低版本的包名和类名有所改动,从低版本升级的开发者需要考量是否要升级。**
|
|
||||||
**2. 为了让开发者方便切换support库和x库,SwipeRecyclerView的support库和x库除了依赖时的名称不一样外,包名、控件名和类名都是一样的,因此两个库不能共存。**
|
|
||||||
|
|
||||||
### 加入布局
|
|
||||||
在布局的xml中加入`SwipeRecyclerView`:
|
|
||||||
```xml
|
|
||||||
<com.yanzhenjie.recyclerview.SwipeRecyclerView
|
|
||||||
.../>
|
|
||||||
```
|
|
||||||
|
|
||||||
### ItemDecoration
|
|
||||||
也就是分割线,支持Grid形式和Linear形式,可以选择某个ViewType不画分割线:
|
|
||||||
```java
|
|
||||||
// 默认构造,传入颜色即可。
|
|
||||||
ItemDecoration itemDecoration = new DefaultDecoration(color);
|
|
||||||
|
|
||||||
// 或者:颜色,宽,高,最后一个参数是不画分割线的ViewType,可以传入多个。
|
|
||||||
itemDecoration = new DefaultDecoration(color, width, height, excludeViewType);
|
|
||||||
|
|
||||||
// 或者:例如下面的123都是不画分割线的ViewType:
|
|
||||||
itemDecoration = new DefaultDecoration(color, width, height, 1, 2, 3);
|
|
||||||
|
|
||||||
SwipeRecyclerView recyclerView = ...;
|
|
||||||
recyclerView.setDecoration(itemDecoration);
|
|
||||||
```
|
|
||||||
|
|
||||||
### Item点击监听
|
|
||||||
```java
|
|
||||||
recyclerView.setOnItemClickListener(new OnItemClickListener() {
|
|
||||||
@Override
|
|
||||||
public void onItemClick(View view, int position) {
|
|
||||||
// TODO...
|
|
||||||
}
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
### 侧滑菜单
|
|
||||||
```java
|
|
||||||
// 设置监听器。
|
|
||||||
swipeRecyclerView.setSwipeMenuCreator(mSwipeMenuCreator);
|
|
||||||
|
|
||||||
// 创建菜单:
|
|
||||||
SwipeMenuCreator mSwipeMenuCreator = new SwipeMenuCreator() {
|
|
||||||
@Override
|
|
||||||
public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int position) {
|
|
||||||
SwipeMenuItem deleteItem = new SwipeMenuItem(mContext)
|
|
||||||
...; // 各种文字和图标属性设置。
|
|
||||||
leftMenu.addMenuItem(deleteItem); // 在Item左侧添加一个菜单。
|
|
||||||
|
|
||||||
SwipeMenuItem deleteItem = new SwipeMenuItem(mContext)
|
|
||||||
...; // 各种文字和图标属性设置。
|
|
||||||
leftMenu.addMenuItem(deleteItem); // 在Item右侧添加一个菜单。
|
|
||||||
|
|
||||||
// 注意:哪边不想要菜单,那么不要添加即可。
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// 菜单点击监听。
|
|
||||||
swipeRecyclerView.setOnItemMenuClickListener(mItemMenuClickListener);
|
|
||||||
|
|
||||||
OnItemMenuClickListener mItemMenuClickListener = new OnItemMenuClickListener() {
|
|
||||||
@Override
|
|
||||||
public void onItemClick(SwipeMenuBridge menuBridge, int position) {
|
|
||||||
// 任何操作必须先关闭菜单,否则可能出现Item菜单打开状态错乱。
|
|
||||||
menuBridge.closeMenu();
|
|
||||||
|
|
||||||
// 左侧还是右侧菜单:
|
|
||||||
int direction = menuBridge.getDirection();
|
|
||||||
// 菜单在Item中的Position:
|
|
||||||
int menuPosition = menuBridge.getPosition();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
```
|
|
||||||
|
|
||||||
**注意**:菜单需要设置高度,关于菜单高度:
|
|
||||||
1. `MATCH_PARENT`,自动适应Item高度,保持和Item一样高,比较推荐;
|
|
||||||
2. 指定具体的高,比如80;
|
|
||||||
3. `WRAP_CONTENT`,自身高度,极不推荐;
|
|
||||||
|
|
||||||
### 侧滑删除和拖拽
|
|
||||||
拖拽和侧滑删除的功能默认关闭的,所以先要打开功能:
|
|
||||||
```java
|
|
||||||
recyclerView.setLongPressDragEnabled(true); // 拖拽排序,默认关闭。
|
|
||||||
recyclerView.setItemViewSwipeEnabled(true); // 侧滑删除,默认关闭。
|
|
||||||
```
|
|
||||||
|
|
||||||
只需要设置上面两个属性就可以进行相应的动作了,如果不需要哪个,不要打开就可以了。
|
|
||||||
|
|
||||||
然后监听拖拽和侧滑的动作,进行数据更新:
|
|
||||||
```java
|
|
||||||
recyclerView.setOnItemMoveListener(mItemMoveListener);// 监听拖拽,更新UI。
|
|
||||||
|
|
||||||
OnItemMoveListener mItemMoveListener = new OnItemMoveListener() {
|
|
||||||
@Override
|
|
||||||
public boolean onItemMove(ViewHolder srcHolder, ViewHolder targetHolder) {
|
|
||||||
// 此方法在Item拖拽交换位置时被调用。
|
|
||||||
// 第一个参数是要交换为之的Item,第二个是目标位置的Item。
|
|
||||||
|
|
||||||
// 交换数据,并更新adapter。
|
|
||||||
int fromPosition = srcHolder.getAdapterPosition();
|
|
||||||
int toPosition = targetHolder.getAdapterPosition();
|
|
||||||
Collections.swap(mDataList, fromPosition, toPosition);
|
|
||||||
adapter.notifyItemMoved(fromPosition, toPosition);
|
|
||||||
|
|
||||||
// 返回true,表示数据交换成功,ItemView可以交换位置。
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onItemDismiss(ViewHolder srcHolder) {
|
|
||||||
// 此方法在Item在侧滑删除时被调用。
|
|
||||||
|
|
||||||
// 从数据源移除该Item对应的数据,并刷新Adapter。
|
|
||||||
int position = srcHolder.getAdapterPosition();
|
|
||||||
mDataList.remove(position);
|
|
||||||
adapter.notifyItemRemoved(position);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
```
|
|
||||||
|
|
||||||
**特别注意**:如果`LayoutManager`是`List`形式,那么Item拖拽时只能从1-2-3-4这样走,如果你的`LayoutManager`是`Grid`形式的,那么Item可以从1直接到3或者5或者6...,这样数据就会错乱,所以**当`LayoutManager`是Grid形式时**这里要特别注意转换数据位置的算法:
|
|
||||||
```java
|
|
||||||
@Override
|
|
||||||
public boolean onItemMove(ViewHolder srcHolder, ViewHolder targetHolder) {
|
|
||||||
int fromPosition = srcHolder.getAdapterPosition();
|
|
||||||
int toPosition = targetHolder.getAdapterPosition();
|
|
||||||
if (fromPosition < toPosition) {
|
|
||||||
for (int i = fromPosition; i < toPosition; i++) {
|
|
||||||
Collections.swap(mDataList, i, i + 1);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
for (int i = fromPosition; i > toPosition; i--) {
|
|
||||||
Collections.swap(mDataList, i, i - 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
mMenuAdapter.notifyItemMoved(fromPosition, toPosition);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
我们还可以监听用户的侧滑删除和拖拽Item时的手指状态:
|
|
||||||
```java
|
|
||||||
recyclerView.setOnItemStateChangedListener(mStateChangedListener);
|
|
||||||
|
|
||||||
...
|
|
||||||
|
|
||||||
private OnItemStateChangedListener mStateChangedListener = (viewHolder, actionState) -> {
|
|
||||||
if (actionState == OnItemStateChangedListener.ACTION_STATE_DRAG) {
|
|
||||||
// 状态:正在拖拽。
|
|
||||||
} else if (actionState == OnItemStateChangedListener.ACTION_STATE_SWIPE) {
|
|
||||||
// 状态:滑动删除。
|
|
||||||
} else if (actionState == OnItemStateChangedListener.ACTION_STATE_IDLE) {
|
|
||||||
// 状态:手指松开。
|
|
||||||
}
|
|
||||||
};
|
|
||||||
```
|
|
||||||
|
|
||||||
想用户触摸到某个`Item`时就开始拖拽或者侧滑删除时,只需要调用`startDrag()`和`startSwipe()`并转入当前`Item`的`ViewHoler`即可。
|
|
||||||
|
|
||||||
触摸拖拽:
|
|
||||||
```java
|
|
||||||
swipeRecyclerView.startDrag(ViewHolder);
|
|
||||||
```
|
|
||||||
|
|
||||||
触摸侧滑删除:
|
|
||||||
```java
|
|
||||||
swipeRecyclerView.startSwipe(ViewHolder);
|
|
||||||
```
|
|
||||||
|
|
||||||
### HeaderView和FooterView
|
|
||||||
主要方法:
|
|
||||||
```java
|
|
||||||
addHeaderView(View); // 添加HeaderView。
|
|
||||||
removeHeaderView(View); // 移除HeaderView。
|
|
||||||
addFooterView(View); // 添加FooterView。
|
|
||||||
removeFooterView(View); // 移除FooterView。
|
|
||||||
getHeaderItemCount(); // 获取HeaderView个数。
|
|
||||||
getFooterItemCount(); // 获取FooterView个数。
|
|
||||||
getItemViewType(int); // 获取Item的ViewType,包括HeaderView、FooterView、普通ItemView。
|
|
||||||
```
|
|
||||||
添加/移除`HeaderView`/`FooterView`和`setAdapter()`的调用不分先后顺序。
|
|
||||||
|
|
||||||
**特别注意**:
|
|
||||||
1. 如果添加了`HeaderView`,凡是通过`ViewHolder`拿到的`position`都要减掉`HeaderView`的数量才能得到正确的`position`。
|
|
||||||
|
|
||||||
### 加载更多
|
|
||||||
本库默认提供了加载更多的动画和View,开发者也可以自定义,默认支持`RecyclerView`自带的三种布局管理器。
|
|
||||||
|
|
||||||
默认加载更多:
|
|
||||||
```java
|
|
||||||
RecyclerView recyclerView = ...;
|
|
||||||
...
|
|
||||||
|
|
||||||
recyclerView.useDefaultLoadMore(); // 使用默认的加载更多的View。
|
|
||||||
recyclerView.setLoadMoreListener(mLoadMoreListener); // 加载更多的监听。
|
|
||||||
|
|
||||||
LoadMoreListener mLoadMoreListener = new LoadMoreListener() {
|
|
||||||
@Override
|
|
||||||
public void onLoadMore() {
|
|
||||||
// 该加载更多啦。
|
|
||||||
|
|
||||||
... // 请求数据,并更新数据源操作。
|
|
||||||
mMainAdapter.notifyDataSetChanged();
|
|
||||||
|
|
||||||
// 数据完更多数据,一定要调用这个方法。
|
|
||||||
// 第一个参数:表示此次数据是否为空。
|
|
||||||
// 第二个参数:表示是否还有更多数据。
|
|
||||||
mRecyclerView.loadMoreFinish(false, true);
|
|
||||||
|
|
||||||
// 如果加载失败调用下面的方法,传入errorCode和errorMessage。
|
|
||||||
// errorCode随便传,你自定义LoadMoreView时可以根据errorCode判断错误类型。
|
|
||||||
// errorMessage是会显示到loadMoreView上的,用户可以看到。
|
|
||||||
// mRecyclerView.loadMoreError(0, "请求网络失败");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
```
|
|
||||||
|
|
||||||
自定义加载更多View也很简单,自定义一个View,并实现一个接口即可:
|
|
||||||
```java
|
|
||||||
public class DefineLoadMoreView extends LinearLayout
|
|
||||||
implements SwipeRecyclerView.LoadMoreView,
|
|
||||||
View.OnClickListener {
|
|
||||||
|
|
||||||
private LoadMoreListener mLoadMoreListener;
|
|
||||||
|
|
||||||
public DefineLoadMoreView(Context context) {
|
|
||||||
super(context);
|
|
||||||
...
|
|
||||||
setOnClickListener(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 马上开始回调加载更多了,这里应该显示进度条。
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void onLoading() {
|
|
||||||
// 展示加载更多的动画和提示信息。
|
|
||||||
...
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 加载更多完成了。
|
|
||||||
*
|
|
||||||
* @param dataEmpty 是否请求到空数据。
|
|
||||||
* @param hasMore 是否还有更多数据等待请求。
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void onLoadFinish(boolean dataEmpty, boolean hasMore) {
|
|
||||||
// 根据参数,显示没有数据的提示、没有更多数据的提示。
|
|
||||||
// 如果都不存在,则都不用显示。
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 加载出错啦,下面的错误码和错误信息二选一。
|
|
||||||
*
|
|
||||||
* @param errorCode 错误码。
|
|
||||||
* @param errorMessage 错误信息。
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void onLoadError(int errorCode, String errorMessage) {
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 调用了setAutoLoadMore(false)后,在需要加载更多的时候,此方法被调用,并传入listener。
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void onWaitToLoadMore(SwipeRecyclerView.LoadMoreListener loadMoreListener) {
|
|
||||||
this.mLoadMoreListener = loadMoreListener;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 非自动加载更多时mLoadMoreListener才不为空。
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void onClick(View v) {
|
|
||||||
if (mLoadMoreListener != null) mLoadMoreListener.onLoadMore();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## 感谢与参考
|
|
||||||
* [cube-sdk](https://github.com/liaohuqiu/cube-sdk)
|
|
||||||
* [SwipeMenu](https://github.com/TUBB/SwipeMenu/)
|
|
||||||
* [HeaderAndFooterWrapper](https://github.com/hongyangAndroid/baseAdapter/blob/master/baseadapter-recyclerview/src/main/java/com/zhy/adapter/recyclerview/wrapper/HeaderAndFooterWrapper.java)
|
|
||||||
|
|
||||||
加载更多的灵感来自`cube-sdk`,侧滑菜单参考了`SwipeMenu`,添加`HeaderView`参考了`HeaderAndFooterWrapper`类,特别感谢上述开源库及其作者。
|
|
||||||
|
|
||||||
## License
|
|
||||||
```text
|
|
||||||
Copyright 2019 Zhenjie Yan
|
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
you may not use this file except in compliance with the License.
|
|
||||||
You may obtain a copy of the License at
|
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
See the License for the specific language governing permissions and
|
|
||||||
limitations under the License.
|
|
||||||
```
|
|
||||||
+29
-59
@@ -1,14 +1,8 @@
|
|||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
// alias(libs.plugins.android.application)
|
alias(libs.plugins.android.application)
|
||||||
// alias(libs.plugins.kotlin.android)
|
alias(libs.plugins.kotlin.android)
|
||||||
// id("com.google.devtools.ksp") version "2.0.21-1.0.27"
|
id("com.google.devtools.ksp") version "2.0.21-1.0.27"
|
||||||
id("com.android.application")
|
|
||||||
id("org.jetbrains.kotlin.android")
|
|
||||||
// id("com.google.dagger.hilt.android")
|
|
||||||
id("com.google.devtools.ksp")
|
|
||||||
id("kotlin-parcelize")
|
|
||||||
kotlin("kapt")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
android {
|
android {
|
||||||
@@ -16,7 +10,7 @@ android {
|
|||||||
compileSdk = 36
|
compileSdk = 36
|
||||||
|
|
||||||
defaultConfig {
|
defaultConfig {
|
||||||
applicationId = "com.shuwei.dish.match.new"
|
applicationId = "com.shuwei.dish.match"
|
||||||
minSdk = 29
|
minSdk = 29
|
||||||
targetSdk = 36
|
targetSdk = 36
|
||||||
versionCode = 1
|
versionCode = 1
|
||||||
@@ -29,7 +23,7 @@ android {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 设置输出APK文件名格式
|
// 设置输出APK文件名格式
|
||||||
setProperty("archivesBaseName", "pbc_v${versionName}")
|
setProperty("archivesBaseName", "菜品配比终端v${versionName}")
|
||||||
}
|
}
|
||||||
signingConfigs {
|
signingConfigs {
|
||||||
create("debug_507") {
|
create("debug_507") {
|
||||||
@@ -69,7 +63,7 @@ android {
|
|||||||
}
|
}
|
||||||
packagingOptions {
|
packagingOptions {
|
||||||
pickFirst("lib/armeabi-v7a/libserial_port.so")
|
pickFirst("lib/armeabi-v7a/libserial_port.so")
|
||||||
pickFirst("lib/arme64-v8a/libserial_port.so")
|
pickFirst("lib/arm64-v8a/libserial_port.so")
|
||||||
}
|
}
|
||||||
sourceSets {
|
sourceSets {
|
||||||
named("main") {
|
named("main") {
|
||||||
@@ -83,9 +77,7 @@ android {
|
|||||||
}
|
}
|
||||||
// li
|
// li
|
||||||
}
|
}
|
||||||
val isDebug = gradle.startParameter.taskNames.any {
|
|
||||||
it.contains("debug", ignoreCase = true)
|
|
||||||
}
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation(fileTree("libs") { include("*.jar", "*.aar") })
|
implementation(fileTree("libs") { include("*.jar", "*.aar") })
|
||||||
implementation(libs.androidx.core.ktx)
|
implementation(libs.androidx.core.ktx)
|
||||||
@@ -97,57 +89,35 @@ dependencies {
|
|||||||
testImplementation(libs.junit)
|
testImplementation(libs.junit)
|
||||||
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.fragment.ktx)
|
|
||||||
implementation(libs.androidx.lifecycle.runtime.ktx)
|
|
||||||
implementation(libs.androidx.lifecycle.viewmodel.ktx)
|
|
||||||
|
|
||||||
implementation(libs.gson)
|
implementation("com.squareup.okhttp3:okhttp:4.9.1")
|
||||||
implementation(libs.okhttp)
|
implementation("com.squareup.okhttp3:logging-interceptor:4.9.1")
|
||||||
implementation(libs.logging.interceptor)
|
implementation("com.squareup.retrofit2:retrofit:2.9.0")
|
||||||
implementation(libs.retrofit)
|
implementation("com.squareup.retrofit2:converter-gson:2.9.0")
|
||||||
implementation(libs.java.websocket)
|
implementation("com.google.code.gson:gson:2.10.1")
|
||||||
implementation(libs.converter.gson)
|
// implementation("com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.30")
|
||||||
implementation(libs.flexbox)
|
|
||||||
|
|
||||||
implementation(libs.baserecyclerviewadapterhelper4)
|
implementation("io.github.cymchad:BaseRecyclerViewAdapterHelper4:4.1.2")
|
||||||
|
|
||||||
// room
|
implementation("androidx.room:room-runtime:2.5.2")
|
||||||
implementation(libs.androidx.room.runtime)
|
ksp("androidx.room:room-compiler:2.5.2")
|
||||||
ksp(libs.androidx.room.compiler)
|
implementation("androidx.room:room-ktx:2.5.2") // Kotlin扩展
|
||||||
implementation(libs.androidx.room.ktx)
|
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.7")
|
||||||
|
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.7")
|
||||||
|
implementation("androidx.activity:activity-ktx:1.8.0")
|
||||||
|
|
||||||
// implementation("biz.laenger.android:vpbs:0.0.6")
|
// implementation("biz.laenger.android:vpbs:0.0.6")
|
||||||
|
|
||||||
// refresh-layout
|
//必须 1.0.0 以上
|
||||||
implementation(libs.refresh.layout.kernel)
|
implementation("io.github.scwang90:refresh-layout-kernel:3.0.0-alpha")
|
||||||
implementation(libs.refresh.header.classics)
|
//核心必须依赖
|
||||||
implementation(libs.refresh.header.radar)
|
implementation("io.github.scwang90:refresh-header-classics:3.0.0-alpha")
|
||||||
implementation(libs.refresh.footer.classics)
|
//经典刷新头
|
||||||
|
implementation("io.github.scwang90:refresh-header-radar:3.0.0-alpha")
|
||||||
|
implementation("io.github.scwang90:refresh-footer-classics:3.0.0-alpha")
|
||||||
|
//经典加载
|
||||||
|
|
||||||
//implementation("com.geyifeng.immersionbar:immersionbar:3.2.2")
|
//implementation("com.geyifeng.immersionbar:immersionbar:3.2.2")
|
||||||
|
|
||||||
// glide
|
implementation("com.google.android.flexbox:flexbox:3.0.0")
|
||||||
implementation(libs.glide)
|
|
||||||
annotationProcessor(libs.compiler)
|
|
||||||
|
|
||||||
// camerax
|
|
||||||
implementation(libs.androidx.camera.core)
|
|
||||||
implementation(libs.androidx.camera.camera2)
|
|
||||||
implementation(libs.androidx.camera.lifecycle)
|
|
||||||
implementation(libs.androidx.camera.view)
|
|
||||||
implementation(libs.androidx.camera.extensions)
|
|
||||||
|
|
||||||
//pytorch
|
|
||||||
implementation (libs.pytorch.android)
|
|
||||||
implementation (libs.pytorch.android.torchvision)
|
|
||||||
|
|
||||||
// objectbox
|
|
||||||
if (isDebug) {
|
|
||||||
debugImplementation(libs.objectbox.android.objectbrowser)
|
|
||||||
} else {
|
|
||||||
releaseImplementation(libs.objectbox.android)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
apply(plugin = "io.objectbox")
|
|
||||||
Binary file not shown.
@@ -1,54 +0,0 @@
|
|||||||
{
|
|
||||||
"_note1": "KEEP THIS FILE! Check it into a version control system (VCS) like git.",
|
|
||||||
"_note2": "ObjectBox manages crucial IDs for your object model. See docs for details.",
|
|
||||||
"_note3": "If you have VCS merge conflicts, you must resolve them according to ObjectBox docs.",
|
|
||||||
"entities": [
|
|
||||||
{
|
|
||||||
"id": "1:6465153867413579585",
|
|
||||||
"lastPropertyId": "5:7592685238899911344",
|
|
||||||
"name": "Food",
|
|
||||||
"properties": [
|
|
||||||
{
|
|
||||||
"id": "1:3688350375714699356",
|
|
||||||
"name": "id",
|
|
||||||
"type": 6,
|
|
||||||
"flags": 1
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "2:6503828433160216329",
|
|
||||||
"name": "name",
|
|
||||||
"type": 9
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "3:1726525909323356793",
|
|
||||||
"name": "foodIdx",
|
|
||||||
"type": 5
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "4:3660727688686055762",
|
|
||||||
"name": "foodVector",
|
|
||||||
"indexId": "1:5497952887792054610",
|
|
||||||
"type": 28,
|
|
||||||
"flags": 8
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "5:7592685238899911344",
|
|
||||||
"name": "version",
|
|
||||||
"type": 9
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"relations": []
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"lastEntityId": "1:6465153867413579585",
|
|
||||||
"lastIndexId": "1:5497952887792054610",
|
|
||||||
"lastRelationId": "0:0",
|
|
||||||
"lastSequenceId": "0:0",
|
|
||||||
"modelVersion": 5,
|
|
||||||
"modelVersionParserMinimum": 5,
|
|
||||||
"retiredEntityUids": [],
|
|
||||||
"retiredIndexUids": [],
|
|
||||||
"retiredPropertyUids": [],
|
|
||||||
"retiredRelationUids": [],
|
|
||||||
"version": 1
|
|
||||||
}
|
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,15 +1,11 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
xmlns:tools="http://schemas.android.com/tools">
|
xmlns:tools="http://schemas.android.com/tools"
|
||||||
<!-- android:sharedUserId="android.uid.system" -->
|
android:sharedUserId="android.uid.system">
|
||||||
|
|
||||||
<uses-feature android:name="android.hardware.usb.host" />
|
<uses-feature android:name="android.hardware.usb.host" />
|
||||||
|
|
||||||
<uses-feature
|
|
||||||
android:name="android.hardware.camera"
|
|
||||||
android:required="false" />
|
|
||||||
|
|
||||||
<uses-permission android:name="android.permission.INTERNET" />
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
<uses-permission android:name="android.permission.CAMERA" />
|
|
||||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
||||||
<uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE"
|
<uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE"
|
||||||
tools:ignore="ProtectedPermissions" />
|
tools:ignore="ProtectedPermissions" />
|
||||||
@@ -45,9 +41,7 @@
|
|||||||
<activity
|
<activity
|
||||||
android:name=".ui.InitActivity"
|
android:name=".ui.InitActivity"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
android:launchMode="singleTask"
|
|
||||||
android:screenOrientation="portrait"
|
android:screenOrientation="portrait"
|
||||||
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>
|
||||||
<action android:name="android.intent.action.MAIN" />
|
<action android:name="android.intent.action.MAIN" />
|
||||||
@@ -56,59 +50,24 @@
|
|||||||
</intent-filter>
|
</intent-filter>
|
||||||
</activity>
|
</activity>
|
||||||
<activity android:name=".ui.HomeActivity"
|
<activity android:name=".ui.HomeActivity"
|
||||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
|
||||||
android:screenOrientation="portrait"
|
|
||||||
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"
|
android:screenOrientation="portrait"
|
||||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||||
|
|
||||||
<activity
|
<activity
|
||||||
android:name=".ui.CookingModeActivity"
|
android:name=".ui.SelectDishActivity"
|
||||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
|
||||||
android:launchMode="singleTask"
|
android:launchMode="singleTask"
|
||||||
android:screenOrientation="portrait"
|
android:screenOrientation="portrait"
|
||||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||||
<activity
|
<activity
|
||||||
android:name=".ui.PrepareFoodActivity"
|
android:name=".ui.PrepareCookActivity"
|
||||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
|
||||||
android:screenOrientation="portrait"
|
android:screenOrientation="portrait"
|
||||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||||
<!-- <activity-->
|
|
||||||
<!-- android:name=".ui.DishSamplingActivity"-->
|
|
||||||
<!-- android:theme="@style/Theme.DishMatch.NoSplash"-->
|
|
||||||
<!-- android:screenOrientation="portrait"-->
|
|
||||||
<!-- tools:ignore="DiscouragedApi,LockedOrientationActivity" />-->
|
|
||||||
<activity
|
<activity
|
||||||
android:name=".ui.SamplingModeActivity"
|
android:name=".ui.DishSamplingActivity"
|
||||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
android:screenOrientation="portrait"
|
||||||
|
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||||
|
<activity
|
||||||
|
android:name=".ui.SamplingListActivity"
|
||||||
android:launchMode="singleTask"
|
android:launchMode="singleTask"
|
||||||
android:screenOrientation="portrait"
|
android:screenOrientation="portrait"
|
||||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||||
@@ -123,43 +82,10 @@
|
|||||||
<!-- tools:ignore="DiscouragedApi,LockedOrientationActivity" />-->
|
<!-- tools:ignore="DiscouragedApi,LockedOrientationActivity" />-->
|
||||||
<activity
|
<activity
|
||||||
android:name=".ui.FoodSearchActivity"
|
android:name=".ui.FoodSearchActivity"
|
||||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
|
||||||
android:screenOrientation="portrait"
|
android:screenOrientation="portrait"
|
||||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||||
<!-- <activity android:name="com.shuwei.dish.match.ui.DeviceConfigActivity"-->
|
<activity android:name="com.shuwei.dish.match.ui.DeviceConfigActivity" />
|
||||||
<!-- android:theme="@style/Theme.DishMatch.NoSplash" />-->
|
<activity android:name="com.shuwei.dish.match.ui.SubmitFoodActivity" />
|
||||||
<activity android:name="com.shuwei.dish.match.ui.SettingActivity"
|
|
||||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
|
||||||
android:screenOrientation="portrait"
|
|
||||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
|
||||||
<activity android:name="com.shuwei.dish.match.ui.SubmitFoodActivity"
|
|
||||||
android:theme="@style/Theme.DishMatch.NoSplash" />
|
|
||||||
<activity
|
|
||||||
android:name="com.shuwei.dish.match.ui.MasterScaleActivity"
|
|
||||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
|
||||||
android:screenOrientation="portrait"
|
|
||||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
|
||||||
<activity
|
|
||||||
android:name="com.shuwei.dish.match.ui.SingleFragmentActivity"
|
|
||||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
|
||||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
|
||||||
<activity
|
|
||||||
android:name="com.shuwei.dish.match.ui.FoodRecognizeActivity"
|
|
||||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
|
||||||
android:screenOrientation="portrait"
|
|
||||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
|
||||||
<activity
|
|
||||||
android:name="com.shuwei.dish.match.ui.CollectedFoodActivity"
|
|
||||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
|
||||||
android:screenOrientation="portrait"
|
|
||||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
|
||||||
<activity
|
|
||||||
android:name="com.shuwei.dish.match.ui.SlaveActivity"
|
|
||||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
|
||||||
android:launchMode="singleTask"
|
|
||||||
android:screenOrientation="landscape"
|
|
||||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
|
||||||
<activity android:name="com.shuwei.dish.match.ui.FoodSearchV2Activity" />
|
|
||||||
|
|
||||||
<receiver
|
<receiver
|
||||||
android:name=".utils.BootReceiver"
|
android:name=".utils.BootReceiver"
|
||||||
|
|||||||
@@ -1,272 +0,0 @@
|
|||||||
{
|
|
||||||
"class_names": [
|
|
||||||
"三黄鸡",
|
|
||||||
"上海青WP2026020200041",
|
|
||||||
"冰草WP2026020900054",
|
|
||||||
"刀豆",
|
|
||||||
"北豆腐WP2025111900007",
|
|
||||||
"味精WP2026013000034",
|
|
||||||
"圆生菜WP2026020900053",
|
|
||||||
"圆白菜[卷心菜,包菜]WP2025111000063",
|
|
||||||
"基围虾WP2025110700019",
|
|
||||||
"多宝鱼WP2025112600011",
|
|
||||||
"大白菜(代表值)WP2026022800638",
|
|
||||||
"大葱WP2026013000025",
|
|
||||||
"姜[黄姜]WP2026022800956",
|
|
||||||
"娃娃菜WP2026020200005",
|
|
||||||
"小白菜WP2026022800031",
|
|
||||||
"小米辣椒WP2026013000027",
|
|
||||||
"小葱WP2026013000029",
|
|
||||||
"山药(带皮)WP2026020200008",
|
|
||||||
"巨人笋",
|
|
||||||
"广东菜心WP2025120100014",
|
|
||||||
"木耳(干)[黑木耳,云耳]WP2026022801182",
|
|
||||||
"杏鲍菇WP2026022700030",
|
|
||||||
"松花蛋",
|
|
||||||
"松茸菌WP2025120100016",
|
|
||||||
"沙葱",
|
|
||||||
"海带(浸)[江白菜,昆布]WP2026022800035",
|
|
||||||
"牛腩WP2025110700043",
|
|
||||||
"猪五花肉WP2026020300048",
|
|
||||||
"猪腿肉WP2025110700040",
|
|
||||||
"玉米WP2025120100017",
|
|
||||||
"玉米糁(黄)WP2026022800038",
|
|
||||||
"番茄[西红柿]WP2026021000028",
|
|
||||||
"白吉饼WP2026013000024",
|
|
||||||
"笋",
|
|
||||||
"粉丝",
|
|
||||||
"紫甘蓝",
|
|
||||||
"红心萝卜[心里美]WP2026022800368",
|
|
||||||
"红提子WP2025111900006",
|
|
||||||
"红椒WP2026030300055",
|
|
||||||
"红洋葱WP2026030600054",
|
|
||||||
"红美人椒WP2026020300049",
|
|
||||||
"红薯",
|
|
||||||
"红薯粉条(袋)",
|
|
||||||
"羊排WP2025120300021",
|
|
||||||
"羊血WP2026013000038",
|
|
||||||
"胡萝卜WP2025110600008",
|
|
||||||
"芋头",
|
|
||||||
"花卷",
|
|
||||||
"芹菜WP2025111000065",
|
|
||||||
"苦菊",
|
|
||||||
"茄子(紫皮,长)WP2025110700024",
|
|
||||||
"茼蒿WP2026020200045",
|
|
||||||
"莲藕(带皮)",
|
|
||||||
"莴笋(鲜)[莴苣]WP2026020200009",
|
|
||||||
"菜花(白色)[花椰菜]",
|
|
||||||
"菠菜(鲜)[赤根菜]WP2026022800700",
|
|
||||||
"蒜WP2025111400003",
|
|
||||||
"蒜苗WP2026013000028",
|
|
||||||
"蒜薹(圆)",
|
|
||||||
"蒸鱼豉油WP2026013000032",
|
|
||||||
"薏米[薏仁米,苡米]WP2026022800037",
|
|
||||||
"西兰花[绿菜花]WP2025110700029",
|
|
||||||
"西葫芦",
|
|
||||||
"豆腐皮WP2025111000059",
|
|
||||||
"豆角",
|
|
||||||
"辣椒(红,小)WP2025111000066",
|
|
||||||
"辣椒(青,尖)WP2026022800504",
|
|
||||||
"醪糟",
|
|
||||||
"金针菇[(鲜)[智力菇]WP2026030600051",
|
|
||||||
"青线椒WP2026013000031",
|
|
||||||
"韭菜WP2026020200044",
|
|
||||||
"韭黄",
|
|
||||||
"馒头(代表值)WP2026030600056",
|
|
||||||
"香椿[香椿芽]WP2026022801086",
|
|
||||||
"香菇(鲜)[香蕈,冬菇]WP2026030600050",
|
|
||||||
"香菜WP2026013000030",
|
|
||||||
"马铃薯[土豆、洋芋]WP2026012900001",
|
|
||||||
"鸡全腿(带骨)",
|
|
||||||
"鸡翅(带骨)",
|
|
||||||
"鸡腿肉WP2025110700048",
|
|
||||||
"鸡腿(带骨)",
|
|
||||||
"鸡蛋WP2026013000039",
|
|
||||||
"麦芹",
|
|
||||||
"黄瓜(鲜)[胡瓜]WP2025110700031",
|
|
||||||
"黄豆芽WP2026020200042",
|
|
||||||
"黑袋子",
|
|
||||||
"黑鱼(整条鱼)WP2025110600012"
|
|
||||||
],
|
|
||||||
"class_to_idx": {
|
|
||||||
"三黄鸡": 0,
|
|
||||||
"上海青WP2026020200041": 1,
|
|
||||||
"冰草WP2026020900054": 2,
|
|
||||||
"刀豆": 3,
|
|
||||||
"北豆腐WP2025111900007": 4,
|
|
||||||
"味精WP2026013000034": 5,
|
|
||||||
"圆生菜WP2026020900053": 6,
|
|
||||||
"圆白菜[卷心菜,包菜]WP2025111000063": 7,
|
|
||||||
"基围虾WP2025110700019": 8,
|
|
||||||
"多宝鱼WP2025112600011": 9,
|
|
||||||
"大白菜(代表值)WP2026022800638": 10,
|
|
||||||
"大葱WP2026013000025": 11,
|
|
||||||
"姜[黄姜]WP2026022800956": 12,
|
|
||||||
"娃娃菜WP2026020200005": 13,
|
|
||||||
"小白菜WP2026022800031": 14,
|
|
||||||
"小米辣椒WP2026013000027": 15,
|
|
||||||
"小葱WP2026013000029": 16,
|
|
||||||
"山药(带皮)WP2026020200008": 17,
|
|
||||||
"巨人笋": 18,
|
|
||||||
"广东菜心WP2025120100014": 19,
|
|
||||||
"木耳(干)[黑木耳,云耳]WP2026022801182": 20,
|
|
||||||
"杏鲍菇WP2026022700030": 21,
|
|
||||||
"松花蛋": 22,
|
|
||||||
"松茸菌WP2025120100016": 23,
|
|
||||||
"沙葱": 24,
|
|
||||||
"海带(浸)[江白菜,昆布]WP2026022800035": 25,
|
|
||||||
"牛腩WP2025110700043": 26,
|
|
||||||
"猪五花肉WP2026020300048": 27,
|
|
||||||
"猪腿肉WP2025110700040": 28,
|
|
||||||
"玉米WP2025120100017": 29,
|
|
||||||
"玉米糁(黄)WP2026022800038": 30,
|
|
||||||
"番茄[西红柿]WP2026021000028": 31,
|
|
||||||
"白吉饼WP2026013000024": 32,
|
|
||||||
"笋": 33,
|
|
||||||
"粉丝": 34,
|
|
||||||
"紫甘蓝": 35,
|
|
||||||
"红心萝卜[心里美]WP2026022800368": 36,
|
|
||||||
"红提子WP2025111900006": 37,
|
|
||||||
"红椒WP2026030300055": 38,
|
|
||||||
"红洋葱WP2026030600054": 39,
|
|
||||||
"红美人椒WP2026020300049": 40,
|
|
||||||
"红薯": 41,
|
|
||||||
"红薯粉条(袋)": 42,
|
|
||||||
"羊排WP2025120300021": 43,
|
|
||||||
"羊血WP2026013000038": 44,
|
|
||||||
"胡萝卜WP2025110600008": 45,
|
|
||||||
"芋头": 46,
|
|
||||||
"花卷": 47,
|
|
||||||
"芹菜WP2025111000065": 48,
|
|
||||||
"苦菊": 49,
|
|
||||||
"茄子(紫皮,长)WP2025110700024": 50,
|
|
||||||
"茼蒿WP2026020200045": 51,
|
|
||||||
"莲藕(带皮)": 52,
|
|
||||||
"莴笋(鲜)[莴苣]WP2026020200009": 53,
|
|
||||||
"菜花(白色)[花椰菜]": 54,
|
|
||||||
"菠菜(鲜)[赤根菜]WP2026022800700": 55,
|
|
||||||
"蒜WP2025111400003": 56,
|
|
||||||
"蒜苗WP2026013000028": 57,
|
|
||||||
"蒜薹(圆)": 58,
|
|
||||||
"蒸鱼豉油WP2026013000032": 59,
|
|
||||||
"薏米[薏仁米,苡米]WP2026022800037": 60,
|
|
||||||
"西兰花[绿菜花]WP2025110700029": 61,
|
|
||||||
"西葫芦": 62,
|
|
||||||
"豆腐皮WP2025111000059": 63,
|
|
||||||
"豆角": 64,
|
|
||||||
"辣椒(红,小)WP2025111000066": 65,
|
|
||||||
"辣椒(青,尖)WP2026022800504": 66,
|
|
||||||
"醪糟": 67,
|
|
||||||
"金针菇[(鲜)[智力菇]WP2026030600051": 68,
|
|
||||||
"青线椒WP2026013000031": 69,
|
|
||||||
"韭菜WP2026020200044": 70,
|
|
||||||
"韭黄": 71,
|
|
||||||
"馒头(代表值)WP2026030600056": 72,
|
|
||||||
"香椿[香椿芽]WP2026022801086": 73,
|
|
||||||
"香菇(鲜)[香蕈,冬菇]WP2026030600050": 74,
|
|
||||||
"香菜WP2026013000030": 75,
|
|
||||||
"马铃薯[土豆、洋芋]WP2026012900001": 76,
|
|
||||||
"鸡全腿(带骨)": 77,
|
|
||||||
"鸡翅(带骨)": 78,
|
|
||||||
"鸡腿肉WP2025110700048": 79,
|
|
||||||
"鸡腿(带骨)": 80,
|
|
||||||
"鸡蛋WP2026013000039": 81,
|
|
||||||
"麦芹": 82,
|
|
||||||
"黄瓜(鲜)[胡瓜]WP2025110700031": 83,
|
|
||||||
"黄豆芽WP2026020200042": 84,
|
|
||||||
"黑袋子": 85,
|
|
||||||
"黑鱼(整条鱼)WP2025110600012": 86
|
|
||||||
},
|
|
||||||
"idx_to_class": {
|
|
||||||
"0": "三黄鸡",
|
|
||||||
"1": "上海青WP2026020200041",
|
|
||||||
"2": "冰草WP2026020900054",
|
|
||||||
"3": "刀豆",
|
|
||||||
"4": "北豆腐WP2025111900007",
|
|
||||||
"5": "味精WP2026013000034",
|
|
||||||
"6": "圆生菜WP2026020900053",
|
|
||||||
"7": "圆白菜[卷心菜,包菜]WP2025111000063",
|
|
||||||
"8": "基围虾WP2025110700019",
|
|
||||||
"9": "多宝鱼WP2025112600011",
|
|
||||||
"10": "大白菜(代表值)WP2026022800638",
|
|
||||||
"11": "大葱WP2026013000025",
|
|
||||||
"12": "姜[黄姜]WP2026022800956",
|
|
||||||
"13": "娃娃菜WP2026020200005",
|
|
||||||
"14": "小白菜WP2026022800031",
|
|
||||||
"15": "小米辣椒WP2026013000027",
|
|
||||||
"16": "小葱WP2026013000029",
|
|
||||||
"17": "山药(带皮)WP2026020200008",
|
|
||||||
"18": "巨人笋",
|
|
||||||
"19": "广东菜心WP2025120100014",
|
|
||||||
"20": "木耳(干)[黑木耳,云耳]WP2026022801182",
|
|
||||||
"21": "杏鲍菇WP2026022700030",
|
|
||||||
"22": "松花蛋",
|
|
||||||
"23": "松茸菌WP2025120100016",
|
|
||||||
"24": "沙葱",
|
|
||||||
"25": "海带(浸)[江白菜,昆布]WP2026022800035",
|
|
||||||
"26": "牛腩WP2025110700043",
|
|
||||||
"27": "猪五花肉WP2026020300048",
|
|
||||||
"28": "猪腿肉WP2025110700040",
|
|
||||||
"29": "玉米WP2025120100017",
|
|
||||||
"30": "玉米糁(黄)WP2026022800038",
|
|
||||||
"31": "番茄[西红柿]WP2026021000028",
|
|
||||||
"32": "白吉饼WP2026013000024",
|
|
||||||
"33": "笋",
|
|
||||||
"34": "粉丝",
|
|
||||||
"35": "紫甘蓝",
|
|
||||||
"36": "红心萝卜[心里美]WP2026022800368",
|
|
||||||
"37": "红提子WP2025111900006",
|
|
||||||
"38": "红椒WP2026030300055",
|
|
||||||
"39": "红洋葱WP2026030600054",
|
|
||||||
"40": "红美人椒WP2026020300049",
|
|
||||||
"41": "红薯",
|
|
||||||
"42": "红薯粉条(袋)",
|
|
||||||
"43": "羊排WP2025120300021",
|
|
||||||
"44": "羊血WP2026013000038",
|
|
||||||
"45": "胡萝卜WP2025110600008",
|
|
||||||
"46": "芋头",
|
|
||||||
"47": "花卷",
|
|
||||||
"48": "芹菜WP2025111000065",
|
|
||||||
"49": "苦菊",
|
|
||||||
"50": "茄子(紫皮,长)WP2025110700024",
|
|
||||||
"51": "茼蒿WP2026020200045",
|
|
||||||
"52": "莲藕(带皮)",
|
|
||||||
"53": "莴笋(鲜)[莴苣]WP2026020200009",
|
|
||||||
"54": "菜花(白色)[花椰菜]",
|
|
||||||
"55": "菠菜(鲜)[赤根菜]WP2026022800700",
|
|
||||||
"56": "蒜WP2025111400003",
|
|
||||||
"57": "蒜苗WP2026013000028",
|
|
||||||
"58": "蒜薹(圆)",
|
|
||||||
"59": "蒸鱼豉油WP2026013000032",
|
|
||||||
"60": "薏米[薏仁米,苡米]WP2026022800037",
|
|
||||||
"61": "西兰花[绿菜花]WP2025110700029",
|
|
||||||
"62": "西葫芦",
|
|
||||||
"63": "豆腐皮WP2025111000059",
|
|
||||||
"64": "豆角",
|
|
||||||
"65": "辣椒(红,小)WP2025111000066",
|
|
||||||
"66": "辣椒(青,尖)WP2026022800504",
|
|
||||||
"67": "醪糟",
|
|
||||||
"68": "金针菇[(鲜)[智力菇]WP2026030600051",
|
|
||||||
"69": "青线椒WP2026013000031",
|
|
||||||
"70": "韭菜WP2026020200044",
|
|
||||||
"71": "韭黄",
|
|
||||||
"72": "馒头(代表值)WP2026030600056",
|
|
||||||
"73": "香椿[香椿芽]WP2026022801086",
|
|
||||||
"74": "香菇(鲜)[香蕈,冬菇]WP2026030600050",
|
|
||||||
"75": "香菜WP2026013000030",
|
|
||||||
"76": "马铃薯[土豆、洋芋]WP2026012900001",
|
|
||||||
"77": "鸡全腿(带骨)",
|
|
||||||
"78": "鸡翅(带骨)",
|
|
||||||
"79": "鸡腿肉WP2025110700048",
|
|
||||||
"80": "鸡腿(带骨)",
|
|
||||||
"81": "鸡蛋WP2026013000039",
|
|
||||||
"82": "麦芹",
|
|
||||||
"83": "黄瓜(鲜)[胡瓜]WP2025110700031",
|
|
||||||
"84": "黄豆芽WP2026020200042",
|
|
||||||
"85": "黑袋子",
|
|
||||||
"86": "黑鱼(整条鱼)WP2025110600012"
|
|
||||||
},
|
|
||||||
"embedding_dim": 512,
|
|
||||||
"total_images": 2093,
|
|
||||||
"build_time": "2026-03-10T10:33:47.104848"
|
|
||||||
}
|
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,31 +0,0 @@
|
|||||||
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.ListItemCollectedFoodBinding
|
|
||||||
import com.shuwei.dish.match.model.CollectedFoodItem
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 已采集食材列表适配器
|
|
||||||
* 展示食材名称和已采集数量,支持删除操作
|
|
||||||
*/
|
|
||||||
class CollectedFoodAdapter(list: MutableList<CollectedFoodItem>) :
|
|
||||||
BaseQuickAdapter<CollectedFoodItem, CollectedFoodAdapter.VH>(list) {
|
|
||||||
|
|
||||||
/** ViewHolder,持有列表项 ViewBinding */
|
|
||||||
inner class VH(val binding: ListItemCollectedFoodBinding) : QuickViewHolder(binding.root)
|
|
||||||
|
|
||||||
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
|
||||||
val binding = ListItemCollectedFoodBinding.inflate(LayoutInflater.from(context), parent, false)
|
|
||||||
return VH(binding)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onBindViewHolder(holder: VH, position: Int, item: CollectedFoodItem?) {
|
|
||||||
item ?: return
|
|
||||||
holder.binding.tvFoodName.text = item.foodName.split("WP").first()
|
|
||||||
holder.binding.tvCollectCount.text = "已采集${item.collectCount}"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package com.shuwei.dish.match.adapter
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
|
import com.chad.library.adapter4.BaseQuickAdapter
|
||||||
|
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||||
|
import com.shuwei.dish.match.R
|
||||||
|
import com.shuwei.dish.match.databinding.ListItemDishCookBinding
|
||||||
|
import com.shuwei.dish.match.model.GoodsItem
|
||||||
|
import com.shuwei.dish.match.utils.ext.roundedOneDecimalPlace
|
||||||
|
|
||||||
|
class DishPartAdapter(list: MutableList<GoodsItem>) :
|
||||||
|
BaseQuickAdapter<GoodsItem, DishPartAdapter.VH>(list) {
|
||||||
|
|
||||||
|
inner class VH(var binding: ListItemDishCookBinding) : QuickViewHolder(binding.root)
|
||||||
|
|
||||||
|
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
||||||
|
val inflater = LayoutInflater.from(context)
|
||||||
|
val binding = ListItemDishCookBinding.inflate(inflater, parent, false)
|
||||||
|
return VH(binding)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBindViewHolder(holder: VH, position: Int, item: GoodsItem?) {
|
||||||
|
holder.binding.run {
|
||||||
|
tvDishName.text = item!!.goodsName
|
||||||
|
tvDishType.text = if (item.materialType == 1) "主辅材:主材" else if (item.materialType == 2) "主辅材:辅材" else ""
|
||||||
|
tvDishWeight.text =
|
||||||
|
if (item.useWeight == null || item.useWeight == 0.toDouble()) "" else "${item.useWeight!!.roundedOneDecimalPlace()}克"
|
||||||
|
tvDishWeight.setTextColor(
|
||||||
|
ContextCompat.getColor(
|
||||||
|
context,
|
||||||
|
if (item.isSamplingPage) R.color.black999 else R.color.dish_green
|
||||||
|
)
|
||||||
|
)
|
||||||
|
ivOperateIcon.setImageResource(
|
||||||
|
if (item.isSamplingPage)
|
||||||
|
R.drawable.ic_delete
|
||||||
|
else
|
||||||
|
if (item.isSetFinished) R.drawable.ic_dish_selected
|
||||||
|
else R.drawable.ic_dish_unselected
|
||||||
|
)
|
||||||
|
root.setBackgroundResource(
|
||||||
|
if (item.isClicked) R.drawable.shape_item_cook_dish
|
||||||
|
else R.drawable.shape_white_fb_15_corners
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
package com.shuwei.dish.match.adapter
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
|
import com.chad.library.adapter4.BaseQuickAdapter
|
||||||
|
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||||
|
import com.shuwei.dish.match.R
|
||||||
|
import com.shuwei.dish.match.model.FoodRecord
|
||||||
|
import com.shuwei.dish.match.databinding.ListItemDishBinding
|
||||||
|
import com.shuwei.dish.match.utils.ext.gone
|
||||||
|
import com.shuwei.dish.match.utils.ext.visible
|
||||||
|
import java.text.DecimalFormat
|
||||||
|
|
||||||
|
class DishShowAdapter(list: MutableList<FoodRecord>) :
|
||||||
|
BaseQuickAdapter<FoodRecord, DishShowAdapter.VH>(list) {
|
||||||
|
|
||||||
|
inner class VH(var binding: ListItemDishBinding) : QuickViewHolder(binding.root)
|
||||||
|
|
||||||
|
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
||||||
|
val inflater = LayoutInflater.from(context)
|
||||||
|
val binding = ListItemDishBinding.inflate(inflater, parent, false)
|
||||||
|
return VH(binding)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBindViewHolder(holder: VH, position: Int, item: FoodRecord?) {
|
||||||
|
holder.binding.run {
|
||||||
|
val isCooking = item!!.isCooking
|
||||||
|
val totalWeight = item.totalWeight ?: 0.toDouble()
|
||||||
|
tvDishName.text = item!!.foodName
|
||||||
|
if (isCooking) {
|
||||||
|
tvDishName.setTextColor(
|
||||||
|
ContextCompat.getColor(holder.itemView.context, R.color.black)
|
||||||
|
)
|
||||||
|
clBlock.setBackgroundResource(R.drawable.shape_white_fb_15_corners)
|
||||||
|
tvDishCount.visible()
|
||||||
|
tvDishCount.text = "制作统计:-kg"
|
||||||
|
tvShowState.text = "烹饪中"
|
||||||
|
} else if (totalWeight > 0.toDouble()) {
|
||||||
|
tvDishName.setTextColor(
|
||||||
|
ContextCompat.getColor(holder.itemView.context, R.color.dish_green)
|
||||||
|
)
|
||||||
|
clBlock.setBackgroundResource(R.drawable.shape_white_fb_15_corners)
|
||||||
|
tvDishCount.visible()
|
||||||
|
tvDishCount.text =
|
||||||
|
"累计统计:${df.format(totalWeight / 1000.0F)}kg(${item.count}次)"
|
||||||
|
tvShowState.text = "${df.format((item.foodWeight ?: 0.toDouble()) / 1000.0F)}kg"
|
||||||
|
} else {
|
||||||
|
tvDishName.setTextColor(
|
||||||
|
ContextCompat.getColor(holder.itemView.context, R.color.black999)
|
||||||
|
)
|
||||||
|
clBlock.setBackgroundResource(R.drawable.shape_white_dash_15_corners)
|
||||||
|
tvDishCount.gone()
|
||||||
|
tvShowState.text = "-"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val df = DecimalFormat("0.000")
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
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()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
package com.shuwei.dish.match.adapter
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.view.LayoutInflater
|
|
||||||
import android.view.View
|
|
||||||
import android.view.ViewGroup
|
|
||||||
import com.chad.library.adapter4.BaseQuickAdapter
|
|
||||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
|
||||||
import com.shuwei.dish.match.databinding.ListItemFood3Binding
|
|
||||||
import com.shuwei.dish.match.model.GoodsItem
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 向量采集页面的适配器
|
|
||||||
*/
|
|
||||||
class Food3Adapter(list: MutableList<GoodsItem>) :
|
|
||||||
BaseQuickAdapter<GoodsItem, Food3Adapter.VH>(list) {
|
|
||||||
|
|
||||||
override fun onBindViewHolder(
|
|
||||||
holder: VH,
|
|
||||||
position: Int,
|
|
||||||
item: GoodsItem?
|
|
||||||
) {
|
|
||||||
item ?: return
|
|
||||||
holder.binding.tvFoodName.run {
|
|
||||||
text = item.goodsName
|
|
||||||
isChecked = item.isClicked
|
|
||||||
}
|
|
||||||
// 显示当前选中的净材种类,无数据时隐藏
|
|
||||||
holder.binding.tvRawMaterialsType.run {
|
|
||||||
if (item.rawMaterialsType.isNullOrEmpty()) {
|
|
||||||
visibility = View.GONE
|
|
||||||
} else {
|
|
||||||
visibility = View.VISIBLE
|
|
||||||
text = item.rawMaterialsType
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onCreateViewHolder(
|
|
||||||
context: Context,
|
|
||||||
parent: ViewGroup,
|
|
||||||
viewType: Int
|
|
||||||
): VH {
|
|
||||||
val binding = ListItemFood3Binding.inflate(LayoutInflater.from(context), parent, false)
|
|
||||||
return VH(binding)
|
|
||||||
}
|
|
||||||
|
|
||||||
inner class VH(var binding: ListItemFood3Binding) : QuickViewHolder(binding.root)
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
package com.shuwei.dish.match.adapter
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.view.LayoutInflater
|
|
||||||
import android.view.ViewGroup
|
|
||||||
import androidx.core.content.ContextCompat
|
|
||||||
import com.chad.library.adapter4.BaseQuickAdapter
|
|
||||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
|
||||||
import com.shuwei.dish.match.R
|
|
||||||
import com.shuwei.dish.match.databinding.ListItemFoodBinding
|
|
||||||
import com.shuwei.dish.match.model.GoodsItem
|
|
||||||
import com.shuwei.dish.match.utils.ext.gone
|
|
||||||
import com.shuwei.dish.match.utils.ext.roundedDecimalPlace
|
|
||||||
import com.shuwei.dish.match.utils.ext.visible
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 识别页面和搜索弹窗的适配器
|
|
||||||
*/
|
|
||||||
class FoodAdapter(list: MutableList<GoodsItem>) :
|
|
||||||
BaseQuickAdapter<GoodsItem, FoodAdapter.VH>(list) {
|
|
||||||
|
|
||||||
override fun onBindViewHolder(
|
|
||||||
holder: VH,
|
|
||||||
position: Int,
|
|
||||||
item: GoodsItem?
|
|
||||||
) {
|
|
||||||
item ?: return
|
|
||||||
holder.binding.root.run {
|
|
||||||
setBackgroundResource(
|
|
||||||
if (item.isClicked) R.drawable.shape_green_stroke
|
|
||||||
else R.drawable.shape_white_12_corners
|
|
||||||
)
|
|
||||||
}
|
|
||||||
holder.binding.tvGoodsInfo.run {
|
|
||||||
text = item.goodsName
|
|
||||||
setTextColor(
|
|
||||||
ContextCompat.getColor(
|
|
||||||
context,
|
|
||||||
if (item.isClicked) R.color.dish_green
|
|
||||||
else R.color.black666
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
if (item.foodScore == -1) {
|
|
||||||
holder.binding.tvFoodScore.gone()
|
|
||||||
} else {
|
|
||||||
holder.binding.tvFoodScore.let {
|
|
||||||
it.visible()
|
|
||||||
val foodScoreText = "${(item.foodScore / 100.0).roundedDecimalPlace(2)}%"
|
|
||||||
it.text = foodScoreText
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (item.rawMaterialsType.isNullOrBlank()) {
|
|
||||||
holder.binding.tvRawMaterialsType.gone()
|
|
||||||
} else {
|
|
||||||
holder.binding.tvRawMaterialsType.let {
|
|
||||||
it.visible()
|
|
||||||
it.text = item.rawMaterialsType
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onCreateViewHolder(
|
|
||||||
context: Context,
|
|
||||||
parent: ViewGroup,
|
|
||||||
viewType: Int
|
|
||||||
): VH {
|
|
||||||
val binding =
|
|
||||||
ListItemFoodBinding.inflate(LayoutInflater.from(context), parent, false)
|
|
||||||
return VH(binding)
|
|
||||||
}
|
|
||||||
|
|
||||||
inner class VH(var binding: ListItemFoodBinding) : QuickViewHolder(binding.root)
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,100 +0,0 @@
|
|||||||
package com.shuwei.dish.match.adapter
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.view.LayoutInflater
|
|
||||||
import android.view.ViewGroup
|
|
||||||
import androidx.core.content.ContextCompat
|
|
||||||
import com.chad.library.adapter4.BaseQuickAdapter
|
|
||||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
|
||||||
import com.shuwei.dish.match.R
|
|
||||||
import com.shuwei.dish.match.databinding.ListItemFoodListBinding
|
|
||||||
import com.shuwei.dish.match.model.FoodRecord
|
|
||||||
import com.shuwei.dish.match.utils.ext.gone
|
|
||||||
import com.shuwei.dish.match.utils.ext.visible
|
|
||||||
import java.text.DecimalFormat
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 菜品列表通用 Adapter,合并了 DishShowAdapter 与 SamplingAdapter 的功能。
|
|
||||||
*
|
|
||||||
* @param list 数据列表
|
|
||||||
* @param mode 显示模式:
|
|
||||||
* - [DisplayMode.COOKING_MODE]:制作模式,支持空状态(虚线边框、隐藏统计行、灰色文字)
|
|
||||||
* - [DisplayMode.SAMPLING_MODE]:采样模式,始终显示统计行,重量为零时显示 `-`
|
|
||||||
*/
|
|
||||||
class FoodListAdapter(
|
|
||||||
list: MutableList<FoodRecord>,
|
|
||||||
private val mode: DisplayMode = DisplayMode.COOKING_MODE
|
|
||||||
) : BaseQuickAdapter<FoodRecord, FoodListAdapter.VH>(list) {
|
|
||||||
|
|
||||||
/** 显示模式枚举 */
|
|
||||||
enum class DisplayMode {
|
|
||||||
/** 制作模式(原 DishShowAdapter 逻辑) */
|
|
||||||
COOKING_MODE,
|
|
||||||
/** 采样模式(原 SamplingAdapter 逻辑) */
|
|
||||||
SAMPLING_MODE
|
|
||||||
}
|
|
||||||
|
|
||||||
/** item 主体点击回调 */
|
|
||||||
var onItemClick: ((position: Int) -> Unit)? = null
|
|
||||||
|
|
||||||
inner class VH(var binding: ListItemFoodListBinding) : QuickViewHolder(binding.root)
|
|
||||||
|
|
||||||
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
|
||||||
val binding = ListItemFoodListBinding.inflate(LayoutInflater.from(context), parent, false)
|
|
||||||
return VH(binding)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* - 烹饪中:黑色文字、实线背景、显示"烹饪中"
|
|
||||||
* - 有累计重量:绿色文字、实线背景、显示累计统计
|
|
||||||
* - 空状态:灰色文字、虚线背景、隐藏统计行
|
|
||||||
*/
|
|
||||||
override fun onBindViewHolder(holder: VH, position: Int, item: FoodRecord?) {
|
|
||||||
holder.binding.run {
|
|
||||||
val isCooking = item!!.isCooking
|
|
||||||
val totalWeight = item.totalWeight ?: 0.0
|
|
||||||
val foodWeight = item.foodWeight ?: 0.0
|
|
||||||
|
|
||||||
clBlock.setOnClickListener {
|
|
||||||
onItemClick?.invoke(holder.bindingAdapterPosition)
|
|
||||||
}
|
|
||||||
|
|
||||||
tvDishName.text = item.foodName
|
|
||||||
// 烹饪中
|
|
||||||
if (isCooking) {
|
|
||||||
tvDishName.setTextColor(ContextCompat.getColor(holder.itemView.context, R.color.black))
|
|
||||||
clBlock.setBackgroundResource(R.drawable.shape_white_fb_15_corners)
|
|
||||||
tvDishCount.visible()
|
|
||||||
tvDishCount.text = "制作统计:-kg"
|
|
||||||
tvShowState.text = "烹饪中"
|
|
||||||
return@run
|
|
||||||
}
|
|
||||||
// 非烹饪中,制作模式
|
|
||||||
if (mode == DisplayMode.COOKING_MODE) {
|
|
||||||
if (totalWeight > 0.0) {
|
|
||||||
tvDishName.setTextColor(ContextCompat.getColor(holder.itemView.context, R.color.dish_green))
|
|
||||||
clBlock.setBackgroundResource(R.drawable.shape_white_fb_15_corners)
|
|
||||||
tvDishCount.visible()
|
|
||||||
tvDishCount.text = "累计统计:${df.format(totalWeight / 1000.0F)}kg(${item.count}次)"
|
|
||||||
tvShowState.text = "${df.format(foodWeight / 1000.0F)}kg"
|
|
||||||
} else {
|
|
||||||
tvDishName.setTextColor(ContextCompat.getColor(holder.itemView.context, R.color.black999))
|
|
||||||
clBlock.setBackgroundResource(R.drawable.shape_white_dash_15_corners)
|
|
||||||
tvDishCount.gone()
|
|
||||||
tvShowState.text = "-"
|
|
||||||
}
|
|
||||||
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 showTotalWeight = if (realTotalWeight == 0.0) "-" else df.format(realTotalWeight / 1000.0F)
|
|
||||||
tvDishCount.text = "累计统计:${showTotalWeight}kg(${item.count ?: "-"}次)"
|
|
||||||
val showFoodWeight = if (foodWeight == 0.0) "-" else df.format(foodWeight / 1000.0F)
|
|
||||||
tvShowState.text = "${showFoodWeight}kg"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private val df = DecimalFormat("0.000")
|
|
||||||
}
|
|
||||||
@@ -1,86 +0,0 @@
|
|||||||
package com.shuwei.dish.match.adapter
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.res.ColorStateList
|
|
||||||
import android.view.LayoutInflater
|
|
||||||
import android.view.ViewGroup
|
|
||||||
import androidx.core.content.ContextCompat
|
|
||||||
import com.chad.library.adapter4.BaseQuickAdapter
|
|
||||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
|
||||||
import com.shuwei.dish.match.R
|
|
||||||
import com.shuwei.dish.match.databinding.ListItemFoodMaterialBinding
|
|
||||||
import com.shuwei.dish.match.model.GoodsItem
|
|
||||||
import com.shuwei.dish.match.utils.ext.gone
|
|
||||||
import com.shuwei.dish.match.utils.ext.roundedOneDecimalPlace
|
|
||||||
import com.shuwei.dish.match.utils.ext.visible
|
|
||||||
import androidx.core.graphics.toColorInt
|
|
||||||
import com.shuwei.dish.match.ui.MaterialTypeTool
|
|
||||||
|
|
||||||
class FoodMaterialAdapter(list: MutableList<GoodsItem>) :
|
|
||||||
BaseQuickAdapter<GoodsItem, FoodMaterialAdapter.VH>(list) {
|
|
||||||
|
|
||||||
/** item 主体点击回调 */
|
|
||||||
var onItemClick: ((position: Int) -> Unit)? = null
|
|
||||||
|
|
||||||
inner class VH(var binding: ListItemFoodMaterialBinding) : QuickViewHolder(binding.root)
|
|
||||||
|
|
||||||
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
|
||||||
val inflater = LayoutInflater.from(context)
|
|
||||||
val binding = ListItemFoodMaterialBinding.inflate(inflater, parent, false)
|
|
||||||
return VH(binding)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onBindViewHolder(holder: VH, position: Int, item: GoodsItem?) {
|
|
||||||
holder.binding.run {
|
|
||||||
val data = item ?: return
|
|
||||||
|
|
||||||
clBlock.setOnClickListener {
|
|
||||||
onItemClick?.invoke(holder.bindingAdapterPosition)
|
|
||||||
}
|
|
||||||
tvDishName.text = data.goodsName
|
|
||||||
//if (data.isOriginalData) {
|
|
||||||
// tvDishName.text = data.goodsName
|
|
||||||
//} else {
|
|
||||||
// tvDishName.text = data.goodsName + "-${data.rawMaterialsType}"
|
|
||||||
//}
|
|
||||||
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 =
|
|
||||||
if (data.useWeight == null || data.useWeight == 0.toDouble()) "" else "${data.useWeight!!.roundedOneDecimalPlace()}克"
|
|
||||||
tvDishWeight.setTextColor(
|
|
||||||
ContextCompat.getColor(
|
|
||||||
context,
|
|
||||||
if (data.isSamplingPage) R.color.black999 else R.color.dish_green
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
ivOperateIcon.run {
|
|
||||||
if (data.isSamplingPage) gone() else visible()
|
|
||||||
}
|
|
||||||
// ivClearIcon.visible()
|
|
||||||
// ivClearIcon.setImageResource(
|
|
||||||
// if (data.isOriginalData) R.drawable.ic_dish_clear
|
|
||||||
// else R.drawable.ic_delete
|
|
||||||
// )
|
|
||||||
// isOriginalData 时根据是否有重量信息控制图标颜色:无重量染灰色,有重量恢复原色
|
|
||||||
if (data.isOriginalData) {
|
|
||||||
val hasWeight = data.useWeight != null && data.useWeight != 0.0
|
|
||||||
ivClearIcon.imageTintList = if (hasWeight) null
|
|
||||||
else ColorStateList.valueOf("#BFBFBF".toColorInt())
|
|
||||||
} else {
|
|
||||||
ivClearIcon.imageTintList = null
|
|
||||||
}
|
|
||||||
ivOperateIcon.setImageResource(
|
|
||||||
if (data.isSetFinished) R.drawable.ic_dish_selected
|
|
||||||
else R.drawable.ic_dish_unselected
|
|
||||||
)
|
|
||||||
clBlock.setBackgroundResource(
|
|
||||||
if (data.isClicked) R.drawable.shape_item_cook_dish
|
|
||||||
else R.drawable.shape_white_fb_15_corners
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+5
-8
@@ -5,16 +5,13 @@ import android.view.LayoutInflater
|
|||||||
import android.view.ViewGroup
|
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.ListItemDishRecordBinding
|
||||||
import com.shuwei.dish.match.model.FoodRecord
|
import com.shuwei.dish.match.model.FoodRecord
|
||||||
|
|
||||||
/**
|
class FoodRecordAdapter(list: MutableList<FoodRecord>) :
|
||||||
* 菜品搜索页面的适配器
|
BaseQuickAdapter<FoodRecord, FoodRecordAdapter.VH>(list) {
|
||||||
*/
|
|
||||||
class Food2Adapter(list: MutableList<FoodRecord>) :
|
|
||||||
BaseQuickAdapter<FoodRecord, Food2Adapter.VH>(list) {
|
|
||||||
|
|
||||||
inner class VH(var binding: ListItemFood2Binding) : QuickViewHolder(binding.root)
|
inner class VH(var binding: ListItemDishRecordBinding) : QuickViewHolder(binding.root)
|
||||||
|
|
||||||
override fun onBindViewHolder(
|
override fun onBindViewHolder(
|
||||||
holder: VH,
|
holder: VH,
|
||||||
@@ -30,7 +27,7 @@ class Food2Adapter(list: MutableList<FoodRecord>) :
|
|||||||
viewType: Int
|
viewType: Int
|
||||||
): VH {
|
): VH {
|
||||||
val inflater = LayoutInflater.from(context)
|
val inflater = LayoutInflater.from(context)
|
||||||
val binding = ListItemFood2Binding.inflate(inflater, parent, false)
|
val binding = ListItemDishRecordBinding.inflate(inflater, parent, false)
|
||||||
return VH(binding)
|
return VH(binding)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,245 +0,0 @@
|
|||||||
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,49 @@
|
|||||||
|
package com.shuwei.dish.match.adapter
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
|
import com.chad.library.adapter4.BaseQuickAdapter
|
||||||
|
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||||
|
import com.shuwei.dish.match.R
|
||||||
|
import com.shuwei.dish.match.databinding.ListItemSearchGoodsInfoBinding
|
||||||
|
import com.shuwei.dish.match.model.GoodsItem
|
||||||
|
|
||||||
|
class GoodsInfoSearchAdapter(private var list: MutableList<GoodsItem>) :
|
||||||
|
BaseQuickAdapter<GoodsItem, GoodsInfoSearchAdapter.VH>(list) {
|
||||||
|
|
||||||
|
override fun onBindViewHolder(
|
||||||
|
holder: VH,
|
||||||
|
position: Int,
|
||||||
|
item: GoodsItem?
|
||||||
|
) {
|
||||||
|
holder.binding.tvGoodsInfo.run {
|
||||||
|
text = item?.goodsName
|
||||||
|
setBackgroundResource(
|
||||||
|
if (item?.isClicked == true) R.drawable.shape_green_stroke
|
||||||
|
else R.drawable.shape_white_12_corners
|
||||||
|
)
|
||||||
|
setTextColor(
|
||||||
|
ContextCompat.getColor(
|
||||||
|
context,
|
||||||
|
if (item?.isClicked == true) R.color.dish_green
|
||||||
|
else R.color.black666
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreateViewHolder(
|
||||||
|
context: Context,
|
||||||
|
parent: ViewGroup,
|
||||||
|
viewType: Int
|
||||||
|
): VH {
|
||||||
|
val binding =
|
||||||
|
ListItemSearchGoodsInfoBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||||
|
return VH(binding)
|
||||||
|
}
|
||||||
|
|
||||||
|
inner class VH(var binding: ListItemSearchGoodsInfoBinding) : QuickViewHolder(binding.root)
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
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"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
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"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,149 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package com.shuwei.dish.match.adapter
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
|
import com.chad.library.adapter4.BaseQuickAdapter
|
||||||
|
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||||
|
import com.shuwei.dish.match.R
|
||||||
|
import com.shuwei.dish.match.model.FoodRecord
|
||||||
|
import com.shuwei.dish.match.databinding.ListItemDishBinding
|
||||||
|
import com.shuwei.dish.match.utils.ext.gone
|
||||||
|
import com.shuwei.dish.match.utils.ext.visible
|
||||||
|
import java.text.DecimalFormat
|
||||||
|
|
||||||
|
class SamplingAdapter(list: MutableList<FoodRecord>) :
|
||||||
|
BaseQuickAdapter<FoodRecord, SamplingAdapter.VH>(list) {
|
||||||
|
|
||||||
|
inner class VH(var binding: ListItemDishBinding) : QuickViewHolder(binding.root)
|
||||||
|
|
||||||
|
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
||||||
|
val inflater = LayoutInflater.from(context)
|
||||||
|
val binding = ListItemDishBinding.inflate(inflater, parent, false)
|
||||||
|
return VH(binding)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBindViewHolder(holder: VH, position: Int, item: FoodRecord?) {
|
||||||
|
holder.binding.run {
|
||||||
|
val isCooking = item!!.isCooking
|
||||||
|
clBlock.setBackgroundResource(R.drawable.shape_white_fb_15_corners)
|
||||||
|
val totalWeight = item!!.totalWeight ?: 0.toDouble()
|
||||||
|
tvDishName.run {
|
||||||
|
text = item!!.foodName
|
||||||
|
setTextColor(
|
||||||
|
ContextCompat.getColor(
|
||||||
|
holder.itemView.context,
|
||||||
|
if (isCooking) R.color.black else R.color.dish_green
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
tvDishCount.visible()
|
||||||
|
if (isCooking) {
|
||||||
|
tvDishCount.text = "制作统计:-kg"
|
||||||
|
tvShowState.text = "烹饪中"
|
||||||
|
} else {
|
||||||
|
val useWeight = if (totalWeight > 0.toDouble()) totalWeight else (item.foodWeight ?: 0.toDouble())
|
||||||
|
tvDishCount.text = "累计统计:${df.format(useWeight / 1000.0F)}kg(${item.count}次)"
|
||||||
|
tvShowState.text = "${df.format((item.foodWeight ?: 0.toDouble()) / 1000.0F)}kg"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val df = DecimalFormat("0.000")
|
||||||
|
}
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
package com.shuwei.dish.match.adapter
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.view.LayoutInflater
|
|
||||||
import android.view.ViewGroup
|
|
||||||
import androidx.core.content.ContextCompat
|
|
||||||
import androidx.recyclerview.widget.RecyclerView
|
|
||||||
import com.chad.library.adapter4.BaseQuickAdapter
|
|
||||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
|
||||||
import com.shuwei.dish.match.R
|
|
||||||
import com.shuwei.dish.match.databinding.ListItemScaleRowBinding
|
|
||||||
import com.shuwei.dish.match.utils.WeightUtil
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 线性列表秤数据 Adapter
|
|
||||||
* 用于 SlaveActivity 非22/18格子设备的秤列表展示
|
|
||||||
* 通过 updateItem / updateName / removeByAddress 同步更新,避免 submitList 的
|
|
||||||
* AsyncListDiffer 异步窗口期导致点击事件丢失
|
|
||||||
*/
|
|
||||||
class ScaleRowAdapter : BaseQuickAdapter<ScaleRowAdapter.ScaleItem, ScaleRowAdapter.VH>() {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 秤数据条目
|
|
||||||
* @param address 秤地址
|
|
||||||
* @param weight 重量(克)
|
|
||||||
* @param state 状态码
|
|
||||||
* @param name 调料名称,未配置时为空
|
|
||||||
*/
|
|
||||||
data class ScaleItem(val address: Int, val weight: Double, val state: Int, val name: String = "")
|
|
||||||
|
|
||||||
/** item 点击回调 */
|
|
||||||
var onItemClick: ((ScaleItem) -> Unit)? = null
|
|
||||||
|
|
||||||
inner class VH(val b: ListItemScaleRowBinding) : QuickViewHolder(b.root)
|
|
||||||
|
|
||||||
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
|
||||||
return VH(ListItemScaleRowBinding.inflate(LayoutInflater.from(context), parent, false))
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onBindViewHolder(holder: VH, position: Int, item: ScaleItem?) {
|
|
||||||
item ?: return
|
|
||||||
holder.b.tvScaleLabel.text = "秤 ${item.address}"
|
|
||||||
holder.b.tvName.text = item.name.ifEmpty { "-" }
|
|
||||||
holder.b.tvWeight.text = "${item.weight} g"
|
|
||||||
holder.b.tvState.text = WeightUtil.getStateStr(item.state)
|
|
||||||
if (item.state == WeightUtil.STATE_OVER_WEIGHT) {
|
|
||||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell_over_weight)
|
|
||||||
val white = ContextCompat.getColor(holder.b.root.context, R.color.white)
|
|
||||||
holder.b.tvScaleLabel.setTextColor(white)
|
|
||||||
holder.b.tvName.setTextColor(white)
|
|
||||||
holder.b.tvWeight.setTextColor(white)
|
|
||||||
holder.b.tvState.setTextColor(white)
|
|
||||||
} else {
|
|
||||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell)
|
|
||||||
holder.b.tvScaleLabel.setTextColor(ContextCompat.getColor(holder.b.root.context, R.color.black))
|
|
||||||
holder.b.tvName.setTextColor(ContextCompat.getColor(holder.b.root.context, R.color.black))
|
|
||||||
holder.b.tvWeight.setTextColor(ContextCompat.getColor(holder.b.root.context, R.color.home_title))
|
|
||||||
holder.b.tvState.setTextColor(ContextCompat.getColor(holder.b.root.context, R.color.home_sub_title))
|
|
||||||
}
|
|
||||||
// 点击时通过 bindingAdapterPosition 取最新数据,避免闭包捕获过期 item
|
|
||||||
holder.b.root.setOnClickListener {
|
|
||||||
val pos = holder.bindingAdapterPosition
|
|
||||||
if (pos != RecyclerView.NO_POSITION) {
|
|
||||||
items.getOrNull(pos)?.let { onItemClick?.invoke(it) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 同步更新单条秤数据:存在则定点刷新,不存在则按 address 升序插入
|
|
||||||
* 使用 set/add 替代 submitList,消除 AsyncListDiffer 异步窗口期
|
|
||||||
* @param item 最新秤数据
|
|
||||||
*/
|
|
||||||
fun updateItem(item: ScaleItem) {
|
|
||||||
val idx = items.indexOfFirst { it.address == item.address }
|
|
||||||
if (idx >= 0) {
|
|
||||||
set(idx, item)
|
|
||||||
} else {
|
|
||||||
// 找到按 address 升序的插入位置
|
|
||||||
val insertPos = items.indexOfFirst { it.address > item.address }
|
|
||||||
.let { if (it < 0) items.size else it }
|
|
||||||
add(insertPos, item)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 同步更新指定地址的调料名称
|
|
||||||
* @param address 秤地址
|
|
||||||
* @param name 新名称
|
|
||||||
*/
|
|
||||||
fun updateName(address: Int, name: String) {
|
|
||||||
val idx = items.indexOfFirst { it.address == address }
|
|
||||||
if (idx >= 0) set(idx, items[idx].copy(name = name))
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 同步移除指定地址的条目
|
|
||||||
* @param address 秤地址
|
|
||||||
*/
|
|
||||||
fun removeByAddress(address: Int) {
|
|
||||||
val idx = items.indexOfFirst { it.address == address }
|
|
||||||
if (idx >= 0) removeAt(idx)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,177 +0,0 @@
|
|||||||
package com.shuwei.dish.match.adapter
|
|
||||||
|
|
||||||
import android.annotation.SuppressLint
|
|
||||||
import android.content.Context
|
|
||||||
import android.view.LayoutInflater
|
|
||||||
import android.view.View
|
|
||||||
import android.view.ViewGroup
|
|
||||||
import androidx.core.content.ContextCompat
|
|
||||||
import androidx.core.view.updateLayoutParams
|
|
||||||
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.ListItemScale22RowBinding
|
|
||||||
import com.shuwei.dish.match.scale.ScaleData
|
|
||||||
import com.shuwei.dish.match.scale.ScaleDeviceConfig
|
|
||||||
import com.shuwei.dish.match.utils.WeightUtil
|
|
||||||
import com.shuwei.dish.match.utils.ext.dp
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 18格网格 Adapter,同时服务于调料配置页和主设备秤总览页。
|
|
||||||
*
|
|
||||||
* @param showNameOnly true = 调料配置模式,仅显示 tvName,隐藏 tvWeight/tvState;
|
|
||||||
* false = 秤总览模式,三行全部显示
|
|
||||||
* @param showAddress true = 显示秤地址行(tvAddress),仅 MasterScaleActivity 使用
|
|
||||||
*/
|
|
||||||
class Seasoning18GridAdapter(
|
|
||||||
private val showNameOnly: Boolean = false,
|
|
||||||
private val showAddress: Boolean = false,
|
|
||||||
private val leftRightSpace: Int = 10.dp
|
|
||||||
) : BaseQuickAdapter<ScaleData, Seasoning18GridAdapter.VH>(mutableListOf()) {
|
|
||||||
|
|
||||||
/** 空位哨兵,address=0 表示无效 */
|
|
||||||
private val empty = ScaleData("", 0, 0.0, -1, 0)
|
|
||||||
|
|
||||||
/** 当前高亮的格子位置,-1 表示无高亮 */
|
|
||||||
private var highlightedPosition: Int = -1
|
|
||||||
|
|
||||||
/** 点击回调 */
|
|
||||||
var onItemClick: ((ScaleData, Int) -> Unit)? = null
|
|
||||||
|
|
||||||
inner class VH(val b: ListItemScale22RowBinding) : QuickViewHolder(b.root)
|
|
||||||
|
|
||||||
/** 前6个位置为第1行(viewType=0,margin大),其余为第2-3行(viewType=1,margin小) */
|
|
||||||
override fun getItemViewType(position: Int, list: List<ScaleData>) =
|
|
||||||
if (position < 6) 0 else 1
|
|
||||||
|
|
||||||
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
|
||||||
val b = ListItemScale22RowBinding.inflate(LayoutInflater.from(context), parent, false)
|
|
||||||
val margin = if (viewType == 0) 12.dp else 2.dp
|
|
||||||
val screenWidth = parent.resources.displayMetrics.widthPixels
|
|
||||||
val cellSize = (screenWidth - 6 * margin * 2 - leftRightSpace) / 6
|
|
||||||
b.root.updateLayoutParams<ViewGroup.MarginLayoutParams> {
|
|
||||||
width = cellSize
|
|
||||||
height = cellSize
|
|
||||||
if (viewType == 0) setMargins(margin, 0, margin, 2.dp)
|
|
||||||
else setMargins(margin, margin, margin, margin)
|
|
||||||
}
|
|
||||||
val baseSp = (cellSize / parent.resources.displayMetrics.density).toInt()
|
|
||||||
b.tvAddress.textSize = (baseSp * 0.14f).coerceIn(8f, 12f)
|
|
||||||
b.tvName.textSize = (baseSp * 0.18f).coerceIn(10f, 16f)
|
|
||||||
b.tvWeight.textSize = (baseSp * 0.22f).coerceIn(12f, 20f)
|
|
||||||
b.tvState.textSize = (baseSp * 0.14f).coerceIn(8f, 12f)
|
|
||||||
// 秤地址行:仅 MasterScaleActivity 显示
|
|
||||||
b.tvAddress.visibility = if (showAddress) View.VISIBLE else View.GONE
|
|
||||||
// 调料配置模式隐藏重量和状态行
|
|
||||||
if (showNameOnly) {
|
|
||||||
b.tvWeight.visibility = View.GONE
|
|
||||||
b.tvState.visibility = View.GONE
|
|
||||||
}
|
|
||||||
val vh = VH(b)
|
|
||||||
b.root.setOnClickListener {
|
|
||||||
val pos = vh.bindingAdapterPosition
|
|
||||||
if (pos != RecyclerView.NO_POSITION) {
|
|
||||||
items.getOrNull(pos)?.takeIf { it.address != 0 }?.let { item -> onItemClick?.invoke(item, pos) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return vh
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressLint("SetTextI18n")
|
|
||||||
override fun onBindViewHolder(holder: VH, position: Int, item: ScaleData?) {
|
|
||||||
val valid = (item?.address ?: 0) != 0
|
|
||||||
if (!valid) {
|
|
||||||
holder.b.tvAddress.text = ""
|
|
||||||
holder.b.tvName.text = "-"
|
|
||||||
holder.b.tvWeight.text = ""
|
|
||||||
holder.b.tvState.text = ""
|
|
||||||
} else {
|
|
||||||
holder.b.tvAddress.text = "秤${item!!.address}"
|
|
||||||
holder.b.tvName.text = if (!item.name.isNullOrBlank()) item.name else "-"
|
|
||||||
holder.b.tvWeight.text = "${item.weight}g"
|
|
||||||
holder.b.tvState.text = WeightUtil.getStateStr(item.state)
|
|
||||||
}
|
|
||||||
val white = ContextCompat.getColor(holder.b.root.context, R.color.white)
|
|
||||||
when {
|
|
||||||
valid && item!!.state == WeightUtil.STATE_OVER_WEIGHT -> {
|
|
||||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell_over_weight)
|
|
||||||
holder.b.tvAddress.setTextColor(white)
|
|
||||||
holder.b.tvName.setTextColor(white)
|
|
||||||
holder.b.tvWeight.setTextColor(white)
|
|
||||||
holder.b.tvState.setTextColor(white)
|
|
||||||
}
|
|
||||||
position == highlightedPosition -> {
|
|
||||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell_highlight)
|
|
||||||
holder.b.tvAddress.setTextColor(white)
|
|
||||||
holder.b.tvName.setTextColor(white)
|
|
||||||
holder.b.tvWeight.setTextColor(white)
|
|
||||||
holder.b.tvState.setTextColor(white)
|
|
||||||
}
|
|
||||||
else -> {
|
|
||||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell)
|
|
||||||
val normal = ContextCompat.getColor(holder.b.root.context, R.color.home_title)
|
|
||||||
val sub = ContextCompat.getColor(holder.b.root.context, R.color.home_sub_title)
|
|
||||||
val black = ContextCompat.getColor(holder.b.root.context, R.color.black)
|
|
||||||
holder.b.tvAddress.setTextColor(sub)
|
|
||||||
holder.b.tvName.setTextColor(black)
|
|
||||||
holder.b.tvWeight.setTextColor(normal)
|
|
||||||
holder.b.tvState.setTextColor(sub)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 高亮指定位置的格子(红底白字),同时清除上一个高亮
|
|
||||||
*/
|
|
||||||
fun highlightPosition(position: Int) {
|
|
||||||
val prev = highlightedPosition
|
|
||||||
highlightedPosition = position
|
|
||||||
if (prev >= 0) notifyItemChanged(prev)
|
|
||||||
if (position >= 0) notifyItemChanged(position)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 清除所有高亮,恢复默认样式
|
|
||||||
*/
|
|
||||||
fun clearHighlight() {
|
|
||||||
highlightPosition(-1)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 更新指定位置的名称并刷新对应格子
|
|
||||||
*/
|
|
||||||
fun updateItemName(position: Int, name: String) {
|
|
||||||
items.getOrNull(position)?.let {
|
|
||||||
set(position, it.copy(name = name))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 按 SCALE_ORDER_18 的 sort 顺序更新数据,空位用哨兵填充
|
|
||||||
* 只更新显示字段有变化的格子,避免全量刷新导致 ViewHolder 重建影响点击监听
|
|
||||||
*/
|
|
||||||
fun update(list: List<ScaleData>) {
|
|
||||||
val byAddress = list.associateBy { it.address }
|
|
||||||
val filled = ScaleDeviceConfig.SCALE_ORDER_18.map { addr ->
|
|
||||||
byAddress[addr] ?: empty.copy(address = addr)
|
|
||||||
}
|
|
||||||
if (items.isEmpty()) {
|
|
||||||
submitList(filled)
|
|
||||||
} else {
|
|
||||||
filled.forEachIndexed { i, scale ->
|
|
||||||
val cur = items.getOrNull(i)
|
|
||||||
if (cur == null || cur.address != scale.address || cur.weight != scale.weight || cur.state != scale.state || cur.name != scale.name) {
|
|
||||||
set(i, scale)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 将 ScaleData 列表按 SCALE_ORDER_18 重排后调用 update
|
|
||||||
*/
|
|
||||||
fun updateByAddress(scales: List<ScaleData>) {
|
|
||||||
update(scales)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,182 +0,0 @@
|
|||||||
package com.shuwei.dish.match.adapter
|
|
||||||
|
|
||||||
import android.annotation.SuppressLint
|
|
||||||
import android.content.Context
|
|
||||||
import android.view.LayoutInflater
|
|
||||||
import android.view.View
|
|
||||||
import android.view.ViewGroup
|
|
||||||
import androidx.core.content.ContextCompat
|
|
||||||
import androidx.core.view.updateLayoutParams
|
|
||||||
import androidx.recyclerview.widget.RecyclerView
|
|
||||||
import com.chad.library.adapter4.BaseQuickAdapter
|
|
||||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
|
||||||
import com.google.android.flexbox.FlexboxLayoutManager
|
|
||||||
import com.shuwei.dish.match.R
|
|
||||||
import com.shuwei.dish.match.databinding.ListItemScale22RowBinding
|
|
||||||
import com.shuwei.dish.match.scale.ScaleData
|
|
||||||
import com.shuwei.dish.match.scale.ScaleDeviceConfig
|
|
||||||
import com.shuwei.dish.match.utils.SizeTool
|
|
||||||
import com.shuwei.dish.match.utils.WeightUtil
|
|
||||||
import com.shuwei.dish.match.utils.ext.dp
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 22格网格 Adapter,同时服务于调料配置页和主设备秤总览页。
|
|
||||||
*
|
|
||||||
* @param largeSize 前4个大格子的宽度(px)
|
|
||||||
* @param smallSize 其余小格子的宽度(px)
|
|
||||||
* @param cellAspectRatio 格子高宽比(height / width)
|
|
||||||
* @param showNameOnly true = 调料配置模式,仅显示 tvName,隐藏 tvWeight/tvState;
|
|
||||||
* false = 秤总览模式,三行全部显示
|
|
||||||
* @param showAddress true = 显示秤地址行(tvAddress),仅 MasterScaleActivity 使用
|
|
||||||
*/
|
|
||||||
class Seasoning22GridAdapter(
|
|
||||||
private val largeSize: Int,
|
|
||||||
private val smallSize: Int,
|
|
||||||
private val cellAspectRatio: Float = SizeTool.DEFAULT_CELL_ASPECT_RATIO,
|
|
||||||
private val showNameOnly: Boolean = false,
|
|
||||||
private val showAddress: Boolean = false
|
|
||||||
) : BaseQuickAdapter<ScaleData, Seasoning22GridAdapter.VH>(mutableListOf()) {
|
|
||||||
|
|
||||||
/** 空位哨兵,address=0 表示无效 */
|
|
||||||
private val empty = ScaleData("", 0, 0.0, -1, 0)
|
|
||||||
|
|
||||||
/** 当前高亮的格子位置,-1 表示无高亮 */
|
|
||||||
private var highlightedPosition: Int = -1
|
|
||||||
|
|
||||||
/** 点击回调 */
|
|
||||||
var onItemClick: ((ScaleData, Int) -> Unit)? = null
|
|
||||||
|
|
||||||
inner class VH(val b: ListItemScale22RowBinding) : QuickViewHolder(b.root)
|
|
||||||
|
|
||||||
/** 前4个位置为大格子(viewType=1),其余为小格子(viewType=0) */
|
|
||||||
override fun getItemViewType(position: Int, list: List<ScaleData>) =
|
|
||||||
if (position < 4) 1 else 0
|
|
||||||
|
|
||||||
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
|
||||||
val b = ListItemScale22RowBinding.inflate(LayoutInflater.from(context), parent, false)
|
|
||||||
val cellWidth = if (viewType == 1) largeSize else smallSize
|
|
||||||
val cellHeight = (cellWidth * cellAspectRatio).toInt()
|
|
||||||
b.root.updateLayoutParams<FlexboxLayoutManager.LayoutParams> {
|
|
||||||
width = cellWidth
|
|
||||||
height = cellHeight
|
|
||||||
setMargins(2.dp, 2.dp, 2.dp, 2.dp)
|
|
||||||
}
|
|
||||||
val baseSp = (cellWidth / parent.resources.displayMetrics.density).toInt()
|
|
||||||
b.tvAddress.textSize = (baseSp * 0.14f).coerceIn(8f, 12f)
|
|
||||||
b.tvName.textSize = (baseSp * 0.18f).coerceIn(10f, 16f)
|
|
||||||
b.tvWeight.textSize = (baseSp * 0.22f).coerceIn(12f, 20f)
|
|
||||||
b.tvState.textSize = (baseSp * 0.14f).coerceIn(8f, 12f)
|
|
||||||
// 秤地址行:仅 MasterScaleActivity 显示
|
|
||||||
b.tvAddress.visibility = if (showAddress) View.VISIBLE else View.GONE
|
|
||||||
// 调料配置模式隐藏重量和状态行
|
|
||||||
if (showNameOnly) {
|
|
||||||
b.tvWeight.visibility = View.GONE
|
|
||||||
b.tvState.visibility = View.GONE
|
|
||||||
}
|
|
||||||
val vh = VH(b)
|
|
||||||
b.root.setOnClickListener {
|
|
||||||
val pos = vh.bindingAdapterPosition
|
|
||||||
if (pos != RecyclerView.NO_POSITION) {
|
|
||||||
items.getOrNull(pos)?.takeIf { it.address != 0 }?.let { item -> onItemClick?.invoke(item, pos) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return vh
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressLint("SetTextI18n")
|
|
||||||
override fun onBindViewHolder(holder: VH, position: Int, item: ScaleData?) {
|
|
||||||
val valid = (item?.address ?: 0) != 0
|
|
||||||
if (!valid) {
|
|
||||||
holder.b.tvAddress.text = ""
|
|
||||||
holder.b.tvName.text = "-"
|
|
||||||
holder.b.tvWeight.text = ""
|
|
||||||
holder.b.tvState.text = ""
|
|
||||||
} else {
|
|
||||||
holder.b.tvAddress.text = "秤${item!!.address}"
|
|
||||||
holder.b.tvName.text = if (!item.name.isNullOrBlank()) item.name else "-"
|
|
||||||
holder.b.tvWeight.text = "${item.weight}g"
|
|
||||||
holder.b.tvState.text = WeightUtil.getStateStr(item.state)
|
|
||||||
}
|
|
||||||
val white = ContextCompat.getColor(holder.b.root.context, R.color.white)
|
|
||||||
when {
|
|
||||||
valid && item!!.state == WeightUtil.STATE_OVER_WEIGHT -> {
|
|
||||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell_over_weight)
|
|
||||||
holder.b.tvAddress.setTextColor(white)
|
|
||||||
holder.b.tvName.setTextColor(white)
|
|
||||||
holder.b.tvWeight.setTextColor(white)
|
|
||||||
holder.b.tvState.setTextColor(white)
|
|
||||||
}
|
|
||||||
position == highlightedPosition -> {
|
|
||||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell_highlight)
|
|
||||||
holder.b.tvAddress.setTextColor(white)
|
|
||||||
holder.b.tvName.setTextColor(white)
|
|
||||||
holder.b.tvWeight.setTextColor(white)
|
|
||||||
holder.b.tvState.setTextColor(white)
|
|
||||||
}
|
|
||||||
else -> {
|
|
||||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell)
|
|
||||||
val normal = ContextCompat.getColor(holder.b.root.context, R.color.home_title)
|
|
||||||
val sub = ContextCompat.getColor(holder.b.root.context, R.color.home_sub_title)
|
|
||||||
val black = ContextCompat.getColor(holder.b.root.context, R.color.black)
|
|
||||||
holder.b.tvAddress.setTextColor(sub)
|
|
||||||
holder.b.tvName.setTextColor(black)
|
|
||||||
holder.b.tvWeight.setTextColor(normal)
|
|
||||||
holder.b.tvState.setTextColor(sub)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 高亮指定位置的格子(红底白字),同时清除上一个高亮
|
|
||||||
*/
|
|
||||||
fun highlightPosition(position: Int) {
|
|
||||||
val prev = highlightedPosition
|
|
||||||
highlightedPosition = position
|
|
||||||
if (prev >= 0) notifyItemChanged(prev)
|
|
||||||
if (position >= 0) notifyItemChanged(position)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 清除所有高亮,恢复默认样式
|
|
||||||
*/
|
|
||||||
fun clearHighlight() {
|
|
||||||
highlightPosition(-1)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 更新指定位置的名称并刷新对应格子
|
|
||||||
*/
|
|
||||||
fun updateItemName(position: Int, name: String) {
|
|
||||||
items.getOrNull(position)?.let {
|
|
||||||
set(position, it.copy(name = name))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 按 SCALE_ORDER_22 的 sort 顺序更新数据,空位用哨兵填充
|
|
||||||
* 只更新显示字段有变化的格子,避免全量刷新导致 ViewHolder 重建影响点击监听
|
|
||||||
*/
|
|
||||||
fun update(list: List<ScaleData>) {
|
|
||||||
val byAddress = list.associateBy { it.address }
|
|
||||||
val filled = ScaleDeviceConfig.SCALE_ORDER_22.map { addr ->
|
|
||||||
byAddress[addr] ?: empty.copy(address = addr)
|
|
||||||
}
|
|
||||||
if (items.isEmpty()) {
|
|
||||||
submitList(filled)
|
|
||||||
} else {
|
|
||||||
filled.forEachIndexed { i, scale ->
|
|
||||||
val cur = items.getOrNull(i)
|
|
||||||
if (cur == null || cur.address != scale.address || cur.weight != scale.weight || cur.state != scale.state || cur.name != scale.name) {
|
|
||||||
set(i, scale)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 将 ScaleData 列表按 SCALE_ORDER_22 重排后调用 update
|
|
||||||
*/
|
|
||||||
fun updateByAddress(scales: List<ScaleData>) {
|
|
||||||
update(scales)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
//package com.shuwei.dish.match.adapter
|
||||||
|
//
|
||||||
|
//import android.content.Context
|
||||||
|
//import android.view.LayoutInflater
|
||||||
|
//import android.view.ViewGroup
|
||||||
|
//import androidx.core.view.updateLayoutParams
|
||||||
|
//import com.chad.library.adapter4.BaseQuickAdapter
|
||||||
|
//import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||||
|
//import com.shuwei.dish.match.databinding.ListItemCellBinding
|
||||||
|
//import com.shuwei.dish.match.model.GoodsItem
|
||||||
|
//import com.shuwei.dish.match.utils.ext.dp
|
||||||
|
//
|
||||||
|
///**
|
||||||
|
// * 调料格子列表适配器,使用 list_item_cell 布局展示调料名称与用量
|
||||||
|
// */
|
||||||
|
//class SeasoningAdapter(list: MutableList<GoodsItem>) :
|
||||||
|
// BaseQuickAdapter<GoodsItem, SeasoningAdapter.VH>(list) {
|
||||||
|
//
|
||||||
|
// override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
||||||
|
// val binding = ListItemCellBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||||
|
// return VH(binding)
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// override fun onBindViewHolder(holder: VH, position: Int, item: GoodsItem?) {
|
||||||
|
// item ?: return
|
||||||
|
// holder.binding.root.updateLayoutParams<ViewGroup.MarginLayoutParams> {
|
||||||
|
// width = 226.dp
|
||||||
|
// height = 120.dp
|
||||||
|
// leftMargin = 7.dp
|
||||||
|
// rightMargin = 8.dp
|
||||||
|
// topMargin = 7.dp
|
||||||
|
// bottomMargin = 8.dp
|
||||||
|
// }
|
||||||
|
// holder.binding.tvCell.text = TextCellAdapter.getTextSpan(item.toSeasoningEntity())
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// inner class VH(val binding: ListItemCellBinding) : QuickViewHolder(binding.root)
|
||||||
|
//}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
//package com.shuwei.dish.match.adapter
|
||||||
|
//
|
||||||
|
//import android.annotation.SuppressLint
|
||||||
|
//import android.widget.TextView
|
||||||
|
//import androidx.recyclerview.widget.GridLayoutManager
|
||||||
|
//import androidx.recyclerview.widget.RecyclerView
|
||||||
|
//import com.shuwei.dish.match.base.BaseActivity
|
||||||
|
//import com.shuwei.dish.match.dialog.BottomDialog2
|
||||||
|
//import com.shuwei.dish.match.db.entity.SeasoningEntity
|
||||||
|
//import com.shuwei.dish.match.ui.DeviceSettingActivity
|
||||||
|
//import com.shuwei.dish.match.ui.SubmitDishActivity
|
||||||
|
//import com.shuwei.dish.match.utils.DataUtil
|
||||||
|
//
|
||||||
|
//object SeasoningCellTool {
|
||||||
|
// private val TAG = "SeasoningCellTool"
|
||||||
|
//
|
||||||
|
// private val list = mutableListOf<SeasoningEntity>()
|
||||||
|
// private lateinit var activity: BaseActivity
|
||||||
|
// private var pageType: Int = 0
|
||||||
|
//
|
||||||
|
// @SuppressLint("StaticFieldLeak")
|
||||||
|
// private lateinit var cellAdapter: TextCellAdapter
|
||||||
|
//
|
||||||
|
// @SuppressLint("NotifyDataSetChanged")
|
||||||
|
// fun loadData(
|
||||||
|
// activity: BaseActivity,
|
||||||
|
// initList: MutableList<SeasoningEntity>? = null,
|
||||||
|
// recyclerView: RecyclerView,
|
||||||
|
// tvCell: TextView,
|
||||||
|
// pageType: Int = 0
|
||||||
|
// ) {
|
||||||
|
// this.activity = activity
|
||||||
|
// this.pageType = pageType
|
||||||
|
// list.clear()
|
||||||
|
// val tempList = buildData(initList, pageType)
|
||||||
|
// list.addAll(tempList)
|
||||||
|
// recyclerView.run {
|
||||||
|
// if (adapter == null) {
|
||||||
|
// layoutManager = GridLayoutManager(
|
||||||
|
// activity,
|
||||||
|
// 3,
|
||||||
|
// GridLayoutManager.VERTICAL,
|
||||||
|
// false
|
||||||
|
// )
|
||||||
|
// cellAdapter = TextCellAdapter(list).apply {
|
||||||
|
// onCellClick = { position ->
|
||||||
|
// val currentAddress = DataUtil.getWeighAddressArray().get(position)
|
||||||
|
// BottomDialog2(
|
||||||
|
// weighIndex = position,
|
||||||
|
// weighAddress = currentAddress,
|
||||||
|
// clickName = list[position].goodsName
|
||||||
|
// ).show(activity) { item ->
|
||||||
|
// list[position].let { current ->
|
||||||
|
// syncItem(current, item)
|
||||||
|
// //3-调料
|
||||||
|
// current.materialType = 3
|
||||||
|
// current.sort = position
|
||||||
|
// }
|
||||||
|
// notifyItemChanged(position)
|
||||||
|
// if (position == 14) {
|
||||||
|
// syncItem(list[10], list[14])
|
||||||
|
// syncItem(list[11], list[14])
|
||||||
|
// syncItem(list[13], list[14])
|
||||||
|
// TextCellAdapter.loadCell(tvCell, list[14])
|
||||||
|
// notifyItemChanged(10)
|
||||||
|
// notifyItemChanged(11)
|
||||||
|
// notifyItemChanged(13)
|
||||||
|
// notifyItemChanged(14)
|
||||||
|
// }
|
||||||
|
// if (activity is DeviceSettingActivity) {
|
||||||
|
// //activity.list = list
|
||||||
|
// activity.saveSeasoning(list[position])
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// adapter = cellAdapter
|
||||||
|
// } else {
|
||||||
|
// cellAdapter.notifyDataSetChanged()
|
||||||
|
// }
|
||||||
|
// if (activity is SubmitDishActivity) {
|
||||||
|
// activity.updateSeasoningList(list)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// if (pageType == 1) {
|
||||||
|
// tvCell.setOnClickListener {
|
||||||
|
// cellAdapter.onCellClick?.invoke(14)
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// TextCellAdapter.loadCell(tvCell, list[list.size - 1])
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// private fun buildData(
|
||||||
|
// initList: MutableList<SeasoningEntity>?,
|
||||||
|
// pageType: Int = 0
|
||||||
|
// ): MutableList<SeasoningEntity> {
|
||||||
|
// val list = mutableListOf<SeasoningEntity>()
|
||||||
|
// repeat(15) {
|
||||||
|
// list.add(SeasoningEntity().apply { this.pageType = pageType })
|
||||||
|
// }
|
||||||
|
// if (initList.isNullOrEmpty().not()) {
|
||||||
|
// initList.forEach {
|
||||||
|
// if (it.sort < list.size) {
|
||||||
|
// list[it.sort] = it.apply { this.pageType = pageType }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// var lastItem = initList.firstOrNull { it.sort == 14 }
|
||||||
|
// lastItem = lastItem ?: list[list.size - 1]
|
||||||
|
// list[10] = lastItem
|
||||||
|
// list[11] = lastItem
|
||||||
|
// list[13] = lastItem
|
||||||
|
// }
|
||||||
|
// return list
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// private fun syncItem(item: SeasoningEntity, newItem: SeasoningEntity) {
|
||||||
|
// item.run {
|
||||||
|
// goodsId = newItem.goodsId
|
||||||
|
// goodsName = newItem.goodsName
|
||||||
|
// goodsOrRelationCode = newItem.goodsOrRelationCode
|
||||||
|
// relateionType = newItem.relateionType
|
||||||
|
// materialType = newItem.materialType
|
||||||
|
// allEdible = newItem.allEdible
|
||||||
|
// useWeight = newItem.useWeight
|
||||||
|
// popularName = newItem.popularName
|
||||||
|
// canteenId = newItem.canteenId
|
||||||
|
// relateionType_dictText = newItem.relateionType_dictText
|
||||||
|
//
|
||||||
|
// foodId = newItem.foodId
|
||||||
|
// sort = newItem.sort
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
//}
|
||||||
@@ -7,12 +7,9 @@ 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.ListItemSeasoningBinding
|
import com.shuwei.dish.match.databinding.ListItemSearchGoodsInfoBinding
|
||||||
import com.shuwei.dish.match.model.GoodsItem
|
import com.shuwei.dish.match.model.GoodsItem
|
||||||
|
|
||||||
/**
|
|
||||||
* 调料搜索弹窗适配器
|
|
||||||
*/
|
|
||||||
class SeasoningSearchAdapter(private var list: MutableList<GoodsItem>) :
|
class SeasoningSearchAdapter(private var list: MutableList<GoodsItem>) :
|
||||||
BaseQuickAdapter<GoodsItem, SeasoningSearchAdapter.VH>(list) {
|
BaseQuickAdapter<GoodsItem, SeasoningSearchAdapter.VH>(list) {
|
||||||
|
|
||||||
@@ -23,6 +20,10 @@ 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,
|
||||||
@@ -31,10 +32,6 @@ 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 +40,10 @@ class SeasoningSearchAdapter(private var list: MutableList<GoodsItem>) :
|
|||||||
viewType: Int
|
viewType: Int
|
||||||
): VH {
|
): VH {
|
||||||
val binding =
|
val binding =
|
||||||
ListItemSeasoningBinding.inflate(LayoutInflater.from(context), parent, false)
|
ListItemSearchGoodsInfoBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||||
return VH(binding)
|
return VH(binding)
|
||||||
}
|
}
|
||||||
|
|
||||||
inner class VH(var binding: ListItemSeasoningBinding) : QuickViewHolder(binding.root)
|
inner class VH(var binding: ListItemSearchGoodsInfoBinding) : QuickViewHolder(binding.root)
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
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.ItemSeasoningWeightBinding
|
|
||||||
import com.shuwei.dish.match.databinding.ItemSeasoningWeightListBinding
|
|
||||||
import com.shuwei.dish.match.utils.ext.roundedDecimalPlace
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 调料使用重量列表 Adapter
|
|
||||||
* 用于 SubmitFoodActivity 展示各调料槽位的实时用量
|
|
||||||
* 同名调料已在外部聚合,adapter 按 goodsName 作为唯一标识
|
|
||||||
* 支持两种布局模式:
|
|
||||||
* - VIEW_TYPE_GRID(默认):4 列卡片,名称与重量垂直排列
|
|
||||||
* - VIEW_TYPE_LIST:2 列,名称与重量水平排列,名称占剩余空间
|
|
||||||
*/
|
|
||||||
class SeasoningWeightAdapter : BaseQuickAdapter<SeasoningWeightAdapter.Item, QuickViewHolder>() {
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
/** 4 列卡片模式 */
|
|
||||||
const val VIEW_TYPE_GRID = 0
|
|
||||||
/** 2 列水平模式 */
|
|
||||||
const val VIEW_TYPE_LIST = 1
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 调料展示数据项,key = goodsName(同名调料已聚合) */
|
|
||||||
data class Item(
|
|
||||||
val goodsId: String,
|
|
||||||
val goodsName: String,
|
|
||||||
/** 使用重量(克),同名调料已累加 */
|
|
||||||
val useWeight: Double
|
|
||||||
)
|
|
||||||
|
|
||||||
/** 当前布局模式,由外部切换后调用 notifyDataSetChanged 生效 */
|
|
||||||
var isListMode: Boolean = false
|
|
||||||
|
|
||||||
override fun getItemViewType(position: Int, list: List<Item>): Int {
|
|
||||||
return if (isListMode) VIEW_TYPE_LIST else VIEW_TYPE_GRID
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 更新单个 item,按 goodsName 匹配;不存在则追加
|
|
||||||
*/
|
|
||||||
fun updateItem(item: Item) {
|
|
||||||
val idx = items.indexOfFirst { it.goodsName == item.goodsName }
|
|
||||||
if (idx >= 0) {
|
|
||||||
set(idx, item)
|
|
||||||
} else {
|
|
||||||
add(item)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 移除指定 goodsName 的 item(聚合后用量不足阈值时调用)
|
|
||||||
*/
|
|
||||||
fun removeItem(goodsName: String) {
|
|
||||||
val idx = items.indexOfFirst { it.goodsName == goodsName }
|
|
||||||
if (idx >= 0) removeAt(idx)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): QuickViewHolder {
|
|
||||||
return if (viewType == VIEW_TYPE_LIST) {
|
|
||||||
val binding = ItemSeasoningWeightListBinding.inflate(LayoutInflater.from(context), parent, false)
|
|
||||||
QuickViewHolder(binding.root)
|
|
||||||
} else {
|
|
||||||
val binding = ItemSeasoningWeightBinding.inflate(LayoutInflater.from(context), parent, false)
|
|
||||||
QuickViewHolder(binding.root)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onBindViewHolder(holder: QuickViewHolder, position: Int, item: Item?) {
|
|
||||||
item ?: return
|
|
||||||
val showWeight = "${item.useWeight.roundedDecimalPlace(1)}g"
|
|
||||||
holder.setText(com.shuwei.dish.match.R.id.tvSeasoningName, item.goodsName)
|
|
||||||
holder.setText(com.shuwei.dish.match.R.id.tvSeasoningWeight, showWeight)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
package com.shuwei.dish.match.adapter
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.view.LayoutInflater
|
|
||||||
import android.view.ViewGroup
|
|
||||||
import com.chad.library.adapter4.BaseQuickAdapter
|
|
||||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
|
||||||
import com.shuwei.dish.match.databinding.ListItemSettingBinding
|
|
||||||
import com.shuwei.dish.match.model.SettingItem
|
|
||||||
import com.shuwei.dish.match.utils.ext.gone
|
|
||||||
import com.shuwei.dish.match.utils.ext.visible
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 设置页面列表适配器
|
|
||||||
* 点击事件直接调用 item.onClick(),无需在 Adapter 中分发业务逻辑
|
|
||||||
*/
|
|
||||||
class SettingAdapter : BaseQuickAdapter<SettingItem, SettingAdapter.VH>() {
|
|
||||||
|
|
||||||
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
|
||||||
val binding = ListItemSettingBinding.inflate(LayoutInflater.from(context), parent, false)
|
|
||||||
return VH(binding)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onBindViewHolder(holder: VH, position: Int, item: SettingItem?) {
|
|
||||||
item ?: return
|
|
||||||
holder.binding.tvTitle.text = item.title
|
|
||||||
|
|
||||||
// 有副标题则显示,否则隐藏
|
|
||||||
val subtitle = item.subtitle
|
|
||||||
if (subtitle != null) {
|
|
||||||
holder.binding.tvSubtitle.visible()
|
|
||||||
holder.binding.tvSubtitle.text = subtitle
|
|
||||||
} else {
|
|
||||||
holder.binding.tvSubtitle.gone()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
inner class VH(val binding: ListItemSettingBinding) : QuickViewHolder(binding.root)
|
|
||||||
}
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -17,7 +17,8 @@
|
|||||||
//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.ListItemCellBinding
|
//import com.shuwei.dish.match.databinding.ListItemCellBinding
|
||||||
//import com.shuwei.dish.match.entity.SeasoningEntity
|
//import com.shuwei.dish.match.db.entity.SeasoningEntity
|
||||||
|
//import com.shuwei.dish.match.model.GoodsItem
|
||||||
//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
|
||||||
|
|||||||
@@ -1,58 +0,0 @@
|
|||||||
package com.shuwei.dish.match.adapter
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.view.LayoutInflater
|
|
||||||
import android.view.View
|
|
||||||
import android.view.ViewGroup
|
|
||||||
import android.widget.ImageView
|
|
||||||
import com.chad.library.adapter4.BaseQuickAdapter
|
|
||||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
|
||||||
import com.shuwei.dish.match.R
|
|
||||||
import com.shuwei.dish.match.databinding.ListItemVectorCollectionBinding
|
|
||||||
import com.shuwei.dish.match.model.FoodCollectionBean
|
|
||||||
import com.shuwei.dish.match.utils.ext.load
|
|
||||||
|
|
||||||
class VectorCollectionAdapter (var list: MutableList<FoodCollectionBean>) :
|
|
||||||
BaseQuickAdapter<FoodCollectionBean, VectorCollectionAdapter.VH>(list) {
|
|
||||||
|
|
||||||
inner class VH(var binding: ListItemVectorCollectionBinding) : QuickViewHolder(binding.root)
|
|
||||||
|
|
||||||
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
|
||||||
val inflater = LayoutInflater.from(context)
|
|
||||||
val binding = ListItemVectorCollectionBinding.inflate(inflater, parent, false)
|
|
||||||
return VH(binding)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onBindViewHolder(holder: VH, position: Int, item: FoodCollectionBean?) {
|
|
||||||
val binding = holder.binding
|
|
||||||
item?.let {
|
|
||||||
binding.ivFinish.visibility = if (it.isFinish) View.VISIBLE else View.GONE
|
|
||||||
binding.ivDelete.visibility = if (it.isShowCamera) View.GONE else View.VISIBLE
|
|
||||||
binding.imageView.run {
|
|
||||||
if (it.isShowCamera) {
|
|
||||||
scaleType = ImageView.ScaleType.CENTER
|
|
||||||
setImageResource(R.drawable.ic_camera_default)
|
|
||||||
} else {
|
|
||||||
//scaleType = ImageView.ScaleType.FIT_CENTER
|
|
||||||
scaleType = ImageView.ScaleType.CENTER_CROP
|
|
||||||
//setImageURI(it.imageUri)
|
|
||||||
//setImageBitmap(it.bitmap)
|
|
||||||
if (it.imageUri!=null) {
|
|
||||||
setImageURI(it.imageUri)
|
|
||||||
} else {
|
|
||||||
load(it.imageFile)
|
|
||||||
}
|
|
||||||
// it.bitmap?.let { bitmap ->
|
|
||||||
// GlideUtils.loadRoundCornerWitBitmap(
|
|
||||||
// context,
|
|
||||||
// url = bitmap,
|
|
||||||
// imageView = this,
|
|
||||||
// radius = 8.dp
|
|
||||||
// )
|
|
||||||
// }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
package com.shuwei.dish.match.base
|
package com.shuwei.dish.match.base
|
||||||
|
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
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
|
||||||
@@ -10,82 +9,100 @@ import android.view.View
|
|||||||
import android.widget.FrameLayout
|
import android.widget.FrameLayout
|
||||||
import android.widget.ImageView
|
import android.widget.ImageView
|
||||||
import android.widget.TextView
|
import android.widget.TextView
|
||||||
|
import androidx.activity.enableEdgeToEdge
|
||||||
|
import androidx.activity.result.ActivityResultLauncher
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
import androidx.activity.viewModels
|
import androidx.activity.viewModels
|
||||||
import androidx.appcompat.app.AppCompatActivity
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
import androidx.core.content.ContextCompat
|
import androidx.core.content.ContextCompat
|
||||||
import androidx.core.view.WindowCompat
|
|
||||||
import androidx.core.view.WindowInsetsCompat
|
|
||||||
import androidx.core.view.WindowInsetsControllerCompat
|
|
||||||
import com.shuwei.dish.match.R
|
import com.shuwei.dish.match.R
|
||||||
import com.shuwei.dish.match.databinding.ActivityBaseBinding
|
import com.shuwei.dish.match.databinding.ActivityBaseBinding
|
||||||
|
import com.shuwei.dish.match.db.DbViewModel
|
||||||
import com.shuwei.dish.match.dialog.Loading
|
import com.shuwei.dish.match.dialog.Loading
|
||||||
import com.shuwei.dish.match.net.NetViewModel
|
import com.shuwei.dish.match.net.NetViewModel
|
||||||
import com.shuwei.dish.match.db.DbViewModel
|
import com.shuwei.dish.match.viewmodel.AppViewModel
|
||||||
|
import com.shuwei.dish.match.ui.HomeActivity.Companion.TAG
|
||||||
import com.shuwei.dish.match.ui.InitActivity
|
import com.shuwei.dish.match.ui.InitActivity
|
||||||
import com.shuwei.dish.match.utils.ActivityManager
|
import com.shuwei.dish.match.utils.ActivityManager
|
||||||
import com.shuwei.dish.match.utils.KeyboardUtil
|
|
||||||
import com.shuwei.dish.match.utils.ext.dp
|
|
||||||
import com.shuwei.dish.match.utils.ext.gone
|
import com.shuwei.dish.match.utils.ext.gone
|
||||||
import com.shuwei.dish.match.utils.ext.invisible
|
import com.shuwei.dish.match.utils.ext.invisible
|
||||||
|
import com.shuwei.dish.match.utils.ext.put
|
||||||
|
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.time.LocalDateTime
|
import java.time.LocalDateTime
|
||||||
import java.time.ZoneId
|
import java.time.ZoneId
|
||||||
import java.time.format.DateTimeFormatter
|
import java.time.format.DateTimeFormatter
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
import kotlin.getValue
|
|
||||||
|
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
open class BaseActivity : AppCompatActivity() {
|
open class BaseActivity : AppCompatActivity() {
|
||||||
|
|
||||||
companion object {
|
val netViewModel: NetViewModel by viewModels()
|
||||||
const val TAG = "BaseActivity"
|
val dbViewModel: DbViewModel by viewModels()
|
||||||
/** 日期时间格式化器,复用避免每秒重复创建 */
|
val appViewModel: AppViewModel by viewModels()
|
||||||
private val DATE_FORMATTER =
|
|
||||||
DateTimeFormatter.ofPattern("yyyy年MM月dd日 EEEE***HH:mm:ss", Locale.CHINA)
|
|
||||||
}
|
|
||||||
|
|
||||||
private lateinit var binding: ActivityBaseBinding
|
private lateinit var binding: ActivityBaseBinding
|
||||||
|
private var launcher: ActivityResultLauncher<Intent>? = null
|
||||||
|
private var launchCallback: ((Intent?) -> Unit)? = null
|
||||||
|
|
||||||
|
public fun launch(cls: Class<*>, launchCallback: (Intent?) -> Unit) {
|
||||||
|
this.launchCallback = launchCallback
|
||||||
|
launcher?.launch(Intent(this, cls))
|
||||||
|
}
|
||||||
|
|
||||||
|
public fun launch(intent: Intent, launchCallback: (Intent?) -> Unit) {
|
||||||
|
this.launchCallback = launchCallback
|
||||||
|
launcher?.launch(intent)
|
||||||
|
}
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
// 提前隐藏系统栏,避免窗口创建时导航栏闪烁
|
|
||||||
hideSystemBars()
|
|
||||||
// 主设备竖屏,子设备横屏
|
|
||||||
// requestedOrientation = if (GlobalData.deviceRole == DeviceRole.MASTER)
|
|
||||||
// ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
|
|
||||||
// else
|
|
||||||
// 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) {
|
||||||
binding.root.setBackgroundColor(ContextCompat.getColor(this, R.color.bg_color))
|
binding.root.setBackgroundColor(ContextCompat.getColor(this, R.color.bg_color))
|
||||||
}
|
}
|
||||||
setContentView(binding.root)
|
setContentView(binding.root)
|
||||||
statusBarDarkFont(enable = false)
|
statusBarDarkFont(enable = false)
|
||||||
// 主设备垂直 padding 30dp,子设备 15dp
|
launcher =
|
||||||
val verticalPadding = if (GlobalData.deviceRole == DeviceRole.MASTER) 30.dp else 10.dp
|
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
|
||||||
binding.tvLeftTime.setPadding(0, verticalPadding, 0, verticalPadding)
|
if (result.resultCode == RESULT_OK) {
|
||||||
binding.tvRightTime.setPadding(0, verticalPadding, 0, verticalPadding)
|
launchCallback?.invoke(result.data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// window.setDecorFitsSystemWindows(false) // 启用 Edge-to-Edge
|
||||||
|
// window.insetsController?.apply {
|
||||||
|
// hide(WindowInsets.Type.statusBars()) // 隐藏状态栏
|
||||||
|
// systemBarsBehavior =
|
||||||
|
// WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE // 滑动时临时显示
|
||||||
|
// }
|
||||||
binding.llTitleBar.gone()
|
binding.llTitleBar.gone()
|
||||||
binding.ivBack.setOnClickListener { finish() }
|
binding.ivBack.setOnClickListener { finish() }
|
||||||
binding.root.setOnClickListener { hideKeyboard() }
|
}
|
||||||
|
|
||||||
|
private var bgState = true
|
||||||
|
fun useBackground(enable: Boolean) {
|
||||||
|
bgState = enable
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onDestroy() {
|
override fun onDestroy() {
|
||||||
handler.removeCallbacksAndMessages(null)
|
dismissLoading()
|
||||||
// 只关闭自己弹出的 Loading,防止误关其他 Activity 的 Loading
|
|
||||||
Loading.dismissIfOwnedBy(this)
|
|
||||||
super.onDestroy()
|
super.onDestroy()
|
||||||
ActivityManager.removeActivity(this)
|
ActivityManager.removeActivity(this)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun hideStatusBar() {
|
fun hideStatusBar() {
|
||||||
hideSystemBars()
|
enableEdgeToEdge()
|
||||||
|
// val uiOptions = (View.SYSTEM_UI_FLAG_FULLSCREEN // 隐藏状态栏
|
||||||
|
// or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) // 隐藏导航栏(可选)
|
||||||
|
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
|
||||||
}
|
}
|
||||||
|
|
||||||
fun statusBarDarkFont(enable: Boolean) {
|
fun statusBarDarkFont(enable: Boolean) {
|
||||||
val color = ContextCompat.getColor(
|
//window.decorView.systemUiVisibility = if (enable) View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR else 0
|
||||||
this, if (enable) R.color.black else R.color.white
|
val color = ContextCompat.getColor(this,
|
||||||
|
if (enable) R.color.black else R.color.white
|
||||||
)
|
)
|
||||||
binding.tvLeftTime.setTextColor(color)
|
binding.tvLeftTime.setTextColor(color)
|
||||||
binding.tvRightTime.setTextColor(color)
|
binding.tvRightTime.setTextColor(color)
|
||||||
@@ -95,13 +112,12 @@ 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,
|
||||||
rightIconAction: ((ImageView) -> Unit)? = null
|
rightIconActon: ((ImageView) -> Unit)? = null
|
||||||
) {
|
) {
|
||||||
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)
|
||||||
rightIconAction?.invoke(binding.ivRightIcon)
|
rightIconActon?.invoke(binding.ivRightIcon)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setHeaderBgVisible(show: Boolean) {
|
fun setHeaderBgVisible(show: Boolean) {
|
||||||
@@ -110,15 +126,12 @@ open class BaseActivity : AppCompatActivity() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setHeaderBackground(isHomePage: Boolean = false) {
|
public fun setHeaderBackground(isHomePage: Boolean = false) {
|
||||||
binding.ivHeaderBg.setImageResource(
|
binding.ivHeaderBg.setImageResource(
|
||||||
if (isHomePage) R.drawable.bg_home_page else R.drawable.bg_other_page
|
if (isHomePage) R.drawable.bg_home_page else R.drawable.bg_other_page
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 返回 Fragment 容器的 View ID,供子类加载 Fragment 使用 */
|
|
||||||
protected fun getFragmentContainerId(): Int = R.id.flContainer
|
|
||||||
|
|
||||||
override fun setContentView(view: View?) {
|
override fun setContentView(view: View?) {
|
||||||
if (view == binding.root) {
|
if (view == binding.root) {
|
||||||
super.setContentView(view)
|
super.setContentView(view)
|
||||||
@@ -128,7 +141,8 @@ open class BaseActivity : AppCompatActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun updateDateTime() {
|
private fun updateDateTime() {
|
||||||
val dateTime = DATE_FORMATTER.format(LocalDateTime.now(ZoneId.of("Asia/Shanghai")))
|
val formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 EEEE***HH:mm:ss", Locale.CHINA)
|
||||||
|
val dateTime = formatter.format(LocalDateTime.now(ZoneId.of("Asia/Shanghai")))
|
||||||
val arr = dateTime.split("***")
|
val arr = dateTime.split("***")
|
||||||
binding.tvRightTime.text = arr[0]
|
binding.tvRightTime.text = arr[0]
|
||||||
binding.tvLeftTime.text = arr[1]
|
binding.tvLeftTime.text = arr[1]
|
||||||
@@ -153,127 +167,20 @@ open class BaseActivity : AppCompatActivity() {
|
|||||||
handler.removeCallbacks(updateTask)
|
handler.removeCallbacks(updateTask)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun showLoading(msg: String = "加载中……", timeoutMs: Long = Loading.DEFAULT_TIMEOUT_MS) {
|
fun showLoading() {
|
||||||
handler.post {
|
Loading.show(this)
|
||||||
Loading.show(
|
|
||||||
context = this,
|
|
||||||
message = msg,
|
|
||||||
timeoutMs = timeoutMs
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun dismissLoading() {
|
fun dismissLoading() {
|
||||||
Log.d(TAG, "dismissLoading, ${this.javaClass.simpleName}")
|
Loading.dismiss()
|
||||||
handler.post {
|
|
||||||
Loading.dismiss()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun delayDismissLoading() {
|
fun delayDismissLoading() {
|
||||||
Log.d(TAG, "delayDismissLoading, ${this.javaClass.simpleName}")
|
window.decorView.postDelayed({
|
||||||
handler.postDelayed({
|
|
||||||
Loading.dismiss()
|
Loading.dismiss()
|
||||||
}, 500)
|
},500)
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 在主线程延迟执行任务,供子类使用
|
|
||||||
* @param delayMs 延迟毫秒数
|
|
||||||
* @param block 待执行的任务
|
|
||||||
*/
|
|
||||||
protected fun postDelayed(delayMs: Long, block: () -> Unit) {
|
|
||||||
handler.postDelayed(block, delayMs)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
val netViewModel: NetViewModel by viewModels()
|
|
||||||
val dbViewModel: DbViewModel by viewModels()
|
|
||||||
|
|
||||||
private var singlePermissionCallback: ((isGranted: Boolean) -> Unit)? = null
|
|
||||||
private var multiplePermissionsCallback: ((isGranted: Boolean) -> Unit)? = null
|
|
||||||
private var activityCallback: ((intent: Intent?) -> Unit)? = null
|
|
||||||
|
|
||||||
fun requestMultiplePermissions(
|
|
||||||
permissions: Array<String>,
|
|
||||||
callback: (isGranted: Boolean) -> Unit
|
|
||||||
) {
|
|
||||||
this.multiplePermissionsCallback = callback
|
|
||||||
requestMultiplePermissionsLauncher.launch(permissions)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun requestPermission(permission: String, callback: (isGranted: Boolean) -> Unit) {
|
|
||||||
this.singlePermissionCallback = callback
|
|
||||||
requestPermissionLauncher.launch(permission)
|
|
||||||
}
|
|
||||||
|
|
||||||
private val requestMultiplePermissionsLauncher = registerForActivityResult(
|
|
||||||
ActivityResultContracts.RequestMultiplePermissions()
|
|
||||||
) { permissions ->
|
|
||||||
var isGranted = true
|
|
||||||
permissions.entries.forEach {
|
|
||||||
if (!it.value) {
|
|
||||||
isGranted = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
multiplePermissionsCallback?.invoke(isGranted)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 权限请求回调
|
|
||||||
private val requestPermissionLauncher = registerForActivityResult(
|
|
||||||
ActivityResultContracts.RequestPermission()
|
|
||||||
) { isGranted ->
|
|
||||||
singlePermissionCallback?.invoke(isGranted)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun startActivity(intent: Intent, callback: (Intent?) -> Unit) {
|
|
||||||
this.activityCallback = callback
|
|
||||||
startActivityLauncher.launch(intent)
|
|
||||||
}
|
|
||||||
|
|
||||||
// activity页面返回的回调
|
|
||||||
private val startActivityLauncher = registerForActivityResult(
|
|
||||||
ActivityResultContracts.StartActivityForResult()
|
|
||||||
) {
|
|
||||||
activityCallback?.invoke(it.data)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 窗口焦点变化时回调
|
|
||||||
* 场景:弹出 Dialog 后焦点丢失,Dialog 消失后焦点恢复,此时需重新隐藏系统栏,
|
|
||||||
* 避免系统栏在 Dialog 关闭后意外"复活"
|
|
||||||
*/
|
|
||||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
|
||||||
super.onWindowFocusChanged(hasFocus)
|
|
||||||
if (hasFocus) {
|
|
||||||
hideSystemBars()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 隐藏状态栏和导航栏
|
|
||||||
* 使用 WindowInsetsControllerCompat(Androidx 推荐方式,向下兼容性好)
|
|
||||||
* - setDecorFitsSystemWindows 只在首次调用时设置,避免反复触发布局重绘
|
|
||||||
* (重绘会导致 RecyclerView 滑动时抛出 "view is not a child, cannot hide" 异常)
|
|
||||||
* - 每次调用仍重新执行 hide(),保证系统栏在滑出后能被重新隐藏
|
|
||||||
*/
|
|
||||||
private var systemBarsConfigured = false
|
|
||||||
private fun hideSystemBars() {
|
|
||||||
if (!systemBarsConfigured) {
|
|
||||||
// 只执行一次:允许布局延伸到系统栏区域
|
|
||||||
WindowCompat.setDecorFitsSystemWindows(window, false)
|
|
||||||
systemBarsConfigured = true
|
|
||||||
}
|
|
||||||
WindowInsetsControllerCompat(window, window.decorView).apply {
|
|
||||||
hide(WindowInsetsCompat.Type.systemBars())
|
|
||||||
systemBarsBehavior =
|
|
||||||
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun hideKeyboard() {
|
|
||||||
KeyboardUtil.hideKeyboard(binding.root)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1,22 +1,14 @@
|
|||||||
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 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.scale.ScaleDeviceConfig
|
|
||||||
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.SpTool
|
|
||||||
import com.shuwei.dish.match.utils.WeightUtil
|
|
||||||
|
|
||||||
class BaseApp : Application() {
|
class BaseApp : Application() {
|
||||||
|
|
||||||
@@ -25,76 +17,30 @@ class BaseApp : Application() {
|
|||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
instance = this
|
instance = this
|
||||||
// 读取本地保存的环境地址,覆盖默认值
|
|
||||||
val savedBaseUrl = SpTool.baseUrl
|
|
||||||
if (savedBaseUrl.isNotEmpty()) {
|
|
||||||
GlobalData.appBaseUrl = savedBaseUrl
|
|
||||||
}
|
|
||||||
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) {}
|
|
||||||
})
|
|
||||||
|
|
||||||
// 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)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
private val TAG = "BaseApp"
|
|
||||||
var canteenId = "0"
|
|
||||||
var appVersion: String = "1"
|
|
||||||
|
|
||||||
|
// const val canteenId = "1678234139391512577"
|
||||||
|
var canteenId = "0"
|
||||||
|
var configUrl = ""
|
||||||
|
|
||||||
|
var token: String? = null
|
||||||
|
var appVersion: String = "1"
|
||||||
@Volatile
|
@Volatile
|
||||||
private var sharedPref: SharedPreferences? = null
|
private var sharedPref: SharedPreferences? = null
|
||||||
|
|
||||||
lateinit var instance: BaseApp
|
public var instance: BaseApp? = null
|
||||||
|
fun getSharedPref(): SharedPreferences? {
|
||||||
/** 双重检查锁,保证多线程下只初始化一次 */
|
if (sharedPref != null) {
|
||||||
fun getSharedPref(): SharedPreferences {
|
return sharedPref
|
||||||
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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,16 +18,8 @@ abstract class BaseFragment<VB : ViewBinding> : Fragment() {
|
|||||||
|
|
||||||
abstract fun inflateBinding(inflater: LayoutInflater, container: ViewGroup?): VB
|
abstract fun inflateBinding(inflater: LayoutInflater, container: ViewGroup?): VB
|
||||||
|
|
||||||
abstract fun initialize()
|
|
||||||
|
|
||||||
override fun onDestroyView() {
|
override fun onDestroyView() {
|
||||||
super.onDestroyView()
|
super.onDestroyView()
|
||||||
_binding = null
|
_binding = null
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
|
||||||
super.onViewCreated(view, savedInstanceState)
|
|
||||||
initialize()
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.shuwei.dish.match.base
|
||||||
|
|
||||||
|
class BaseReq<T> {
|
||||||
|
var code: Int? = null
|
||||||
|
var success: Boolean? = null
|
||||||
|
var data: T? = null
|
||||||
|
var message: String? = null
|
||||||
|
var result: T? = null
|
||||||
|
var msg: String? = null
|
||||||
|
}
|
||||||
@@ -8,17 +8,18 @@ package com.shuwei.dish.match.base
|
|||||||
enum class DeviceRole { MASTER, SLAVE }
|
enum class DeviceRole { MASTER, SLAVE }
|
||||||
|
|
||||||
object GlobalData {
|
object GlobalData {
|
||||||
var appBaseUrl: String = LOCAL_BASE_URL
|
var appBaseUrl: String = TEST_BASE_URL
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 具体业务 BaseUrl
|
* 具体业务 BaseUrl
|
||||||
*/
|
*/
|
||||||
// const val LOCAL_BASE_URL = "http://192.168.1.201:14801"
|
const val TEST_BASE_URL = "http://192.168.1.201:14801"
|
||||||
const val LOCAL_BASE_URL = "http://192.168.10.101:24801"
|
const val UAT_BASE_URL = "https://dev.yixiong-tech.com:8083"
|
||||||
|
|
||||||
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"
|
||||||
|
|
||||||
|
//临时用于测试
|
||||||
|
const val DEVICE_ID_2 = "8fc2ab34-2137-3112-acca-f884ea8736d4"
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 设备id
|
* 设备id
|
||||||
*/
|
*/
|
||||||
@@ -28,8 +29,6 @@ object GlobalData {
|
|||||||
* 当前设备角色,启动时从 SpTool 读取,默认为 SLAVE
|
* 当前设备角色,启动时从 SpTool 读取,默认为 SLAVE
|
||||||
*/
|
*/
|
||||||
var deviceRole: DeviceRole = DeviceRole.SLAVE
|
var deviceRole: DeviceRole = DeviceRole.SLAVE
|
||||||
|
|
||||||
var userName = "张三"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import androidx.lifecycle.viewModelScope
|
|||||||
import androidx.sqlite.db.SimpleSQLiteQuery
|
import androidx.sqlite.db.SimpleSQLiteQuery
|
||||||
import com.shuwei.dish.match.model.CollectedFoodItem
|
import com.shuwei.dish.match.model.CollectedFoodItem
|
||||||
import com.shuwei.dish.match.db.entity.CookFoodEntity
|
import com.shuwei.dish.match.db.entity.CookFoodEntity
|
||||||
import com.shuwei.dish.match.objbox.ObjectBox
|
|
||||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||||
import com.shuwei.dish.match.db.entity.SeasoningEntity
|
import com.shuwei.dish.match.db.entity.SeasoningEntity
|
||||||
import com.shuwei.dish.match.db.entity.SeasoningSlotEntity
|
import com.shuwei.dish.match.db.entity.SeasoningSlotEntity
|
||||||
@@ -582,43 +581,43 @@ class DbViewModel : ViewModel() {
|
|||||||
private val _collectedFoodListState = MutableStateFlow<List<CollectedFoodItem>>(emptyList())
|
private val _collectedFoodListState = MutableStateFlow<List<CollectedFoodItem>>(emptyList())
|
||||||
val collectedFoodListState: StateFlow<List<CollectedFoodItem>> = _collectedFoodListState.asStateFlow()
|
val collectedFoodListState: StateFlow<List<CollectedFoodItem>> = _collectedFoodListState.asStateFlow()
|
||||||
|
|
||||||
/**
|
// /**
|
||||||
* 加载已采集食材列表,按名称分组统计数量
|
// * 加载已采集食材列表,按名称分组统计数量
|
||||||
* 使用属性查询只读 name 字段,不加载 foodVector,节省内存
|
// * 使用属性查询只读 name 字段,不加载 foodVector,节省内存
|
||||||
* @param nameFilter 名称过滤关键词,为空时加载全部
|
// * @param nameFilter 名称过滤关键词,为空时加载全部
|
||||||
*/
|
// */
|
||||||
fun loadCollectedFoodList(nameFilter: String? = null) {
|
// fun loadCollectedFoodList(nameFilter: String? = null) {
|
||||||
viewModelScope.launch {
|
// viewModelScope.launch {
|
||||||
val result = ObjectBox.queryFoodNameCounts(nameFilter)
|
// val result = ObjectBox.queryFoodNameCounts(nameFilter)
|
||||||
_collectedFoodListState.value = result.map { (name, count) ->
|
// _collectedFoodListState.value = result.map { (name, count) ->
|
||||||
CollectedFoodItem(foodName = name, collectCount = count)
|
// CollectedFoodItem(foodName = name, collectCount = count)
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
/**
|
// /**
|
||||||
* 删除指定名称的所有采集记录,删除完成后刷新列表
|
// * 删除指定名称的所有采集记录,删除完成后刷新列表
|
||||||
* @param foodName 食材名称
|
// * @param foodName 食材名称
|
||||||
* @param nameFilter 当前搜索关键词,用于删除后刷新列表
|
// * @param nameFilter 当前搜索关键词,用于删除后刷新列表
|
||||||
*/
|
// */
|
||||||
fun removeCollectedFood(foodName: String, nameFilter: String? = null) {
|
// fun removeCollectedFood(foodName: String, nameFilter: String? = null) {
|
||||||
viewModelScope.launch {
|
// viewModelScope.launch {
|
||||||
ObjectBox.remove(foodName)
|
// ObjectBox.remove(foodName)
|
||||||
loadCollectedFoodList(nameFilter)
|
// loadCollectedFoodList(nameFilter)
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
/**
|
// /**
|
||||||
* 清除所有向量采集数据,完成后刷新列表
|
// * 清除所有向量采集数据,完成后刷新列表
|
||||||
* @param onDone 清除完成后在主线程执行的回调
|
// * @param onDone 清除完成后在主线程执行的回调
|
||||||
*/
|
// */
|
||||||
fun clearAllCollectedFood(onDone: (() -> Unit)? = null) {
|
// fun clearAllCollectedFood(onDone: (() -> Unit)? = null) {
|
||||||
viewModelScope.launch {
|
// viewModelScope.launch {
|
||||||
ObjectBox.removeAll()
|
// ObjectBox.removeAll()
|
||||||
loadCollectedFoodList()
|
// loadCollectedFoodList()
|
||||||
onDone?.invoke()
|
// onDone?.invoke()
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
|
||||||
//--------------------------------------------------------------------------------------------------------
|
//--------------------------------------------------------------------------------------------------------
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.shuwei.dish.match.db.entity
|
||||||
|
|
||||||
|
/** 默认调料配置 JSON 反序列化的包装类 */
|
||||||
|
data class ResetReasoningRecord(
|
||||||
|
val list: MutableList<SeasoningEntity> = mutableListOf()
|
||||||
|
)
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
package com.shuwei.dish.match.db.entity
|
package com.shuwei.dish.match.db.entity
|
||||||
|
|
||||||
import androidx.room.Entity
|
import androidx.room.Entity
|
||||||
|
import androidx.room.Ignore
|
||||||
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.time.LocalDateTime
|
import java.time.LocalDateTime
|
||||||
|
|
||||||
@@ -71,5 +73,25 @@ data class SeasoningEntity(
|
|||||||
var isDel: Int = 0,
|
var isDel: Int = 0,
|
||||||
var createTime: String = DateTimeUtil.formatDateTime(LocalDateTime.now())
|
var createTime: String = DateTimeUtil.formatDateTime(LocalDateTime.now())
|
||||||
) : BaseEntity {
|
) : BaseEntity {
|
||||||
|
/** UI 状态:格子类型,非数据库字段 */
|
||||||
|
@Ignore var pageType: Int = 0
|
||||||
|
/** UI 状态:是否选中,非数据库字段 */
|
||||||
|
@Ignore var isClicked: Boolean = false
|
||||||
|
|
||||||
constructor() : this(goodsId = "") // 必需的空构造
|
constructor() : this(goodsId = "") // 必需的空构造
|
||||||
|
|
||||||
|
/** 转换为 GoodsItem,用于 UI 层展示 */
|
||||||
|
fun toGoodsItem(): GoodsItem = GoodsItem(
|
||||||
|
goodsId = goodsId,
|
||||||
|
goodsName = goodsName,
|
||||||
|
popularName = popularName,
|
||||||
|
zjmCode = zjmCode,
|
||||||
|
materId = materId,
|
||||||
|
materialType = materialType,
|
||||||
|
useWeight = useWeight,
|
||||||
|
relateionType = relateionType,
|
||||||
|
allEdible = allEdible,
|
||||||
|
goodsOrRelationCode = goodsOrRelationCode,
|
||||||
|
rawMaterialsType = rawMaterialsType
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,193 @@
|
|||||||
|
package com.shuwei.dish.match.dialog
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.util.Log
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.View
|
||||||
|
import androidx.core.view.isEmpty
|
||||||
|
import androidx.core.widget.addTextChangedListener
|
||||||
|
import androidx.recyclerview.widget.GridLayoutManager
|
||||||
|
import androidx.recyclerview.widget.RecyclerView
|
||||||
|
import com.google.android.material.bottomsheet.BottomSheetDialog
|
||||||
|
import com.shuwei.dish.match.R
|
||||||
|
import com.shuwei.dish.match.adapter.GoodsInfoSearchAdapter
|
||||||
|
import com.shuwei.dish.match.base.BaseActivity
|
||||||
|
import com.shuwei.dish.match.base.BaseApp
|
||||||
|
import com.shuwei.dish.match.databinding.DialogBottomSheetBinding
|
||||||
|
import com.shuwei.dish.match.model.GoodsItem
|
||||||
|
import com.shuwei.dish.match.net.RemoteRepository
|
||||||
|
import com.shuwei.dish.match.net.UiState
|
||||||
|
import com.shuwei.dish.match.utils.KeyboardUtil
|
||||||
|
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
||||||
|
import androidx.lifecycle.lifecycleScope
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import com.shuwei.dish.match.utils.ext.toast
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param goodsType 1-调料,0-食材
|
||||||
|
*/
|
||||||
|
class BottomDialog(
|
||||||
|
private var goodsType: Int = 1,
|
||||||
|
private var defGoodsName:String? = null
|
||||||
|
) {
|
||||||
|
companion object {
|
||||||
|
const val TAG = "BottomDialog"
|
||||||
|
}
|
||||||
|
|
||||||
|
private var list = mutableListOf<GoodsItem>()
|
||||||
|
|
||||||
|
private lateinit var binding: DialogBottomSheetBinding
|
||||||
|
private lateinit var goodsInfoSearchAdapter: GoodsInfoSearchAdapter
|
||||||
|
private var goodsName: String? = null
|
||||||
|
|
||||||
|
private var activity: BaseActivity? = null
|
||||||
|
|
||||||
|
fun show(activity: BaseActivity, callback: (item: GoodsItem) -> Unit) {
|
||||||
|
this.activity = activity
|
||||||
|
//直接使用BottomSheetDialog
|
||||||
|
var dialog: BottomSheetDialog? = null
|
||||||
|
val inflater = LayoutInflater.from(activity)
|
||||||
|
binding = DialogBottomSheetBinding.inflate(inflater)
|
||||||
|
|
||||||
|
binding.tvSheetName.text = if (goodsType == 1) "调料检索" else "食材检索"
|
||||||
|
binding.etSheetInput.hint = if (goodsType == 1) "输入调料名称" else "输入食材名称或速记码"
|
||||||
|
goodsInfoSearchAdapter = GoodsInfoSearchAdapter(list).apply {
|
||||||
|
setOnItemClickListener { _, _, position ->
|
||||||
|
list[position].isClicked = true
|
||||||
|
notifyItemChanged(position)
|
||||||
|
Handler(Looper.getMainLooper()).postDelayed({
|
||||||
|
callback(list[position])
|
||||||
|
dialog?.dismiss()
|
||||||
|
}, 300)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
binding.recyclerView.run {
|
||||||
|
layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
||||||
|
adapter = goodsInfoSearchAdapter
|
||||||
|
addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
||||||
|
override fun onScrollStateChanged(rv: RecyclerView, newState: Int) {
|
||||||
|
super.onScrollStateChanged(rv, newState);
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) {
|
||||||
|
//解决RecyclerView和smartRefreshLayout滑动冲突问题
|
||||||
|
super.onScrolled(rv, dx, dy)
|
||||||
|
val topRowVerticalPosition = if (rv.isEmpty()) 0 else rv.getChildAt(0).top
|
||||||
|
binding.refreshLayout.setNestedScrollingEnabled(topRowVerticalPosition >= 0)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
dialog = BottomSheetDialog(activity, R.style.BottomSheet).apply {
|
||||||
|
setContentView(binding.root)
|
||||||
|
setCancelable(true)
|
||||||
|
behavior.skipCollapsed = false // 跳过折叠状态
|
||||||
|
// behavior.peekHeight = 880.dp
|
||||||
|
// window?.setLayout(-1, 880.dp)
|
||||||
|
show()
|
||||||
|
setOnDismissListener {
|
||||||
|
activity.hideStatusBar()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
binding.refreshLayout.setOnRefreshListener {
|
||||||
|
pageNo = 1
|
||||||
|
getGoodsList()
|
||||||
|
}
|
||||||
|
|
||||||
|
binding.refreshLayout.setOnLoadMoreListener {
|
||||||
|
getGoodsList()
|
||||||
|
}
|
||||||
|
binding.etSheetInput.addTextChangedListener(
|
||||||
|
onTextChanged = { text, start, before, count ->
|
||||||
|
goodsName = text.toString()
|
||||||
|
})
|
||||||
|
binding.ivSearch.setOnClickListener { v ->
|
||||||
|
searchGoods(v)
|
||||||
|
}
|
||||||
|
binding.root.setOnClickListener { v ->
|
||||||
|
KeyboardUtil.hideKeyboard(v.context, v)
|
||||||
|
}
|
||||||
|
binding.etSheetInput.let { v ->
|
||||||
|
v.addOnActionSearchListener {
|
||||||
|
searchGoods(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
binding.refreshLayout.setEnableRefresh(false)
|
||||||
|
binding.refreshLayout.setEnableLoadMore(false)
|
||||||
|
|
||||||
|
if (defGoodsName.isNullOrBlank().not()) {
|
||||||
|
binding.etSheetInput.let {
|
||||||
|
it.setText(defGoodsName)
|
||||||
|
searchGoods(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun searchGoods(v: View) {
|
||||||
|
if (goodsName.isNullOrBlank()) {
|
||||||
|
activity?.toast("请${binding.etSheetInput.hint}")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
pageNo = 1
|
||||||
|
getGoodsList()
|
||||||
|
KeyboardUtil.hideKeyboard(v.context, v)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var pageNo = 1
|
||||||
|
private val pageSize = 120
|
||||||
|
|
||||||
|
/**
|
||||||
|
*/
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
private fun getGoodsList() {
|
||||||
|
val param = mutableMapOf<String, Any>(
|
||||||
|
"goodsType" to "$goodsType",
|
||||||
|
"placeId" to BaseApp.canteenId,
|
||||||
|
"pageNum" to pageNo,
|
||||||
|
"pageSize" to pageSize
|
||||||
|
)
|
||||||
|
if (goodsName.isNullOrBlank().not()) {
|
||||||
|
param["goodsName"] = goodsName!!
|
||||||
|
}
|
||||||
|
Log.d(TAG, "getGoodsList: param=$param")
|
||||||
|
activity?.lifecycleScope?.launch {
|
||||||
|
val state = RemoteRepository().queryGoodsList(param)
|
||||||
|
when (state) {
|
||||||
|
is UiState.Success -> {
|
||||||
|
val records = state.data
|
||||||
|
if (records.isNullOrEmpty()) {
|
||||||
|
activity?.toast(if (goodsType == 1) "暂未搜索到调料信息" else "暂未搜索到食材信息")
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
if (pageNo == 1) {
|
||||||
|
list.clear()
|
||||||
|
}
|
||||||
|
list.addAll(records)
|
||||||
|
goodsInfoSearchAdapter.notifyDataSetChanged()
|
||||||
|
if (pageNo == 1) {
|
||||||
|
binding.refreshLayout.finishRefresh(1200)
|
||||||
|
} else {
|
||||||
|
binding.refreshLayout.finishLoadMore(1200)
|
||||||
|
}
|
||||||
|
val isLoadMoreEnable = records.size >= pageSize
|
||||||
|
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
|
||||||
|
if (isLoadMoreEnable) {
|
||||||
|
pageNo++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
is UiState.Error -> {
|
||||||
|
activity?.toast(state.msg)
|
||||||
|
if (pageNo == 1) {
|
||||||
|
binding.refreshLayout.finishRefresh(1200)
|
||||||
|
} else {
|
||||||
|
binding.refreshLayout.finishLoadMore(1200)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
package com.shuwei.dish.match.dialog
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.graphics.Typeface
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.text.SpannableStringBuilder
|
||||||
|
import android.text.style.AbsoluteSizeSpan
|
||||||
|
import android.text.style.ForegroundColorSpan
|
||||||
|
import android.text.style.LineHeightSpan
|
||||||
|
import android.text.style.StyleSpan
|
||||||
|
import android.util.Log
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import android.view.View
|
||||||
|
import androidx.core.graphics.toColorInt
|
||||||
|
import androidx.core.view.isEmpty
|
||||||
|
import androidx.core.widget.addTextChangedListener
|
||||||
|
import androidx.recyclerview.widget.GridLayoutManager
|
||||||
|
import androidx.recyclerview.widget.RecyclerView
|
||||||
|
import com.google.android.material.bottomsheet.BottomSheetDialog
|
||||||
|
import com.shuwei.dish.match.R
|
||||||
|
import com.shuwei.dish.match.adapter.SeasoningSearchAdapter
|
||||||
|
import com.shuwei.dish.match.base.BaseActivity
|
||||||
|
import com.shuwei.dish.match.base.BaseApp
|
||||||
|
import com.shuwei.dish.match.databinding.DialogBottomSheet2Binding
|
||||||
|
import com.shuwei.dish.match.model.GoodsItem
|
||||||
|
import com.shuwei.dish.match.net.RemoteRepository
|
||||||
|
import com.shuwei.dish.match.net.UiState
|
||||||
|
import com.shuwei.dish.match.utils.KeyboardUtil
|
||||||
|
import com.shuwei.dish.match.utils.WeightUtil
|
||||||
|
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
||||||
|
import androidx.lifecycle.lifecycleScope
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import com.shuwei.dish.match.utils.ext.appendText
|
||||||
|
import com.shuwei.dish.match.utils.ext.buildSpannableString
|
||||||
|
import com.shuwei.dish.match.utils.ext.dp
|
||||||
|
import com.shuwei.dish.match.utils.ext.roundedDecimalPlace
|
||||||
|
import com.shuwei.dish.match.utils.ext.roundedOneDecimalPlace
|
||||||
|
import com.shuwei.dish.match.utils.ext.toast
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param goodsType 1-调料,0-食材
|
||||||
|
*/
|
||||||
|
class BottomDialog2(
|
||||||
|
private var weighIndex: Int,
|
||||||
|
private var weighAddress: Int,
|
||||||
|
private var clickName: String? = null
|
||||||
|
) {
|
||||||
|
companion object {
|
||||||
|
const val TAG = "BottomDialog2"
|
||||||
|
}
|
||||||
|
|
||||||
|
private val goodsType: Int = 1
|
||||||
|
private var list = mutableListOf<GoodsItem>()
|
||||||
|
|
||||||
|
private lateinit var binding: DialogBottomSheet2Binding
|
||||||
|
private lateinit var searchAdapter: SeasoningSearchAdapter
|
||||||
|
private var goodsName: String? = null
|
||||||
|
|
||||||
|
private var activity: BaseActivity? = null
|
||||||
|
|
||||||
|
fun show(activity: BaseActivity, callback: (item: GoodsItem) -> Unit) {
|
||||||
|
this.activity = activity
|
||||||
|
//直接使用BottomSheetDialog
|
||||||
|
var dialog: BottomSheetDialog? = null
|
||||||
|
val inflater = LayoutInflater.from(activity)
|
||||||
|
binding = DialogBottomSheet2Binding.inflate(inflater)
|
||||||
|
|
||||||
|
//binding.tvSheetName.text = if (goodsType == 1) "调料检索" else "食材检索"
|
||||||
|
binding.etSheetInput.hint = if (goodsType == 1) "输入调料名称" else "输入食材名称或速记码"
|
||||||
|
searchAdapter = SeasoningSearchAdapter(list).apply {
|
||||||
|
setOnItemClickListener { _, _, position ->
|
||||||
|
list[position].isClicked = true
|
||||||
|
notifyItemChanged(position)
|
||||||
|
Handler(Looper.getMainLooper()).postDelayed({
|
||||||
|
callback(list[position].also { it.useWeight = currentWeight })
|
||||||
|
dialog?.dismiss()
|
||||||
|
}, 300)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
binding.recyclerView.run {
|
||||||
|
layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
||||||
|
adapter = searchAdapter
|
||||||
|
addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
||||||
|
override fun onScrollStateChanged(rv: RecyclerView, newState: Int) {
|
||||||
|
super.onScrollStateChanged(rv, newState);
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) {
|
||||||
|
//解决RecyclerView和smartRefreshLayout滑动冲突问题
|
||||||
|
super.onScrolled(rv, dx, dy)
|
||||||
|
val topRowVerticalPosition = if (rv.isEmpty()) 0 else rv.getChildAt(0).top
|
||||||
|
binding.refreshLayout.setNestedScrollingEnabled(topRowVerticalPosition >= 0)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
dialog = BottomSheetDialog(activity, R.style.BottomSheet).apply {
|
||||||
|
setContentView(binding.root)
|
||||||
|
setCancelable(true)
|
||||||
|
behavior.skipCollapsed = false // 跳过折叠状态
|
||||||
|
// behavior.peekHeight = 880.dp
|
||||||
|
// window?.setLayout(-1, 880.dp)
|
||||||
|
show()
|
||||||
|
setOnDismissListener {
|
||||||
|
activity.hideStatusBar()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
binding.refreshLayout.setOnRefreshListener {
|
||||||
|
pageNo = 1
|
||||||
|
getGoodsList()
|
||||||
|
}
|
||||||
|
|
||||||
|
binding.refreshLayout.setOnLoadMoreListener {
|
||||||
|
getGoodsList()
|
||||||
|
}
|
||||||
|
binding.etSheetInput.addTextChangedListener(
|
||||||
|
onTextChanged = { text, start, before, count ->
|
||||||
|
goodsName = text.toString()
|
||||||
|
})
|
||||||
|
binding.ivSearch.setOnClickListener { v ->
|
||||||
|
searchGoods(v)
|
||||||
|
}
|
||||||
|
binding.root.setOnClickListener { v ->
|
||||||
|
KeyboardUtil.hideKeyboard(v.context, v)
|
||||||
|
}
|
||||||
|
binding.etSheetInput.let { v ->
|
||||||
|
v.addOnActionSearchListener {
|
||||||
|
searchGoods(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
binding.refreshLayout.setEnableRefresh(false)
|
||||||
|
binding.tvClear.setOnClickListener {
|
||||||
|
Log.d(TAG, "show: weighAddress=$weighAddress")
|
||||||
|
WeightUtil.tareTwo(weighAddress)
|
||||||
|
// repeat(14) { num->
|
||||||
|
// Log.d(TAG, "show: num=$num")
|
||||||
|
// WeightUtil.tareTwo(num+1)
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
WeightUtil.addWeightListener (
|
||||||
|
weightKey = TAG,
|
||||||
|
getWeight = { address, state, weight ->
|
||||||
|
if (weighAddress == address) {
|
||||||
|
this.currentWeight = weight.toDouble()
|
||||||
|
binding.tvWeight.text = getTextSpan(weight)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
binding.tvWeight.text = getTextSpan(0.0)
|
||||||
|
|
||||||
|
if (clickName.isNullOrBlank().not()) {
|
||||||
|
binding.etSheetInput.setText(clickName!!.trim())
|
||||||
|
pageNo = 1
|
||||||
|
getGoodsList()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun searchGoods(v: View) {
|
||||||
|
if (goodsName.isNullOrBlank()) {
|
||||||
|
activity?.toast("请${binding.etSheetInput.hint}")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
pageNo = 1
|
||||||
|
getGoodsList()
|
||||||
|
KeyboardUtil.hideKeyboard(v.context, v)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var currentWeight = 0.toDouble()
|
||||||
|
private var pageNo = 1
|
||||||
|
private val pageSize = 120
|
||||||
|
|
||||||
|
/**
|
||||||
|
*/
|
||||||
|
@SuppressLint("NotifyDataSetChanged")
|
||||||
|
private fun getGoodsList() {
|
||||||
|
val param = mutableMapOf<String, Any>(
|
||||||
|
"goodsType" to "$goodsType",
|
||||||
|
"placeId" to BaseApp.canteenId,
|
||||||
|
"pageNum" to pageNo,
|
||||||
|
"pageSize" to pageSize
|
||||||
|
)
|
||||||
|
if (goodsName.isNullOrBlank().not()) {
|
||||||
|
param["goodsName"] = goodsName!!
|
||||||
|
}
|
||||||
|
Log.d(TAG, "getGoodsList: param=$param")
|
||||||
|
activity?.lifecycleScope?.launch {
|
||||||
|
val state = RemoteRepository().queryGoodsList(param)
|
||||||
|
when (state) {
|
||||||
|
is UiState.Success -> {
|
||||||
|
val records = state.data
|
||||||
|
if (records.isNullOrEmpty()) {
|
||||||
|
activity?.toast(if (goodsType == 1) "暂未搜索到调料信息" else "暂未搜索到食材信息")
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
if (pageNo == 1) {
|
||||||
|
list.clear()
|
||||||
|
}
|
||||||
|
list.addAll(records)
|
||||||
|
searchAdapter.notifyDataSetChanged()
|
||||||
|
if (pageNo == 1) {
|
||||||
|
binding.refreshLayout.finishRefresh(1200)
|
||||||
|
} else {
|
||||||
|
binding.refreshLayout.finishLoadMore(1200)
|
||||||
|
}
|
||||||
|
val isLoadMoreEnable = records.size >= pageSize
|
||||||
|
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
|
||||||
|
if (isLoadMoreEnable) {
|
||||||
|
pageNo++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
is UiState.Error -> {
|
||||||
|
activity?.toast(state.msg)
|
||||||
|
if (pageNo == 1) {
|
||||||
|
binding.refreshLayout.finishRefresh(1200)
|
||||||
|
} else {
|
||||||
|
binding.refreshLayout.finishLoadMore(1200)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getTextSpan(weight: Double): SpannableStringBuilder {
|
||||||
|
var topWeight = "$weight"
|
||||||
|
var bottomUnit = "克"
|
||||||
|
if (weight >= 1000) {
|
||||||
|
topWeight = "${(weight/1000).roundedDecimalPlace(3)}"
|
||||||
|
bottomUnit = "千克"
|
||||||
|
}
|
||||||
|
return buildSpannableString {
|
||||||
|
appendText(
|
||||||
|
topWeight,
|
||||||
|
ForegroundColorSpan("#000000".toColorInt()),
|
||||||
|
StyleSpan(Typeface.BOLD),
|
||||||
|
AbsoluteSizeSpan(72, true),
|
||||||
|
LineHeightSpan { text, start, end, spanstartv, v, fm ->
|
||||||
|
fm.descent += 10.dp // 增加行间距
|
||||||
|
}
|
||||||
|
)
|
||||||
|
append("\n")
|
||||||
|
appendText(
|
||||||
|
bottomUnit,
|
||||||
|
ForegroundColorSpan("#999999".toColorInt()),
|
||||||
|
AbsoluteSizeSpan(30, true)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,19 +1,18 @@
|
|||||||
package com.shuwei.dish.match.dialog
|
package com.shuwei.dish.match.dialog
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
import android.app.Dialog
|
import android.app.Dialog
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.graphics.drawable.ColorDrawable
|
import android.graphics.drawable.ColorDrawable
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.view.View
|
import android.view.View
|
||||||
import android.view.Window
|
import android.view.Window
|
||||||
import android.widget.LinearLayout
|
import android.view.WindowManager
|
||||||
import android.widget.TextView
|
import androidx.annotation.StyleRes
|
||||||
import androidx.core.view.updateLayoutParams
|
import androidx.fragment.app.FragmentActivity
|
||||||
import com.shuwei.dish.match.base.DeviceRole
|
|
||||||
import com.shuwei.dish.match.base.GlobalData
|
|
||||||
import com.shuwei.dish.match.databinding.DialogCommonBinding
|
import com.shuwei.dish.match.databinding.DialogCommonBinding
|
||||||
import com.shuwei.dish.match.utils.ext.dp
|
import com.shuwei.dish.match.utils.ext.dp
|
||||||
import com.shuwei.dish.match.R
|
import java.lang.ref.WeakReference
|
||||||
|
|
||||||
open class CommonDialog(
|
open class CommonDialog(
|
||||||
context: Context
|
context: Context
|
||||||
@@ -21,165 +20,62 @@ open class CommonDialog(
|
|||||||
|
|
||||||
private lateinit var binding: DialogCommonBinding
|
private lateinit var binding: DialogCommonBinding
|
||||||
|
|
||||||
private var titleText: String? = null
|
|
||||||
private var contentText: CharSequence? = null
|
|
||||||
private var negativeText = "取消"
|
|
||||||
private var positiveText = "确认"
|
|
||||||
private var neutralText: String? = null
|
|
||||||
private var singleText: String? = null
|
|
||||||
private var negativeClick: (() -> Unit)? = null
|
|
||||||
// 返回 true 时关闭弹窗,返回 false 时保持弹窗显示(用于校验不通过的场景)
|
|
||||||
private var positiveClick: (() -> Boolean)? = null
|
|
||||||
private var neutralClick: (() -> Unit)? = null
|
|
||||||
private var singleClick: (() -> Unit)? = null
|
|
||||||
private var dismissCallback: (() -> Unit)? = null
|
|
||||||
// 待添加到 llContent 的自定义 View,在 onCreate 后挂载
|
|
||||||
private var pendingContentView: View? = null
|
|
||||||
// pendingContentView 非空时对 tvContent 的灵活控制回调(可调整可见性、间距等)
|
|
||||||
private var tvContentConfigurator: ((TextView) -> Unit)? = null
|
|
||||||
|
|
||||||
/** 设置标题,为空时隐藏 */
|
|
||||||
fun setTitle(text: String): CommonDialog = apply { titleText = text }
|
|
||||||
|
|
||||||
/** 设置内容,为空时隐藏 */
|
|
||||||
fun setContent(text: CharSequence): CommonDialog = apply { contentText = text }
|
|
||||||
|
|
||||||
/** 设置左侧取消按钮文字及点击回调(3按钮模式下对应顶部按钮) */
|
|
||||||
fun setNegativeButton(text: String, onClick: (() -> Unit)? = null): CommonDialog = apply {
|
|
||||||
negativeText = text
|
|
||||||
negativeClick = onClick
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 设置右侧确认按钮文字及点击回调(3按钮模式下对应底部按钮),点击后自动关闭弹窗 */
|
|
||||||
fun setPositiveButton(text: String, onClick: (() -> Unit)? = null): CommonDialog = apply {
|
|
||||||
positiveText = text
|
|
||||||
positiveClick = onClick?.let { cb -> { cb(); true } }
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 设置右侧确认按钮文字及可拦截的点击回调
|
|
||||||
* 回调返回 true 时关闭弹窗,返回 false 时保持弹窗显示(用于校验不通过的场景)
|
|
||||||
*/
|
|
||||||
fun setPositiveButtonInterceptable(text: String, onClick: () -> Boolean): CommonDialog = apply {
|
|
||||||
positiveText = text
|
|
||||||
positiveClick = onClick
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 设置中间第三个按钮文字及点击回调,调用后自动切换为垂直3按钮布局 */
|
|
||||||
fun setNeutralButton(text: String, onClick: (() -> Unit)? = null): CommonDialog = apply {
|
|
||||||
neutralText = text
|
|
||||||
neutralClick = onClick
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 设置单按钮文字及点击回调,调用后自动切换为单按钮布局(优先级最高) */
|
|
||||||
fun setSingleButton(text: String, onClick: (() -> Unit)? = null): CommonDialog = apply {
|
|
||||||
singleText = text
|
|
||||||
singleClick = onClick
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 设置弹窗消失回调 */
|
|
||||||
fun setOnDismissCallback(callback: () -> Unit): CommonDialog = apply {
|
|
||||||
dismissCallback = callback
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 向弹窗自定义内容区域添加 View,调用后 llContent 自动显示
|
|
||||||
* @param view 要嵌入的自定义布局(如单选列表)
|
|
||||||
* @param tvContentConfig 可选回调,用于在 pendingContentView 非空时灵活控制 tvContent 的可见性及间距等属性
|
|
||||||
*/
|
|
||||||
fun addContentView(view: View, tvContentConfig: ((TextView) -> Unit)? = null): CommonDialog = apply {
|
|
||||||
pendingContentView = view
|
|
||||||
tvContentConfigurator = tvContentConfig
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
requestWindowFeature(Window.FEATURE_NO_TITLE)
|
requestWindowFeature(Window.FEATURE_NO_TITLE)
|
||||||
binding = DialogCommonBinding.inflate(layoutInflater)
|
binding = DialogCommonBinding.inflate(layoutInflater)
|
||||||
setContentView(binding.root)
|
setContentView(binding.root)
|
||||||
// 弹窗不允许点击外部关闭
|
|
||||||
setCancelable(false)
|
|
||||||
val isMaster = GlobalData.deviceRole == DeviceRole.MASTER
|
|
||||||
window?.run {
|
window?.run {
|
||||||
val screenWidth = context.resources.displayMetrics.widthPixels
|
// decorView.setPadding(0.dp, 0, 0.dp, 0)
|
||||||
attributes = attributes.apply {
|
attributes = attributes.apply {
|
||||||
width = if (isMaster) (screenWidth * 0.72f).toInt() else (screenWidth * 0.60f).toInt()
|
width = 708.dp
|
||||||
}
|
}
|
||||||
// 透明背景,让 shape_dialog_bg 的阴影层正常显示
|
|
||||||
setBackgroundDrawable(ColorDrawable())
|
setBackgroundDrawable(ColorDrawable())
|
||||||
// 应用缩放+淡入淡出动画
|
setCancelable(false)
|
||||||
setWindowAnimations(R.style.CommonDialogAnimation)
|
// setFlags(
|
||||||
}
|
// WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
|
||||||
// 主/从设备边距微调:主设备内容区域更大,适当增加上下留白
|
// WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
|
||||||
val verticalMargin = if (isMaster) 48.dp else 36.dp
|
// )
|
||||||
binding.tvTitle.updateLayoutParams<LinearLayout.LayoutParams> { topMargin = verticalMargin }
|
|
||||||
binding.tvContent.updateLayoutParams<LinearLayout.LayoutParams> { bottomMargin = verticalMargin }
|
|
||||||
|
|
||||||
// 2按钮点击事件
|
|
||||||
binding.btnLeft.setOnClickListener {
|
|
||||||
negativeClick?.invoke()
|
|
||||||
dismiss()
|
|
||||||
}
|
|
||||||
binding.btnRight.setOnClickListener {
|
|
||||||
// 回调返回 false 时阻止关闭,null 或 true 时正常关闭
|
|
||||||
if (positiveClick?.invoke() != false) dismiss()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3按钮点击事件(negativeClick/positiveClick 与2按钮模式共用)
|
binding.llContent.run {
|
||||||
binding.btnTop.setOnClickListener {
|
removeAllViews()
|
||||||
negativeClick?.invoke()
|
addView(messageView)
|
||||||
dismiss()
|
|
||||||
}
|
|
||||||
binding.btnMiddle.setOnClickListener {
|
|
||||||
neutralClick?.invoke()
|
|
||||||
dismiss()
|
|
||||||
}
|
|
||||||
binding.btnBottom.setOnClickListener {
|
|
||||||
if (positiveClick?.invoke() != false) dismiss()
|
|
||||||
}
|
|
||||||
|
|
||||||
// 单按钮点击事件
|
|
||||||
binding.btnSingle.setOnClickListener {
|
|
||||||
singleClick?.invoke()
|
|
||||||
dismiss()
|
|
||||||
}
|
|
||||||
|
|
||||||
setOnDismissListener { dismissCallback?.invoke() }
|
|
||||||
|
|
||||||
// 挂载自定义内容 View,并执行 tvContent 的灵活控制回调
|
|
||||||
pendingContentView?.let {
|
|
||||||
binding.llContent.removeAllViews()
|
|
||||||
binding.llContent.addView(it)
|
|
||||||
binding.llContent.visibility = View.VISIBLE
|
|
||||||
tvContentConfigurator?.invoke(binding.tvContent)
|
|
||||||
}
|
}
|
||||||
|
addListener()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun addListener() {
|
||||||
|
binding.btnLeft.setOnClickListener { onLeftClick?.invoke() }
|
||||||
|
binding.btnRight.setOnClickListener { onRightClick?.invoke() }
|
||||||
|
setOnDismissListener { onDismiss?.invoke() }
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
override fun show() {
|
override fun show() {
|
||||||
super.show()
|
super.show()
|
||||||
binding.tvTitle.text = titleText
|
binding.btnLeft.text = leftText
|
||||||
binding.tvContent.text = contentText
|
binding.btnRight.text = rightText
|
||||||
binding.tvTitle.visibility = if (titleText.isNullOrEmpty()) View.GONE else View.VISIBLE
|
}
|
||||||
binding.tvContent.visibility = if (contentText.isNullOrEmpty()) View.GONE else View.VISIBLE
|
|
||||||
|
|
||||||
val hasThreeButtons = !neutralText.isNullOrEmpty()
|
var messageView: View? = null
|
||||||
val hasSingleButton = !singleText.isNullOrEmpty()
|
var onLeftClick: (() -> Unit)? = null
|
||||||
binding.btnSingle.visibility = if (hasSingleButton) View.VISIBLE else View.GONE
|
var onRightClick: (() -> Unit)? = null
|
||||||
binding.layoutButtonsHorizontal.visibility = if (!hasSingleButton && !hasThreeButtons) View.VISIBLE else View.GONE
|
|
||||||
binding.layoutButtonsVertical.visibility = if (hasThreeButtons) View.VISIBLE else View.GONE
|
|
||||||
|
|
||||||
if (hasSingleButton) {
|
var leftText = ""
|
||||||
// 单按钮模式
|
var rightText = ""
|
||||||
binding.btnSingle.text = singleText
|
|
||||||
} else if (hasThreeButtons) {
|
var onDismiss: (() -> Unit)? = null
|
||||||
// 3按钮模式:顶部=取消,中间=中立,底部=确认
|
|
||||||
binding.btnTop.text = negativeText
|
}
|
||||||
binding.btnMiddle.text = neutralText
|
|
||||||
binding.btnBottom.text = positiveText
|
open class SafeDialog(activity: Activity, @StyleRes themeResId: Int) :
|
||||||
} else {
|
Dialog(activity, themeResId) {
|
||||||
// 2按钮模式
|
private val weakContext = WeakReference(activity)
|
||||||
binding.btnLeft.text = negativeText
|
|
||||||
binding.btnRight.text = positiveText
|
override fun show() {
|
||||||
|
weakContext.get()?.let {
|
||||||
|
if (!it.isFinishing && !it.isDestroyed) super.show()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.shuwei.dish.match.dialog
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.view.LayoutInflater
|
||||||
|
import com.shuwei.dish.match.databinding.LayoutFoodRemindBinding
|
||||||
|
|
||||||
|
object DialogTool {
|
||||||
|
|
||||||
|
fun load(
|
||||||
|
context: Context,
|
||||||
|
title:String,
|
||||||
|
content:String,
|
||||||
|
leftBtnText: String,
|
||||||
|
rightBtnText: String,
|
||||||
|
leftBtnClick: () -> Unit = {},
|
||||||
|
rightBtnClick: () -> Unit = {}
|
||||||
|
) {
|
||||||
|
val layoutInflater = LayoutInflater.from(context)
|
||||||
|
val remindBinding = LayoutFoodRemindBinding.inflate(layoutInflater)
|
||||||
|
remindBinding.tvDialogTitle.text = title
|
||||||
|
remindBinding.tvDialogContent.text = content
|
||||||
|
CommonDialog(context).apply {
|
||||||
|
messageView = remindBinding.root
|
||||||
|
leftText = leftBtnText
|
||||||
|
rightText = rightBtnText
|
||||||
|
onLeftClick = {
|
||||||
|
leftBtnClick()
|
||||||
|
dismiss()
|
||||||
|
}
|
||||||
|
onRightClick = {
|
||||||
|
rightBtnClick()
|
||||||
|
dismiss()
|
||||||
|
}
|
||||||
|
onDismiss = { }
|
||||||
|
}.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
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()
|
|
||||||
}
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
//package com.shuwei.dish.match.dialog
|
|
||||||
//
|
|
||||||
//import android.annotation.SuppressLint
|
|
||||||
//import android.os.Handler
|
|
||||||
//import android.os.Looper
|
|
||||||
//import android.view.LayoutInflater
|
|
||||||
//import androidx.recyclerview.widget.GridLayoutManager
|
|
||||||
//import com.google.android.material.bottomsheet.BottomSheetDialog
|
|
||||||
//import com.shuwei.dish.match.R
|
|
||||||
//import com.shuwei.dish.match.adapter.FoodAdapter
|
|
||||||
//import com.shuwei.dish.match.base.BaseActivity
|
|
||||||
//import com.shuwei.dish.match.databinding.DialogFoodRecognizeBinding
|
|
||||||
//import com.shuwei.dish.match.entity.GoodsItem
|
|
||||||
//
|
|
||||||
///**
|
|
||||||
// * 菜品识别结果弹窗,继承 BottomSheetDialog 确保只初始化一次
|
|
||||||
// * @param activity 宿主 Activity
|
|
||||||
// * @param onDismiss 弹窗关闭时的额外回调(可选)
|
|
||||||
// * @param onItemSelected 用户点击某一菜品时的回调
|
|
||||||
// */
|
|
||||||
//class FoodRecognizeDialog(
|
|
||||||
// private val activity: BaseActivity,
|
|
||||||
// private val onDismiss: (() -> Unit)? = null,
|
|
||||||
// private val onItemSelected: (item: GoodsItem) -> Unit
|
|
||||||
//) : BottomSheetDialog(activity, R.style.BottomSheet) {
|
|
||||||
//
|
|
||||||
// private val binding = DialogFoodRecognizeBinding.inflate(LayoutInflater.from(activity))
|
|
||||||
// private val list = mutableListOf<GoodsItem>()
|
|
||||||
// private val adapter = FoodAdapter(list).apply {
|
|
||||||
// setOnItemClickListener { _, _, position ->
|
|
||||||
// list[position].isClicked = true
|
|
||||||
// notifyItemChanged(position)
|
|
||||||
// Handler(Looper.getMainLooper()).postDelayed({
|
|
||||||
// onItemSelected(list[position])
|
|
||||||
// dismiss()
|
|
||||||
// }, 300)
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// init {
|
|
||||||
// setContentView(binding.root)
|
|
||||||
// setCancelable(true)
|
|
||||||
// behavior.skipCollapsed = false
|
|
||||||
// setOnDismissListener { activity.hideStatusBar(); onDismiss?.invoke() }
|
|
||||||
// binding.recyclerView.run {
|
|
||||||
// layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
|
||||||
// adapter = this@FoodRecognizeDialog.adapter
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// /**
|
|
||||||
// * 加载识别结果数据并显示弹窗
|
|
||||||
// * @param items 识别到的菜品列表
|
|
||||||
// */
|
|
||||||
// @SuppressLint("NotifyDataSetChanged")
|
|
||||||
// fun loadData(items: List<GoodsItem>) {
|
|
||||||
// list.clear()
|
|
||||||
// list.addAll(items)
|
|
||||||
// adapter.notifyDataSetChanged()
|
|
||||||
// if (!isShowing) show()
|
|
||||||
// }
|
|
||||||
//}
|
|
||||||
@@ -1,291 +0,0 @@
|
|||||||
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.lifecycle.Lifecycle
|
|
||||||
import androidx.lifecycle.lifecycleScope
|
|
||||||
import androidx.lifecycle.repeatOnLifecycle
|
|
||||||
import androidx.recyclerview.widget.GridLayoutManager
|
|
||||||
import androidx.recyclerview.widget.LinearLayoutManager
|
|
||||||
import com.chad.library.adapter4.util.setOnDebouncedItemClick
|
|
||||||
import com.google.android.material.bottomsheet.BottomSheetDialog
|
|
||||||
import com.shuwei.dish.match.R
|
|
||||||
import com.shuwei.dish.match.adapter.FoodAdapter
|
|
||||||
import com.shuwei.dish.match.base.BaseActivity
|
|
||||||
import com.shuwei.dish.match.databinding.DialogFoodSearchBinding
|
|
||||||
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
|
||||||
import com.shuwei.dish.match.model.GoodsItem
|
|
||||||
import com.shuwei.dish.match.net.UiState
|
|
||||||
import com.shuwei.dish.match.utils.KeyboardUtil
|
|
||||||
import com.shuwei.dish.match.utils.showRawMaterialsDialog
|
|
||||||
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
|
||||||
import com.shuwei.dish.match.utils.ext.toast
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 食材搜索弹窗,继承 BottomSheetDialog 确保只初始化一次
|
|
||||||
* @param activity 宿主 Activity
|
|
||||||
* @param defGoodsName 默认填充的食材名称(可选)
|
|
||||||
* @param onItemSelected 用户点击某一食材时的回调
|
|
||||||
*/
|
|
||||||
class FoodSearchDialog(
|
|
||||||
private val activity: BaseActivity,
|
|
||||||
private val defGoodsName: String? = null,
|
|
||||||
private val onItemSelected: (item: GoodsItem) -> Unit
|
|
||||||
) : BottomSheetDialog(activity, R.style.BottomSheet) {
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
const val PAGE_SIZE = 50
|
|
||||||
}
|
|
||||||
|
|
||||||
private val binding = DialogFoodSearchBinding.inflate(LayoutInflater.from(activity))
|
|
||||||
private val list = mutableListOf<GoodsItem>()
|
|
||||||
|
|
||||||
private val adapter = FoodAdapter(list).apply {
|
|
||||||
isStateViewEnable = true
|
|
||||||
setOnDebouncedItemClick { _, _, position ->
|
|
||||||
val item = list.getOrNull(position) ?: return@setOnDebouncedItemClick
|
|
||||||
// 弹出净材种类单选弹窗,确认后再回调并关闭弹窗
|
|
||||||
showRawMaterialsDialog(
|
|
||||||
context = activity,
|
|
||||||
types = item.rawMaterialsTypes,
|
|
||||||
checkedType = item.rawMaterialsType
|
|
||||||
) { selectedType ->
|
|
||||||
item.rawMaterialsType = selectedType
|
|
||||||
item.isClicked = true
|
|
||||||
notifyItemChanged(position)
|
|
||||||
binding.root.postDelayed({
|
|
||||||
onItemSelected(item)
|
|
||||||
dismiss()
|
|
||||||
}, 300)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private var goodsName: String? = null
|
|
||||||
private var pageNo = 1
|
|
||||||
|
|
||||||
init {
|
|
||||||
setContentView(binding.root)
|
|
||||||
setCancelable(true)
|
|
||||||
behavior.skipCollapsed = false
|
|
||||||
setOnDismissListener { activity.hideStatusBar() }
|
|
||||||
|
|
||||||
binding.tvSheetName.text = "食材检索"
|
|
||||||
|
|
||||||
// 输入框:清空时重置列表
|
|
||||||
binding.etSheetInput.run {
|
|
||||||
hint = "输入食材名称或速记码"
|
|
||||||
addTextChangedListener(
|
|
||||||
onTextChanged = { text, _, _, _ -> goodsName = text.toString() },
|
|
||||||
afterTextChanged = { it: Editable? ->
|
|
||||||
if (it.isNullOrBlank()) {
|
|
||||||
list.clear()
|
|
||||||
adapter.notifyDataSetChanged()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
addOnActionSearchListener { searchGoods(this) }
|
|
||||||
}
|
|
||||||
|
|
||||||
// RecyclerView 初始化
|
|
||||||
binding.recyclerView.run {
|
|
||||||
layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
|
||||||
adapter = this@FoodSearchDialog.adapter
|
|
||||||
// addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
|
||||||
// override fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) {
|
|
||||||
// super.onScrolled(rv, dx, dy)
|
|
||||||
// // 解决 RecyclerView 与 SmartRefreshLayout 滑动冲突
|
|
||||||
// val topRowVerticalPosition = if (rv.isEmpty()) 0 else rv.getChildAt(0).top
|
|
||||||
// binding.refreshLayout.setNestedScrollingEnabled(topRowVerticalPosition >= 0)
|
|
||||||
// }
|
|
||||||
// })
|
|
||||||
}
|
|
||||||
|
|
||||||
binding.refreshLayout.run {
|
|
||||||
setEnableRefresh(true)
|
|
||||||
setEnableLoadMore(false)
|
|
||||||
setOnRefreshListener { pageNo = 1; getGoodsList() }
|
|
||||||
setOnLoadMoreListener { getGoodsList() }
|
|
||||||
}
|
|
||||||
|
|
||||||
binding.ivSearch.setOnClickListener { searchGoods(it) }
|
|
||||||
binding.root.setOnClickListener { KeyboardUtil.hideKeyboard(it) }
|
|
||||||
|
|
||||||
initObserver()
|
|
||||||
|
|
||||||
// 若有默认食材名称,自动填充并触发搜索
|
|
||||||
//if (!defGoodsName.isNullOrBlank()) {
|
|
||||||
//binding.etSheetInput.setText(defGoodsName)
|
|
||||||
pageNo = 1
|
|
||||||
getGoodsList()
|
|
||||||
KeyboardUtil.hideKeyboard(binding.root)
|
|
||||||
//}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 弹窗显示时在 Window.Callback 层提前拦截触摸,解决 BottomSheet 拖拽与列表滑动的手势冲突 */
|
|
||||||
override fun show() {
|
|
||||||
super.show()
|
|
||||||
// Window.Callback.dispatchTouchEvent 在整个 View 树的 onInterceptTouchEvent 之前执行,
|
|
||||||
// 是最早能感知触摸的时机。在此处判断触摸点位置来控制 behavior.isDraggable,
|
|
||||||
// 从而确保 BottomSheetBehavior 在 CoordinatorLayout.onInterceptTouchEvent 时
|
|
||||||
// 已经是禁用状态,不会拦截列表区域的滑动手势。
|
|
||||||
val originalCallback = window?.callback ?: return
|
|
||||||
window?.callback = object : Window.Callback by originalCallback {
|
|
||||||
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
|
|
||||||
when (event.actionMasked) {
|
|
||||||
MotionEvent.ACTION_DOWN -> {
|
|
||||||
val rect = Rect()
|
|
||||||
binding.refreshLayout.getGlobalVisibleRect(rect)
|
|
||||||
// 触摸点落在列表区域内则禁止 BottomSheet 拖拽
|
|
||||||
behavior.isDraggable = !rect.contains(event.rawX.toInt(), event.rawY.toInt())
|
|
||||||
}
|
|
||||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
|
||||||
behavior.isDraggable = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return originalCallback.dispatchTouchEvent(event)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onPointerCaptureChanged(hasCapture: Boolean) {
|
|
||||||
originalCallback.onPointerCaptureChanged(hasCapture)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onProvideKeyboardShortcuts(
|
|
||||||
data: List<KeyboardShortcutGroup?>?,
|
|
||||||
menu: Menu?,
|
|
||||||
deviceId: Int
|
|
||||||
) {
|
|
||||||
originalCallback.onProvideKeyboardShortcuts(data, menu, deviceId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 收集 foodSearchGoodsListState,统一处理 Loading / Success / Error 状态
|
|
||||||
* 使用独立的 State,避免与 FoodRecognizeActivity 等页面共用 goodsListState 产生干扰
|
|
||||||
*/
|
|
||||||
private fun initObserver() {
|
|
||||||
activity.lifecycleScope.launch {
|
|
||||||
activity.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
|
||||||
activity.netViewModel.foodSearchGoodsListState.collect { state ->
|
|
||||||
when (state) {
|
|
||||||
is UiState.Success -> loadGoodsList(state.data)
|
|
||||||
is UiState.Error -> {
|
|
||||||
activity.toast(state.msg)
|
|
||||||
finishRefresh()
|
|
||||||
}
|
|
||||||
else -> {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 触发搜索:校验输入、隐藏键盘、发起请求
|
|
||||||
*/
|
|
||||||
private fun searchGoods(v: View) {
|
|
||||||
if (goodsName.isNullOrBlank()) {
|
|
||||||
activity.toast("请${binding.etSheetInput.hint}")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
pageNo = 1
|
|
||||||
getGoodsList()
|
|
||||||
KeyboardUtil.hideKeyboard(v)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 请求食材列表,使用弹窗专用接口,结果写入 foodSearchGoodsListState
|
|
||||||
*/
|
|
||||||
private fun getGoodsList() {
|
|
||||||
activity.netViewModel.queryFoodSearchGoodsList(
|
|
||||||
goodsType = "0",
|
|
||||||
pageNum = pageNo,
|
|
||||||
pageSize = PAGE_SIZE,
|
|
||||||
goodsName = goodsName.takeUnless { it.isNullOrBlank() }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 将返回数据填充到列表
|
|
||||||
*/
|
|
||||||
@SuppressLint("NotifyDataSetChanged")
|
|
||||||
private fun loadGoodsList(records: MutableList<GoodsItem>?) {
|
|
||||||
finishRefresh()
|
|
||||||
if (records.isNullOrEmpty()) {
|
|
||||||
if (pageNo == 1) {
|
|
||||||
loadEmptyView()
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// 仅当当前不是 GridLayoutManager 时才重新赋值(空态切回网格时)
|
|
||||||
binding.recyclerView.run {
|
|
||||||
if (layoutManager !is GridLayoutManager) {
|
|
||||||
layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (pageNo == 1) list.clear()
|
|
||||||
// 将接口返回的 rawMaterialsType(全部种类)移存到 rawMaterialsTypes,供弹窗使用
|
|
||||||
records.forEach {
|
|
||||||
it.rawMaterialsTypes = it.rawMaterialsType
|
|
||||||
it.rawMaterialsType = null
|
|
||||||
it.oldGoodsId = it.goodsId
|
|
||||||
it.goodsId = it.materId ?: ""
|
|
||||||
}
|
|
||||||
list.addAll(records)
|
|
||||||
adapter.notifyDataSetChanged()
|
|
||||||
val isLoadMoreEnable = records.size >= PAGE_SIZE
|
|
||||||
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
|
|
||||||
if (isLoadMoreEnable) pageNo++
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun finishRefresh() {
|
|
||||||
if (pageNo == 1) binding.refreshLayout.finishRefresh()
|
|
||||||
else binding.refreshLayout.finishLoadMore()
|
|
||||||
}
|
|
||||||
|
|
||||||
private var emptyViewBinding: LayoutEmptyViewBinding? = null
|
|
||||||
|
|
||||||
@SuppressLint("NotifyDataSetChanged")
|
|
||||||
private fun loadEmptyView() {
|
|
||||||
try {
|
|
||||||
binding.refreshLayout.setEnableRefresh(true)
|
|
||||||
binding.refreshLayout.setEnableLoadMore(false)
|
|
||||||
list.clear()
|
|
||||||
adapter.notifyDataSetChanged()
|
|
||||||
if (emptyViewBinding == null) {
|
|
||||||
emptyViewBinding = LayoutEmptyViewBinding.inflate(
|
|
||||||
LayoutInflater.from(activity),
|
|
||||||
binding.recyclerView,
|
|
||||||
false
|
|
||||||
)
|
|
||||||
}
|
|
||||||
emptyViewBinding?.let {
|
|
||||||
it.tvContent.text = "暂无数据"
|
|
||||||
it.tvSubContent.text = "未查询到食材信息,请联系管理员添加"
|
|
||||||
// it.root.setOnClickListener { loadGoodsList(buildMockGoodsList().toMutableList()) }
|
|
||||||
it.root.layoutParams = FrameLayout.LayoutParams(
|
|
||||||
FrameLayout.LayoutParams.MATCH_PARENT,
|
|
||||||
FrameLayout.LayoutParams.MATCH_PARENT
|
|
||||||
)
|
|
||||||
binding.recyclerView.layoutManager = LinearLayoutManager(activity)
|
|
||||||
binding.recyclerView.post {
|
|
||||||
it.root.minimumHeight = binding.recyclerView.height
|
|
||||||
adapter.stateView = it.root
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
e.printStackTrace()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
package com.shuwei.dish.match.dialog
|
|
||||||
|
|
||||||
import android.graphics.Rect
|
|
||||||
import android.view.KeyboardShortcutGroup
|
|
||||||
import android.view.LayoutInflater
|
|
||||||
import android.view.Menu
|
|
||||||
import android.view.MotionEvent
|
|
||||||
import android.view.ViewGroup
|
|
||||||
import androidx.recyclerview.widget.LinearLayoutManager
|
|
||||||
import com.google.android.material.bottomsheet.BottomSheetDialog
|
|
||||||
import com.shuwei.dish.match.R
|
|
||||||
import com.shuwei.dish.match.adapter.GoodsPreviewAdapter
|
|
||||||
import com.shuwei.dish.match.databinding.DialogGoodsPreviewBinding
|
|
||||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
|
||||||
import com.shuwei.dish.match.utils.ext.gone
|
|
||||||
import com.shuwei.dish.match.utils.ext.visible
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 用料明细预览弹窗,以 BottomSheetDialog 形式展示当前 goodsList
|
|
||||||
* @param context 宿主 Context(Activity)
|
|
||||||
* @param goodsList 需要展示的物品列表
|
|
||||||
*/
|
|
||||||
class GoodsPreviewDialog(
|
|
||||||
context: android.content.Context,
|
|
||||||
private val goodsList: List<CookFoodGoodsEntity>
|
|
||||||
) : BottomSheetDialog(context, R.style.BottomSheet) {
|
|
||||||
|
|
||||||
private val binding = DialogGoodsPreviewBinding.inflate(LayoutInflater.from(context))
|
|
||||||
|
|
||||||
init {
|
|
||||||
setContentView(binding.root)
|
|
||||||
setCancelable(true)
|
|
||||||
window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
|
|
||||||
|
|
||||||
binding.rvGoodsList.run {
|
|
||||||
layoutManager = LinearLayoutManager(context)
|
|
||||||
adapter = GoodsPreviewAdapter(goodsList)
|
|
||||||
}
|
|
||||||
// foodId 对同一菜品所有条目相同,统一显示在列表上方
|
|
||||||
val foodId = goodsList.firstOrNull()?.foodId.orEmpty()
|
|
||||||
binding.tvFoodId.text = "菜品ID:${foodId.ifEmpty { "-" }}"
|
|
||||||
if (goodsList.isEmpty()) {
|
|
||||||
binding.rvGoodsList.gone()
|
|
||||||
binding.tvEmpty.visible()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 弹出时注入 Window.Callback,解决 RecyclerView 与 BottomSheet 拖拽的滑动冲突 */
|
|
||||||
override fun show() {
|
|
||||||
super.show()
|
|
||||||
val originalCallback = window?.callback ?: return
|
|
||||||
window?.callback = object : android.view.Window.Callback by originalCallback {
|
|
||||||
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
|
|
||||||
when (event.actionMasked) {
|
|
||||||
MotionEvent.ACTION_DOWN -> {
|
|
||||||
val rect = Rect()
|
|
||||||
binding.rvGoodsList.getGlobalVisibleRect(rect)
|
|
||||||
behavior.isDraggable = !rect.contains(event.rawX.toInt(), event.rawY.toInt())
|
|
||||||
}
|
|
||||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
|
||||||
behavior.isDraggable = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return originalCallback.dispatchTouchEvent(event)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onPointerCaptureChanged(hasCapture: Boolean) {
|
|
||||||
originalCallback.onPointerCaptureChanged(hasCapture)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onProvideKeyboardShortcuts(
|
|
||||||
data: List<KeyboardShortcutGroup?>?,
|
|
||||||
menu: Menu?,
|
|
||||||
deviceId: Int
|
|
||||||
) {
|
|
||||||
originalCallback.onProvideKeyboardShortcuts(data, menu, deviceId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,214 +0,0 @@
|
|||||||
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,103 +1,43 @@
|
|||||||
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 show(context: Context) {
|
||||||
return dialog != null && dialog!!.isShowing
|
|
||||||
}
|
|
||||||
|
|
||||||
fun updateContent(content: String) {
|
|
||||||
if (isShowing().not()) return
|
|
||||||
dialog!!.updateContent(content)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 显示 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?.updateContent(message)
|
dialog?.dismiss()
|
||||||
owner = context // 同一弹窗最后一次 show 决定 owner
|
}
|
||||||
resetTimeout(timeoutMs)
|
|
||||||
return
|
if (dialog == null) {
|
||||||
|
dialog = LoadingDialog(context)
|
||||||
}
|
}
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,32 +45,25 @@ object Loading {
|
|||||||
|
|
||||||
class LoadingDialog(
|
class LoadingDialog(
|
||||||
context: Context,
|
context: Context,
|
||||||
message: String,
|
message: String = "加载中……",
|
||||||
private var onDismiss: () -> Unit
|
private var onDismiss: () -> Unit = {}
|
||||||
) : Dialog(context, R.style.LoadingDialog) {
|
) : Dialog(context, R.style.LoadingDialog) {
|
||||||
private val binding: DialogLoadingBinding by lazy {
|
|
||||||
DialogLoadingBinding.inflate(LayoutInflater.from(context))
|
|
||||||
}
|
|
||||||
|
|
||||||
init {
|
init {
|
||||||
|
val binding = DialogLoadingBinding.inflate(LayoutInflater.from(context))
|
||||||
binding.tvMessage.text = message
|
binding.tvMessage.text = message
|
||||||
setContentView(binding.root)
|
setContentView(binding.root)
|
||||||
setCancelable(true)
|
setCancelable(true)
|
||||||
window?.run {
|
window?.run {
|
||||||
setBackgroundDrawable(Color.TRANSPARENT.toDrawable())
|
setBackgroundDrawable(Color.TRANSPARENT.toDrawable())
|
||||||
// setFlags(
|
setFlags(
|
||||||
// WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
|
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
|
||||||
// WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
|
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
|
||||||
// );
|
);
|
||||||
}
|
}
|
||||||
setOnDismissListener {
|
setOnDismissListener {
|
||||||
onDismiss()
|
onDismiss()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun updateContent(content: String) {
|
|
||||||
binding.tvMessage.text = content
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//class LoadingDialog3(
|
//class LoadingDialog3(
|
||||||
|
|||||||
@@ -1,259 +0,0 @@
|
|||||||
//package com.shuwei.dish.match.dialog
|
|
||||||
//
|
|
||||||
//import android.annotation.SuppressLint
|
|
||||||
//import android.graphics.Typeface
|
|
||||||
//import android.os.Handler
|
|
||||||
//import android.os.Looper
|
|
||||||
//import android.text.SpannableStringBuilder
|
|
||||||
//import android.text.style.AbsoluteSizeSpan
|
|
||||||
//import android.text.style.ForegroundColorSpan
|
|
||||||
//import android.text.style.LineHeightSpan
|
|
||||||
//import android.text.style.StyleSpan
|
|
||||||
//import android.util.Log
|
|
||||||
//import android.view.Gravity
|
|
||||||
//import android.view.LayoutInflater
|
|
||||||
//import android.view.View
|
|
||||||
//import android.view.ViewGroup
|
|
||||||
//import android.view.WindowManager
|
|
||||||
//import androidx.core.graphics.toColorInt
|
|
||||||
//import androidx.core.view.isEmpty
|
|
||||||
//import androidx.core.widget.addTextChangedListener
|
|
||||||
//import androidx.lifecycle.Lifecycle
|
|
||||||
//import androidx.lifecycle.lifecycleScope
|
|
||||||
//import androidx.lifecycle.repeatOnLifecycle
|
|
||||||
//import androidx.recyclerview.widget.GridLayoutManager
|
|
||||||
//import androidx.recyclerview.widget.RecyclerView
|
|
||||||
//import com.google.android.material.bottomsheet.BottomSheetDialog
|
|
||||||
//import com.shuwei.dish.match.R
|
|
||||||
//import com.shuwei.dish.match.adapter.SeasoningSearchAdapter
|
|
||||||
//import com.shuwei.dish.match.base.BaseActivity
|
|
||||||
//import com.shuwei.dish.match.base.BaseApp
|
|
||||||
//import com.shuwei.dish.match.databinding.DialogSeasoningSearchBinding
|
|
||||||
//import com.shuwei.dish.match.entity.SeasoningEntity
|
|
||||||
//import com.shuwei.dish.match.net.UiState
|
|
||||||
//import com.shuwei.dish.match.utils.KeyboardUtil
|
|
||||||
//import com.shuwei.dish.match.utils.WeightUtil
|
|
||||||
//import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
|
||||||
//import com.shuwei.dish.match.utils.ext.appendText
|
|
||||||
//import com.shuwei.dish.match.utils.ext.buildSpannableString
|
|
||||||
//import com.shuwei.dish.match.utils.ext.dp
|
|
||||||
//import com.shuwei.dish.match.utils.ext.roundedDecimalPlace
|
|
||||||
//import com.shuwei.dish.match.utils.ext.toast
|
|
||||||
//import kotlinx.coroutines.launch
|
|
||||||
//
|
|
||||||
///**
|
|
||||||
// * 调料搜索弹窗,继承 BottomSheetDialog 确保只初始化一次
|
|
||||||
// * @param activity 宿主 Activity
|
|
||||||
// * @param weighIndex 秤的索引
|
|
||||||
// * @param weighAddress 秤的地址,用于监听重量和去皮
|
|
||||||
// * @param clickName 默认填充的调料名称(可选)
|
|
||||||
// * @param onItemSelected 用户点击某一调料时的回调,携带当前重量
|
|
||||||
// */
|
|
||||||
//class SeasoningSearchDialog(
|
|
||||||
// private val activity: BaseActivity,
|
|
||||||
// private val weighIndex: Int,
|
|
||||||
// private val weighAddress: Int,
|
|
||||||
// private val clickName: String? = null,
|
|
||||||
// private val onItemSelected: (item: SeasoningEntity) -> Unit
|
|
||||||
//) : BottomSheetDialog(activity, R.style.BottomSheet) {
|
|
||||||
//
|
|
||||||
// companion object {
|
|
||||||
// const val TAG = "BottomDialog2"
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// private val binding = DialogSeasoningSearchBinding.inflate(LayoutInflater.from(activity))
|
|
||||||
// private val list = mutableListOf<SeasoningEntity>()
|
|
||||||
// private val adapter = SeasoningSearchAdapter(list).apply {
|
|
||||||
// setOnItemClickListener { _, _, position ->
|
|
||||||
// list[position].isClicked = true
|
|
||||||
// notifyItemChanged(position)
|
|
||||||
// Handler(Looper.getMainLooper()).postDelayed({
|
|
||||||
// onItemSelected(list[position].also { it.useWeight = currentWeight })
|
|
||||||
// dismiss()
|
|
||||||
// }, 300)
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// private var goodsName: String? = null
|
|
||||||
// private var currentWeight = 0.0
|
|
||||||
// private var pageNo = 1
|
|
||||||
// private val pageSize = 50
|
|
||||||
//
|
|
||||||
// init {
|
|
||||||
// setContentView(binding.root)
|
|
||||||
// setCancelable(true)
|
|
||||||
// behavior.skipCollapsed = false
|
|
||||||
// window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
|
|
||||||
// window?.setGravity(Gravity.BOTTOM)
|
|
||||||
// window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
|
|
||||||
// window?.setWindowAnimations(R.style.DialogSoftInputAnimation)
|
|
||||||
// window?.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
|
|
||||||
//
|
|
||||||
// setOnDismissListener {
|
|
||||||
// // 弹窗关闭时移除重量监听,避免内存泄漏
|
|
||||||
// WeightUtil.removeWeightListener(TAG)
|
|
||||||
// activity.hideStatusBar()
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// // 输入框:清空时重置列表
|
|
||||||
// binding.etSheetInput.run {
|
|
||||||
// hint = "输入调料名称"
|
|
||||||
// addTextChangedListener(
|
|
||||||
// onTextChanged = { text, _, _, _ -> goodsName = text.toString() },
|
|
||||||
// afterTextChanged = {
|
|
||||||
// if (it.isNullOrBlank()) {
|
|
||||||
// list.clear()
|
|
||||||
// adapter.notifyDataSetChanged()
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// )
|
|
||||||
// addOnActionSearchListener { searchGoods(this) }
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// // RecyclerView 初始化及滑动冲突处理
|
|
||||||
// binding.recyclerView.let {
|
|
||||||
// it.layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
|
||||||
// it.adapter = adapter
|
|
||||||
// it.addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
|
||||||
// override fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) {
|
|
||||||
// super.onScrolled(rv, dx, dy)
|
|
||||||
// // 解决 RecyclerView 与 SmartRefreshLayout 滑动冲突
|
|
||||||
// val topRowVerticalPosition = if (rv.isEmpty()) 0 else rv.getChildAt(0).top
|
|
||||||
// binding.refreshLayout.setNestedScrollingEnabled(topRowVerticalPosition >= 0)
|
|
||||||
// }
|
|
||||||
// })
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// binding.refreshLayout.run {
|
|
||||||
// setEnableRefresh(false)
|
|
||||||
// setEnableLoadMore(false)
|
|
||||||
// setOnRefreshListener { pageNo = 1; getGoodsList() }
|
|
||||||
// setOnLoadMoreListener { getGoodsList() }
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// binding.ivSearch.setOnClickListener { searchGoods(it) }
|
|
||||||
// binding.root.setOnClickListener { KeyboardUtil.hideKeyboard(it) }
|
|
||||||
//
|
|
||||||
// // 去皮按钮
|
|
||||||
// binding.tvClear.setOnClickListener {
|
|
||||||
// Log.d(TAG, "tareTwo: weighAddress=$weighAddress")
|
|
||||||
// WeightUtil.tareTwo(weighAddress)
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// // 监听对应秤的重量变化
|
|
||||||
// WeightUtil.addWeightListener(
|
|
||||||
// weightKey = TAG,
|
|
||||||
// getWeight = { address, _, weight ->
|
|
||||||
// if (weighAddress == address) {
|
|
||||||
// currentWeight = weight.toDouble()
|
|
||||||
// binding.tvWeight.text = getTextSpan(weight)
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// )
|
|
||||||
// binding.tvWeight.text = getTextSpan(0.0)
|
|
||||||
//
|
|
||||||
// initObserver()
|
|
||||||
//
|
|
||||||
// // 若有默认调料名称,自动填充并触发搜索
|
|
||||||
// if (!clickName.isNullOrBlank()) {
|
|
||||||
// binding.etSheetInput.setText(clickName.trim())
|
|
||||||
// pageNo = 1
|
|
||||||
// getGoodsList()
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// /**
|
|
||||||
// * 收集 seasoningListState,统一处理 Loading / Success / Error 状态
|
|
||||||
// */
|
|
||||||
// private fun initObserver() {
|
|
||||||
// activity.lifecycleScope.launch {
|
|
||||||
// activity.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
|
||||||
// activity.netViewModel.seasoningListState.collect { state ->
|
|
||||||
// when (state) {
|
|
||||||
// is UiState.Success -> loadGoodsList(state.data)
|
|
||||||
// is UiState.Error -> {
|
|
||||||
// activity.toast(state.msg)
|
|
||||||
// finishRefresh()
|
|
||||||
// }
|
|
||||||
// else -> {}
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// /**
|
|
||||||
// * 触发搜索:校验输入、隐藏键盘、发起请求
|
|
||||||
// */
|
|
||||||
// private fun searchGoods(v: View) {
|
|
||||||
// if (goodsName.isNullOrBlank()) {
|
|
||||||
// activity.toast("请${binding.etSheetInput.hint}")
|
|
||||||
// return
|
|
||||||
// }
|
|
||||||
// pageNo = 1
|
|
||||||
// getGoodsList()
|
|
||||||
// KeyboardUtil.hideKeyboard(v)
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// /**
|
|
||||||
// * 请求调料列表
|
|
||||||
// */
|
|
||||||
// private fun getGoodsList() {
|
|
||||||
// val param = mutableMapOf<String, Any>(
|
|
||||||
// "goodsType" to "1",
|
|
||||||
// "placeId" to BaseApp.canteenId,
|
|
||||||
// "pageNum" to pageNo,
|
|
||||||
// "pageSize" to pageSize
|
|
||||||
// )
|
|
||||||
// if (!goodsName.isNullOrBlank()) {
|
|
||||||
// param["goodsName"] = goodsName!!
|
|
||||||
// }
|
|
||||||
// activity.netViewModel.querySeasoningList(param)
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// /**
|
|
||||||
// * 将返回数据填充到列表
|
|
||||||
// */
|
|
||||||
// @SuppressLint("NotifyDataSetChanged")
|
|
||||||
// private fun loadGoodsList(records: MutableList<SeasoningEntity>?) {
|
|
||||||
// finishRefresh()
|
|
||||||
// if (records.isNullOrEmpty()) {
|
|
||||||
// activity.toast("暂未搜索到调料信息")
|
|
||||||
// return
|
|
||||||
// }
|
|
||||||
// if (pageNo == 1) list.clear()
|
|
||||||
// list.addAll(records)
|
|
||||||
// adapter.notifyDataSetChanged()
|
|
||||||
// val isLoadMoreEnable = records.size >= pageSize
|
|
||||||
// binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
|
|
||||||
// if (isLoadMoreEnable) pageNo++
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// private fun finishRefresh() {
|
|
||||||
// if (pageNo == 1) binding.refreshLayout.finishRefresh()
|
|
||||||
// else binding.refreshLayout.finishLoadMore()
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// /**
|
|
||||||
// * 生成重量显示的富文本:数值大字加粗,单位小字灰色
|
|
||||||
// */
|
|
||||||
// fun getTextSpan(weight: Double): SpannableStringBuilder {
|
|
||||||
// val topWeight = if (weight >= 1000) "${(weight / 1000).roundedDecimalPlace(3)}" else "$weight"
|
|
||||||
// val bottomUnit = if (weight >= 1000) "千克" else "克"
|
|
||||||
// return buildSpannableString {
|
|
||||||
// appendText(
|
|
||||||
// topWeight,
|
|
||||||
// ForegroundColorSpan("#000000".toColorInt()),
|
|
||||||
// StyleSpan(Typeface.BOLD),
|
|
||||||
// AbsoluteSizeSpan(72, true),
|
|
||||||
// LineHeightSpan { _, _, _, _, _, fm -> fm.descent += 10.dp }
|
|
||||||
// )
|
|
||||||
// append("\n")
|
|
||||||
// appendText(
|
|
||||||
// bottomUnit,
|
|
||||||
// ForegroundColorSpan("#999999".toColorInt()),
|
|
||||||
// AbsoluteSizeSpan(30, true)
|
|
||||||
// )
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
//}
|
|
||||||
@@ -1,283 +0,0 @@
|
|||||||
package com.shuwei.dish.match.dialog
|
|
||||||
|
|
||||||
import android.annotation.SuppressLint
|
|
||||||
import android.graphics.Rect
|
|
||||||
import android.os.Handler
|
|
||||||
import android.os.Looper
|
|
||||||
import android.view.Gravity
|
|
||||||
import android.view.KeyboardShortcutGroup
|
|
||||||
import android.view.LayoutInflater
|
|
||||||
import android.view.Menu
|
|
||||||
import android.view.MotionEvent
|
|
||||||
import android.view.View
|
|
||||||
import android.view.ViewGroup
|
|
||||||
import android.view.Window
|
|
||||||
import android.view.WindowManager
|
|
||||||
import android.widget.FrameLayout
|
|
||||||
import androidx.core.widget.addTextChangedListener
|
|
||||||
import androidx.lifecycle.lifecycleScope
|
|
||||||
import androidx.recyclerview.widget.GridLayoutManager
|
|
||||||
import androidx.recyclerview.widget.LinearLayoutManager
|
|
||||||
import com.google.android.material.bottomsheet.BottomSheetDialog
|
|
||||||
import com.shuwei.dish.match.R
|
|
||||||
import com.shuwei.dish.match.adapter.SeasoningSearchAdapter
|
|
||||||
import com.shuwei.dish.match.base.BaseActivity
|
|
||||||
import com.shuwei.dish.match.databinding.DialogSeasoningSelectBinding
|
|
||||||
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
|
||||||
import com.shuwei.dish.match.model.GoodsItem
|
|
||||||
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
|
|
||||||
import kotlinx.coroutines.Job
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 调料选择弹窗,不含重量显示,继承 BottomSheetDialog 确保只初始化一次
|
|
||||||
* @param activity 宿主 Activity
|
|
||||||
* @param onItemSelected 用户点击某一调料时的回调
|
|
||||||
*/
|
|
||||||
class SeasoningSelectDialog(
|
|
||||||
private val activity: BaseActivity,
|
|
||||||
private val onItemSelected: (item: GoodsItem) -> Unit
|
|
||||||
) : BottomSheetDialog(activity, R.style.BottomSheet) {
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
const val TAG = "SeasoningSelectDialog"
|
|
||||||
const val PAGE_SIZE = 50
|
|
||||||
}
|
|
||||||
|
|
||||||
private val binding = DialogSeasoningSelectBinding.inflate(LayoutInflater.from(activity))
|
|
||||||
private val list = mutableListOf<GoodsItem>()
|
|
||||||
private val adapter = SeasoningSearchAdapter(list).apply {
|
|
||||||
isStateViewEnable = true
|
|
||||||
setOnItemClickListener { _, v, position ->
|
|
||||||
val item = list.getOrNull(position) ?: return@setOnItemClickListener
|
|
||||||
item.isClicked = true
|
|
||||||
notifyItemChanged(position)
|
|
||||||
v.postDelayed({
|
|
||||||
onItemSelected(item)
|
|
||||||
dismiss()
|
|
||||||
}, 300)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private var goodsName: String? = null
|
|
||||||
private var pageNo = 1
|
|
||||||
private var collectJob: Job? = null
|
|
||||||
|
|
||||||
init {
|
|
||||||
setContentView(binding.root)
|
|
||||||
setCancelable(true)
|
|
||||||
behavior.skipCollapsed = false
|
|
||||||
window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
|
|
||||||
window?.setGravity(Gravity.BOTTOM)
|
|
||||||
window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
|
|
||||||
window?.setWindowAnimations(R.style.DialogSoftInputAnimation)
|
|
||||||
window?.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
|
|
||||||
|
|
||||||
setOnDismissListener {
|
|
||||||
collectJob?.cancel()
|
|
||||||
activity.hideStatusBar()
|
|
||||||
}
|
|
||||||
|
|
||||||
// 输入框:清空时重置列表
|
|
||||||
binding.etSheetInput.run {
|
|
||||||
hint = "输入调料名称"
|
|
||||||
addTextChangedListener(
|
|
||||||
onTextChanged = { text, _, _, _ -> goodsName = text.toString() },
|
|
||||||
afterTextChanged = {
|
|
||||||
if (it.isNullOrBlank()) {
|
|
||||||
list.clear()
|
|
||||||
adapter.notifyDataSetChanged()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
addOnActionSearchListener { searchGoods(this) }
|
|
||||||
}
|
|
||||||
|
|
||||||
// RecyclerView 初始化
|
|
||||||
binding.recyclerView.run {
|
|
||||||
layoutManager = GridLayoutManager(activity, 3, GridLayoutManager.VERTICAL, false)
|
|
||||||
adapter = this@SeasoningSelectDialog.adapter
|
|
||||||
}
|
|
||||||
|
|
||||||
binding.refreshLayout.run {
|
|
||||||
setEnableRefresh(true)
|
|
||||||
setEnableLoadMore(false)
|
|
||||||
setOnRefreshListener { pageNo = 1; getGoodsList() }
|
|
||||||
setOnLoadMoreListener { getGoodsList() }
|
|
||||||
}
|
|
||||||
|
|
||||||
binding.ivSearch.setOnClickListener { searchGoods(it) }
|
|
||||||
binding.root.setOnClickListener { KeyboardUtil.hideKeyboard(it) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 弹窗显示时自动加载默认调料列表,并在 Window.Callback 层提前拦截触摸以解决滑动冲突 */
|
|
||||||
override fun show() {
|
|
||||||
super.show()
|
|
||||||
// 启动 StateFlow 收集,弹窗关闭时由 setOnDismissListener 取消
|
|
||||||
collectJob = activity.lifecycleScope.launch {
|
|
||||||
activity.netViewModel.foodSearchGoodsListState.collect { state ->
|
|
||||||
when (state) {
|
|
||||||
is UiState.Loading -> {}
|
|
||||||
is UiState.Success -> loadGoodsList(state.data)
|
|
||||||
is UiState.Error -> {
|
|
||||||
activity.toast(state.msg)
|
|
||||||
finishRefresh()
|
|
||||||
if (pageNo == 1) {
|
|
||||||
loadEmptyView()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
is UiState.Idle -> {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pageNo = 1
|
|
||||||
getGoodsList()
|
|
||||||
// Window.Callback.dispatchTouchEvent 在整个 View 树的 onInterceptTouchEvent 之前执行,
|
|
||||||
// 是最早能感知触摸的时机。在此处判断触摸点位置来控制 behavior.isDraggable,
|
|
||||||
// 从而确保 BottomSheetBehavior 在 CoordinatorLayout.onInterceptTouchEvent 时
|
|
||||||
// 已经是禁用状态,不会拦截列表区域的滑动手势。
|
|
||||||
val originalCallback = window?.callback ?: return
|
|
||||||
window?.callback = object : Window.Callback by originalCallback {
|
|
||||||
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
|
|
||||||
when (event.actionMasked) {
|
|
||||||
MotionEvent.ACTION_DOWN -> {
|
|
||||||
val rect = Rect()
|
|
||||||
binding.refreshLayout.getGlobalVisibleRect(rect)
|
|
||||||
// 触摸点落在列表区域内则禁止 BottomSheet 拖拽
|
|
||||||
behavior.isDraggable = !rect.contains(event.rawX.toInt(), event.rawY.toInt())
|
|
||||||
}
|
|
||||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
|
||||||
behavior.isDraggable = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return originalCallback.dispatchTouchEvent(event)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onPointerCaptureChanged(hasCapture: Boolean) {
|
|
||||||
originalCallback.onPointerCaptureChanged(hasCapture)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onProvideKeyboardShortcuts(
|
|
||||||
data: List<KeyboardShortcutGroup?>?,
|
|
||||||
menu: Menu?,
|
|
||||||
deviceId: Int
|
|
||||||
) {
|
|
||||||
originalCallback.onProvideKeyboardShortcuts(data, menu, deviceId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 触发搜索:校验输入、隐藏键盘、发起请求
|
|
||||||
*/
|
|
||||||
private fun searchGoods(v: View) {
|
|
||||||
if (goodsName.isNullOrBlank()) {
|
|
||||||
activity.toast("请${binding.etSheetInput.hint}")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
pageNo = 1
|
|
||||||
getGoodsList()
|
|
||||||
KeyboardUtil.hideKeyboard( v)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 请求调料列表
|
|
||||||
*/
|
|
||||||
private fun getGoodsList() {
|
|
||||||
activity.netViewModel.queryFoodSearchGoodsList(
|
|
||||||
goodsType = "1",
|
|
||||||
pageNum = pageNo,
|
|
||||||
pageSize = PAGE_SIZE,
|
|
||||||
goodsName = goodsName.takeUnless { it.isNullOrBlank() }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 加载本地模拟数据,仅用于联调时点击空布局快速验证 UI
|
|
||||||
*/
|
|
||||||
private fun loadMockData() {
|
|
||||||
val nameList = listOf(
|
|
||||||
"盐", "白砂糖", "冰糖", "鸡精", "味精", "陈醋", "老抽", "生抽", "番茄酱", "胡椒粉", "孜然", "十三香",
|
|
||||||
"料酒", "白醋", "蚝油", "辣椒面", "辣椒酱", "豆瓣酱", "淀粉", "葱", "蒜", "姜", "香菜", "油"
|
|
||||||
)
|
|
||||||
val mockData = mutableListOf<GoodsItem>()
|
|
||||||
nameList.forEachIndexed { index, name ->
|
|
||||||
val padString = "${index + 1}".padStart(2, '0')
|
|
||||||
mockData.add(GoodsItem(goodsId = "1000$padString", goodsName = name))
|
|
||||||
}
|
|
||||||
pageNo = 1
|
|
||||||
loadGoodsList(mockData)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 将返回数据转换并填充到列表
|
|
||||||
*/
|
|
||||||
@SuppressLint("NotifyDataSetChanged")
|
|
||||||
private fun loadGoodsList(records: MutableList<GoodsItem>?) {
|
|
||||||
finishRefresh()
|
|
||||||
if (records.isNullOrEmpty()) {
|
|
||||||
//activity.toast("暂未搜索到调料信息")
|
|
||||||
if (pageNo == 1) {
|
|
||||||
loadEmptyView()
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
binding.recyclerView.layoutManager = GridLayoutManager(activity, 3, GridLayoutManager.VERTICAL, false)
|
|
||||||
if (pageNo == 1) list.clear()
|
|
||||||
list.addAll(records)
|
|
||||||
list.forEach {
|
|
||||||
it.oldGoodsId = it.goodsId
|
|
||||||
//materId才是提交数据需要的goodsId数据
|
|
||||||
it.goodsId = it.materId ?:""
|
|
||||||
}
|
|
||||||
adapter.notifyDataSetChanged()
|
|
||||||
val isLoadMoreEnable = records.size >= PAGE_SIZE
|
|
||||||
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
|
|
||||||
if (isLoadMoreEnable) pageNo++
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun finishRefresh() {
|
|
||||||
if (pageNo == 1) binding.refreshLayout.finishRefresh()
|
|
||||||
else binding.refreshLayout.finishLoadMore()
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private var emptyViewBinding: LayoutEmptyViewBinding? = null
|
|
||||||
|
|
||||||
@SuppressLint("NotifyDataSetChanged")
|
|
||||||
private fun loadEmptyView() {
|
|
||||||
try {
|
|
||||||
binding.refreshLayout.setEnableRefresh(true)
|
|
||||||
binding.refreshLayout.setEnableLoadMore(false)
|
|
||||||
list.clear()
|
|
||||||
adapter.notifyDataSetChanged()
|
|
||||||
if (emptyViewBinding == null) {
|
|
||||||
emptyViewBinding = LayoutEmptyViewBinding.inflate(
|
|
||||||
LayoutInflater.from(activity),
|
|
||||||
binding.recyclerView,
|
|
||||||
false
|
|
||||||
)
|
|
||||||
}
|
|
||||||
emptyViewBinding?.let {
|
|
||||||
it.tvContent.text = "暂无数据"
|
|
||||||
it.tvSubContent.text = "未查询到调料信息,请联系管理员添加"
|
|
||||||
// 点击空布局加载本地模拟数据,方便联调时验证 UI
|
|
||||||
//it.root.setOnClickListener { loadMockData() }
|
|
||||||
it.root.layoutParams = FrameLayout.LayoutParams(
|
|
||||||
FrameLayout.LayoutParams.MATCH_PARENT,
|
|
||||||
FrameLayout.LayoutParams.MATCH_PARENT
|
|
||||||
)
|
|
||||||
binding.recyclerView.layoutManager = LinearLayoutManager(activity)
|
|
||||||
binding.recyclerView.post {
|
|
||||||
it.root.minimumHeight = binding.recyclerView.height
|
|
||||||
adapter.stateView = it.root
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
e.printStackTrace()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
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,52 +0,0 @@
|
|||||||
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
|
|
||||||
)
|
|
||||||
@@ -11,11 +11,11 @@ import java.io.Serializable
|
|||||||
data class GoodsItem(
|
data class GoodsItem(
|
||||||
// 接口返回字段
|
// 接口返回字段
|
||||||
var goodsId: String = "",
|
var goodsId: String = "",
|
||||||
var goodsName: String? = null,
|
val goodsName: String? = null,
|
||||||
val popularName: String? = null,
|
val popularName: String? = null,
|
||||||
val zjmCode: String? = null,
|
val zjmCode: String? = null,
|
||||||
var materId: String? = null,
|
var materId: String? = null,
|
||||||
var materCode: String? = null,
|
val materCode: String? = null,
|
||||||
|
|
||||||
// 从 CookFoodGoodsEntity 迁移的数据字段(DishPartAdapter 显示及转换用)
|
// 从 CookFoodGoodsEntity 迁移的数据字段(DishPartAdapter 显示及转换用)
|
||||||
var materialType: Int = 0,
|
var materialType: Int = 0,
|
||||||
|
|||||||
@@ -1,264 +0,0 @@
|
|||||||
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
|
|
||||||
)
|
|
||||||
@@ -11,25 +11,30 @@ package com.shuwei.dish.match.model
|
|||||||
*/
|
*/
|
||||||
data class SettingItem(
|
data class SettingItem(
|
||||||
val type: Type,
|
val type: Type,
|
||||||
val title: String = type.label,
|
val title: String,
|
||||||
val subtitle: String? = null,
|
val subtitle: String? = null,
|
||||||
val isHidden: Boolean = false,
|
val isHidden: Boolean = false,
|
||||||
val onClick: () -> Unit
|
val onClick: () -> Unit
|
||||||
) {
|
) {
|
||||||
/** 设置菜单项类型枚举 */
|
/** 设置菜单项类型枚举 */
|
||||||
enum class Type(val label: String) {
|
enum class Type {
|
||||||
COOK_MODE("菜品模式"),
|
/** 菜品模式切换 */
|
||||||
SEASONING_CONFIG("调料区设置"),
|
COOK_MODE,
|
||||||
FOOD_COLLECT("食材采集"),
|
/** 调料区设置 */
|
||||||
WEIGHT_CONFIG("减重配置"),
|
SEASONING_CONFIG,
|
||||||
CLEAN_PACKAGE("净菜包"),
|
/** 食材采集 */
|
||||||
MEAL_PACKAGE("餐品净菜包"),
|
FOOD_COLLECT,
|
||||||
GROUP_TASK("组配任务"),
|
/** 减重配置 */
|
||||||
// MEAL_PACKAGE_TEST("餐品净菜包-测试"),
|
WEIGHT_CONFIG,
|
||||||
DB_INSPECT("数据库查看"),
|
/** 数据库查看(隐藏项) */
|
||||||
SCALE_OBSERVE("秤数据监控"),
|
DB_INSPECT,
|
||||||
ENV_SWITCH("切换环境"),
|
/** 秤数据监控(隐藏项) */
|
||||||
CLEAR_DATA("数据清除"),
|
SCALE_OBSERVE,
|
||||||
TEST_SEASONING("测试调料拿取"),
|
/** 切换环境(隐藏项) */
|
||||||
|
ENV_SWITCH,
|
||||||
|
/** 数据清除(隐藏项) */
|
||||||
|
CLEAR_DATA,
|
||||||
|
/** 测试调料拿取(隐藏项) */
|
||||||
|
TEST_SEASONING,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,131 +0,0 @@
|
|||||||
package com.shuwei.dish.match.net
|
|
||||||
|
|
||||||
import com.google.gson.JsonSyntaxException
|
|
||||||
import com.shuwei.dish.match.utils.ext.toJsonString
|
|
||||||
import com.shuwei.dish.match.utils.ext.toObject
|
|
||||||
import com.shuwei.dish.match.utils.ext.toType
|
|
||||||
import org.apache.http.conn.ConnectTimeoutException
|
|
||||||
import retrofit2.HttpException
|
|
||||||
import java.io.IOException
|
|
||||||
import java.net.SocketTimeoutException
|
|
||||||
import java.net.UnknownHostException
|
|
||||||
|
|
||||||
///**
|
|
||||||
// * 通用网络请求封装,统一处理异常
|
|
||||||
// * @param onRequest 实际的 Retrofit 接口请求
|
|
||||||
// * @param onSuccess 成功回调
|
|
||||||
// * @param onFailure 自定义错误回调(可选,不传则用默认提示)
|
|
||||||
// */
|
|
||||||
//suspend fun <T> apiRequest(
|
|
||||||
// onRequest: suspend () -> T,
|
|
||||||
// onSuccess: (T) -> Unit,
|
|
||||||
// onFailure: ((ApiException) -> Unit)? = null
|
|
||||||
//) {
|
|
||||||
// try {
|
|
||||||
// // 执行实际的网络请求
|
|
||||||
// val result = onRequest()
|
|
||||||
// onSuccess(result)
|
|
||||||
// } catch (e: Exception) {
|
|
||||||
// val apiException = getApiException(e)
|
|
||||||
// // 优先执行自定义错误回调,没有则用默认提示
|
|
||||||
// if (onFailure != null) {
|
|
||||||
// onFailure(apiException)
|
|
||||||
// } else {
|
|
||||||
// // 默认的错误提示(可根据 ErrorType 定制)
|
|
||||||
// val tip = apiException.errorMsg
|
|
||||||
// // 切换到UI线程弹提示(用 MainScope 确保在主线程)
|
|
||||||
// MainScope().launch {
|
|
||||||
// BaseApp.instance?.toast(tip)
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
//}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 通用网络请求封装,统一处理异常
|
|
||||||
* @param onRequest 实际的 Retrofit 接口请求
|
|
||||||
* @param onSuccess 成功回调
|
|
||||||
* @param onFailure 自定义错误回调(可选,不传则用默认提示)
|
|
||||||
*/
|
|
||||||
@Suppress("UNCHECKED_CAST")
|
|
||||||
suspend fun <T> request(
|
|
||||||
onRequest: suspend () -> ApiResponse<T>,
|
|
||||||
onSuccess: (T) -> Unit,
|
|
||||||
onFailure: (String, String) -> Unit
|
|
||||||
) {
|
|
||||||
var response: ApiResponse<T>?
|
|
||||||
try {
|
|
||||||
// 执行实际的网络请求
|
|
||||||
response = onRequest()
|
|
||||||
} catch (e: Exception) {
|
|
||||||
val apiException = getApiException(e)
|
|
||||||
onFailure("-1", apiException.errorMsg)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (response.isSuccess()) {
|
|
||||||
onSuccess(response.data as T)
|
|
||||||
} else {
|
|
||||||
onFailure(response.code, response.msg ?: "")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
data class CodeMsg(
|
|
||||||
var code: String? = null,
|
|
||||||
var msg: String? = null
|
|
||||||
)
|
|
||||||
|
|
||||||
@Suppress("DEPRECATION")
|
|
||||||
fun getApiException(e: Exception): ApiException {
|
|
||||||
// 捕获各类网络异常并转换为自定义异常
|
|
||||||
return when (e) {
|
|
||||||
is HttpException -> httpException2ApiException(e)
|
|
||||||
|
|
||||||
is JsonSyntaxException -> ApiException(
|
|
||||||
ErrorType.NETWORK_ERROR,
|
|
||||||
errorMsg = "服务器响应异常,请稍后重试"
|
|
||||||
)
|
|
||||||
|
|
||||||
is UnknownHostException -> ApiException(
|
|
||||||
ErrorType.NETWORK_ERROR,
|
|
||||||
errorMsg = "网络未连接,请检查网络"
|
|
||||||
)
|
|
||||||
|
|
||||||
is SocketTimeoutException -> ApiException(
|
|
||||||
ErrorType.TIMEOUT_ERROR,
|
|
||||||
errorMsg = "请求超时,请稍后重试"
|
|
||||||
)
|
|
||||||
|
|
||||||
is ConnectTimeoutException -> ApiException(
|
|
||||||
ErrorType.TIMEOUT_ERROR,
|
|
||||||
errorMsg = "连接超时,请检查网络"
|
|
||||||
)
|
|
||||||
|
|
||||||
is IOException -> ApiException(
|
|
||||||
ErrorType.NETWORK_ERROR,
|
|
||||||
errorMsg = "网络异常:${e.message ?: "未知IO错误"}"
|
|
||||||
)
|
|
||||||
|
|
||||||
is ApiException -> e
|
|
||||||
else -> ApiException(
|
|
||||||
ErrorType.UNKNOWN_ERROR,
|
|
||||||
errorMsg = "未知错误:${e.message ?: "未知"}",
|
|
||||||
throwable = e
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun httpException2ApiException(e: HttpException): ApiException {
|
|
||||||
val body = e.response()?.errorBody()?.string()
|
|
||||||
val codeMsg: CodeMsg? = try {
|
|
||||||
body?.toObject<CodeMsg>()
|
|
||||||
} catch (_: Exception) {
|
|
||||||
null
|
|
||||||
}
|
|
||||||
return ApiException(
|
|
||||||
ErrorType.NETWORK_ERROR,
|
|
||||||
errorMsg = if (codeMsg == null) "数据解析异常(${e.code()})"
|
|
||||||
else codeMsg.msg ?: "服务器错误(${e.code()})"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,173 +0,0 @@
|
|||||||
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>
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,10 @@
|
|||||||
package com.shuwei.dish.match.net
|
package com.shuwei.dish.match.net
|
||||||
|
|
||||||
|
import java.io.IOException
|
||||||
|
import java.net.ConnectException
|
||||||
|
import java.net.SocketTimeoutException
|
||||||
|
import java.net.UnknownHostException
|
||||||
|
|
||||||
// 1. 网络异常类型枚举
|
// 1. 网络异常类型枚举
|
||||||
enum class ErrorType {
|
enum class ErrorType {
|
||||||
NETWORK_ERROR, // 网络错误(无网)
|
NETWORK_ERROR, // 网络错误(无网)
|
||||||
@@ -17,3 +22,13 @@ class ApiException(
|
|||||||
val errorMsg: String,
|
val errorMsg: String,
|
||||||
val throwable: Throwable? = null
|
val throwable: Throwable? = null
|
||||||
) : Exception(errorMsg, throwable)
|
) : Exception(errorMsg, throwable)
|
||||||
|
|
||||||
|
/** 将任意异常转换为 ApiException,供 safeApiCall 统一使用 */
|
||||||
|
fun getApiException(e: Exception): ApiException = when (e) {
|
||||||
|
is ApiException -> e
|
||||||
|
is UnknownHostException -> ApiException(ErrorType.NETWORK_ERROR, errorMsg = "网络未连接,请检查网络")
|
||||||
|
is SocketTimeoutException -> ApiException(ErrorType.TIMEOUT_ERROR, errorMsg = "请求超时,请稍后重试")
|
||||||
|
is ConnectException -> ApiException(ErrorType.TIMEOUT_ERROR, errorMsg = "连接超时,请检查网络")
|
||||||
|
is IOException -> ApiException(ErrorType.NETWORK_ERROR, errorMsg = "网络异常:${e.message ?: "未知IO错误"}")
|
||||||
|
else -> ApiException(ErrorType.UNKNOWN_ERROR, errorMsg = "未知错误:${e.message ?: "未知"}", throwable = e)
|
||||||
|
}
|
||||||
@@ -1,327 +0,0 @@
|
|||||||
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))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
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,109 +0,0 @@
|
|||||||
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) }
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
package com.shuwei.dish.match.objbox
|
|
||||||
|
|
||||||
import io.objectbox.annotation.Entity
|
|
||||||
import io.objectbox.annotation.HnswIndex
|
|
||||||
import io.objectbox.annotation.Id
|
|
||||||
import io.objectbox.annotation.VectorDistanceType
|
|
||||||
|
|
||||||
@Entity
|
|
||||||
data class Food(
|
|
||||||
@Id var id: Long = 0,
|
|
||||||
var name: String? = null,
|
|
||||||
var foodIdx: Int = 0,
|
|
||||||
@HnswIndex(dimensions = 512, distanceType = VectorDistanceType.DOT_PRODUCT)
|
|
||||||
var foodVector: FloatArray? = null,
|
|
||||||
var version: String? = null
|
|
||||||
) {
|
|
||||||
override fun equals(other: Any?): Boolean {
|
|
||||||
if (this === other) return true
|
|
||||||
if (javaClass != other?.javaClass) return false
|
|
||||||
|
|
||||||
other as Food
|
|
||||||
|
|
||||||
if (id != other.id) return false
|
|
||||||
if (foodIdx != other.foodIdx) return false
|
|
||||||
if (name != other.name) return false
|
|
||||||
if (!foodVector.contentEquals(other.foodVector)) return false
|
|
||||||
if (version != other.version) return false
|
|
||||||
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun hashCode(): Int {
|
|
||||||
var result = id.hashCode()
|
|
||||||
result = 31 * result + foodIdx
|
|
||||||
result = 31 * result + (name?.hashCode() ?: 0)
|
|
||||||
result = 31 * result + (foodVector?.contentHashCode() ?: 0)
|
|
||||||
result = 31 * result + (version?.hashCode() ?: 0)
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
package com.shuwei.dish.match.objbox
|
|
||||||
|
|
||||||
import android.graphics.Bitmap
|
|
||||||
import android.net.Uri
|
|
||||||
import java.io.File
|
|
||||||
|
|
||||||
data class FoodClassInfo(
|
|
||||||
var class_names: List<String>,
|
|
||||||
var class_to_idx: Map<String, Int>,
|
|
||||||
var idx_to_class: Map<String, String>
|
|
||||||
)
|
|
||||||
|
|
||||||
@@ -1,319 +0,0 @@
|
|||||||
package com.shuwei.dish.match.objbox
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.graphics.Bitmap
|
|
||||||
import android.util.Log
|
|
||||||
import androidx.core.graphics.scale
|
|
||||||
import com.google.gson.Gson
|
|
||||||
import com.google.gson.reflect.TypeToken
|
|
||||||
import com.shuwei.dish.match.utils.AssetsTool
|
|
||||||
import com.shuwei.dish.match.utils.LogSaveUtil
|
|
||||||
import com.shuwei.dish.match.utils.ext.toJsonString
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import org.pytorch.IValue
|
|
||||||
import org.pytorch.Module
|
|
||||||
import org.pytorch.torchvision.TensorImageUtils
|
|
||||||
import java.io.File
|
|
||||||
import java.io.FileOutputStream
|
|
||||||
import java.io.IOException
|
|
||||||
import java.io.InputStream
|
|
||||||
|
|
||||||
|
|
||||||
object FoodModule {
|
|
||||||
|
|
||||||
private lateinit var module: Module
|
|
||||||
|
|
||||||
private val NO_MEAN_RGB = floatArrayOf(0.0f, 0.0f, 0.0f)
|
|
||||||
private val NO_STD_RGB = floatArrayOf(1.0f, 1.0f, 1.0f)
|
|
||||||
|
|
||||||
// 1. 定义你的模型固定输入尺寸 (根据你的tflite模型修改,比如224x224)
|
|
||||||
private const val MODEL_INPUT_WIDTH = 300
|
|
||||||
private const val MODEL_INPUT_HEIGHT = 300
|
|
||||||
const val DEFAULT_FOOD_INDEX = -1
|
|
||||||
const val DEFAULT_QUERY_COUNT = 50
|
|
||||||
|
|
||||||
const val BAG_RATE = 0.05
|
|
||||||
|
|
||||||
suspend fun init(context: Context) {
|
|
||||||
withContext(Dispatchers.IO) {
|
|
||||||
module = Module.load(copyAssetToCache(context, "best_embedding_model_mobile.pt"))
|
|
||||||
// initDefFoodData(context)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// fun uri2FloatArray(uri: Uri): FloatArray? {
|
|
||||||
// return MyApp.instance?.let { context ->
|
|
||||||
// ImageUtil.uriToBitmap(context, uri)?.let {
|
|
||||||
// bitmap2FloatArray(it)
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
fun bitmap2FloatArray(originBitmap: Bitmap, isRecycle: Boolean): FloatArray? {
|
|
||||||
// 模型未初始化时直接返回 null,避免 UninitializedPropertyAccessException
|
|
||||||
if (!::module.isInitialized) {
|
|
||||||
logInfo("bitmap2FloatArray: module 尚未初始化,跳过推理")
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
var rgb565Bitmap: Bitmap? = null
|
|
||||||
try {
|
|
||||||
val scaledBitmap = originBitmap.scale(MODEL_INPUT_WIDTH, MODEL_INPUT_HEIGHT)
|
|
||||||
if (isRecycle) {
|
|
||||||
originBitmap.recycle()
|
|
||||||
}
|
|
||||||
rgb565Bitmap = scaledBitmap.copy(Bitmap.Config.RGB_565, false)
|
|
||||||
scaledBitmap.recycle()
|
|
||||||
val inputTensor = TensorImageUtils.bitmapToFloat32Tensor(
|
|
||||||
rgb565Bitmap,
|
|
||||||
NO_MEAN_RGB, // [0.485, 0.456, 0.406] TORCHVISION_NORM_MEAN_RGB
|
|
||||||
NO_STD_RGB // [0.229, 0.224, 0.225] TORCHVISION_NORM_STD_RGB
|
|
||||||
)
|
|
||||||
val outputTensor = module.forward(IValue.from(inputTensor)).toTensor()
|
|
||||||
return outputTensor.dataAsFloatArray
|
|
||||||
} catch (e: OutOfMemoryError) {
|
|
||||||
e.printStackTrace()
|
|
||||||
logInfo("bitmap2FloatArray异常:${e.message}")
|
|
||||||
} finally {
|
|
||||||
if (rgb565Bitmap != null && rgb565Bitmap.isRecycled.not()) {
|
|
||||||
rgb565Bitmap.recycle()
|
|
||||||
}
|
|
||||||
//System.gc()
|
|
||||||
//System.runFinalization()
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
// fun queryFood(uri: Uri, queryCount: Int = DEFAULT_QUERY_COUNT): List<String>? {
|
|
||||||
// return uri2FloatArray(uri)?.let {
|
|
||||||
// queryFood(it, queryCount)
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// /**
|
|
||||||
// * 返回识别物品名称列表
|
|
||||||
// */
|
|
||||||
// fun queryFood(bitmap: Bitmap, queryCount: Int = DEFAULT_QUERY_COUNT): List<String> {
|
|
||||||
// val floatArray = bitmap2FloatArray(bitmap)
|
|
||||||
// return queryFood(floatArray, queryCount)
|
|
||||||
// }
|
|
||||||
|
|
||||||
// /**
|
|
||||||
// * 返回识别物品IdNameScore对象列表
|
|
||||||
// */
|
|
||||||
// fun queryFoodNameScore(bitmap: Bitmap, queryCount: Int = DEFAULT_QUERY_COUNT): List<IdNameScore> {
|
|
||||||
// val floatArray = bitmap2FloatArray(bitmap)
|
|
||||||
// return queryFoodNameScore(floatArray, queryCount)
|
|
||||||
// }
|
|
||||||
|
|
||||||
suspend fun queryFoodNameScore(
|
|
||||||
floatArray: FloatArray?,
|
|
||||||
queryCount: Int = DEFAULT_QUERY_COUNT
|
|
||||||
): List<IdNameScore> {
|
|
||||||
if (floatArray == null) return emptyList()
|
|
||||||
// val query: Query<Food> = box.query(Food_.foodVector.nearestNeighbors(floatArray, queryCount)).build()
|
|
||||||
// //查询比较分数
|
|
||||||
//// val tempList = query.findWithScores().sortedBy { it.score }.map { "${it.get().name}|${it.get().foodIdx}|${it.score}" }
|
|
||||||
// var idScoreList: List<IdWithScore>
|
|
||||||
// try {
|
|
||||||
// idScoreList = query.findIdsWithScores();
|
|
||||||
// } finally {
|
|
||||||
// // 先关闭Query,释放Cursor
|
|
||||||
// query.close()
|
|
||||||
// }
|
|
||||||
|
|
||||||
logInfo("queryFood向量:${floatArray.slice(0 until 50).toJsonString()}")
|
|
||||||
val idScoreList = ObjectBox.query(floatArray, queryCount)
|
|
||||||
// 批量加载所有实体,一次DB操作替代循环单条查询
|
|
||||||
val foodMap = ObjectBox.getByIds(idScoreList.map { it.id }).associateBy { it.id }
|
|
||||||
val nameScoreList = mutableListOf<IdNameScore>()
|
|
||||||
idScoreList.forEach {
|
|
||||||
val name = foodMap[it.id]?.name ?: ""
|
|
||||||
val arr = name.split("&&")
|
|
||||||
var rawMaterialsType = ""
|
|
||||||
if (arr.size > 1) {
|
|
||||||
rawMaterialsType = arr[1]
|
|
||||||
}
|
|
||||||
nameScoreList.add(IdNameScore(id = it.id, name = arr[0], score = it.score, rawMaterialsType = rawMaterialsType))
|
|
||||||
}
|
|
||||||
logInfo("queryFood数据:${nameScoreList.toJsonString()}")
|
|
||||||
return nameScoreList
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun getFoodScoreList(bitmap: Bitmap, queryCount: Int = DEFAULT_QUERY_COUNT): List<IdNameScore> {
|
|
||||||
val floatArray = bitmap2FloatArray(bitmap, false) ?: return emptyList()
|
|
||||||
logInfo("getFoodScoreList向量:${floatArray.toJsonString()}")
|
|
||||||
val nameScoreList = queryFoodNameScore(floatArray, queryCount)
|
|
||||||
if (nameScoreList.isEmpty()) {
|
|
||||||
return emptyList()
|
|
||||||
}
|
|
||||||
//暂时不过滤
|
|
||||||
val maxScoreList = nameScoreList
|
|
||||||
//.filter { it.score < 0.15 }
|
|
||||||
.groupBy { it.name }
|
|
||||||
.map { (_, value) -> value.minByOrNull { it.score }!! }
|
|
||||||
.toMutableList()
|
|
||||||
// val map = mutableMapOf<String, Int>()
|
|
||||||
// nameScoreList.forEach {
|
|
||||||
// val key = it.name
|
|
||||||
// val count = map[key] ?: 0
|
|
||||||
// map[key] = count + 1
|
|
||||||
// }
|
|
||||||
// val orderList = map.entries.sortedByDescending { it.value }.map { it.key }.toMutableList()
|
|
||||||
// val firstFood = nameScoreList[0].name
|
|
||||||
// orderList.remove(firstFood)
|
|
||||||
// orderList.add(0, firstFood)
|
|
||||||
//
|
|
||||||
// val sortedScoreList = maxScoreList.sortedWith(compareBy {
|
|
||||||
// orderList.indexOf(it.name)
|
|
||||||
// })
|
|
||||||
val sortedScoreList = maxScoreList.sortedBy { it.score }
|
|
||||||
logInfo("getFoodScoreList数据:${sortedScoreList.toJsonString()}")
|
|
||||||
return sortedScoreList
|
|
||||||
}
|
|
||||||
|
|
||||||
// suspend fun queryFood(floatArray: FloatArray, queryCount: Int = DEFAULT_QUERY_COUNT): List<String> {
|
|
||||||
// val map = mutableMapOf<String, Int>()
|
|
||||||
// val nameScoreList = queryFoodNameScore(floatArray, queryCount)
|
|
||||||
// nameScoreList.filter { it.score < 0.05 }.forEach {
|
|
||||||
// val count = map[it.name] ?: 0
|
|
||||||
// map[it.name] = count + 1
|
|
||||||
// }
|
|
||||||
// val list = map.entries.sortedByDescending { it.value }.map { it.key }
|
|
||||||
// return list
|
|
||||||
// }
|
|
||||||
|
|
||||||
data class IdNameScore(
|
|
||||||
val id: Long,
|
|
||||||
var name: String,
|
|
||||||
val score: Double,
|
|
||||||
val rawMaterialsType: String
|
|
||||||
)
|
|
||||||
|
|
||||||
suspend fun initDefFoodData(context: Context, action: () -> Unit = {}) {
|
|
||||||
try {
|
|
||||||
val count = ObjectBox.countIndexField(DEFAULT_FOOD_INDEX)
|
|
||||||
if (count > 0) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
val embeddingsJson = AssetsTool.readAssetsFile(context, "data/embeddings.json")
|
|
||||||
val labelsJson = AssetsTool.readAssetsFile(context, "data/labels.json")
|
|
||||||
val classInfoJson = AssetsTool.readAssetsFile(context, "data/class_info.json")
|
|
||||||
|
|
||||||
val embeddingsList: List<List<Float>> =
|
|
||||||
Gson().fromJson(embeddingsJson, object : TypeToken<List<List<Float>>>() {}.type)
|
|
||||||
val labelsList: IntArray = Gson().fromJson(labelsJson, IntArray::class.java)
|
|
||||||
val classInfo: FoodClassInfo =
|
|
||||||
Gson().fromJson(classInfoJson, FoodClassInfo::class.java)
|
|
||||||
|
|
||||||
val foodMap = classInfo.idx_to_class
|
|
||||||
val list = mutableListOf<Food>()
|
|
||||||
val size = embeddingsList.size
|
|
||||||
val size2 = labelsList.size
|
|
||||||
val size3 = foodMap.size
|
|
||||||
logInfo("initDefFoodData: $size,$size2,$size3")
|
|
||||||
embeddingsList.forEachIndexed { index, floatList ->
|
|
||||||
val classIdx = labelsList[index]
|
|
||||||
val foodName = foodMap["$classIdx"]
|
|
||||||
val array = floatList.toFloatArray()
|
|
||||||
// ObjectBox.boxStore.runInTx {
|
|
||||||
// box.put(Food(name = foodName, foodVector = array, foodIdx = DEFAULT_FOOD_INDEX))
|
|
||||||
// }
|
|
||||||
val food = Food(name = foodName, foodVector = array, foodIdx = DEFAULT_FOOD_INDEX)
|
|
||||||
list.add(food)
|
|
||||||
}
|
|
||||||
// val tempList = list.chunked(10)
|
|
||||||
ObjectBox.putAll(list)
|
|
||||||
action()
|
|
||||||
} catch (e: Exception) {
|
|
||||||
e.printStackTrace()
|
|
||||||
logInfo("initDefFoodData: ---${e.message}--")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* ,此方法的主要目的是:从assets 拷贝到 app的cache目录
|
|
||||||
* @param context
|
|
||||||
* @param fileName
|
|
||||||
* @return 例如是这样:/data/user/0/com.frizzle.pluginhookandroid9/cache/plugin-debug.apk
|
|
||||||
*
|
|
||||||
* 不可能反正SD
|
|
||||||
*/
|
|
||||||
// fun copyAssetToCache(context: Context, fileName: String): String? {
|
|
||||||
// // 此app的缓存目录 --> 会默认在 cache目录...,可以自己去看看哦
|
|
||||||
// val cacheDir = context.getCacheDir()
|
|
||||||
// if (!cacheDir.exists()) {
|
|
||||||
// cacheDir.mkdirs() // TODO 如果没有缓存目录,就创建
|
|
||||||
// }
|
|
||||||
// val outPath = File(cacheDir, fileName) // TODO 创建输出的文件位置
|
|
||||||
// if (outPath.exists()) {
|
|
||||||
// outPath.delete() // TODO 如果该文件已经存在,就删掉
|
|
||||||
// }
|
|
||||||
// var `is`: InputStream? = null // 读取
|
|
||||||
// var fos: FileOutputStream? = null // 写入
|
|
||||||
// try {
|
|
||||||
// // 创建文件,如果创建成功,就返回true
|
|
||||||
// val res = outPath.createNewFile()
|
|
||||||
// if (res) {
|
|
||||||
// `is` = context.getAssets().open(fileName) // 拿到main/assets目录的输入流,用于读取字节
|
|
||||||
// fos = FileOutputStream(outPath) // 读取出来的字节最终写到outPath
|
|
||||||
// val buf = ByteArray(`is`.available()) // 缓存区
|
|
||||||
// var byteCount: Int
|
|
||||||
//
|
|
||||||
// // 开始循环读取
|
|
||||||
// while ((`is`.read(buf).also { byteCount = it }) != -1) {
|
|
||||||
// fos.write(buf, 0, byteCount)
|
|
||||||
// }
|
|
||||||
// return outPath.getAbsolutePath()
|
|
||||||
// }
|
|
||||||
// } catch (e: IOException) {
|
|
||||||
// e.printStackTrace()
|
|
||||||
// } finally {
|
|
||||||
// try {
|
|
||||||
// // TODO 一定要记得关闭资源,为了不去性能的磨损
|
|
||||||
// fos?.flush()
|
|
||||||
// `is`?.close()
|
|
||||||
// fos?.close()
|
|
||||||
// } catch (e: IOException) {
|
|
||||||
// e.printStackTrace()
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// return null
|
|
||||||
// }
|
|
||||||
|
|
||||||
fun copyAssetToCache(context: Context, fileName: String): String? {
|
|
||||||
val cacheFile = File(context.cacheDir, fileName)
|
|
||||||
val buffer = ByteArray(8 * 1024)
|
|
||||||
var inputStream: InputStream? = null
|
|
||||||
var outputStream: FileOutputStream? = null
|
|
||||||
|
|
||||||
try {
|
|
||||||
inputStream = context.assets.open(fileName)
|
|
||||||
outputStream = FileOutputStream(cacheFile)
|
|
||||||
var byteCount: Int
|
|
||||||
while (inputStream.read(buffer).also { byteCount = it } != -1) {
|
|
||||||
outputStream.write(buffer, 0, byteCount)
|
|
||||||
}
|
|
||||||
outputStream.channel.force(true) // 强制物理落盘,比flush更彻底
|
|
||||||
return cacheFile.absolutePath
|
|
||||||
} catch (e: IOException) {
|
|
||||||
e.printStackTrace()
|
|
||||||
logInfo("文件拷贝失败 fileName=$fileName, error=${e.message}")
|
|
||||||
// 拷贝失败时删除残缺文件,避免下次读取到损坏文件
|
|
||||||
if (cacheFile.exists()) {
|
|
||||||
cacheFile.delete()
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
outputStream?.close()
|
|
||||||
inputStream?.close()
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun logInfo(msg:String) {
|
|
||||||
Log.d("FoodModule", msg)
|
|
||||||
LogSaveUtil.saveLogFile(msg)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,332 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2024 ObjectBox Ltd. All rights reserved.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
|
|
||||||
package com.shuwei.dish.match.objbox
|
|
||||||
|
|
||||||
import android.annotation.SuppressLint
|
|
||||||
import android.content.Context
|
|
||||||
import android.util.Log
|
|
||||||
import com.shuwei.dish.match.base.BaseApp
|
|
||||||
import com.shuwei.dish.match.utils.LogSaveUtil
|
|
||||||
import io.objectbox.Box
|
|
||||||
import io.objectbox.BoxStore
|
|
||||||
import io.objectbox.BoxStoreBuilder
|
|
||||||
import io.objectbox.exception.DbException
|
|
||||||
import io.objectbox.exception.FileCorruptException
|
|
||||||
import io.objectbox.kotlin.boxFor
|
|
||||||
import io.objectbox.query.Query
|
|
||||||
import io.objectbox.sync.Sync
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.sync.Mutex
|
|
||||||
import kotlinx.coroutines.sync.withLock
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import java.io.File
|
|
||||||
import java.io.FileInputStream
|
|
||||||
import java.io.FileOutputStream
|
|
||||||
import java.io.IOException
|
|
||||||
import java.util.zip.GZIPOutputStream
|
|
||||||
import com.shuwei.dish.match.BuildConfig
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Singleton to keep BoxStore reference and provide current list of Notes Objects.
|
|
||||||
* Inserts demo data if no Objects are stored.
|
|
||||||
*/
|
|
||||||
object ObjectBox {
|
|
||||||
|
|
||||||
// 确保所有设备/版本使用相同的objectbox-models/default.json
|
|
||||||
// 避免直接修改自动生成的MyObjectBox类
|
|
||||||
// 跨版本升级时使用boxStore.runInTx执行数据迁移
|
|
||||||
|
|
||||||
private const val TAG = "ObjectBox"
|
|
||||||
|
|
||||||
// 添加 @Volatile 保证多线程下的可见性
|
|
||||||
@Volatile
|
|
||||||
var boxStore: BoxStore? = null
|
|
||||||
|
|
||||||
/**
|
|
||||||
* If building the [boxStore] failed, contains the thrown error message.
|
|
||||||
*/
|
|
||||||
var dbExceptionMessage: String? = null
|
|
||||||
private set
|
|
||||||
|
|
||||||
fun init(context: Context) {
|
|
||||||
if (boxStore != null && boxStore!!.isClosed.not()) return
|
|
||||||
// 优化:调大事务回收超时时间
|
|
||||||
System.setProperty("objectbox.finalizerTimeout", "30000");
|
|
||||||
// On Android make sure to pass a Context when building the Store.
|
|
||||||
boxStore = try {
|
|
||||||
MyObjectBox.builder()
|
|
||||||
.androidContext(context.applicationContext)
|
|
||||||
//.disableMultiProcess() // 开启多进程支持(按需关闭,单进程可删)
|
|
||||||
//.disableFileCompression() // 禁用文件压缩,避免存储异常
|
|
||||||
.build()
|
|
||||||
} catch (e: DbException) {
|
|
||||||
if (e.javaClass == DbException::class.java || e is FileCorruptException) {
|
|
||||||
// Failed to build BoxStore due to database file issue, store message;
|
|
||||||
// checked in NoteListActivity to notify user.
|
|
||||||
dbExceptionMessage = e.toString()
|
|
||||||
LogSaveUtil.saveLogFile("ObjectBox.init异常1:$dbExceptionMessage")
|
|
||||||
return
|
|
||||||
} else {
|
|
||||||
LogSaveUtil.saveLogFile("ObjectBox.init异常2:${e.message}")
|
|
||||||
// Failed to build BoxStore due to developer error.
|
|
||||||
throw e
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (BuildConfig.DEBUG) {
|
|
||||||
var syncAvailable = if (Sync.isAvailable()) "available" else "unavailable"
|
|
||||||
Log.d(
|
|
||||||
TAG,
|
|
||||||
"Using ObjectBox ${BoxStore.getVersion()} (${BoxStore.getVersionNative()}, sync $syncAvailable)"
|
|
||||||
)
|
|
||||||
// Enable ObjectBox Admin on debug builds.
|
|
||||||
// https://docs.objectbox.io/data-browser
|
|
||||||
io.objectbox.android.Admin(boxStore).start(context.applicationContext)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* If the database file is not in use, compresses (GZIP) and copies it to the given [target].
|
|
||||||
* 增加 IOException 捕获,避免文件异常导致崩溃。
|
|
||||||
*/
|
|
||||||
fun copyAndGzipDatabaseFileTo(target: File, context: Context): Boolean {
|
|
||||||
if (BoxStore.isDatabaseOpen(context, null)) {
|
|
||||||
// Do not copy if database file is still in use.
|
|
||||||
// If it would be open, the copy will likely get corrupted
|
|
||||||
// as BoxStore may currently write data to the file.
|
|
||||||
Log.e(TAG, "Database file is still in use, can not copy.")
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// If a name was given when building BoxStore use that instead of the default below.
|
|
||||||
val dbName = BoxStoreBuilder.DEFAULT_NAME
|
|
||||||
return try {
|
|
||||||
File(context.filesDir, "objectbox/$dbName/data.mdb").inputStream().use { input ->
|
|
||||||
target.parentFile?.mkdirs()
|
|
||||||
GZIPOutputStream(target.outputStream()).use { output ->
|
|
||||||
input.copyTo(output, DEFAULT_BUFFER_SIZE)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
true
|
|
||||||
} catch (e: IOException) {
|
|
||||||
Log.e(TAG, "备份数据库文件失败", e)
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// 获取指定实体的Box,自动关联BoxStore
|
|
||||||
inline fun <reified T> getBox(): Box<T>? = boxStore?.boxFor()
|
|
||||||
|
|
||||||
// 协程安全执行数据库操作(推荐所有操作使用此方法)
|
|
||||||
suspend fun <T> safeDbOp(operation: suspend () -> T): T? {
|
|
||||||
return withContext(Dispatchers.IO) {
|
|
||||||
try {
|
|
||||||
dbMutex.withLock { operation() }
|
|
||||||
} catch (e: FileCorruptException) {
|
|
||||||
// 操作中触发损坏,尝试重建数据库
|
|
||||||
e.printStackTrace()
|
|
||||||
LogSaveUtil.saveLogFile("safeDbOp出现FileCorruptException异常:${e.message},${e.errorCode}")
|
|
||||||
// 使用安全调用替代 !! 断言,避免 NPE
|
|
||||||
val app = BaseApp.instance ?: return@withContext null
|
|
||||||
init(app)
|
|
||||||
null
|
|
||||||
} catch (e: Exception) {
|
|
||||||
e.printStackTrace()
|
|
||||||
LogSaveUtil.saveLogFile("safeDbOp出现其它异常:${e.message}")
|
|
||||||
null
|
|
||||||
} finally {
|
|
||||||
// 线程资源清理
|
|
||||||
boxStore?.closeThreadResources()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun query(floatArray: FloatArray, queryCount: Int) = safeDbOp {
|
|
||||||
val query: Query<Food>? = getBox<Food>()?.query(
|
|
||||||
Food_.foodVector
|
|
||||||
.nearestNeighbors(floatArray, queryCount)
|
|
||||||
)?.build()
|
|
||||||
try {
|
|
||||||
query?.findIdsWithScores()
|
|
||||||
} finally {
|
|
||||||
// 先关闭Query,释放Cursor
|
|
||||||
query?.close()
|
|
||||||
}
|
|
||||||
} ?: emptyList()
|
|
||||||
|
|
||||||
suspend fun get(id: Long) = safeDbOp {
|
|
||||||
getBox<Food>()?.get(id)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 批量按ID加载,一次DB事务替代循环单条查询
|
|
||||||
suspend fun getByIds(ids: List<Long>): List<Food> = safeDbOp {
|
|
||||||
if (ids.isEmpty()) return@safeDbOp emptyList<Food>()
|
|
||||||
getBox<Food>()?.get(ids.toLongArray()) ?: emptyList<Food>()
|
|
||||||
} ?: emptyList()
|
|
||||||
|
|
||||||
suspend fun put(entity: Food) = safeDbOp {
|
|
||||||
getBox<Food>()?.put(entity)
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun putAll(entities: List<Food>) = safeDbOp {
|
|
||||||
val box = getBox<Food>()
|
|
||||||
box?.put(entities)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 使用 QueryBuilder 在数据库层计数,避免全量加载到内存
|
|
||||||
suspend fun countNameField(name: String) = safeDbOp {
|
|
||||||
getBox<Food>()?.query(Food_.name.equal(name))?.build()?.count()
|
|
||||||
} ?: 0L
|
|
||||||
|
|
||||||
suspend fun countIndexField(idx: Int) = safeDbOp {
|
|
||||||
getBox<Food>()?.query(Food_.foodIdx.equal(idx))?.build()?.count()
|
|
||||||
} ?: 0L
|
|
||||||
|
|
||||||
// 使用 QueryBuilder 在数据库层过滤,避免全量加载到内存
|
|
||||||
suspend fun filter(name: String?) = safeDbOp {
|
|
||||||
if (!name.isNullOrBlank()) {
|
|
||||||
getBox<Food>()?.query(Food_.name.contains(name))?.build()?.find()
|
|
||||||
?.distinctBy { it.name }
|
|
||||||
} else {
|
|
||||||
getBox<Food>()?.all?.distinctBy { it.name }
|
|
||||||
} ?: emptyList()
|
|
||||||
}
|
|
||||||
|
|
||||||
// 使用 QueryBuilder 在数据库层删除,避免全量加载到内存
|
|
||||||
suspend fun remove(name: String) = safeDbOp {
|
|
||||||
getBox<Food>()?.query(Food_.name.equal(name))?.build()?.remove()
|
|
||||||
}
|
|
||||||
|
|
||||||
// 清除所有向量采集数据
|
|
||||||
suspend fun removeAll() = safeDbOp {
|
|
||||||
getBox<Food>()?.removeAll()
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 按名称分组统计采集数量
|
|
||||||
* 使用属性查询只加载 name 字段,不加载 foodVector,节省大量内存
|
|
||||||
* @param nameFilter 名称过滤关键词,为空时查询全部
|
|
||||||
* @return 按名称分组后的 (名称, 数量) 列表,按名称排序
|
|
||||||
*/
|
|
||||||
suspend fun queryFoodNameCounts(nameFilter: String? = null) = safeDbOp {
|
|
||||||
val box = getBox<Food>() ?: return@safeDbOp emptyList<Pair<String, Int>>()
|
|
||||||
val query = if (!nameFilter.isNullOrBlank()) {
|
|
||||||
box.query(Food_.name.contains(nameFilter)).build()
|
|
||||||
} else {
|
|
||||||
box.query().build()
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
// 只查 name 字段,完全不加载 foodVector
|
|
||||||
query.property(Food_.name).findStrings()
|
|
||||||
.groupingBy { it }
|
|
||||||
.eachCount()
|
|
||||||
.map { (name, count) -> Pair(name, count) }
|
|
||||||
.sortedBy { it.first }
|
|
||||||
} finally {
|
|
||||||
query.close()
|
|
||||||
}
|
|
||||||
} ?: emptyList()
|
|
||||||
|
|
||||||
private val dbMutex = Mutex() // 协程并发锁,保证写入操作原子性
|
|
||||||
private const val DB_DIR_NAME = "objectbox" // ObjectBox 默认数据库目录
|
|
||||||
private const val BACKUP_DIR_NAME = "objectbox_backup" // 备份目录
|
|
||||||
|
|
||||||
// 检查内部存储是否可读写(操作数据库前调用)
|
|
||||||
// 修复:原逻辑错误地检查外部存储状态,数据库存于内部存储,与外部存储无关
|
|
||||||
fun isStorageAvailable(context: Context): Boolean {
|
|
||||||
return try {
|
|
||||||
context.filesDir.canRead() && context.filesDir.canWrite()
|
|
||||||
} catch (e: Exception) {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 备份数据库到应用私有目录(无权限要求,推荐)
|
|
||||||
suspend fun backupDb(context: Context): Boolean = withContext(Dispatchers.IO) {
|
|
||||||
if (!isStorageAvailable(context)) return@withContext false
|
|
||||||
val dbDir = File(context.filesDir, DB_DIR_NAME)
|
|
||||||
val backupDir = File(context.filesDir, BACKUP_DIR_NAME)
|
|
||||||
return@withContext copyDir(dbDir, backupDir)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 从备份恢复数据库(恢复后会重建BoxStore)
|
|
||||||
suspend fun restoreDb(context: Context): Boolean = withContext(Dispatchers.IO) {
|
|
||||||
if (!isStorageAvailable(context)) return@withContext false
|
|
||||||
val dbDir = File(context.filesDir, DB_DIR_NAME)
|
|
||||||
val backupDir = File(context.filesDir, BACKUP_DIR_NAME)
|
|
||||||
if (!backupDir.exists()) return@withContext false
|
|
||||||
// 先关闭旧的BoxStore,删除损坏文件,再恢复备份
|
|
||||||
boxStore?.close()
|
|
||||||
deleteDbFiles(context)
|
|
||||||
val isSuccess = copyDir(backupDir, dbDir)
|
|
||||||
// 重新初始化
|
|
||||||
init(context)
|
|
||||||
return@withContext isSuccess
|
|
||||||
}
|
|
||||||
|
|
||||||
// 递归删除数据库文件
|
|
||||||
private fun deleteDbFiles(context: Context) {
|
|
||||||
val dbDir = File(context.filesDir, DB_DIR_NAME)
|
|
||||||
if (dbDir.exists()) deleteDirRecursively(dbDir)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 递归删除目录
|
|
||||||
private fun deleteDirRecursively(file: File) {
|
|
||||||
if (file.isDirectory) {
|
|
||||||
file.listFiles()?.forEach { deleteDirRecursively(it) }
|
|
||||||
}
|
|
||||||
file.delete()
|
|
||||||
}
|
|
||||||
|
|
||||||
// 递归复制目录(核心备份/恢复逻辑)
|
|
||||||
private fun copyDir(srcDir: File, destDir: File): Boolean {
|
|
||||||
return try {
|
|
||||||
if (!srcDir.exists()) return false
|
|
||||||
if (!destDir.exists()) destDir.mkdirs()
|
|
||||||
srcDir.listFiles()?.forEach { srcFile ->
|
|
||||||
val destFile = File(destDir, srcFile.name)
|
|
||||||
if (srcFile.isDirectory) {
|
|
||||||
copyDir(srcFile, destFile)
|
|
||||||
} else {
|
|
||||||
copyFile(srcFile, destFile)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
true
|
|
||||||
} catch (e: IOException) {
|
|
||||||
e.printStackTrace()
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 复制单个文件(使用NIO,高效稳定)
|
|
||||||
private fun copyFile(srcFile: File, destFile: File) {
|
|
||||||
FileInputStream(srcFile).channel.use { srcChannel ->
|
|
||||||
FileOutputStream(destFile).channel.use { destChannel ->
|
|
||||||
destChannel.transferFrom(srcChannel, 0, srcChannel.size())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 关闭BoxStore(应用退出时调用,可选)
|
|
||||||
fun close() {
|
|
||||||
boxStore?.close()
|
|
||||||
boxStore = null
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,155 +0,0 @@
|
|||||||
package com.shuwei.dish.match.scale
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.net.nsd.NsdManager
|
|
||||||
import android.net.nsd.NsdServiceInfo
|
|
||||||
import android.util.Log
|
|
||||||
import java.util.LinkedList
|
|
||||||
|
|
||||||
/**
|
|
||||||
* mDNS 设备发现管理器(仅主设备运行)
|
|
||||||
* 持续扫描局域网,发现或丢失 DishMatch 子设备时通过回调通知连接管理器
|
|
||||||
*
|
|
||||||
* 注意:Android NsdManager.resolveService 不支持并发调用,多台子设备同时被发现时
|
|
||||||
* 会报 FAILURE_ALREADY_ACTIVE(3) 导致解析失败。此处使用串行队列逐一解析。
|
|
||||||
*/
|
|
||||||
class MdnsDiscoveryManager(private val context: Context) {
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
private const val TAG = "MdnsDiscoveryManager"
|
|
||||||
}
|
|
||||||
|
|
||||||
private val nsdManager: NsdManager by lazy {
|
|
||||||
context.getSystemService(Context.NSD_SERVICE) as NsdManager
|
|
||||||
}
|
|
||||||
|
|
||||||
private var discoveryListener: NsdManager.DiscoveryListener? = null
|
|
||||||
private var isDiscovering = false
|
|
||||||
|
|
||||||
/** 待解析队列,串行处理避免并发解析失败 */
|
|
||||||
private val resolveQueue = LinkedList<NsdServiceInfo>()
|
|
||||||
private var isResolving = false
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 发现新设备时的回调:(deviceId, host, port)
|
|
||||||
*/
|
|
||||||
var onDeviceFound: ((deviceId: String, host: String, port: Int) -> Unit)? = null
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 设备离线时的回调:(deviceId)
|
|
||||||
*/
|
|
||||||
var onDeviceLost: ((deviceId: String) -> Unit)? = null
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 开始扫描局域网中的 DishMatch 设备
|
|
||||||
*/
|
|
||||||
fun startDiscovery() {
|
|
||||||
if (isDiscovering) return
|
|
||||||
|
|
||||||
discoveryListener = object : NsdManager.DiscoveryListener {
|
|
||||||
override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) {
|
|
||||||
Log.e(TAG, "开始扫描失败: errorCode=$errorCode")
|
|
||||||
isDiscovering = false
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) {
|
|
||||||
Log.e(TAG, "停止扫描失败: errorCode=$errorCode")
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onDiscoveryStarted(serviceType: String) {
|
|
||||||
Log.d(TAG, "mDNS 扫描已启动")
|
|
||||||
isDiscovering = true
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onDiscoveryStopped(serviceType: String) {
|
|
||||||
Log.d(TAG, "mDNS 扫描已停止")
|
|
||||||
isDiscovering = false
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onServiceFound(service: NsdServiceInfo) {
|
|
||||||
// 只处理 DishMatch 服务
|
|
||||||
if (!service.serviceName.startsWith("DishMatch-")) return
|
|
||||||
Log.d(TAG, "发现设备: ${service.serviceName}")
|
|
||||||
enqueueResolve(service)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onServiceLost(service: NsdServiceInfo) {
|
|
||||||
if (!service.serviceName.startsWith("DishMatch-")) return
|
|
||||||
val deviceId = service.serviceName.removePrefix("DishMatch-")
|
|
||||||
Log.d(TAG, "设备离线: $deviceId")
|
|
||||||
onDeviceLost?.invoke(deviceId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
nsdManager.discoverServices(
|
|
||||||
MdnsRegisterManager.SERVICE_TYPE,
|
|
||||||
NsdManager.PROTOCOL_DNS_SD,
|
|
||||||
discoveryListener
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 解析服务获取 IP 和端口
|
|
||||||
*/
|
|
||||||
private fun resolveService(service: NsdServiceInfo) {
|
|
||||||
nsdManager.resolveService(service, object : NsdManager.ResolveListener {
|
|
||||||
override fun onResolveFailed(info: NsdServiceInfo, errorCode: Int) {
|
|
||||||
Log.e(TAG, "解析设备地址失败: ${info.serviceName}, errorCode=$errorCode")
|
|
||||||
// 解析结束(失败),继续处理队列中下一个
|
|
||||||
processNextResolve()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onServiceResolved(info: NsdServiceInfo) {
|
|
||||||
val deviceId = info.serviceName.removePrefix("DishMatch-")
|
|
||||||
val host = info.host?.hostAddress ?: run {
|
|
||||||
processNextResolve()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
val port = info.port
|
|
||||||
Log.d(TAG, "设备地址已解析: $deviceId -> $host:$port")
|
|
||||||
onDeviceFound?.invoke(deviceId, host, port)
|
|
||||||
// 解析结束(成功),继续处理队列中下一个
|
|
||||||
processNextResolve()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 将待解析服务加入队列,若当前无解析任务则立即开始 */
|
|
||||||
@Synchronized
|
|
||||||
private fun enqueueResolve(service: NsdServiceInfo) {
|
|
||||||
resolveQueue.add(service)
|
|
||||||
if (!isResolving) {
|
|
||||||
processNextResolve()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 从队列取出下一个服务进行解析 */
|
|
||||||
@Synchronized
|
|
||||||
private fun processNextResolve() {
|
|
||||||
val next = resolveQueue.poll() ?: run {
|
|
||||||
isResolving = false
|
|
||||||
return
|
|
||||||
}
|
|
||||||
isResolving = true
|
|
||||||
resolveService(next)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 停止扫描,在应用退出时调用
|
|
||||||
*/
|
|
||||||
fun stopDiscovery() {
|
|
||||||
if (!isDiscovering) return
|
|
||||||
discoveryListener?.let {
|
|
||||||
try {
|
|
||||||
nsdManager.stopServiceDiscovery(it)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.e(TAG, "停止扫描异常: ${e.message}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
discoveryListener = null
|
|
||||||
synchronized(this) {
|
|
||||||
resolveQueue.clear()
|
|
||||||
isResolving = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
package com.shuwei.dish.match.scale
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.net.nsd.NsdManager
|
|
||||||
import android.net.nsd.NsdServiceInfo
|
|
||||||
import android.util.Log
|
|
||||||
|
|
||||||
/**
|
|
||||||
* mDNS 服务注册管理器(主设备和子设备均运行)
|
|
||||||
* 将本机 WebSocket 服务以 mDNS 形式广播到局域网,让主设备能发现本机 IP:PORT
|
|
||||||
*/
|
|
||||||
class MdnsRegisterManager(private val context: Context) {
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
private const val TAG = "MdnsRegisterManager"
|
|
||||||
/** mDNS 服务类型,所有 DishMatch 设备使用统一类型 */
|
|
||||||
const val SERVICE_TYPE = "_dishmatch._tcp."
|
|
||||||
/** WebSocket 服务监听端口 */
|
|
||||||
const val WS_PORT = 8765
|
|
||||||
}
|
|
||||||
|
|
||||||
private val nsdManager: NsdManager by lazy {
|
|
||||||
context.getSystemService(Context.NSD_SERVICE) as NsdManager
|
|
||||||
}
|
|
||||||
|
|
||||||
private var registrationListener: NsdManager.RegistrationListener? = null
|
|
||||||
private var isRegistered = false
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 向局域网注册 mDNS 服务
|
|
||||||
* @param deviceId 当前设备 ID,作为服务名称后缀,便于主设备识别
|
|
||||||
*/
|
|
||||||
fun register(deviceId: String) {
|
|
||||||
if (isRegistered) return
|
|
||||||
|
|
||||||
val serviceInfo = NsdServiceInfo().apply {
|
|
||||||
serviceName = "DishMatch-$deviceId"
|
|
||||||
serviceType = SERVICE_TYPE
|
|
||||||
port = WS_PORT
|
|
||||||
}
|
|
||||||
|
|
||||||
registrationListener = object : NsdManager.RegistrationListener {
|
|
||||||
override fun onRegistrationFailed(info: NsdServiceInfo, errorCode: Int) {
|
|
||||||
Log.e(TAG, "mDNS 注册失败, errorCode=$errorCode")
|
|
||||||
isRegistered = false
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onUnregistrationFailed(info: NsdServiceInfo, errorCode: Int) {
|
|
||||||
Log.e(TAG, "mDNS 注销失败, errorCode=$errorCode")
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onServiceRegistered(info: NsdServiceInfo) {
|
|
||||||
Log.d(TAG, "mDNS 注册成功: ${info.serviceName}")
|
|
||||||
isRegistered = true
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onServiceUnregistered(info: NsdServiceInfo) {
|
|
||||||
Log.d(TAG, "mDNS 已注销: ${info.serviceName}")
|
|
||||||
isRegistered = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
nsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, registrationListener)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 注销 mDNS 服务,在应用退出时调用
|
|
||||||
*/
|
|
||||||
fun unregister() {
|
|
||||||
if (!isRegistered) return
|
|
||||||
registrationListener?.let {
|
|
||||||
try {
|
|
||||||
nsdManager.unregisterService(it)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.e(TAG, "注销 mDNS 异常: ${e.message}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
registrationListener = null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
package com.shuwei.dish.match.scale
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 主设备向子设备发送的控制指令
|
|
||||||
* @param cmd 指令类型,如 "tare"(清零)
|
|
||||||
* @param deviceId 目标设备 ID,子设备收到后校验是否匹配自身
|
|
||||||
* @param address 目标秤地址
|
|
||||||
*/
|
|
||||||
data class ScaleCommand(
|
|
||||||
val cmd: String,
|
|
||||||
val deviceId: String,
|
|
||||||
val address: Int
|
|
||||||
) {
|
|
||||||
companion object {
|
|
||||||
const val CMD_TARE = "tare"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
package com.shuwei.dish.match.scale
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 单个秤的数据快照
|
|
||||||
* @param deviceId 所属设备 ID
|
|
||||||
* @param address 秤地址编号(硬件 address,对应 WeightUtil 回调的 address 参数)
|
|
||||||
* @param weight 重量,单位克
|
|
||||||
* @param state 秤状态:1=稳定,0=不稳定,2=量程溢出(对应 WeightUtil 中的 STATE_* 常量)
|
|
||||||
* @param ts 数据时间戳(毫秒)
|
|
||||||
* @param ip 所属设备的 IP 地址,用于 UI 展示;网络传输数据中可能为空
|
|
||||||
*/
|
|
||||||
data class ScaleData(
|
|
||||||
val deviceId: String,
|
|
||||||
val address: Int,
|
|
||||||
val weight: Double,
|
|
||||||
val state: Int,
|
|
||||||
val ts: Long,
|
|
||||||
val ip: String = "",
|
|
||||||
val name: String? = null
|
|
||||||
)
|
|
||||||
@@ -1,122 +0,0 @@
|
|||||||
package com.shuwei.dish.match.scale
|
|
||||||
|
|
||||||
import android.util.Log
|
|
||||||
import com.shuwei.dish.match.utils.WeightUtil
|
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 秤数据聚合器(仅主设备运行)
|
|
||||||
* 统一管理本机秤(直接读取 WeightUtil)和远端子设备秤(通过 WebSocket 接收)的数据
|
|
||||||
* 通过 StateFlow 将所有秤的最新快照暴露给 UI 层
|
|
||||||
*
|
|
||||||
* 数据 Map 的 key 格式:"{deviceId}#{address}",便于 UI 按设备分组展示
|
|
||||||
*/
|
|
||||||
class ScaleDataAggregator(private val localDeviceId: String) {
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
private const val TAG = "ScaleDataAggregator"
|
|
||||||
/** 本机秤监听器的 key,防止与其他监听器冲突 */
|
|
||||||
private const val LOCAL_LISTENER_KEY = "ScaleDataAggregator_local"
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 所有秤的最新数据,UI 层通过此 Flow 订阅更新 */
|
|
||||||
private val _allScales = MutableStateFlow<Map<String, ScaleData>>(emptyMap())
|
|
||||||
val allScales: StateFlow<Map<String, ScaleData>> = _allScales.asStateFlow()
|
|
||||||
|
|
||||||
/** 内部缓存,并发安全 */
|
|
||||||
private val cache = ConcurrentHashMap<String, ScaleData>()
|
|
||||||
|
|
||||||
/** deviceId → IP 地址映射,用于写入 ScaleData.ip 字段 */
|
|
||||||
private val deviceIpMap = ConcurrentHashMap<String, String>()
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 设置指定设备的 IP 地址
|
|
||||||
* 若缓存中已有该设备的数据且 ip 为空,立即回填并触发 StateFlow 更新,
|
|
||||||
* 解决早期数据包在 IP 到达前入缓存导致一直显示"未知"的问题
|
|
||||||
* @param deviceId 设备 ID
|
|
||||||
* @param ip IP 地址字符串
|
|
||||||
*/
|
|
||||||
fun setDeviceIp(deviceId: String, ip: String) {
|
|
||||||
if (ip.isEmpty()) return
|
|
||||||
deviceIpMap[deviceId] = ip
|
|
||||||
// 回填该设备所有 ip 为空的缓存条目
|
|
||||||
val keys = cache.keys.filter { it.startsWith("$deviceId#") }
|
|
||||||
if (keys.isEmpty()) return
|
|
||||||
var updated = false
|
|
||||||
keys.forEach { key ->
|
|
||||||
val old = cache[key] ?: return@forEach
|
|
||||||
if (old.ip.isEmpty()) {
|
|
||||||
cache[key] = old.copy(ip = ip)
|
|
||||||
updated = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (updated) {
|
|
||||||
_allScales.value = HashMap(cache)
|
|
||||||
Log.d(TAG, "已回填设备IP: $deviceId -> $ip, 共 ${keys.size} 条")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 启动本机秤数据监听
|
|
||||||
* 主设备本机秤直接读取 WeightUtil,无需经过网络
|
|
||||||
*/
|
|
||||||
fun startLocalCollection() {
|
|
||||||
WeightUtil.addWeightListener(LOCAL_LISTENER_KEY) { address, state, weight ->
|
|
||||||
val data = ScaleData(
|
|
||||||
deviceId = localDeviceId,
|
|
||||||
address = address,
|
|
||||||
weight = weight,
|
|
||||||
state = state,
|
|
||||||
ts = System.currentTimeMillis(),
|
|
||||||
ip = deviceIpMap[localDeviceId] ?: ""
|
|
||||||
)
|
|
||||||
updateCache(data)
|
|
||||||
}
|
|
||||||
Log.d(TAG, "本机秤监听已启动, deviceId=$localDeviceId")
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 处理来自 WebSocket 客户端的远端秤数据
|
|
||||||
* 由 ScaleWebSocketClient.onScaleData 回调触发
|
|
||||||
* 自动补充该设备已记录的 IP 信息
|
|
||||||
*/
|
|
||||||
fun onRemoteScaleData(data: ScaleData) {
|
|
||||||
val ip = deviceIpMap[data.deviceId] ?: data.ip
|
|
||||||
updateCache(if (ip.isNotEmpty() && data.ip.isEmpty()) data.copy(ip = ip) else data)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 移除指定设备的所有秤数据(设备离线时调用)
|
|
||||||
*/
|
|
||||||
fun removeDevice(deviceId: String) {
|
|
||||||
val keysToRemove = cache.keys.filter { it.startsWith("$deviceId#") }
|
|
||||||
if (keysToRemove.isEmpty()) return
|
|
||||||
keysToRemove.forEach { cache.remove(it) }
|
|
||||||
deviceIpMap.remove(deviceId)
|
|
||||||
_allScales.value = HashMap(cache)
|
|
||||||
Log.d(TAG, "已移除设备数据: $deviceId, 共 ${keysToRemove.size} 个秤")
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 停止本机秤监听并清空所有数据
|
|
||||||
*/
|
|
||||||
fun stop() {
|
|
||||||
WeightUtil.removeWeightListener(LOCAL_LISTENER_KEY)
|
|
||||||
cache.clear()
|
|
||||||
deviceIpMap.clear()
|
|
||||||
_allScales.value = emptyMap()
|
|
||||||
Log.d(TAG, "ScaleDataAggregator 已停止")
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 更新缓存并发布新快照到 StateFlow
|
|
||||||
*/
|
|
||||||
private fun updateCache(data: ScaleData) {
|
|
||||||
val key = "${data.deviceId}#${data.address}"
|
|
||||||
cache[key] = data
|
|
||||||
_allScales.value = HashMap(cache)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
package com.shuwei.dish.match.scale
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 各子设备的固定 ID 与秤地址排列顺序配置
|
|
||||||
* MasterScaleActivity 和 SlaveActivity 共用此配置,避免重复定义
|
|
||||||
*/
|
|
||||||
object ScaleDeviceConfig {
|
|
||||||
|
|
||||||
const val DEVICE_ID_2 = "8fc2ab34-2137-3112-acca-f884ea8736d4"
|
|
||||||
const val DEVICE_ID_22 = "a46fa55c-113c-3511-bb1f-41e5eff77c4b"
|
|
||||||
const val DEVICE_ID_18 = "1038da9f-c6eb-326e-a1d9-d6d3af978b22"
|
|
||||||
const val DEVICE_ID_1 = "7cc0f6ea-f13d-3013-a867-fc998eb554ac"
|
|
||||||
|
|
||||||
/** 22个秤的显示顺序(按物理位置排列) */
|
|
||||||
val SCALE_ORDER_22 = listOf(20, 22, 19, 21, 6, 12, 18, 5, 11, 17, 4, 10, 16, 3, 9, 15, 2, 8, 14, 1, 7, 13)
|
|
||||||
|
|
||||||
/** 18个秤的显示顺序(按物理位置排列) */
|
|
||||||
val SCALE_ORDER_18 = listOf(6, 5, 4, 3, 2, 1, 12, 11, 10, 9, 8, 7, 18, 17, 16, 15, 14, 13)
|
|
||||||
|
|
||||||
/** 1个秤的地址列表 */
|
|
||||||
val SCALE_ORDER_1 = listOf(1)
|
|
||||||
|
|
||||||
/** 设备在列表中的显示顺序 */
|
|
||||||
val DEVICE_ORDER = listOf(DEVICE_ID_2, DEVICE_ID_22, DEVICE_ID_18, DEVICE_ID_1)
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
package com.shuwei.dish.match.scale
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 秤事件数据类,用于主设备和子设备之间的非重量类通知
|
|
||||||
* @param type 事件类型,参见 companion object 中的常量
|
|
||||||
* @param deviceId 发送方设备 ID
|
|
||||||
* @param address 触发事件的秤地址,TYPE_SEASONING_CONFIG 时为 0(无意义)
|
|
||||||
* @param delta 重量变化量(克),仅 TYPE_SEASONING_ADDED 时有意义
|
|
||||||
* @param slots 调料槽位配置列表,仅 TYPE_SEASONING_CONFIG 时有效
|
|
||||||
*/
|
|
||||||
data class ScaleEvent(
|
|
||||||
val type: String,
|
|
||||||
val deviceId: String,
|
|
||||||
val address: Int = 0,
|
|
||||||
val delta: Double = 0.0,
|
|
||||||
val slots: List<SlotConfig>? = null
|
|
||||||
) {
|
|
||||||
/**
|
|
||||||
* 单个槽位的配置信息,随 TYPE_SEASONING_CONFIG 事件一起传输
|
|
||||||
* @param deviceId 所属设备 ID
|
|
||||||
* @param address 秤硬件地址
|
|
||||||
* @param goodsId 调料 ID
|
|
||||||
* @param goodsName 调料名称
|
|
||||||
*/
|
|
||||||
data class SlotConfig(
|
|
||||||
val deviceId: String,
|
|
||||||
val address: Int,
|
|
||||||
val goodsId: String,
|
|
||||||
val goodsName: String
|
|
||||||
)
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
/** 调料添加事件:某秤重量增加超过阈值 */
|
|
||||||
const val TYPE_SEASONING_ADDED = "seasoning_added"
|
|
||||||
/** 调料槽位配置同步事件:主设备配置变更后广播给子设备 */
|
|
||||||
const val TYPE_SEASONING_CONFIG = "seasoning_config"
|
|
||||||
/** 清除数据事件:主设备通知所有子设备清除本机测试数据 */
|
|
||||||
const val TYPE_CLEAR_DATA = "clear_data"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,277 +0,0 @@
|
|||||||
package com.shuwei.dish.match.scale
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.util.Log
|
|
||||||
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.utils.NetworkUtil
|
|
||||||
import com.shuwei.dish.match.utils.WeightUtil
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.SupervisorJob
|
|
||||||
import kotlinx.coroutines.cancel
|
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 秤服务统一门面(单例)
|
|
||||||
* 根据当前设备角色(MASTER/SLAVE)启动对应的服务组合:
|
|
||||||
*
|
|
||||||
* 所有设备均运行:
|
|
||||||
* - MdnsRegisterManager:将本机 WebSocket 服务广播到局域网
|
|
||||||
* - ScaleWebSocketServer:对外提供本机秤数据推送服务
|
|
||||||
*
|
|
||||||
* 仅主设备(MASTER)额外运行:
|
|
||||||
* - MdnsDiscoveryManager:发现局域网内子设备
|
|
||||||
* - ScaleWebSocketClient:连接子设备 WebSocket
|
|
||||||
* - ScaleDataAggregator:聚合本机 + 远端所有秤数据
|
|
||||||
*
|
|
||||||
* 使用方式:
|
|
||||||
* 在 Application.onCreate() 中调用 ScaleServiceManager.start(context)
|
|
||||||
* 在 Application.onTerminate() 中调用 ScaleServiceManager.stop()
|
|
||||||
* 主设备 UI 通过 ScaleServiceManager.allScales 订阅全量秤数据
|
|
||||||
*/
|
|
||||||
object ScaleServiceManager {
|
|
||||||
|
|
||||||
private const val TAG = "ScaleServiceManager"
|
|
||||||
|
|
||||||
@Volatile private var isStarted = false
|
|
||||||
private var serviceScope: CoroutineScope? = null
|
|
||||||
|
|
||||||
private var mdnsRegister: MdnsRegisterManager? = null
|
|
||||||
private var wsServer: ScaleWebSocketServer? = null
|
|
||||||
private var udpSender: UdpBroadcastSender? = null
|
|
||||||
|
|
||||||
// 以下仅主设备使用
|
|
||||||
private var mdnsDiscovery: MdnsDiscoveryManager? = null
|
|
||||||
private var udpReceiver: UdpBroadcastReceiver? = null
|
|
||||||
private var wsClient: ScaleWebSocketClient? = null
|
|
||||||
private var aggregator: ScaleDataAggregator? = null
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 所有秤数据的实时流,仅主设备有效;子设备返回 null
|
|
||||||
* UI 层通过 lifecycleScope.launch { allScales?.collect { ... } } 订阅
|
|
||||||
*/
|
|
||||||
val allScales: StateFlow<Map<String, ScaleData>>?
|
|
||||||
get() = aggregator?.allScales
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 收到子设备秤事件(如调料添加)时的回调,仅主设备有效
|
|
||||||
* 在子线程中调用,需自行切换到主线程更新 UI
|
|
||||||
*/
|
|
||||||
private var _onScaleEvent: ((ScaleEvent) -> Unit)? = null
|
|
||||||
var onScaleEvent: ((ScaleEvent) -> Unit)?
|
|
||||||
get() = _onScaleEvent
|
|
||||||
set(value) {
|
|
||||||
_onScaleEvent = value
|
|
||||||
wsClient?.onScaleEvent = value
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 收到主设备下发的调料配置同步事件时的回调,仅子设备有效
|
|
||||||
* 在子线程中调用,需自行切换到主线程更新 UI
|
|
||||||
*/
|
|
||||||
var onSeasoningConfig: ((ScaleEvent) -> Unit)?
|
|
||||||
get() = wsServer?.onSeasoningConfig
|
|
||||||
set(value) { wsServer?.onSeasoningConfig = value }
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 收到主设备下发的清除数据事件时的回调,仅子设备有效
|
|
||||||
* 在子线程中调用,需自行切换到主线程更新 UI
|
|
||||||
*/
|
|
||||||
var onClearData: ((ScaleEvent) -> Unit)?
|
|
||||||
get() = wsServer?.onClearData
|
|
||||||
set(value) { wsServer?.onClearData = value }
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 向所有已连接子设备广播调料配置(主设备调用)
|
|
||||||
* @param slots 全量槽位配置列表
|
|
||||||
*/
|
|
||||||
fun sendSeasoningConfig(slots: List<ScaleEvent.SlotConfig>) {
|
|
||||||
wsClient?.sendToAllSlaves(buildConfigEvent(slots))
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 通知所有已连接子设备清除本机数据(主设备调用)
|
|
||||||
* 子设备收到后执行与主设备相同的清除逻辑
|
|
||||||
*/
|
|
||||||
fun sendClearData() {
|
|
||||||
wsClient?.sendToAllSlaves(
|
|
||||||
ScaleEvent(type = ScaleEvent.TYPE_CLEAR_DATA, deviceId = GlobalData.deviceId)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 向单台刚连接的子设备推送调料配置(连接时按需调用)
|
|
||||||
* @param deviceId 目标子设备 ID
|
|
||||||
*/
|
|
||||||
private fun sendSeasoningConfigTo(deviceId: String, slots: List<ScaleEvent.SlotConfig>) {
|
|
||||||
wsClient?.sendToDevice(deviceId, buildConfigEvent(slots))
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun buildConfigEvent(slots: List<ScaleEvent.SlotConfig>) = ScaleEvent(
|
|
||||||
type = ScaleEvent.TYPE_SEASONING_CONFIG,
|
|
||||||
deviceId = GlobalData.deviceId,
|
|
||||||
slots = slots
|
|
||||||
)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 向主设备广播秤事件(子设备调用)
|
|
||||||
* @param event 要广播的事件
|
|
||||||
*/
|
|
||||||
fun broadcastEvent(event: ScaleEvent) {
|
|
||||||
wsServer?.broadcastEvent(event)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 主设备连接状态回调(仅子设备使用)
|
|
||||||
* 设置后会立即转发给 wsServer;需在 start() 之后设置才能生效
|
|
||||||
*/
|
|
||||||
var onMasterConnectionChanged: ((connected: Boolean) -> Unit)?
|
|
||||||
get() = wsServer?.onConnectionChanged
|
|
||||||
set(value) { wsServer?.onConnectionChanged = value }
|
|
||||||
|
|
||||||
/** 当前是否有主设备连接(仅子设备使用) */
|
|
||||||
val isMasterConnected: Boolean
|
|
||||||
get() = wsServer?.isConnected == true
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 启动所有秤服务,在 Application.onCreate() 中调用
|
|
||||||
*/
|
|
||||||
fun start(context: Context) {
|
|
||||||
if (isStarted) return
|
|
||||||
isStarted = true
|
|
||||||
serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
|
||||||
val deviceId = GlobalData.deviceId
|
|
||||||
val role = GlobalData.deviceRole
|
|
||||||
Log.d(TAG, "启动秤服务, deviceId=$deviceId, role=$role")
|
|
||||||
|
|
||||||
// 所有设备:启动 WebSocket 服务端 + mDNS 注册
|
|
||||||
wsServer = ScaleWebSocketServer(deviceId, context).also { it.start() }
|
|
||||||
mdnsRegister = MdnsRegisterManager(context).also { it.register(deviceId) }
|
|
||||||
|
|
||||||
if (role == DeviceRole.MASTER) {
|
|
||||||
startMasterServices(context, deviceId)
|
|
||||||
} else {
|
|
||||||
// 子设备:启动 UDP 广播,作为 mDNS 的兜底发现机制;每次广播时动态获取 IP,避免启动时网络未就绪导致 IP 为空
|
|
||||||
udpSender = UdpBroadcastSender(deviceId = deviceId, ipProvider = { getLocalIp(context) }).also { it.start() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取本机局域网 IP,委托给 NetworkUtil 统一处理版本兼容
|
|
||||||
*/
|
|
||||||
private fun getLocalIp(context: Context): String {
|
|
||||||
return NetworkUtil.getLocalIpAddress(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 启动主设备专属服务
|
|
||||||
*/
|
|
||||||
private fun startMasterServices(context: Context, deviceId: String) {
|
|
||||||
// 聚合器:统一管理本机 + 远端秤数据
|
|
||||||
aggregator = ScaleDataAggregator(deviceId).also {
|
|
||||||
// 记录本机 IP,供本机秤数据展示使用
|
|
||||||
it.setDeviceIp(deviceId, getLocalIp(context))
|
|
||||||
it.startLocalCollection()
|
|
||||||
}
|
|
||||||
|
|
||||||
// WebSocket 客户端
|
|
||||||
val client = ScaleWebSocketClient().also {
|
|
||||||
it.onScaleData = { data -> aggregator?.onRemoteScaleData(data) }
|
|
||||||
it.onScaleEvent = { event -> _onScaleEvent?.invoke(event) }
|
|
||||||
it.onDeviceDisconnected = { remoteId ->
|
|
||||||
aggregator?.removeDevice(remoteId)
|
|
||||||
// 清除 UDP 缓存,确保子设备下次广播时能重新触发 onDeviceFound,立即重连而非等待指数退避
|
|
||||||
udpReceiver?.removeDevice(remoteId)
|
|
||||||
}
|
|
||||||
it.onDeviceConnected = { remoteId ->
|
|
||||||
// 子设备连接成功时,从 Room 读取全量配置并单独推送给该设备
|
|
||||||
serviceScope?.launch {
|
|
||||||
val slots = BaseApp.instance?.database?.seasoningSlotDao()
|
|
||||||
?.queryAll()
|
|
||||||
?.map { slot ->
|
|
||||||
ScaleEvent.SlotConfig(
|
|
||||||
slot.deviceId, slot.address, slot.goodsId, slot.goodsName
|
|
||||||
)
|
|
||||||
} ?: return@launch
|
|
||||||
if (slots.isNotEmpty()) sendSeasoningConfigTo(remoteId, slots)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
wsClient = client
|
|
||||||
|
|
||||||
// 统一的设备发现处理:mDNS 和 UDP 共用同一逻辑
|
|
||||||
fun onDeviceFound(remoteId: String, host: String, port: Int) {
|
|
||||||
if (remoteId == deviceId) return
|
|
||||||
Log.d(TAG, "发现子设备 $remoteId ($host:$port), 建立连接")
|
|
||||||
aggregator?.setDeviceIp(remoteId, host)
|
|
||||||
client.connect(remoteId, host, port)
|
|
||||||
}
|
|
||||||
|
|
||||||
// mDNS 发现:发现子设备 → 建立 WebSocket 连接;设备离线 → 仅清除 UDP 缓存,WebSocket 层自行重连
|
|
||||||
mdnsDiscovery = MdnsDiscoveryManager(context).also { discovery ->
|
|
||||||
discovery.onDeviceFound = { remoteId, host, port ->
|
|
||||||
onDeviceFound(remoteId, host, port)
|
|
||||||
}
|
|
||||||
discovery.onDeviceLost = { remoteId ->
|
|
||||||
// mDNS 抖动不永久断开,WebSocket 层会持续重连直到网络恢复
|
|
||||||
// 仅清除 UDP 缓存,确保 UDP 重新发现时能再次触发 onDeviceFound
|
|
||||||
udpReceiver?.removeDevice(remoteId)
|
|
||||||
Log.d(TAG, "子设备 mDNS 离线: $remoteId, 保持 WebSocket 重连")
|
|
||||||
}
|
|
||||||
discovery.startDiscovery()
|
|
||||||
}
|
|
||||||
|
|
||||||
// UDP 广播接收:作为 mDNS 的兜底,发现 mDNS 未能触发的子设备
|
|
||||||
udpReceiver = UdpBroadcastReceiver().also { receiver ->
|
|
||||||
receiver.onDeviceFound = { remoteId, host, port ->
|
|
||||||
onDeviceFound(remoteId, host, port)
|
|
||||||
}
|
|
||||||
receiver.start()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 向指定设备的指定秤发送清零指令
|
|
||||||
* - 本机秤:直接调用 WeightUtil.tareTwo
|
|
||||||
* - 子设备秤:通过 WebSocket 发送指令
|
|
||||||
* @param deviceId 目标设备 ID
|
|
||||||
* @param address 目标秤地址
|
|
||||||
*/
|
|
||||||
fun sendTare(deviceId: String, address: Int): Boolean {
|
|
||||||
return if (deviceId == GlobalData.deviceId) {
|
|
||||||
WeightUtil.tareTwo(address)
|
|
||||||
true
|
|
||||||
} else {
|
|
||||||
val cmd = ScaleCommand(ScaleCommand.CMD_TARE, deviceId, address)
|
|
||||||
wsClient?.sendCommand(deviceId, cmd) ?: false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 停止所有秤服务,在 Application.onTerminate() 或退出时调用
|
|
||||||
*/
|
|
||||||
fun stop() {
|
|
||||||
serviceScope?.cancel()
|
|
||||||
serviceScope = null
|
|
||||||
isStarted = false
|
|
||||||
mdnsDiscovery?.stopDiscovery()
|
|
||||||
udpReceiver?.stop()
|
|
||||||
udpSender?.stop()
|
|
||||||
wsClient?.shutdown()
|
|
||||||
aggregator?.stop()
|
|
||||||
wsServer?.stop()
|
|
||||||
mdnsRegister?.unregister()
|
|
||||||
|
|
||||||
mdnsDiscovery = null
|
|
||||||
udpReceiver = null
|
|
||||||
udpSender = null
|
|
||||||
wsClient = null
|
|
||||||
aggregator = null
|
|
||||||
wsServer = null
|
|
||||||
mdnsRegister = null
|
|
||||||
Log.d(TAG, "所有秤服务已停止")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,230 +0,0 @@
|
|||||||
package com.shuwei.dish.match.scale
|
|
||||||
|
|
||||||
import android.util.Log
|
|
||||||
import com.google.gson.Gson
|
|
||||||
import okhttp3.OkHttpClient
|
|
||||||
import okhttp3.Request
|
|
||||||
import okhttp3.Response
|
|
||||||
import okhttp3.WebSocket
|
|
||||||
import okhttp3.WebSocketListener
|
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
|
||||||
import java.util.concurrent.Executors
|
|
||||||
import java.util.concurrent.ScheduledExecutorService
|
|
||||||
import java.util.concurrent.ScheduledFuture
|
|
||||||
import java.util.concurrent.TimeUnit
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 秤数据 WebSocket 客户端连接管理器(仅主设备运行)
|
|
||||||
* 管理与多台子设备的 WebSocket 长连接,支持断线自动重连(指数退避)
|
|
||||||
*/
|
|
||||||
class ScaleWebSocketClient {
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
private const val TAG = "ScaleWebSocketClient"
|
|
||||||
/** 初始重连间隔(毫秒) */
|
|
||||||
private const val RECONNECT_BASE_MS = 2_000L
|
|
||||||
/** 最大重连间隔(毫秒) */
|
|
||||||
private const val RECONNECT_MAX_MS = 30_000L
|
|
||||||
}
|
|
||||||
|
|
||||||
private val gson = Gson()
|
|
||||||
|
|
||||||
private val httpClient = OkHttpClient.Builder()
|
|
||||||
.connectTimeout(10, TimeUnit.SECONDS)
|
|
||||||
.readTimeout(0, TimeUnit.SECONDS) // WebSocket 长连接不设置读取超时
|
|
||||||
.pingInterval(20, TimeUnit.SECONDS) // 心跳保活
|
|
||||||
.build()
|
|
||||||
|
|
||||||
/** 各设备当前 WebSocket 连接,key = deviceId */
|
|
||||||
private val connections = ConcurrentHashMap<String, WebSocket>()
|
|
||||||
/** 各设备当前重连任务,key = deviceId */
|
|
||||||
private val reconnectTasks = ConcurrentHashMap<String, ScheduledFuture<*>>()
|
|
||||||
/** 各设备当前重连延迟,key = deviceId */
|
|
||||||
private val reconnectDelays = ConcurrentHashMap<String, Long>()
|
|
||||||
/** 已主动移除的设备集合,不对其触发重连 */
|
|
||||||
private val removedDevices = ConcurrentHashMap.newKeySet<String>()
|
|
||||||
/**
|
|
||||||
* 各设备的连接版本号,每次调用 connect() 时递增
|
|
||||||
* doConnect 执行前校验版本,版本不匹配说明已有更新的连接请求,直接放弃本次连接
|
|
||||||
*/
|
|
||||||
private val connectVersions = ConcurrentHashMap<String, Int>()
|
|
||||||
|
|
||||||
private val scheduler: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()
|
|
||||||
|
|
||||||
/** 收到秤数据时的回调,在子线程调用 */
|
|
||||||
var onScaleData: ((data: ScaleData) -> Unit)? = null
|
|
||||||
|
|
||||||
/** 收到秤事件(如调料添加通知)时的回调,在子线程调用 */
|
|
||||||
var onScaleEvent: ((event: ScaleEvent) -> Unit)? = null
|
|
||||||
|
|
||||||
/** 设备断线时的回调(连接失败或关闭),在子线程调用 */
|
|
||||||
var onDeviceDisconnected: ((deviceId: String) -> Unit)? = null
|
|
||||||
|
|
||||||
/** 子设备首次连接成功时的回调,在子线程调用;可用于主设备主动推送全量配置 */
|
|
||||||
var onDeviceConnected: ((deviceId: String) -> Unit)? = null
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 连接到指定子设备
|
|
||||||
* @param deviceId 子设备 ID
|
|
||||||
* @param host 子设备 IP
|
|
||||||
* @param port 子设备 WebSocket 端口
|
|
||||||
*/
|
|
||||||
fun connect(deviceId: String, host: String, port: Int) {
|
|
||||||
removedDevices.remove(deviceId)
|
|
||||||
// 取消旧重连任务,防止 IP 变化时新旧任务并发竞争
|
|
||||||
reconnectTasks.remove(deviceId)?.cancel(false)
|
|
||||||
reconnectDelays[deviceId] = RECONNECT_BASE_MS
|
|
||||||
// 递增版本号:doConnect 执行前会校验版本,旧任务版本不匹配时直接放弃
|
|
||||||
val version = (connectVersions[deviceId] ?: 0) + 1
|
|
||||||
connectVersions[deviceId] = version
|
|
||||||
doConnect(deviceId, host, port, version)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun doConnect(deviceId: String, host: String, port: Int, version: Int = connectVersions[deviceId] ?: 0) {
|
|
||||||
// 版本校验:若当前版本已被更新的 connect() 调用覆盖,放弃本次连接
|
|
||||||
if (connectVersions[deviceId] != version) {
|
|
||||||
Log.d(TAG, "放弃过期连接任务: $deviceId, version=$version")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// IPv6 地址在 URL 中需用方括号包裹,否则 OkHttp 会将冒号后内容误解析为端口
|
|
||||||
val formattedHost = if (host.contains(':')) "[$host]" else host
|
|
||||||
val url = "ws://$formattedHost:$port"
|
|
||||||
val request = Request.Builder().url(url).build()
|
|
||||||
|
|
||||||
val ws = httpClient.newWebSocket(request, object : WebSocketListener() {
|
|
||||||
override fun onOpen(webSocket: WebSocket, response: Response) {
|
|
||||||
Log.d(TAG, "已连接子设备: $deviceId ($url)")
|
|
||||||
connections[deviceId] = webSocket
|
|
||||||
reconnectDelays[deviceId] = RECONNECT_BASE_MS
|
|
||||||
reconnectTasks.remove(deviceId)?.cancel(false)
|
|
||||||
onDeviceConnected?.invoke(deviceId)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onMessage(webSocket: WebSocket, text: String) {
|
|
||||||
try {
|
|
||||||
// 通过 type 字段区分 ScaleEvent 与 ScaleData
|
|
||||||
val raw = gson.fromJson(text, Map::class.java)
|
|
||||||
if (raw.containsKey("type")) {
|
|
||||||
val event = gson.fromJson(text, ScaleEvent::class.java)
|
|
||||||
onScaleEvent?.invoke(event)
|
|
||||||
} else {
|
|
||||||
val data = gson.fromJson(text, ScaleData::class.java)
|
|
||||||
onScaleData?.invoke(data)
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w(TAG, "解析消息失败: ${e.message}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
|
|
||||||
Log.w(TAG, "连接子设备失败: $deviceId, ${t.message}")
|
|
||||||
// 使用 remove(key, value) 确保只移除自己的实例
|
|
||||||
// 避免旧连接超时触发时误删新连接引用,导致 aggregator 错误清空新连接数据
|
|
||||||
val removed = connections.remove(deviceId, webSocket)
|
|
||||||
if (removed) {
|
|
||||||
onDeviceDisconnected?.invoke(deviceId)
|
|
||||||
scheduleReconnect(deviceId, host, port)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
|
|
||||||
Log.d(TAG, "子设备连接已关闭: $deviceId, reason=$reason")
|
|
||||||
// 同上:只有移除的是自己,才触发断线回调和重连
|
|
||||||
val removed = connections.remove(deviceId, webSocket)
|
|
||||||
if (removed) {
|
|
||||||
onDeviceDisconnected?.invoke(deviceId)
|
|
||||||
scheduleReconnect(deviceId, host, port)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
// 写入新连接前先关闭旧连接,避免 IP 变化时旧 ws 对象悬空造成 TCP 资源泄漏
|
|
||||||
connections.put(deviceId, ws)?.close(1000, "新连接替换")
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 指数退避重连
|
|
||||||
* 入口不拦截 removedDevices,仅在延迟任务执行前检查,
|
|
||||||
* 确保 disconnect() 后已入队的任务不执行,但新断线事件始终能进入重连流程
|
|
||||||
* scheduler 已关闭(shutdown 后)时直接跳过,避免 RejectedExecutionException
|
|
||||||
*/
|
|
||||||
private fun scheduleReconnect(deviceId: String, host: String, port: Int) {
|
|
||||||
if (scheduler.isShutdown) return
|
|
||||||
val delay = reconnectDelays[deviceId] ?: RECONNECT_BASE_MS
|
|
||||||
Log.d(TAG, "将在 ${delay}ms 后重连子设备: $deviceId")
|
|
||||||
// 记录当前版本,延迟任务执行时再次校验,防止期间有新的 connect() 调用
|
|
||||||
val version = connectVersions[deviceId] ?: 0
|
|
||||||
|
|
||||||
val future = scheduler.schedule({
|
|
||||||
if (!removedDevices.contains(deviceId)) {
|
|
||||||
doConnect(deviceId, host, port, version)
|
|
||||||
}
|
|
||||||
}, delay, TimeUnit.MILLISECONDS)
|
|
||||||
|
|
||||||
reconnectTasks[deviceId]?.cancel(false)
|
|
||||||
reconnectTasks[deviceId] = future
|
|
||||||
|
|
||||||
// 下次重连延迟翻倍,上限 30s
|
|
||||||
reconnectDelays[deviceId] = minOf(delay * 2, RECONNECT_MAX_MS)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 向指定子设备发送控制指令
|
|
||||||
* @param deviceId 目标子设备 ID
|
|
||||||
* @param command 指令对象
|
|
||||||
* @return true=发送成功,false=设备未连接
|
|
||||||
*/
|
|
||||||
fun sendCommand(deviceId: String, command: ScaleCommand): Boolean {
|
|
||||||
val ws = connections[deviceId] ?: return false
|
|
||||||
return ws.send(gson.toJson(command))
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 向所有已连接的子设备广播事件(主设备调用,用于配置同步等场景)
|
|
||||||
* @param event 要广播的事件
|
|
||||||
*/
|
|
||||||
fun sendToAllSlaves(event: ScaleEvent) {
|
|
||||||
val json = gson.toJson(event)
|
|
||||||
connections.values.forEach { ws ->
|
|
||||||
try { ws.send(json) } catch (e: Exception) {
|
|
||||||
Log.w(TAG, "sendToAllSlaves 失败: ${e.message}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 向指定子设备发送事件(用于连接时单独推送配置)
|
|
||||||
* @param deviceId 目标子设备 ID
|
|
||||||
* @param event 要发送的事件
|
|
||||||
*/
|
|
||||||
fun sendToDevice(deviceId: String, event: ScaleEvent) {
|
|
||||||
val ws = connections[deviceId] ?: return
|
|
||||||
try { ws.send(gson.toJson(event)) } catch (e: Exception) {
|
|
||||||
Log.w(TAG, "sendToDevice $deviceId 失败: ${e.message}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 断开指定子设备连接(不再重连)
|
|
||||||
* @param deviceId 子设备 ID
|
|
||||||
*/
|
|
||||||
fun disconnect(deviceId: String) {
|
|
||||||
removedDevices.add(deviceId)
|
|
||||||
reconnectTasks.remove(deviceId)?.cancel(false)
|
|
||||||
connections.remove(deviceId)?.close(1000, "设备离线")
|
|
||||||
reconnectDelays.remove(deviceId)
|
|
||||||
connectVersions.remove(deviceId)
|
|
||||||
Log.d(TAG, "已断开子设备: $deviceId")
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 关闭所有连接并释放资源,在应用退出时调用
|
|
||||||
*/
|
|
||||||
fun shutdown() {
|
|
||||||
val ids = connections.keys.toList()
|
|
||||||
ids.forEach { disconnect(it) }
|
|
||||||
scheduler.shutdownNow()
|
|
||||||
httpClient.dispatcher.executorService.shutdown()
|
|
||||||
Log.d(TAG, "ScaleWebSocketClient 已关闭")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,243 +0,0 @@
|
|||||||
package com.shuwei.dish.match.scale
|
|
||||||
|
|
||||||
import android.content.Context
|
|
||||||
import android.util.Log
|
|
||||||
import com.google.gson.Gson
|
|
||||||
import com.shuwei.dish.match.utils.NetworkUtil
|
|
||||||
import com.shuwei.dish.match.utils.WeightUtil
|
|
||||||
import org.java_websocket.WebSocket
|
|
||||||
import org.java_websocket.handshake.ClientHandshake
|
|
||||||
import org.java_websocket.server.WebSocketServer
|
|
||||||
import java.net.InetSocketAddress
|
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
|
||||||
import java.util.concurrent.Executors
|
|
||||||
import java.util.concurrent.ScheduledFuture
|
|
||||||
import java.util.concurrent.TimeUnit
|
|
||||||
import java.util.concurrent.atomic.AtomicInteger
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 秤数据 WebSocket 服务端(主设备和子设备均运行)
|
|
||||||
* 监听 WeightUtil 回调,将本机秤数据实时推送给所有已连接的主设备客户端
|
|
||||||
*/
|
|
||||||
class ScaleWebSocketServer(private val deviceId: String, private val context: Context) {
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
private const val TAG = "ScaleWebSocketServer"
|
|
||||||
/** 节流间隔:两次推送之间的最小间隔(毫秒) */
|
|
||||||
private const val THROTTLE_MS = 100L
|
|
||||||
/** latestData 为空时延迟补推的时间(毫秒),给 WeightUtil 时间产生第一次读数 */
|
|
||||||
private const val RETRY_PUSH_DELAY_MS = 3_000L
|
|
||||||
}
|
|
||||||
|
|
||||||
private val gson = Gson()
|
|
||||||
private var server: InternalServer? = null
|
|
||||||
/** 延迟补推任务的调度器 */
|
|
||||||
private val scheduler = Executors.newSingleThreadScheduledExecutor()
|
|
||||||
|
|
||||||
/** 主设备连接状态变化回调:true=已连接,false=已断开;在主线程外调用,需自行切换线程 */
|
|
||||||
var onConnectionChanged: ((connected: Boolean) -> Unit)? = null
|
|
||||||
|
|
||||||
/** 收到主设备下发的调料配置同步事件时的回调,在子线程调用 */
|
|
||||||
var onSeasoningConfig: ((event: ScaleEvent) -> Unit)? = null
|
|
||||||
|
|
||||||
/** 收到主设备下发的清除数据事件时的回调,在子线程调用 */
|
|
||||||
var onClearData: ((event: ScaleEvent) -> Unit)? = null
|
|
||||||
|
|
||||||
/** 当前是否有主设备连接 */
|
|
||||||
val isConnected: Boolean
|
|
||||||
get() = server?.connections?.isNotEmpty() == true
|
|
||||||
|
|
||||||
/** 每个秤地址的最近一次推送时间,用于节流 */
|
|
||||||
private val lastPushTime = ConcurrentHashMap<Int, Long>()
|
|
||||||
|
|
||||||
/** 缓存各秤最新数据,新客户端连接时立即同步当前状态 */
|
|
||||||
private val latestData = ConcurrentHashMap<Int, ScaleData>()
|
|
||||||
|
|
||||||
/** 节流窗口内的延迟推送任务,key=address;保证窗口结束时最新数据被推送 */
|
|
||||||
private val pendingPushTasks = ConcurrentHashMap<Int, ScheduledFuture<*>>()
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 启动 WebSocket 服务器,并注册 WeightUtil 回调
|
|
||||||
*/
|
|
||||||
fun start() {
|
|
||||||
server = InternalServer(MdnsRegisterManager.WS_PORT)
|
|
||||||
server?.isReuseAddr = true
|
|
||||||
server?.start()
|
|
||||||
Log.d(TAG, "WebSocket 服务端已启动,端口 ${MdnsRegisterManager.WS_PORT}")
|
|
||||||
|
|
||||||
// 注册本机秤数据监听
|
|
||||||
WeightUtil.addWeightListener(TAG) { address, state, weight ->
|
|
||||||
Log.d(TAG, "WebSocket 设备${deviceId}推送数据, address=$address, state=$state, weight=$weight")
|
|
||||||
val now = System.currentTimeMillis()
|
|
||||||
// 数据未变化时直接跳过,避免无效推送
|
|
||||||
val last = latestData[address]
|
|
||||||
if (last?.weight == weight && last.state == state) return@addWeightListener
|
|
||||||
|
|
||||||
val data = ScaleData(
|
|
||||||
deviceId = deviceId,
|
|
||||||
address = address,
|
|
||||||
weight = weight,
|
|
||||||
state = state,
|
|
||||||
ts = now,
|
|
||||||
ip = NetworkUtil.getLocalIpAddress(context)
|
|
||||||
)
|
|
||||||
// 始终更新 latestData,保证最新一帧不丢失
|
|
||||||
latestData[address] = data
|
|
||||||
|
|
||||||
val lastPush = lastPushTime[address] ?: 0L
|
|
||||||
if (now - lastPush >= THROTTLE_MS) {
|
|
||||||
// 窗口已过:立即推送,并取消可能存在的延迟任务
|
|
||||||
lastPushTime[address] = now
|
|
||||||
pendingPushTasks.remove(address)?.cancel(false)
|
|
||||||
broadcast(gson.toJson(data))
|
|
||||||
} else if (pendingPushTasks[address] == null) {
|
|
||||||
// 窗口内首次触发:安排 trailing 推送,保证窗口末尾推最新值
|
|
||||||
val delay = THROTTLE_MS - (now - lastPush)
|
|
||||||
if (!scheduler.isShutdown) {
|
|
||||||
pendingPushTasks[address] = scheduler.schedule({
|
|
||||||
val latest = latestData[address] ?: return@schedule
|
|
||||||
lastPushTime[address] = System.currentTimeMillis()
|
|
||||||
pendingPushTasks.remove(address)
|
|
||||||
broadcast(gson.toJson(latest))
|
|
||||||
}, delay, TimeUnit.MILLISECONDS)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// 窗口内且已安排过 trailing 任务:仅更新 latestData,等 trailing 触发时推送
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 停止 WebSocket 服务器,移除秤监听
|
|
||||||
*/
|
|
||||||
fun stop() {
|
|
||||||
WeightUtil.removeWeightListener(TAG)
|
|
||||||
onConnectionChanged = null
|
|
||||||
onSeasoningConfig = null
|
|
||||||
onClearData = null
|
|
||||||
scheduler.shutdownNow()
|
|
||||||
try {
|
|
||||||
server?.stop(1000)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.e(TAG, "停止服务端异常: ${e.message}")
|
|
||||||
}
|
|
||||||
server = null
|
|
||||||
latestData.clear()
|
|
||||||
lastPushTime.clear()
|
|
||||||
pendingPushTasks.values.forEach { it.cancel(false) }
|
|
||||||
pendingPushTasks.clear()
|
|
||||||
Log.d(TAG, "WebSocket 服务端已停止")
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 向所有已连接的主设备广播秤事件(如调料添加通知)
|
|
||||||
* @param event 要广播的事件
|
|
||||||
*/
|
|
||||||
fun broadcastEvent(event: ScaleEvent) {
|
|
||||||
broadcast(gson.toJson(event))
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 向所有已连接客户端广播消息
|
|
||||||
*/
|
|
||||||
private fun broadcast(json: String) {
|
|
||||||
server?.connections?.forEach { conn ->
|
|
||||||
if (conn.isOpen) {
|
|
||||||
try {
|
|
||||||
conn.send(json)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w(TAG, "推送失败: ${e.message}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 内部 WebSocket 服务器实现
|
|
||||||
*/
|
|
||||||
private inner class InternalServer(port: Int) :
|
|
||||||
WebSocketServer(InetSocketAddress(port)) {
|
|
||||||
|
|
||||||
/** 当前活跃连接计数,用于替代 connections.isNullOrEmpty() 避免竞态 */
|
|
||||||
private val connectionCount = AtomicInteger(0)
|
|
||||||
|
|
||||||
override fun onOpen(conn: WebSocket, handshake: ClientHandshake) {
|
|
||||||
connectionCount.incrementAndGet()
|
|
||||||
Log.d(TAG, "主设备已连接: ${conn.remoteSocketAddress}")
|
|
||||||
onConnectionChanged?.invoke(true)
|
|
||||||
|
|
||||||
// 新客户端连接后,立即推送所有秤的最新数据
|
|
||||||
if (latestData.isNotEmpty()) {
|
|
||||||
latestData.values.forEach { data ->
|
|
||||||
try {
|
|
||||||
conn.send(gson.toJson(data))
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w(TAG, "初始推送失败: ${e.message}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// latestData 为空说明刚重启,WeightUtil 还未产生读数
|
|
||||||
// 延迟 3 秒后补推一次,确保主设备能看到本机秤
|
|
||||||
Log.d(TAG, "latestData 为空,${RETRY_PUSH_DELAY_MS}ms 后补推")
|
|
||||||
scheduler.schedule({
|
|
||||||
if (conn.isOpen && latestData.isNotEmpty()) {
|
|
||||||
latestData.values.forEach { data ->
|
|
||||||
try {
|
|
||||||
conn.send(gson.toJson(data))
|
|
||||||
Log.d(TAG, "补推数据: address=${data.address}, weight=${data.weight}")
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w(TAG, "补推失败: ${e.message}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, RETRY_PUSH_DELAY_MS, TimeUnit.MILLISECONDS)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onClose(conn: WebSocket, code: Int, reason: String, remote: Boolean) {
|
|
||||||
Log.d(TAG, "主设备已断开: ${conn.remoteSocketAddress}, reason=$reason")
|
|
||||||
// 用计数器判断是否还有活跃连接,避免依赖 connections 集合的移除时机导致竞态
|
|
||||||
if (connectionCount.decrementAndGet() <= 0) {
|
|
||||||
connectionCount.set(0)
|
|
||||||
onConnectionChanged?.invoke(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onMessage(conn: WebSocket, message: String) {
|
|
||||||
try {
|
|
||||||
val raw = gson.fromJson(message, Map::class.java)
|
|
||||||
if (raw.containsKey("type")) {
|
|
||||||
// 主设备下发的事件(如调料配置同步)
|
|
||||||
val event = gson.fromJson(message, ScaleEvent::class.java)
|
|
||||||
when (event.type) {
|
|
||||||
ScaleEvent.TYPE_SEASONING_CONFIG -> onSeasoningConfig?.invoke(event)
|
|
||||||
ScaleEvent.TYPE_CLEAR_DATA -> onClearData?.invoke(event)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
val cmd = gson.fromJson(message, ScaleCommand::class.java)
|
|
||||||
// 校验指令目标设备是否为本机
|
|
||||||
if (cmd.deviceId != deviceId) {
|
|
||||||
Log.d(TAG, "收到清零指令, 但设备号不正确, deviceId=${cmd.deviceId}")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
when (cmd.cmd) {
|
|
||||||
ScaleCommand.CMD_TARE -> {
|
|
||||||
Log.d(TAG, "收到清零指令, address=${cmd.address}")
|
|
||||||
WeightUtil.tareTwo(cmd.address)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w(TAG, "收到消息, 解析失败: ${e.message}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onError(conn: WebSocket?, ex: Exception) {
|
|
||||||
Log.e(TAG, "WebSocket 服务端错误: ${ex.message}")
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onStart() {
|
|
||||||
Log.d(TAG, "WebSocket 服务端 onStart")
|
|
||||||
connectionLostTimeout = 60
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,95 +0,0 @@
|
|||||||
package com.shuwei.dish.match.scale
|
|
||||||
|
|
||||||
import android.util.Log
|
|
||||||
import com.google.gson.Gson
|
|
||||||
import java.net.DatagramPacket
|
|
||||||
import java.net.DatagramSocket
|
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
|
||||||
import java.util.concurrent.Executors
|
|
||||||
|
|
||||||
/**
|
|
||||||
* UDP 广播接收器(主设备运行)
|
|
||||||
* 监听子设备发来的 UDP 广播包,解析后通过回调通知连接管理器
|
|
||||||
* 与 mDNS 互为备份,任意一条路发现子设备均可建立 WebSocket 连接
|
|
||||||
*/
|
|
||||||
class UdpBroadcastReceiver {
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
private const val TAG = "UdpBroadcastReceiver"
|
|
||||||
private const val BUFFER_SIZE = 1024
|
|
||||||
}
|
|
||||||
|
|
||||||
private val gson = Gson()
|
|
||||||
private val executor = Executors.newSingleThreadExecutor()
|
|
||||||
|
|
||||||
/** 已发现的设备集合,避免重复触发回调,key=deviceId, value="host:port" */
|
|
||||||
private val knownDevices = ConcurrentHashMap<String, String>()
|
|
||||||
|
|
||||||
@Volatile
|
|
||||||
private var running = false
|
|
||||||
private var socket: DatagramSocket? = null
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 发现新设备时的回调:(deviceId, host, port)
|
|
||||||
* 与 MdnsDiscoveryManager.onDeviceFound 签名一致,可共用同一处理逻辑
|
|
||||||
*/
|
|
||||||
var onDeviceFound: ((deviceId: String, host: String, port: Int) -> Unit)? = null
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 开始监听 UDP 广播
|
|
||||||
*/
|
|
||||||
fun start() {
|
|
||||||
if (running) return
|
|
||||||
running = true
|
|
||||||
executor.execute { listenLoop() }
|
|
||||||
Log.d(TAG, "UDP 广播接收已启动, 监听端口=${UdpBroadcastSender.BROADCAST_PORT}")
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun listenLoop() {
|
|
||||||
try {
|
|
||||||
socket = DatagramSocket(UdpBroadcastSender.BROADCAST_PORT).also { it.broadcast = true }
|
|
||||||
val buf = ByteArray(BUFFER_SIZE)
|
|
||||||
while (running) {
|
|
||||||
val packet = DatagramPacket(buf, buf.size)
|
|
||||||
socket?.receive(packet) ?: break
|
|
||||||
val json = String(packet.data, 0, packet.length, Charsets.UTF_8)
|
|
||||||
handlePacket(json)
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
if (running) Log.w(TAG, "UDP 接收异常: ${e.message}")
|
|
||||||
} finally {
|
|
||||||
socket?.close()
|
|
||||||
socket = null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun handlePacket(json: String) {
|
|
||||||
try {
|
|
||||||
val payload = gson.fromJson(json, UdpBroadcastSender.Payload::class.java)
|
|
||||||
val key = "${payload.ip}:${payload.port}"
|
|
||||||
// 同一设备已通知过则跳过,避免每5秒重复触发连接
|
|
||||||
if (knownDevices.put(payload.deviceId, key) == key) return
|
|
||||||
Log.d(TAG, "UDP 发现设备: ${payload.deviceId} -> ${payload.ip}:${payload.port}")
|
|
||||||
onDeviceFound?.invoke(payload.deviceId, payload.ip, payload.port)
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w(TAG, "解析 UDP 广播包失败: ${e.message}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 移除已知设备记录,设备离线时调用,确保设备重新上线后能再次触发回调
|
|
||||||
*/
|
|
||||||
fun removeDevice(deviceId: String) {
|
|
||||||
knownDevices.remove(deviceId)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 停止监听,释放资源
|
|
||||||
*/
|
|
||||||
fun stop() {
|
|
||||||
running = false
|
|
||||||
socket?.close()
|
|
||||||
executor.shutdownNow()
|
|
||||||
Log.d(TAG, "UDP 广播接收已停止")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
package com.shuwei.dish.match.scale
|
|
||||||
|
|
||||||
import android.util.Log
|
|
||||||
import com.google.gson.Gson
|
|
||||||
import java.net.DatagramPacket
|
|
||||||
import java.net.DatagramSocket
|
|
||||||
import java.net.InetAddress
|
|
||||||
import java.util.concurrent.Executors
|
|
||||||
import java.util.concurrent.ScheduledFuture
|
|
||||||
import java.util.concurrent.TimeUnit
|
|
||||||
|
|
||||||
/**
|
|
||||||
* UDP 广播发送器(子设备运行)
|
|
||||||
* 每隔固定间隔向局域网广播本机的 deviceId、IP、WebSocket 端口
|
|
||||||
* 作为 mDNS 的兜底发现机制,确保主设备能可靠发现子设备
|
|
||||||
*
|
|
||||||
* @param ipProvider 动态获取本机 IP 的函数,每次广播时调用;返回空字符串时跳过本次广播
|
|
||||||
*/
|
|
||||||
class UdpBroadcastSender(
|
|
||||||
private val deviceId: String,
|
|
||||||
private val ipProvider: () -> String,
|
|
||||||
private val wsPort: Int = MdnsRegisterManager.WS_PORT
|
|
||||||
) {
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
private const val TAG = "UdpBroadcastSender"
|
|
||||||
/** UDP 广播目标端口,与 UdpBroadcastReceiver 保持一致 */
|
|
||||||
const val BROADCAST_PORT = 8766
|
|
||||||
/** 广播间隔(秒) */
|
|
||||||
private const val INTERVAL_SEC = 5L
|
|
||||||
}
|
|
||||||
|
|
||||||
private val gson = Gson()
|
|
||||||
private val scheduler = Executors.newSingleThreadScheduledExecutor()
|
|
||||||
private var task: ScheduledFuture<*>? = null
|
|
||||||
|
|
||||||
/** 广播数据包结构 */
|
|
||||||
data class Payload(val deviceId: String, val ip: String, val port: Int)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 开始定时广播
|
|
||||||
*/
|
|
||||||
fun start() {
|
|
||||||
if (task != null) return
|
|
||||||
task = scheduler.scheduleWithFixedDelay({
|
|
||||||
sendBroadcast()
|
|
||||||
}, 0, INTERVAL_SEC, TimeUnit.SECONDS)
|
|
||||||
Log.d(TAG, "UDP 广播已启动, deviceId=$deviceId, port=$wsPort")
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun sendBroadcast() {
|
|
||||||
try {
|
|
||||||
val ip = ipProvider()
|
|
||||||
// 网络未就绪时跳过本次广播,等待下一个周期重试
|
|
||||||
if (ip.isEmpty()) {
|
|
||||||
Log.d(TAG, "IP 未就绪,跳过本次广播")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
val payload = gson.toJson(Payload(deviceId, ip, wsPort))
|
|
||||||
val data = payload.toByteArray(Charsets.UTF_8)
|
|
||||||
DatagramSocket().use { socket ->
|
|
||||||
socket.broadcast = true
|
|
||||||
val packet = DatagramPacket(
|
|
||||||
data, data.size,
|
|
||||||
InetAddress.getByName("255.255.255.255"),
|
|
||||||
BROADCAST_PORT
|
|
||||||
)
|
|
||||||
socket.send(packet)
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.w(TAG, "UDP 广播发送失败: ${e.message}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 停止广播,释放资源
|
|
||||||
*/
|
|
||||||
fun stop() {
|
|
||||||
task?.cancel(false)
|
|
||||||
task = null
|
|
||||||
scheduler.shutdownNow()
|
|
||||||
Log.d(TAG, "UDP 广播已停止")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,716 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user