Compare commits
164
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7b66652c0b | ||
|
|
9e4b2bd009 | ||
|
|
6d3c5490a4 | ||
|
|
45543295e3 | ||
|
|
049c724303 | ||
|
|
acd1dd4605 | ||
|
|
17470bf12c | ||
|
|
0a3185fc9e | ||
|
|
9e41841086 | ||
|
|
80d80e7e63 | ||
|
|
2d88ce1479 | ||
|
|
d580040c55 | ||
|
|
00bf478185 | ||
|
|
ea79e584f3 | ||
|
|
1140d6bf91 | ||
|
|
f3dbb3fe68 | ||
|
|
dc91cdfa2e | ||
|
|
a6ce3a1ed3 | ||
|
|
292fdade81 | ||
|
|
aa539d87d0 | ||
|
|
e570707216 | ||
|
|
87ca6abe1b | ||
|
|
28784fa7c1 | ||
|
|
df01312577 | ||
|
|
7d3cb27b6e | ||
|
|
ef6a29ffb0 | ||
|
|
d7f9fb05fb | ||
|
|
d9cfd3007d | ||
|
|
c1f52c6337 | ||
|
|
5723209614 | ||
|
|
d080ca0690 | ||
|
|
1024d82958 | ||
|
|
8b19da2710 | ||
|
|
25167829cc | ||
|
|
e38f19ac1b | ||
|
|
ada83b64e6 | ||
|
|
d3f02620af | ||
|
|
deb03a0c37 | ||
|
|
b562694665 | ||
|
|
64586175ff | ||
|
|
e8431de53d | ||
|
|
4ccd4eaad0 | ||
|
|
b44f4aae5a | ||
|
|
fee9598689 | ||
|
|
b24435744c | ||
|
|
a257b03b9d | ||
|
|
89fff7c2b0 | ||
|
|
6392b76ac2 | ||
|
|
8398bd4fd3 | ||
|
|
535da33aab | ||
|
|
120f5432de | ||
|
|
61d11c6a78 | ||
|
|
301f470274 | ||
|
|
67d64848de | ||
|
|
ce7d2da6d8 | ||
|
|
65958bf637 | ||
|
|
7e72ce413b | ||
|
|
5745791041 | ||
|
|
d412e03c6e | ||
|
|
b6389be898 | ||
|
|
919e43afba | ||
|
|
0b9b3e8988 | ||
|
|
803ae75e40 | ||
|
|
ec4c3f1232 | ||
|
|
63911fe432 | ||
|
|
8f15c0efb7 | ||
|
|
879af8426f | ||
|
|
dc947df6e3 | ||
|
|
ef13aa8307 | ||
|
|
a9663a21f0 | ||
|
|
d060305417 | ||
|
|
bb319ee4ee | ||
|
|
bb1ecbde43 | ||
|
|
7a03ab8108 | ||
|
|
3b1dc0a03f | ||
|
|
f4d383dfe1 | ||
|
|
a14072af00 | ||
|
|
436de88d73 | ||
|
|
a0137d6979 | ||
|
|
c46264a4cf | ||
|
|
979b93c53d | ||
|
|
9880f2a5a8 | ||
|
|
19b5d721a7 | ||
|
|
0648f458a7 | ||
|
|
c17402c3c2 | ||
|
|
a64a00e099 | ||
|
|
6595c4bde0 | ||
|
|
2de5ec39b5 | ||
|
|
e5fc0c265d | ||
|
|
05063ee9de | ||
|
|
af737b910c | ||
|
|
12c6b5cf94 | ||
|
|
e990652981 | ||
|
|
9cfc481cf3 | ||
|
|
5e46c21469 | ||
|
|
858cc24046 | ||
|
|
dc55d3fde5 | ||
|
|
3842391555 | ||
|
|
d1569faa85 | ||
|
|
a958262dff | ||
|
|
fb691c508d | ||
|
|
8113c1d830 | ||
|
|
db839fd596 | ||
|
|
c2fd14cb6f | ||
|
|
95895e6390 | ||
|
|
9a0b066490 | ||
|
|
e8933fa578 | ||
|
|
425f485b95 | ||
|
|
264198463c | ||
|
|
89fa681722 | ||
|
|
7a75e943db | ||
|
|
634f23a76a | ||
|
|
b110cc97a0 | ||
|
|
fda88fff33 | ||
|
|
c4fbf9dcd6 | ||
|
|
a2f8fb903a | ||
|
|
13fc7c7e0f | ||
|
|
fed161b088 | ||
|
|
594c551a98 | ||
|
|
617ccfb456 | ||
|
|
f3d57177b8 | ||
|
|
267628411a | ||
|
|
58fb78c7bd | ||
|
|
9f0671410f | ||
|
|
0243fe0dc8 | ||
|
|
df0580d68f | ||
|
|
deab289747 | ||
|
|
debc7a0740 | ||
|
|
441cffe4da | ||
|
|
3581975ab0 | ||
|
|
9e99e6ef6d | ||
|
|
16fe64e9fe | ||
|
|
75830b9204 | ||
|
|
0498501b33 | ||
|
|
8c709a3f5f | ||
|
|
9ba6443f4f | ||
|
|
04e4efe1fc | ||
|
|
bce9675b0f | ||
|
|
f25108360b | ||
|
|
4ec02ac2bc | ||
|
|
97b357850c | ||
|
|
b6b5088107 | ||
|
|
bbdebc0c9c | ||
|
|
0a90a8b368 | ||
|
|
07eb626e12 | ||
|
|
736e4820dd | ||
|
|
3fc54d5f52 | ||
|
|
b16d7d19cd | ||
|
|
a81e914b63 | ||
|
|
ffdf364ee8 | ||
|
|
6d3bb96d61 | ||
|
|
da712ed25a | ||
|
|
6b312ec689 | ||
|
|
e175893790 | ||
|
|
82217b4fb1 | ||
|
|
72ecc8fcd6 | ||
|
|
99d670390a | ||
|
|
d3b69c4e46 | ||
|
|
193acff1e0 | ||
|
|
87bf11454c | ||
|
|
768bde79a1 | ||
|
|
c61b1c8ef7 | ||
|
|
77df4a4d82 | ||
|
|
c35572dc41 |
@@ -0,0 +1,356 @@
|
||||
# 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.
|
||||
```
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
plugins {
|
||||
// alias(libs.plugins.android.application)
|
||||
// alias(libs.plugins.kotlin.android)
|
||||
@@ -24,9 +23,8 @@ android {
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
ndk {
|
||||
//设置支持的SO库架构
|
||||
//设置支持的SO库架构;x86_64 仅用于在 Windows 模拟器上调试(秤功能不可用)
|
||||
abiFilters.addAll(listOf("armeabi-v7a"))
|
||||
//, 'x86', 'armeabi-v7a', 'x86_64', 'arm64-v8a'
|
||||
}
|
||||
|
||||
// 设置输出APK文件名格式
|
||||
@@ -48,12 +46,13 @@ android {
|
||||
"proguard-rules.pro"
|
||||
)
|
||||
signingConfig = signingConfigs.getByName("debug_507")
|
||||
// buildConfigField("boolean", "DEBUG", "false")
|
||||
buildConfigField("Boolean", "IS_TEST_DEVICE", "false")
|
||||
}
|
||||
debug {
|
||||
//507扫码秤主板在android.buildTypes{}内增加
|
||||
signingConfig = signingConfigs.getByName("debug_507")
|
||||
// buildConfigField("boolean", "DEBUG", "true")
|
||||
// 调试构建视为测试设备,使用固定的 DEVICE_ID_1 代替真实 UDID
|
||||
buildConfigField("Boolean", "IS_TEST_DEVICE", "false")
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
@@ -98,6 +97,7 @@ dependencies {
|
||||
androidTestImplementation(libs.androidx.junit)
|
||||
androidTestImplementation(libs.androidx.espresso.core)
|
||||
implementation(libs.androidx.activity.ktx)
|
||||
implementation(libs.androidx.fragment.ktx)
|
||||
implementation(libs.androidx.lifecycle.runtime.ktx)
|
||||
implementation(libs.androidx.lifecycle.viewmodel.ktx)
|
||||
|
||||
@@ -138,8 +138,8 @@ dependencies {
|
||||
implementation(libs.androidx.camera.extensions)
|
||||
|
||||
//pytorch
|
||||
implementation (libs.pytorch.android)
|
||||
implementation (libs.pytorch.android.torchvision)
|
||||
implementation(libs.pytorch.android)
|
||||
implementation(libs.pytorch.android.torchvision)
|
||||
|
||||
// objectbox
|
||||
if (isDebug) {
|
||||
|
||||
Binary file not shown.
@@ -5,7 +5,7 @@
|
||||
"entities": [
|
||||
{
|
||||
"id": "1:6465153867413579585",
|
||||
"lastPropertyId": "4:3660727688686055762",
|
||||
"lastPropertyId": "5:7592685238899911344",
|
||||
"name": "Food",
|
||||
"properties": [
|
||||
{
|
||||
@@ -30,6 +30,11 @@
|
||||
"indexId": "1:5497952887792054610",
|
||||
"type": 28,
|
||||
"flags": 8
|
||||
},
|
||||
{
|
||||
"id": "5:7592685238899911344",
|
||||
"name": "version",
|
||||
"type": 9
|
||||
}
|
||||
],
|
||||
"relations": []
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -45,6 +45,8 @@
|
||||
<activity
|
||||
android:name=".ui.InitActivity"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTask"
|
||||
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboardHidden|keyboard|navigation|uiMode|locale|layoutDirection|fontScale|density"
|
||||
tools:ignore="DiscouragedApi,LockedOrientationActivity">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
@@ -58,23 +60,23 @@
|
||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||
|
||||
<activity
|
||||
android:name=".ui.SelectDishActivity"
|
||||
android:name=".ui.CookingModeActivity"
|
||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||
android:launchMode="singleTask"
|
||||
android:screenOrientation="portrait"
|
||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||
<activity
|
||||
android:name=".ui.PrepareCookActivity"
|
||||
android:name=".ui.PrepareFoodActivity"
|
||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||
android:screenOrientation="portrait"
|
||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||
<!-- <activity-->
|
||||
<!-- android:name=".ui.DishSamplingActivity"-->
|
||||
<!-- android:theme="@style/Theme.DishMatch.NoSplash"-->
|
||||
<!-- android:screenOrientation="portrait"-->
|
||||
<!-- tools:ignore="DiscouragedApi,LockedOrientationActivity" />-->
|
||||
<activity
|
||||
android:name=".ui.DishSamplingActivity"
|
||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||
android:screenOrientation="portrait"
|
||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||
<activity
|
||||
android:name=".ui.SamplingListActivity"
|
||||
android:name=".ui.SamplingModeActivity"
|
||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||
android:launchMode="singleTask"
|
||||
android:screenOrientation="portrait"
|
||||
@@ -93,8 +95,8 @@
|
||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||
android:screenOrientation="portrait"
|
||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||
<activity android:name="com.shuwei.dish.match.ui.DeviceConfigActivity"
|
||||
android:theme="@style/Theme.DishMatch.NoSplash" />
|
||||
<!-- <activity android:name="com.shuwei.dish.match.ui.DeviceConfigActivity"-->
|
||||
<!-- android:theme="@style/Theme.DishMatch.NoSplash" />-->
|
||||
<activity android:name="com.shuwei.dish.match.ui.SettingActivity"
|
||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||
android:screenOrientation="portrait"
|
||||
@@ -107,12 +109,16 @@
|
||||
android:screenOrientation="portrait"
|
||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||
<activity
|
||||
android:name="com.shuwei.dish.match.ui.Scale22GridActivity"
|
||||
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.FoodRecognizeActivity"
|
||||
android:name="com.shuwei.dish.match.ui.CollectedFoodActivity"
|
||||
android:theme="@style/Theme.DishMatch.NoSplash"
|
||||
android:screenOrientation="portrait"
|
||||
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.shuwei.dish.match.adapter
|
||||
|
||||
import android.content.Context
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.databinding.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}"
|
||||
}
|
||||
}
|
||||
@@ -1,57 +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.ListItemDishCookBinding
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.utils.ext.roundedOneDecimalPlace
|
||||
import java.text.DecimalFormat
|
||||
|
||||
class DishPartAdapter(list: MutableList<CookFoodGoodsEntity>) :
|
||||
BaseQuickAdapter<CookFoodGoodsEntity, 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: CookFoodGoodsEntity?) {
|
||||
holder.binding.run {
|
||||
tvDishName.text = item!!.goodsName
|
||||
tvDishType.text = if (item.materialType == 1) "主辅材:主材" else if (item.materialType == 2) "主辅材:辅材" else ""
|
||||
//"${DecimalFormat("#").format(item.useWeight)}克"
|
||||
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.run {
|
||||
setBackgroundResource(
|
||||
if (item.isItemClicked) R.drawable.shape_item_cook_dish
|
||||
else R.drawable.shape_white_fb_15_corners
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,62 +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.entity.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")
|
||||
|
||||
}
|
||||
+9
-6
@@ -5,13 +5,16 @@ import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.databinding.ListItemDishRecordBinding
|
||||
import com.shuwei.dish.match.entity.FoodRecord
|
||||
import com.shuwei.dish.match.databinding.ListItemFood2Binding
|
||||
import com.shuwei.dish.match.model.FoodRecord
|
||||
|
||||
class FoodRecordAdapter(list: MutableList<FoodRecord>) :
|
||||
BaseQuickAdapter<FoodRecord, FoodRecordAdapter.VH>(list) {
|
||||
/**
|
||||
* 菜品搜索页面的适配器
|
||||
*/
|
||||
class Food2Adapter(list: MutableList<FoodRecord>) :
|
||||
BaseQuickAdapter<FoodRecord, Food2Adapter.VH>(list) {
|
||||
|
||||
inner class VH(var binding: ListItemDishRecordBinding) : QuickViewHolder(binding.root)
|
||||
inner class VH(var binding: ListItemFood2Binding) : QuickViewHolder(binding.root)
|
||||
|
||||
override fun onBindViewHolder(
|
||||
holder: VH,
|
||||
@@ -27,7 +30,7 @@ class FoodRecordAdapter(list: MutableList<FoodRecord>) :
|
||||
viewType: Int
|
||||
): VH {
|
||||
val inflater = LayoutInflater.from(context)
|
||||
val binding = ListItemDishRecordBinding.inflate(inflater, parent, false)
|
||||
val binding = ListItemFood2Binding.inflate(inflater, parent, false)
|
||||
return VH(binding)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.shuwei.dish.match.adapter
|
||||
|
||||
import android.content.Context
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.databinding.ListItemFood3Binding
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
|
||||
/**
|
||||
* 向量采集页面的适配器
|
||||
*/
|
||||
class Food3Adapter(list: MutableList<GoodsItem>) :
|
||||
BaseQuickAdapter<GoodsItem, Food3Adapter.VH>(list) {
|
||||
|
||||
override fun onBindViewHolder(
|
||||
holder: VH,
|
||||
position: Int,
|
||||
item: GoodsItem?
|
||||
) {
|
||||
item ?: return
|
||||
holder.binding.tvFoodName.run {
|
||||
text = item.goodsName
|
||||
isChecked = item.isClicked
|
||||
}
|
||||
// 显示当前选中的净材种类,无数据时隐藏
|
||||
holder.binding.tvRawMaterialsType.run {
|
||||
if (item.rawMaterialsType.isNullOrEmpty()) {
|
||||
visibility = View.GONE
|
||||
} else {
|
||||
visibility = View.VISIBLE
|
||||
text = item.rawMaterialsType
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreateViewHolder(
|
||||
context: Context,
|
||||
parent: ViewGroup,
|
||||
viewType: Int
|
||||
): VH {
|
||||
val binding = ListItemFood3Binding.inflate(LayoutInflater.from(context), parent, false)
|
||||
return VH(binding)
|
||||
}
|
||||
|
||||
inner class VH(var binding: ListItemFood3Binding) : QuickViewHolder(binding.root)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
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)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
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.model.SampleStatus
|
||||
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)
|
||||
// 已提交采样列表(sample-list):展示实验状态 + 熟重(g)
|
||||
val statusName = item.statusName
|
||||
if (!statusName.isNullOrBlank()) {
|
||||
tvDishCount.text = "熟重:${formatGram(foodWeight)}"
|
||||
tvShowState.text = statusName
|
||||
tvShowState.setTextColor(statusColor(holder, item.status))
|
||||
return@run
|
||||
}
|
||||
val realTotalWeight = if (totalWeight > 0.0) totalWeight else foodWeight
|
||||
val showTotalWeight = if (realTotalWeight == 0.0) "-" else df.format(realTotalWeight / 1000.0F)
|
||||
tvDishCount.text = "累计统计:${showTotalWeight}kg(${item.count ?: "-"}次)"
|
||||
val showFoodWeight = if (foodWeight == 0.0) "-" else df.format(foodWeight / 1000.0F)
|
||||
tvShowState.text = "${showFoodWeight}kg"
|
||||
}
|
||||
}
|
||||
|
||||
/** 熟重(g)格式化,整数不带小数,小数保留 2 位 */
|
||||
private fun formatGram(weight: Double): String {
|
||||
val gramDf = DecimalFormat("0.##")
|
||||
return "${gramDf.format(weight)}g"
|
||||
}
|
||||
|
||||
/** 实验状态着色:1=实验中(灰) / 2=已评测(绿) / 9=已转化(绿) */
|
||||
private fun statusColor(holder: VH, status: Int?): Int {
|
||||
val context = holder.itemView.context
|
||||
return when (status) {
|
||||
SampleStatus.EVALUATED, SampleStatus.CONVERTED ->
|
||||
ContextCompat.getColor(context, R.color.dish_green)
|
||||
else -> ContextCompat.getColor(context, R.color.black999)
|
||||
}
|
||||
}
|
||||
|
||||
private val df = DecimalFormat("0.000")
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
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
|
||||
|
||||
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}"
|
||||
//}
|
||||
tvDishType.text = if (data.materialType == 1) "主辅材:主材" else if (data.materialType == 2) "主辅材:辅材" else ""
|
||||
tvDishWeight.text =
|
||||
if (data.useWeight == null || data.useWeight == 0.toDouble()) "" else "${data.useWeight!!.roundedOneDecimalPlace()}克"
|
||||
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
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,50 +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.ListItemSearchGoodsInfoBinding
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
|
||||
class GoodsInfoSearchAdapter(private var list: MutableList<CookFoodGoodsEntity>) :
|
||||
BaseQuickAdapter<CookFoodGoodsEntity, GoodsInfoSearchAdapter.VH>(list) {
|
||||
|
||||
override fun onBindViewHolder(
|
||||
holder: VH,
|
||||
position: Int,
|
||||
item: CookFoodGoodsEntity?
|
||||
) {
|
||||
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)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.shuwei.dish.match.adapter
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.shuwei.dish.match.databinding.ItemGoodsPreviewBinding
|
||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||
|
||||
/**
|
||||
* 用料明细预览列表适配器
|
||||
* 显示字段:foodId、goodsId、goodsCode、goodsName、materialType、useWeight
|
||||
*/
|
||||
class GoodsPreviewAdapter(
|
||||
private val list: List<CookFoodGoodsEntity>
|
||||
) : RecyclerView.Adapter<GoodsPreviewAdapter.VH>() {
|
||||
|
||||
inner class VH(val binding: ItemGoodsPreviewBinding) : RecyclerView.ViewHolder(binding.root)
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
|
||||
val binding = ItemGoodsPreviewBinding.inflate(
|
||||
LayoutInflater.from(parent.context), parent, false
|
||||
)
|
||||
return VH(binding)
|
||||
}
|
||||
|
||||
@SuppressLint("SetTextI18n")
|
||||
override fun onBindViewHolder(holder: VH, position: Int) {
|
||||
val item = list[position]
|
||||
holder.binding.run {
|
||||
tvGoodsId.text = item.goodsId
|
||||
tvGoodsCode.text = item.goodsCode.orEmpty()
|
||||
tvGoodsName.text = item.goodsName.orEmpty()
|
||||
// materialType:1主料 2辅料 3调料
|
||||
tvMaterialType.text = when (item.materialType) {
|
||||
1 -> "主料"
|
||||
2 -> "辅料"
|
||||
3 -> "调料"
|
||||
else -> "${item.materialType}"
|
||||
}
|
||||
tvUseWeight.text = "${item.useWeight ?: 0.0}g"
|
||||
}
|
||||
}
|
||||
|
||||
override fun getItemCount() = list.size
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.databinding.ListItemHomeModeBinding
|
||||
import com.shuwei.dish.match.entity.HomeModeBean
|
||||
import com.shuwei.dish.match.model.HomeModeBean
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
|
||||
|
||||
@@ -1,58 +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.entity.FoodRecord
|
||||
import com.shuwei.dish.match.databinding.ListItemDishBinding
|
||||
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?:"").ifBlank { "--" }
|
||||
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 realTotalWeight = if (totalWeight > 0.toDouble()) totalWeight else (item.foodWeight
|
||||
?: 0.toDouble())
|
||||
val showTotalWeight =
|
||||
if (realTotalWeight == 0.toDouble()) "-" else df.format(realTotalWeight / 1000.0F)
|
||||
tvDishCount.text = "累计统计:${showTotalWeight}kg(${item.count ?: "-"}次)"
|
||||
val foodWeight = item.foodWeight ?: 0.toDouble()
|
||||
val showFoodWeight = if (foodWeight == 0.toDouble()) "-" else df.format(foodWeight / 1000.0F)
|
||||
tvShowState.text = "${showFoodWeight}kg"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val df = DecimalFormat("0.000")
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
package com.shuwei.dish.match.adapter
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
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
|
||||
* 使用 GridLayoutManager(6列)排列,第1行格子 margin 较大(视觉更小),第2-3行 margin 较小
|
||||
* 点击格子触发清零回调
|
||||
*/
|
||||
class Scale18GridAdapter : BaseQuickAdapter<ScaleData, Scale18GridAdapter.VH>(mutableListOf()) {
|
||||
|
||||
inner class VH(val b: ListItemScale22RowBinding) : QuickViewHolder(b.root)
|
||||
|
||||
/** 用 address=0 的哨兵表示空位 */
|
||||
private val empty = ScaleData("", 0, 0.0, -1, 0)
|
||||
|
||||
/** 点击回调,在 onCreateViewHolder 中绑定,不受 notifyItemChanged 影响 */
|
||||
var onItemClick: ((ScaleData) -> Unit)? = null
|
||||
|
||||
/**
|
||||
* 按 SCALE_ORDER_18 顺序更新数据,空位用哨兵填充
|
||||
* 只更新显示字段有变化的格子,避免全量刷新
|
||||
*/
|
||||
fun update(newList: List<ScaleData?>) {
|
||||
val filled = newList.map { it ?: empty }
|
||||
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) {
|
||||
set(i, scale)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 ScaleData 列表按 SCALE_ORDER_18 重排后调用 update
|
||||
*/
|
||||
fun updateByAddress(scales: List<ScaleData>) {
|
||||
val byAddress = scales.associateBy { it.address }
|
||||
update(ScaleDeviceConfig.SCALE_ORDER_18.map { byAddress[it] })
|
||||
}
|
||||
|
||||
/** 前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)
|
||||
// 第1行 margin=12dp(格子视觉更小),第2-3行 margin=2dp
|
||||
val margin = if (viewType == 0) 12.dp else 2.dp
|
||||
val screenWidth = parent.resources.displayMetrics.widthPixels
|
||||
val cellSize = (screenWidth - 6 * margin * 2 - 10.dp) / 6
|
||||
b.root.layoutParams = (b.root.layoutParams as ViewGroup.MarginLayoutParams).also {
|
||||
it.width = cellSize
|
||||
it.height = cellSize
|
||||
// 第1行:顶部间距为0,底部间距2dp,左右保持原有 margin
|
||||
if (viewType == 0) it.setMargins(margin, 0, margin, 2.dp)
|
||||
else it.setMargins(margin, margin, margin, margin)
|
||||
}
|
||||
val baseSp = (cellSize / parent.resources.displayMetrics.density).toInt()
|
||||
b.tvAddr.textSize = (baseSp * 0.16f).coerceIn(9f, 14f)
|
||||
b.tvWeight.textSize = (baseSp * 0.22f).coerceIn(12f, 20f)
|
||||
b.tvState.textSize = (baseSp * 0.14f).coerceIn(8f, 12f)
|
||||
val vh = VH(b)
|
||||
// 在 ViewHolder 创建时绑定点击,只执行一次,不受 notifyItemChanged 重绑定影响
|
||||
b.root.setOnClickListener {
|
||||
val pos = vh.bindingAdapterPosition
|
||||
if (pos != RecyclerView.NO_POSITION) {
|
||||
items.getOrNull(pos)?.takeIf { it.address != 0 }?.let { onItemClick?.invoke(it) }
|
||||
}
|
||||
}
|
||||
return vh
|
||||
}
|
||||
|
||||
@SuppressLint("SetTextI18n")
|
||||
override fun onBindViewHolder(holder: VH, position: Int, item: ScaleData?) {
|
||||
val valid = (item?.address ?: 0) != 0
|
||||
holder.b.tvAddr.text = if (valid) "秤${item!!.address}" else ""
|
||||
holder.b.tvWeight.text = if (valid) "${item!!.weight}g" else ""
|
||||
holder.b.tvState.text = if (valid) stateStr(item!!.state) else ""
|
||||
}
|
||||
|
||||
private fun stateStr(state: Int) = when (state) {
|
||||
WeightUtil.STATE_STABLE -> "稳定"
|
||||
WeightUtil.STATE_UNSTABLE -> "不稳定"
|
||||
WeightUtil.STATE_OVER_WEIGHT -> "超量"
|
||||
else -> "$state"
|
||||
}
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
package com.shuwei.dish.match.adapter
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
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.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
|
||||
|
||||
/**
|
||||
* 22个秤的网格 Adapter
|
||||
* 使用 FlexboxLayoutManager 按列排列,前4个格子较大(对应物理上的大秤),其余较小
|
||||
* 点击格子触发清零回调
|
||||
*
|
||||
* @param largeSize 前4个大格子的尺寸(px)
|
||||
* @param smallSize 其余小格子的尺寸(px)
|
||||
*/
|
||||
class Scale22GridAdapter(
|
||||
private val largeSize: Int,
|
||||
private val smallSize: Int
|
||||
) : BaseQuickAdapter<ScaleData, Scale22GridAdapter.VH>(mutableListOf()) {
|
||||
|
||||
inner class VH(val b: ListItemScale22RowBinding) : QuickViewHolder(b.root)
|
||||
|
||||
/** 用 address=0 的哨兵表示空位 */
|
||||
private val empty = ScaleData("", 0, 0.0, -1, 0)
|
||||
|
||||
/** 点击回调,在 onCreateViewHolder 中绑定,不受 notifyItemChanged 影响 */
|
||||
var onItemClick: ((ScaleData) -> Unit)? = null
|
||||
|
||||
/**
|
||||
* 按 SCALE_ORDER_22 顺序更新数据,空位用哨兵填充
|
||||
* 只更新显示字段有变化的格子,避免全量刷新
|
||||
*/
|
||||
fun update(newList: List<ScaleData?>) {
|
||||
val filled = newList.map { it ?: empty }
|
||||
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) {
|
||||
set(i, scale)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 ScaleData 列表按 SCALE_ORDER_22 重排后调用 update
|
||||
*/
|
||||
fun updateByAddress(scales: List<ScaleData>) {
|
||||
val byAddress = scales.associateBy { it.address }
|
||||
update(ScaleDeviceConfig.SCALE_ORDER_22.map { byAddress[it] })
|
||||
}
|
||||
|
||||
/** 前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 cellSize = if (viewType == 1) largeSize else smallSize
|
||||
(b.root.layoutParams as? FlexboxLayoutManager.LayoutParams)?.apply {
|
||||
width = cellSize
|
||||
height = cellSize
|
||||
setMargins(2.dp, 2.dp, 2.dp, 2.dp)
|
||||
}
|
||||
val baseSp = (cellSize / parent.resources.displayMetrics.density).toInt()
|
||||
b.tvAddr.textSize = (baseSp * 0.16f).coerceIn(9f, 14f)
|
||||
b.tvWeight.textSize = (baseSp * 0.22f).coerceIn(12f, 20f)
|
||||
b.tvState.textSize = (baseSp * 0.14f).coerceIn(8f, 12f)
|
||||
val vh = VH(b)
|
||||
// 在 ViewHolder 创建时绑定点击,只执行一次,不受 notifyItemChanged 重绑定影响
|
||||
b.root.setOnClickListener {
|
||||
val pos = vh.bindingAdapterPosition
|
||||
if (pos != RecyclerView.NO_POSITION) {
|
||||
items.getOrNull(pos)?.takeIf { it.address != 0 }?.let { onItemClick?.invoke(it) }
|
||||
}
|
||||
}
|
||||
return vh
|
||||
}
|
||||
|
||||
@SuppressLint("SetTextI18n")
|
||||
override fun onBindViewHolder(holder: VH, position: Int, item: ScaleData?) {
|
||||
val valid = (item?.address ?: 0) != 0
|
||||
holder.b.tvAddr.text = if (valid) "秤${item!!.address}" else ""
|
||||
holder.b.tvWeight.text = if (valid) "${item!!.weight}g" else ""
|
||||
holder.b.tvState.text = if (valid) stateStr(item!!.state) else ""
|
||||
}
|
||||
|
||||
private fun stateStr(state: Int) = when (state) {
|
||||
WeightUtil.STATE_STABLE -> "稳定"
|
||||
WeightUtil.STATE_UNSTABLE -> "不稳定"
|
||||
WeightUtil.STATE_OVER_WEIGHT -> "超量"
|
||||
else -> "$state"
|
||||
}
|
||||
}
|
||||
@@ -3,14 +3,19 @@ package com.shuwei.dish.match.adapter
|
||||
import android.content.Context
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.databinding.ListItemScaleRowBinding
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
|
||||
/**
|
||||
* 线性列表秤数据 Adapter
|
||||
* 用于 SlaveActivity 非22/18格子设备的秤列表展示
|
||||
* 通过 updateItem / updateName / removeByAddress 同步更新,避免 submitList 的
|
||||
* AsyncListDiffer 异步窗口期导致点击事件丢失
|
||||
*/
|
||||
class ScaleRowAdapter : BaseQuickAdapter<ScaleRowAdapter.ScaleItem, ScaleRowAdapter.VH>() {
|
||||
|
||||
@@ -19,8 +24,12 @@ class ScaleRowAdapter : BaseQuickAdapter<ScaleRowAdapter.ScaleItem, ScaleRowAdap
|
||||
* @param address 秤地址
|
||||
* @param weight 重量(克)
|
||||
* @param state 状态码
|
||||
* @param name 调料名称,未配置时为空
|
||||
*/
|
||||
data class ScaleItem(val address: Int, val weight: Double, val state: Int)
|
||||
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)
|
||||
|
||||
@@ -31,12 +40,65 @@ class ScaleRowAdapter : BaseQuickAdapter<ScaleRowAdapter.ScaleItem, ScaleRowAdap
|
||||
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 = when (item.state) {
|
||||
WeightUtil.STATE_STABLE -> "稳定"
|
||||
WeightUtil.STATE_UNSTABLE -> "不稳定"
|
||||
WeightUtil.STATE_OVER_WEIGHT -> "超量"
|
||||
else -> "${item.state}"
|
||||
holder.b.tvState.text = WeightUtil.getStateStr(item.state)
|
||||
if (item.state == WeightUtil.STATE_OVER_WEIGHT) {
|
||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell_over_weight)
|
||||
val white = ContextCompat.getColor(holder.b.root.context, R.color.white)
|
||||
holder.b.tvScaleLabel.setTextColor(white)
|
||||
holder.b.tvName.setTextColor(white)
|
||||
holder.b.tvWeight.setTextColor(white)
|
||||
holder.b.tvState.setTextColor(white)
|
||||
} else {
|
||||
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell)
|
||||
holder.b.tvScaleLabel.setTextColor(ContextCompat.getColor(holder.b.root.context, R.color.black))
|
||||
holder.b.tvName.setTextColor(ContextCompat.getColor(holder.b.root.context, R.color.black))
|
||||
holder.b.tvWeight.setTextColor(ContextCompat.getColor(holder.b.root.context, R.color.home_title))
|
||||
holder.b.tvState.setTextColor(ContextCompat.getColor(holder.b.root.context, R.color.home_sub_title))
|
||||
}
|
||||
// 点击时通过 bindingAdapterPosition 取最新数据,避免闭包捕获过期 item
|
||||
holder.b.root.setOnClickListener {
|
||||
val pos = holder.bindingAdapterPosition
|
||||
if (pos != RecyclerView.NO_POSITION) {
|
||||
items.getOrNull(pos)?.let { onItemClick?.invoke(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步更新单条秤数据:存在则定点刷新,不存在则按 address 升序插入
|
||||
* 使用 set/add 替代 submitList,消除 AsyncListDiffer 异步窗口期
|
||||
* @param item 最新秤数据
|
||||
*/
|
||||
fun updateItem(item: ScaleItem) {
|
||||
val idx = items.indexOfFirst { it.address == item.address }
|
||||
if (idx >= 0) {
|
||||
set(idx, item)
|
||||
} else {
|
||||
// 找到按 address 升序的插入位置
|
||||
val insertPos = items.indexOfFirst { it.address > item.address }
|
||||
.let { if (it < 0) items.size else it }
|
||||
add(insertPos, item)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步更新指定地址的调料名称
|
||||
* @param address 秤地址
|
||||
* @param name 新名称
|
||||
*/
|
||||
fun updateName(address: Int, name: String) {
|
||||
val idx = items.indexOfFirst { it.address == address }
|
||||
if (idx >= 0) set(idx, items[idx].copy(name = name))
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步移除指定地址的条目
|
||||
* @param address 秤地址
|
||||
*/
|
||||
fun removeByAddress(address: Int) {
|
||||
val idx = items.indexOfFirst { it.address == address }
|
||||
if (idx >= 0) removeAt(idx)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -7,23 +7,22 @@ import androidx.core.content.ContextCompat
|
||||
import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.databinding.ListItemSearchGoodsInfoBinding
|
||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.databinding.ListItemSeasoningBinding
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
|
||||
class SeasoningSearchAdapter(private var list: MutableList<SeasoningEntity>) :
|
||||
BaseQuickAdapter<SeasoningEntity, SeasoningSearchAdapter.VH>(list) {
|
||||
/**
|
||||
* 调料搜索弹窗适配器
|
||||
*/
|
||||
class SeasoningSearchAdapter(private var list: MutableList<GoodsItem>) :
|
||||
BaseQuickAdapter<GoodsItem, SeasoningSearchAdapter.VH>(list) {
|
||||
|
||||
override fun onBindViewHolder(
|
||||
holder: VH,
|
||||
position: Int,
|
||||
item: SeasoningEntity?
|
||||
item: GoodsItem?
|
||||
) {
|
||||
holder.binding.tvGoodsInfo.run {
|
||||
text = item?.goodsName
|
||||
setBackgroundResource(
|
||||
if (item?.isClicked == true) R.drawable.shape_green_stroke
|
||||
else R.drawable.shape_white_12_corners
|
||||
)
|
||||
setTextColor(
|
||||
ContextCompat.getColor(
|
||||
context,
|
||||
@@ -32,6 +31,10 @@ class SeasoningSearchAdapter(private var list: MutableList<SeasoningEntity>) :
|
||||
)
|
||||
)
|
||||
}
|
||||
holder.binding.root.setBackgroundResource(
|
||||
if (item?.isClicked == true) R.drawable.shape_green_stroke
|
||||
else R.drawable.shape_white_12_corners
|
||||
)
|
||||
}
|
||||
|
||||
override fun onCreateViewHolder(
|
||||
@@ -40,10 +43,10 @@ class SeasoningSearchAdapter(private var list: MutableList<SeasoningEntity>) :
|
||||
viewType: Int
|
||||
): VH {
|
||||
val binding =
|
||||
ListItemSearchGoodsInfoBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||
ListItemSeasoningBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||
return VH(binding)
|
||||
}
|
||||
|
||||
inner class VH(var binding: ListItemSearchGoodsInfoBinding) : QuickViewHolder(binding.root)
|
||||
inner class VH(var binding: ListItemSeasoningBinding) : QuickViewHolder(binding.root)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
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)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.shuwei.dish.match.adapter
|
||||
|
||||
import android.content.Context
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.databinding.ListItemSettingBinding
|
||||
import com.shuwei.dish.match.model.SettingItem
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
|
||||
/**
|
||||
* 设置页面列表适配器
|
||||
* 点击事件直接调用 item.onClick(),无需在 Adapter 中分发业务逻辑
|
||||
*/
|
||||
class SettingAdapter : BaseQuickAdapter<SettingItem, SettingAdapter.VH>() {
|
||||
|
||||
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
||||
val binding = ListItemSettingBinding.inflate(LayoutInflater.from(context), parent, false)
|
||||
return VH(binding)
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: VH, position: Int, item: SettingItem?) {
|
||||
item ?: return
|
||||
holder.binding.tvTitle.text = item.title
|
||||
|
||||
// 有副标题则显示,否则隐藏
|
||||
val subtitle = item.subtitle
|
||||
if (subtitle != null) {
|
||||
holder.binding.tvSubtitle.visible()
|
||||
holder.binding.tvSubtitle.text = subtitle
|
||||
} else {
|
||||
holder.binding.tvSubtitle.gone()
|
||||
}
|
||||
}
|
||||
|
||||
inner class VH(val binding: ListItemSettingBinding) : QuickViewHolder(binding.root)
|
||||
}
|
||||
@@ -1,136 +1,136 @@
|
||||
package com.shuwei.dish.match.adapter
|
||||
|
||||
import android.graphics.Typeface
|
||||
import android.icu.text.DecimalFormat
|
||||
import android.text.SpannableStringBuilder
|
||||
import android.text.style.AbsoluteSizeSpan
|
||||
import android.text.style.ForegroundColorSpan
|
||||
import android.text.style.LineHeightSpan
|
||||
import android.text.style.StyleSpan
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import android.widget.FrameLayout
|
||||
import android.widget.TextView
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.graphics.toColorInt
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.databinding.ListItemCellBinding
|
||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.utils.ext.appendText
|
||||
import com.shuwei.dish.match.utils.ext.buildSpannableString
|
||||
import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import com.shuwei.dish.match.utils.ext.invisible
|
||||
import com.shuwei.dish.match.utils.ext.roundedOneDecimalPlace
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
|
||||
class TextCellAdapter(var list: MutableList<SeasoningEntity>) :
|
||||
RecyclerView.Adapter<TextCellAdapter.VH>() {
|
||||
|
||||
inner class VH(var binding: ListItemCellBinding) : QuickViewHolder(binding.root)
|
||||
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
|
||||
val inflater = LayoutInflater.from(parent.context)
|
||||
val binding = ListItemCellBinding.inflate(inflater, parent, false)
|
||||
return VH(binding)
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: VH, position: Int) {
|
||||
val item = list[position]
|
||||
holder.binding.run {
|
||||
if (position == 10 || position == 11 || position == 13 || position == 14) {
|
||||
root.invisible()
|
||||
} else {
|
||||
root.visible()
|
||||
}
|
||||
loadCell(tvCell, item)
|
||||
//root.setBackgroundResource(R.color.dish_green)
|
||||
(root.layoutParams as RecyclerView.LayoutParams).let {
|
||||
// it.bottomMargin = 15.dp
|
||||
it.width = 226.dp
|
||||
it.height = 120.dp
|
||||
// it.rightMargin = 0
|
||||
// it.leftMargin = if (position % 3 == 0) 0 else 15.dp
|
||||
|
||||
it.leftMargin = 7.dp
|
||||
it.rightMargin = 8.dp
|
||||
it.topMargin = 7.dp
|
||||
it.bottomMargin = 8.dp
|
||||
}
|
||||
if (item.pageType == 1) {
|
||||
root.clickWithDebounce { onCellClick?.invoke(position) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun getItemCount() = list.size
|
||||
|
||||
var onCellClick: ((positon: Int) -> Unit)? = null
|
||||
|
||||
companion object {
|
||||
fun loadLayout(frameLayout: FrameLayout, item: SeasoningEntity) {
|
||||
val child: TextView = frameLayout.getChildAt(0) as TextView
|
||||
child.text = getTextSpan(item)
|
||||
}
|
||||
fun loadCell(tvCell: TextView, item: SeasoningEntity) {
|
||||
tvCell.text = getTextSpan(item)
|
||||
}
|
||||
// fun loadCell2(tvCell: TextView, item: SeasoningEntity) {
|
||||
// if (item.goodsName.isNullOrBlank()) {
|
||||
// tvCell.run {
|
||||
// text = buildSpannableString {
|
||||
// appendText(
|
||||
// "未配置",
|
||||
// ForegroundColorSpan("#999999".toColorInt()),
|
||||
// StyleSpan(Typeface.BOLD),
|
||||
// AbsoluteSizeSpan(28, true),
|
||||
// LineHeightSpan { text, start, end, spanstartv, v, fm ->
|
||||
// fm.descent += 10.dp // 增加行间距
|
||||
// }
|
||||
// )}
|
||||
// //setTextColor(ContextCompat.getColor(context, R.color.black999))
|
||||
// }
|
||||
//package com.shuwei.dish.match.adapter
|
||||
//
|
||||
//import android.graphics.Typeface
|
||||
//import android.icu.text.DecimalFormat
|
||||
//import android.text.SpannableStringBuilder
|
||||
//import android.text.style.AbsoluteSizeSpan
|
||||
//import android.text.style.ForegroundColorSpan
|
||||
//import android.text.style.LineHeightSpan
|
||||
//import android.text.style.StyleSpan
|
||||
//import android.view.LayoutInflater
|
||||
//import android.view.ViewGroup
|
||||
//import android.widget.FrameLayout
|
||||
//import android.widget.TextView
|
||||
//import androidx.core.content.ContextCompat
|
||||
//import androidx.core.graphics.toColorInt
|
||||
//import androidx.recyclerview.widget.RecyclerView
|
||||
//import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
//import com.shuwei.dish.match.R
|
||||
//import com.shuwei.dish.match.databinding.ListItemCellBinding
|
||||
//import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
//import com.shuwei.dish.match.utils.ext.appendText
|
||||
//import com.shuwei.dish.match.utils.ext.buildSpannableString
|
||||
//import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
||||
//import com.shuwei.dish.match.utils.ext.dp
|
||||
//import com.shuwei.dish.match.utils.ext.invisible
|
||||
//import com.shuwei.dish.match.utils.ext.roundedOneDecimalPlace
|
||||
//import com.shuwei.dish.match.utils.ext.visible
|
||||
//
|
||||
//class TextCellAdapter(var list: MutableList<SeasoningEntity>) :
|
||||
// RecyclerView.Adapter<TextCellAdapter.VH>() {
|
||||
//
|
||||
// inner class VH(var binding: ListItemCellBinding) : QuickViewHolder(binding.root)
|
||||
//
|
||||
// override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
|
||||
// val inflater = LayoutInflater.from(parent.context)
|
||||
// val binding = ListItemCellBinding.inflate(inflater, parent, false)
|
||||
// return VH(binding)
|
||||
// }
|
||||
//
|
||||
// override fun onBindViewHolder(holder: VH, position: Int) {
|
||||
// val item = list[position]
|
||||
// holder.binding.run {
|
||||
// if (position == 10 || position == 11 || position == 13 || position == 14) {
|
||||
// root.invisible()
|
||||
// } else {
|
||||
//// if (item.pageType == 1) {
|
||||
//// tvCell.run {
|
||||
//// text = item.goodsName
|
||||
//// setTextColor(ContextCompat.getColor(context, R.color.black))
|
||||
//// }
|
||||
//// } else {
|
||||
// tvCell.text = getTextSpan(item)
|
||||
//// }
|
||||
// root.visible()
|
||||
// }
|
||||
// loadCell(tvCell, item)
|
||||
// //root.setBackgroundResource(R.color.dish_green)
|
||||
// (root.layoutParams as RecyclerView.LayoutParams).let {
|
||||
//// it.bottomMargin = 15.dp
|
||||
// it.width = 226.dp
|
||||
// it.height = 120.dp
|
||||
//// it.rightMargin = 0
|
||||
//// it.leftMargin = if (position % 3 == 0) 0 else 15.dp
|
||||
//
|
||||
// it.leftMargin = 7.dp
|
||||
// it.rightMargin = 8.dp
|
||||
// it.topMargin = 7.dp
|
||||
// it.bottomMargin = 8.dp
|
||||
// }
|
||||
// if (item.pageType == 1) {
|
||||
// root.clickWithDebounce { onCellClick?.invoke(position) }
|
||||
// }
|
||||
// }
|
||||
|
||||
fun getTextSpan(item: SeasoningEntity): SpannableStringBuilder {
|
||||
val endIndex = if (item.sort == 9) 10 else 6
|
||||
var name = if (item.goodsName.isNullOrBlank()) "未配置" else item.goodsName!!
|
||||
if (name.length > endIndex) {
|
||||
name = "${name.substring(0, endIndex)}…"
|
||||
}
|
||||
return buildSpannableString {
|
||||
appendText(
|
||||
name,
|
||||
ForegroundColorSpan(if (item.goodsName.isNullOrBlank()) "#999999".toColorInt() else "#000000".toColorInt()),
|
||||
StyleSpan(Typeface.BOLD),
|
||||
AbsoluteSizeSpan(28, true),
|
||||
LineHeightSpan { text, start, end, spanstartv, v, fm ->
|
||||
fm.descent += 10.dp // 增加行间距
|
||||
}
|
||||
)
|
||||
append("\n")
|
||||
val weight = item.useWeight ?: 0.toDouble()
|
||||
val weightColor = if (weight == 0.toDouble()) "#999999" else "#00BC71"
|
||||
appendText(
|
||||
// "${DecimalFormat("#").format(weight)}g",
|
||||
"${weight.roundedOneDecimalPlace()}g",
|
||||
ForegroundColorSpan(weightColor.toColorInt()),
|
||||
AbsoluteSizeSpan(30, true)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
// }
|
||||
//
|
||||
// override fun getItemCount() = list.size
|
||||
//
|
||||
// var onCellClick: ((positon: Int) -> Unit)? = null
|
||||
//
|
||||
// companion object {
|
||||
// fun loadLayout(frameLayout: FrameLayout, item: SeasoningEntity) {
|
||||
// val child: TextView = frameLayout.getChildAt(0) as TextView
|
||||
// child.text = getTextSpan(item)
|
||||
// }
|
||||
// fun loadCell(tvCell: TextView, item: SeasoningEntity) {
|
||||
// tvCell.text = getTextSpan(item)
|
||||
// }
|
||||
//// fun loadCell2(tvCell: TextView, item: SeasoningEntity) {
|
||||
//// if (item.goodsName.isNullOrBlank()) {
|
||||
//// tvCell.run {
|
||||
//// text = buildSpannableString {
|
||||
//// appendText(
|
||||
//// "未配置",
|
||||
//// ForegroundColorSpan("#999999".toColorInt()),
|
||||
//// StyleSpan(Typeface.BOLD),
|
||||
//// AbsoluteSizeSpan(28, true),
|
||||
//// LineHeightSpan { text, start, end, spanstartv, v, fm ->
|
||||
//// fm.descent += 10.dp // 增加行间距
|
||||
//// }
|
||||
//// )}
|
||||
//// //setTextColor(ContextCompat.getColor(context, R.color.black999))
|
||||
//// }
|
||||
//// } else {
|
||||
////// if (item.pageType == 1) {
|
||||
////// tvCell.run {
|
||||
////// text = item.goodsName
|
||||
////// setTextColor(ContextCompat.getColor(context, R.color.black))
|
||||
////// }
|
||||
////// } else {
|
||||
//// tvCell.text = getTextSpan(item)
|
||||
////// }
|
||||
//// }
|
||||
//// }
|
||||
//
|
||||
// fun getTextSpan(item: SeasoningEntity): SpannableStringBuilder {
|
||||
// val endIndex = if (item.sort == 9) 10 else 6
|
||||
// var name = if (item.goodsName.isNullOrBlank()) "未配置" else item.goodsName!!
|
||||
// if (name.length > endIndex) {
|
||||
// name = "${name.substring(0, endIndex)}…"
|
||||
// }
|
||||
// return buildSpannableString {
|
||||
// appendText(
|
||||
// name,
|
||||
// ForegroundColorSpan(if (item.goodsName.isNullOrBlank()) "#999999".toColorInt() else "#000000".toColorInt()),
|
||||
// StyleSpan(Typeface.BOLD),
|
||||
// AbsoluteSizeSpan(28, true),
|
||||
// LineHeightSpan { text, start, end, spanstartv, v, fm ->
|
||||
// fm.descent += 10.dp // 增加行间距
|
||||
// }
|
||||
// )
|
||||
// append("\n")
|
||||
// val weight = item.useWeight ?: 0.toDouble()
|
||||
// val weightColor = if (weight == 0.toDouble()) "#999999" else "#00BC71"
|
||||
// appendText(
|
||||
//// "${DecimalFormat("#").format(weight)}g",
|
||||
// "${weight.roundedOneDecimalPlace()}g",
|
||||
// ForegroundColorSpan(weightColor.toColorInt()),
|
||||
// AbsoluteSizeSpan(30, true)
|
||||
// )
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
//}
|
||||
+6
-6
@@ -8,18 +8,18 @@ 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.ListItemFoodCollectionBinding
|
||||
import com.shuwei.dish.match.objbox.FoodCollectionBean
|
||||
import com.shuwei.dish.match.databinding.ListItemVectorCollectionBinding
|
||||
import com.shuwei.dish.match.model.FoodCollectionBean
|
||||
import com.shuwei.dish.match.utils.ext.load
|
||||
|
||||
class FoodCollectionAdapter (var list: MutableList<FoodCollectionBean>) :
|
||||
BaseQuickAdapter<FoodCollectionBean, FoodCollectionAdapter.VH>(list) {
|
||||
class VectorCollectionAdapter (var list: MutableList<FoodCollectionBean>) :
|
||||
BaseQuickAdapter<FoodCollectionBean, VectorCollectionAdapter.VH>(list) {
|
||||
|
||||
inner class VH(var binding: ListItemFoodCollectionBinding) : QuickViewHolder(binding.root)
|
||||
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 = ListItemFoodCollectionBinding.inflate(inflater, parent, false)
|
||||
val binding = ListItemVectorCollectionBinding.inflate(inflater, parent, false)
|
||||
return VH(binding)
|
||||
}
|
||||
|
||||
@@ -5,12 +5,11 @@ import android.content.pm.ActivityInfo
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import android.view.View
|
||||
import android.widget.FrameLayout
|
||||
import android.widget.ImageView
|
||||
import android.widget.TextView
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.activity.result.ActivityResultLauncher
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.activity.viewModels
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
@@ -21,11 +20,11 @@ import androidx.core.view.WindowInsetsControllerCompat
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.databinding.ActivityBaseBinding
|
||||
import com.shuwei.dish.match.dialog.Loading
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.net.NetViewModel
|
||||
import com.shuwei.dish.match.db.DbViewModel
|
||||
import com.shuwei.dish.match.ui.InitActivity
|
||||
import com.shuwei.dish.match.utils.ActivityManager
|
||||
import com.shuwei.dish.match.utils.KeyboardUtil
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.invisible
|
||||
@@ -36,13 +35,17 @@ import java.time.format.DateTimeFormatter
|
||||
import java.util.Locale
|
||||
import kotlin.getValue
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
open class BaseActivity : AppCompatActivity() {
|
||||
|
||||
companion object {
|
||||
const val TAG = "BaseActivity"
|
||||
/** 日期时间格式化器,复用避免每秒重复创建 */
|
||||
private val DATE_FORMATTER =
|
||||
DateTimeFormatter.ofPattern("yyyy年MM月dd日 EEEE***HH:mm:ss", Locale.CHINA)
|
||||
}
|
||||
|
||||
private lateinit var binding: ActivityBaseBinding
|
||||
|
||||
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
// 提前隐藏系统栏,避免窗口创建时导航栏闪烁
|
||||
@@ -59,42 +62,28 @@ open class BaseActivity : AppCompatActivity() {
|
||||
}
|
||||
setContentView(binding.root)
|
||||
statusBarDarkFont(enable = false)
|
||||
|
||||
// window.setDecorFitsSystemWindows(false) // 启用 Edge-to-Edge
|
||||
// window.insetsController?.apply {
|
||||
// hide(WindowInsets.Type.statusBars()) // 隐藏状态栏
|
||||
// systemBarsBehavior =
|
||||
// WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE // 滑动时临时显示
|
||||
// }
|
||||
// 主设备垂直 padding 30dp,子设备 15dp
|
||||
val verticalPadding = if (GlobalData.deviceRole == DeviceRole.MASTER) 30.dp else 10.dp
|
||||
binding.tvLeftTime.setPadding(0, verticalPadding, 0, verticalPadding)
|
||||
binding.tvRightTime.setPadding(0, verticalPadding, 0, verticalPadding)
|
||||
binding.llTitleBar.gone()
|
||||
binding.ivBack.setOnClickListener { finish() }
|
||||
}
|
||||
|
||||
private var bgState = true
|
||||
fun useBackground(enable: Boolean) {
|
||||
bgState = enable
|
||||
binding.root.setOnClickListener { hideKeyboard() }
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
dismissLoading()
|
||||
handler.removeCallbacksAndMessages(null)
|
||||
// 只关闭自己弹出的 Loading,防止误关其他 Activity 的 Loading
|
||||
Loading.dismissIfOwnedBy(this)
|
||||
super.onDestroy()
|
||||
ActivityManager.removeActivity(this)
|
||||
}
|
||||
|
||||
fun hideStatusBar() {
|
||||
// enableEdgeToEdge()
|
||||
//// val uiOptions = (View.SYSTEM_UI_FLAG_FULLSCREEN // 隐藏状态栏
|
||||
//// or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) // 隐藏导航栏(可选)
|
||||
// window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
|
||||
hideSystemBars()
|
||||
}
|
||||
|
||||
fun statusBarDarkFont(enable: Boolean) {
|
||||
//window.decorView.systemUiVisibility = if (enable) View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR else 0
|
||||
val color = ContextCompat.getColor(
|
||||
this, if (enable) R.color.black else R.color.white
|
||||
)
|
||||
@@ -106,12 +95,13 @@ open class BaseActivity : AppCompatActivity() {
|
||||
titleBarAction: ((FrameLayout) -> Unit)? = null,
|
||||
backAction: ((ImageView) -> Unit)? = null,
|
||||
titleAction: ((TextView) -> Unit)? = null,
|
||||
rightIconActon: ((ImageView) -> Unit)? = null
|
||||
rightIconAction: ((ImageView) -> Unit)? = null
|
||||
) {
|
||||
binding.llTitleBar.visible()
|
||||
titleBarAction?.invoke(binding.llTitleBar)
|
||||
backAction?.invoke(binding.ivBack)
|
||||
titleAction?.invoke(binding.tvTitle)
|
||||
rightIconActon?.invoke(binding.ivRightIcon)
|
||||
rightIconAction?.invoke(binding.ivRightIcon)
|
||||
}
|
||||
|
||||
fun setHeaderBgVisible(show: Boolean) {
|
||||
@@ -120,12 +110,15 @@ open class BaseActivity : AppCompatActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
public fun setHeaderBackground(isHomePage: Boolean = false) {
|
||||
fun setHeaderBackground(isHomePage: Boolean = false) {
|
||||
binding.ivHeaderBg.setImageResource(
|
||||
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?) {
|
||||
if (view == binding.root) {
|
||||
super.setContentView(view)
|
||||
@@ -135,14 +128,13 @@ open class BaseActivity : AppCompatActivity() {
|
||||
}
|
||||
|
||||
private fun updateDateTime() {
|
||||
val formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 EEEE***HH:mm:ss", Locale.CHINA)
|
||||
val dateTime = formatter.format(LocalDateTime.now(ZoneId.of("Asia/Shanghai")))
|
||||
val dateTime = DATE_FORMATTER.format(LocalDateTime.now(ZoneId.of("Asia/Shanghai")))
|
||||
val arr = dateTime.split("***")
|
||||
binding.tvRightTime.text = arr[0]
|
||||
binding.tvLeftTime.text = arr[1]
|
||||
}
|
||||
|
||||
val handler = Handler(Looper.getMainLooper())
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val updateTask = object : Runnable {
|
||||
override fun run() {
|
||||
updateDateTime()
|
||||
@@ -161,59 +153,61 @@ open class BaseActivity : AppCompatActivity() {
|
||||
handler.removeCallbacks(updateTask)
|
||||
}
|
||||
|
||||
fun showLoading(msg: String = "加载中……") {
|
||||
Loading.show(
|
||||
context = this,
|
||||
message = msg
|
||||
)
|
||||
fun showLoading(msg: String = "加载中……", timeoutMs: Long = Loading.DEFAULT_TIMEOUT_MS) {
|
||||
handler.post {
|
||||
Loading.show(
|
||||
context = this,
|
||||
message = msg,
|
||||
timeoutMs = timeoutMs
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun dismissLoading() {
|
||||
Loading.dismiss()
|
||||
Log.d(TAG, "dismissLoading, ${this.javaClass.simpleName}")
|
||||
handler.post {
|
||||
Loading.dismiss()
|
||||
}
|
||||
}
|
||||
|
||||
fun delayDismissLoading() {
|
||||
window.decorView.postDelayed({
|
||||
Log.d(TAG, "delayDismissLoading, ${this.javaClass.simpleName}")
|
||||
handler.postDelayed({
|
||||
Loading.dismiss()
|
||||
}, 500)
|
||||
}
|
||||
|
||||
/**
|
||||
* 在主线程延迟执行任务,供子类使用
|
||||
* @param delayMs 延迟毫秒数
|
||||
* @param block 待执行的任务
|
||||
*/
|
||||
protected fun postDelayed(delayMs: Long, block: () -> Unit) {
|
||||
handler.postDelayed(block, delayMs)
|
||||
}
|
||||
|
||||
|
||||
val netViewModel: NetViewModel by viewModels()
|
||||
fun queryGoodsList(
|
||||
param: MutableMap<String, Any>,
|
||||
onSuccess: (MutableList<CookFoodGoodsEntity>?) -> Unit,
|
||||
onFailure: (String, String) -> Unit
|
||||
) {
|
||||
netViewModel.queryGoodsList(param, onSuccess, onFailure)
|
||||
}
|
||||
val dbViewModel: DbViewModel by viewModels()
|
||||
|
||||
fun querySeasoningList(
|
||||
param: MutableMap<String, Any>,
|
||||
onSuccess: (MutableList<SeasoningEntity>?) -> Unit,
|
||||
onFailure: (String, String) -> Unit
|
||||
) {
|
||||
netViewModel.querySeasoningList(param, onSuccess, onFailure)
|
||||
}
|
||||
|
||||
|
||||
private var permissionCallback: ((isGranted: Boolean) -> Unit)? = null
|
||||
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.permissionCallback = callback
|
||||
this.multiplePermissionsCallback = callback
|
||||
requestMultiplePermissionsLauncher.launch(permissions)
|
||||
}
|
||||
|
||||
fun requestPermission(permission: String, callback: (isGranted: Boolean) -> Unit) {
|
||||
this.permissionCallback = callback
|
||||
this.singlePermissionCallback = callback
|
||||
requestPermissionLauncher.launch(permission)
|
||||
}
|
||||
|
||||
val requestMultiplePermissionsLauncher = registerForActivityResult(
|
||||
private val requestMultiplePermissionsLauncher = registerForActivityResult(
|
||||
ActivityResultContracts.RequestMultiplePermissions()
|
||||
) { permissions ->
|
||||
var isGranted = true
|
||||
@@ -222,14 +216,14 @@ open class BaseActivity : AppCompatActivity() {
|
||||
isGranted = false
|
||||
}
|
||||
}
|
||||
permissionCallback?.invoke(isGranted)
|
||||
multiplePermissionsCallback?.invoke(isGranted)
|
||||
}
|
||||
|
||||
// 权限请求回调
|
||||
val requestPermissionLauncher = registerForActivityResult(
|
||||
private val requestPermissionLauncher = registerForActivityResult(
|
||||
ActivityResultContracts.RequestPermission()
|
||||
) { isGranted ->
|
||||
permissionCallback?.invoke(isGranted)
|
||||
singlePermissionCallback?.invoke(isGranted)
|
||||
}
|
||||
|
||||
fun startActivity(intent: Intent, callback: (Intent?) -> Unit) {
|
||||
@@ -278,4 +272,8 @@ open class BaseActivity : AppCompatActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
fun hideKeyboard() {
|
||||
KeyboardUtil.hideKeyboard(binding.root)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,22 +1,26 @@
|
||||
package com.shuwei.dish.match.base
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.content.SharedPreferences
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import com.shuwei.dish.match.BuildConfig
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.db.DatabaseProvider
|
||||
import com.shuwei.dish.match.objbox.ObjectBox
|
||||
import com.shuwei.dish.match.scale.ScaleDeviceConfig
|
||||
import com.shuwei.dish.match.scale.ScaleServiceManager
|
||||
import com.shuwei.dish.match.ui.InitActivity.Companion.TAG
|
||||
import com.shuwei.dish.match.utils.AppUtil
|
||||
import com.shuwei.dish.match.utils.SpTool
|
||||
import com.shuwei.dish.match.utils.BootReceiver
|
||||
import com.shuwei.dish.match.utils.CrashHandler
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
import com.shuwei.dish.match.utils.Weigher2
|
||||
|
||||
|
||||
class BaseApp : Application() {
|
||||
|
||||
val database by lazy { DatabaseProvider(this).instance }
|
||||
@@ -24,14 +28,19 @@ class BaseApp : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
instance = this
|
||||
// 读取本地保存的环境地址,覆盖默认值
|
||||
val savedBaseUrl = SpTool.baseUrl
|
||||
if (savedBaseUrl.isNotEmpty()) {
|
||||
GlobalData.appBaseUrl = savedBaseUrl
|
||||
}
|
||||
CrashHandler.init(this)
|
||||
val deviceId = AppUtil.getUDID(this)
|
||||
Log.d(TAG, "onCreate: deviceId=$deviceId")
|
||||
val deviceId = if (BuildConfig.IS_TEST_DEVICE) ScaleDeviceConfig.DEVICE_ID_2 else AppUtil.getUDID(this)
|
||||
Log.d(TAG, "onCreate: deviceId=$deviceId, isTestDevice=${BuildConfig.IS_TEST_DEVICE}")
|
||||
GlobalData.deviceId = deviceId
|
||||
|
||||
// 根据设备 ID 判断角色:指定 ID 为主设备,其余为子设备
|
||||
// 主设备是/dev/ttyS7,子设备是/dev/ttyS4
|
||||
if (deviceId == "8fc2ab34-2137-3112-acca-f884ea8736d4") {
|
||||
if (deviceId == ScaleDeviceConfig.DEVICE_ID_2) {
|
||||
GlobalData.deviceRole = DeviceRole.MASTER
|
||||
Weigher2.setDevicePort("/dev/ttyS7")
|
||||
} else {
|
||||
@@ -42,6 +51,26 @@ class BaseApp : Application() {
|
||||
|
||||
// 启动秤服务(主设备多启动发现+聚合,子设备只启动服务端+注册)
|
||||
ScaleServiceManager.start(this)
|
||||
|
||||
// 初始化秤,进程级生命周期管理:最后一个 Activity 销毁时才停止读取
|
||||
WeightUtil.init()
|
||||
WeightUtil.getWeight()
|
||||
WeightUtil.startContinuousRead()
|
||||
registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
|
||||
private var activityCount = 0
|
||||
override fun onActivityCreated(a: Activity, b: Bundle?) { activityCount++ }
|
||||
override fun onActivityDestroyed(a: Activity) {
|
||||
if (--activityCount <= 0) {
|
||||
WeightUtil.stopContinuousRead()
|
||||
}
|
||||
}
|
||||
override fun onActivityStarted(a: Activity) {}
|
||||
override fun onActivityResumed(a: Activity) {}
|
||||
override fun onActivityPaused(a: Activity) {}
|
||||
override fun onActivityStopped(a: Activity) {}
|
||||
override fun onActivitySaveInstanceState(a: Activity, b: Bundle) {}
|
||||
})
|
||||
|
||||
// GlobalData.deviceId = "39a7abdd06b3c7ab"
|
||||
val filter = IntentFilter(Intent.ACTION_BOOT_COMPLETED)
|
||||
registerReceiver(BootReceiver(), filter)
|
||||
@@ -49,25 +78,22 @@ class BaseApp : Application() {
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
// const val canteenId = "1678234139391512577"
|
||||
private val TAG = "BaseApp"
|
||||
var canteenId = "0"
|
||||
// var configUrl = ""
|
||||
|
||||
// var token: String? = null
|
||||
// var deviceId: String? = null
|
||||
var appVersion: String = "1"
|
||||
@Volatile
|
||||
private var sharedPref: SharedPreferences? = null
|
||||
|
||||
public var instance: BaseApp? = null
|
||||
fun getSharedPref(): SharedPreferences? {
|
||||
if (sharedPref != null) {
|
||||
return sharedPref
|
||||
lateinit var instance: BaseApp
|
||||
|
||||
/** 双重检查锁,保证多线程下只初始化一次 */
|
||||
fun getSharedPref(): SharedPreferences {
|
||||
return sharedPref ?: synchronized(this) {
|
||||
sharedPref ?: instance.getSharedPreferences(
|
||||
instance.getString(R.string.sp_save_name),
|
||||
Context.MODE_PRIVATE
|
||||
).also { sharedPref = it }
|
||||
}
|
||||
val saveName = instance?.getString(R.string.sp_save_name)
|
||||
sharedPref = instance?.getSharedPreferences(saveName, Context.MODE_PRIVATE)
|
||||
return sharedPref
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
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,14 +8,14 @@ package com.shuwei.dish.match.base
|
||||
enum class DeviceRole { MASTER, SLAVE }
|
||||
|
||||
object GlobalData {
|
||||
var appBaseUrl: String = TEST_BASE_URL
|
||||
var appBaseUrl: String = PROD_BASE_URL
|
||||
|
||||
/**
|
||||
* 具体业务 BaseUrl
|
||||
*/
|
||||
const val TEST_BASE_URL = "http://192.168.1.201:14801"
|
||||
const val TEST_BASE_URL = "http://192.168.10.101:24801"
|
||||
const val UAT_BASE_URL = "https://dev.yixiong-tech.com:8081"
|
||||
const val PROD_BASE_URL = "https://api.dm.yixiong-tech.com:8443"
|
||||
const val PROD_BASE_URL = "https://platform-api.uat.shuziweidao.com"
|
||||
/**
|
||||
* 设备id
|
||||
*/
|
||||
@@ -25,8 +25,6 @@ object GlobalData {
|
||||
* 当前设备角色,启动时从 SpTool 读取,默认为 SLAVE
|
||||
*/
|
||||
var deviceRole: DeviceRole = DeviceRole.SLAVE
|
||||
var appId = "Hkz1rBk6PZXbS8KwKr67K2eZtsz8bRoMHLg64bUdgCZj"
|
||||
var sdkKey = "AabXs3sHM8UhhE7oCGf4LVMLrdkGb1nJNksbjjTdVt7k"
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -37,4 +35,5 @@ object GlobalKey {
|
||||
const val KEY_TOKEN = "tokenKey"
|
||||
const val KEY_USER_INFO = "userInfoKey"
|
||||
const val KEY_USER_NAME = "userNameKey"
|
||||
const val KEY_BASE_URL = "baseUrl"
|
||||
}
|
||||
@@ -6,10 +6,14 @@ import androidx.room.Room
|
||||
import androidx.room.RoomDatabase
|
||||
import androidx.room.migration.Migration
|
||||
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
import com.shuwei.dish.match.db.dao.AppDao
|
||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.db.dao.CookFoodDao
|
||||
import com.shuwei.dish.match.db.dao.CookFoodGoodsDao
|
||||
import com.shuwei.dish.match.db.dao.SeasoningDao
|
||||
import com.shuwei.dish.match.db.dao.SeasoningSlotDao
|
||||
import com.shuwei.dish.match.db.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.db.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.db.entity.SeasoningSlotEntity
|
||||
|
||||
|
||||
// 步骤1:更新版本号
|
||||
@@ -19,16 +23,20 @@ import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
SeasoningEntity::class,
|
||||
CookFoodEntity::class,
|
||||
CookFoodGoodsEntity::class,
|
||||
SeasoningSlotEntity::class,
|
||||
],
|
||||
version = 7,
|
||||
version = 13,
|
||||
exportSchema = true
|
||||
)
|
||||
abstract class AppDatabase : RoomDatabase() {
|
||||
// abstract fun seasoningDao(): SeasoningDao
|
||||
// abstract fun cookFoodDao(): CookFoodDao
|
||||
// abstract fun cookFoodGoodsDao(): CookFoodGoodsDao
|
||||
|
||||
abstract fun appDao(): AppDao
|
||||
abstract fun cookFoodDao(): CookFoodDao
|
||||
|
||||
abstract fun cookFoodGoodsDao(): CookFoodGoodsDao
|
||||
|
||||
abstract fun seasoningDao(): SeasoningDao
|
||||
|
||||
abstract fun seasoningSlotDao(): SeasoningSlotDao
|
||||
|
||||
}
|
||||
|
||||
@@ -140,6 +148,20 @@ val MIGRATION_5_6 = MigrationImpl(5, 6) { db ->
|
||||
db.endTransaction()
|
||||
}
|
||||
|
||||
val MIGRATION_7_8 = MigrationImpl(7, 8) { db ->
|
||||
db.execSQL(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS `dm_seasoning_slot` (
|
||||
`deviceId` TEXT NOT NULL,
|
||||
`address` INTEGER NOT NULL,
|
||||
`goodsId` TEXT NOT NULL,
|
||||
`goodsName` TEXT NOT NULL,
|
||||
PRIMARY KEY(`deviceId`, `address`)
|
||||
)
|
||||
""".trimIndent()
|
||||
)
|
||||
}
|
||||
|
||||
val MIGRATION_6_7 = MigrationImpl(6, 7) {db ->
|
||||
runCatching {
|
||||
|
||||
@@ -192,6 +214,48 @@ val MIGRATION_6_7 = MigrationImpl(6, 7) {db ->
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 版本8→9:为 dm_cook_food_goods 和 dm_seasoning 表新增 zjmCode、materId 字段
|
||||
*/
|
||||
val MIGRATION_8_9 = MigrationImpl(8, 9) { db ->
|
||||
db.execSQL("ALTER TABLE dm_cook_food_goods ADD COLUMN zjmCode TEXT DEFAULT ''")
|
||||
db.execSQL("ALTER TABLE dm_cook_food_goods ADD COLUMN materId TEXT DEFAULT ''")
|
||||
db.execSQL("ALTER TABLE dm_seasoning ADD COLUMN zjmCode TEXT DEFAULT ''")
|
||||
db.execSQL("ALTER TABLE dm_seasoning ADD COLUMN materId TEXT DEFAULT ''")
|
||||
}
|
||||
|
||||
/**
|
||||
* 版本9→10:删除 dm_cook_food 表 foodId 唯一索引
|
||||
* 改为由应用层保证同一 foodId 且 isDel=0 只有一条记录,以支持逻辑删除
|
||||
*/
|
||||
val MIGRATION_9_10 = MigrationImpl(9, 10) { db ->
|
||||
db.execSQL("DROP INDEX IF EXISTS dm_cook_food_foodId_IDX")
|
||||
}
|
||||
|
||||
/**
|
||||
* 版本10→11:为 dm_cook_food_goods 和 dm_seasoning 表新增 goodsCode(物料编码)字段
|
||||
*/
|
||||
val MIGRATION_10_11 = MigrationImpl(10, 11) { db ->
|
||||
db.execSQL("ALTER TABLE dm_cook_food_goods ADD COLUMN goodsCode TEXT DEFAULT ''")
|
||||
db.execSQL("ALTER TABLE dm_seasoning ADD COLUMN goodsCode TEXT DEFAULT ''")
|
||||
}
|
||||
|
||||
/**
|
||||
* 版本11→12:为 dm_cook_food_goods 和 dm_seasoning 表新增 rawMaterialsType(净材种类)字段
|
||||
*/
|
||||
val MIGRATION_11_12 = MigrationImpl(11, 12) { db ->
|
||||
db.execSQL("ALTER TABLE dm_cook_food_goods ADD COLUMN rawMaterialsType TEXT DEFAULT NULL")
|
||||
db.execSQL("ALTER TABLE dm_seasoning ADD COLUMN rawMaterialsType TEXT DEFAULT NULL")
|
||||
}
|
||||
|
||||
/**
|
||||
* 版本12→13:为 dm_cook_food 表新增 submitState(接口提交状态)字段
|
||||
* 0-未提交(本地草稿/手动删除),1-接口提交成功后删除
|
||||
*/
|
||||
val MIGRATION_12_13 = MigrationImpl(12, 13) { db ->
|
||||
db.execSQL("ALTER TABLE dm_cook_food ADD COLUMN submitState INTEGER NOT NULL DEFAULT 0")
|
||||
}
|
||||
|
||||
class DatabaseProvider(private val context: Context) {
|
||||
// 单例模式确保全局唯一实例
|
||||
val instance: AppDatabase by lazy {
|
||||
@@ -210,6 +274,12 @@ class DatabaseProvider(private val context: Context) {
|
||||
// .addMigrations(MIGRATION_4_5)
|
||||
// .addMigrations(MIGRATION_5_6)
|
||||
// .addMigrations(MIGRATION_6_7)
|
||||
.addMigrations(MIGRATION_7_8)
|
||||
.addMigrations(MIGRATION_8_9)
|
||||
.addMigrations(MIGRATION_9_10)
|
||||
.addMigrations(MIGRATION_10_11)
|
||||
.addMigrations(MIGRATION_11_12)
|
||||
.addMigrations(MIGRATION_12_13)
|
||||
.build()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,142 +0,0 @@
|
||||
package com.shuwei.dish.match.db
|
||||
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.db.dao.AppDao
|
||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
|
||||
class AppRepository(val appDao: AppDao) {
|
||||
|
||||
suspend fun insertCookFood(item: CookFoodEntity) = withContext(Dispatchers.IO) {
|
||||
appDao.insertCookFood(item)
|
||||
}
|
||||
|
||||
suspend fun updateCookFood(item: CookFoodEntity) = withContext(Dispatchers.IO) {
|
||||
appDao.updateCookFood(item)
|
||||
}
|
||||
|
||||
suspend fun getCookFoodById(foodId: String, cookMode: Int) = withContext(Dispatchers.IO) {
|
||||
appDao.getCookFoodById(BaseApp.canteenId, foodId, cookMode)
|
||||
}
|
||||
|
||||
suspend fun getCookFoodList(cookMode: Int, dinnerType: String) = withContext(Dispatchers.IO) {
|
||||
appDao.getCookFoodList(BaseApp.canteenId, cookMode, dinnerType)
|
||||
}
|
||||
|
||||
suspend fun countCookFood(cookMode: Int) = withContext(Dispatchers.IO) {
|
||||
appDao.countCookFood(BaseApp.canteenId, cookMode)
|
||||
}
|
||||
|
||||
suspend fun deleteCookFood(foodId: String, cookMode: Int) = withContext(Dispatchers.IO) {
|
||||
appDao.deleteCookFood(BaseApp.canteenId, foodId, cookMode)
|
||||
}
|
||||
|
||||
suspend fun deleteCookFoodGoodsList(pid:Long, foodId: String) = withContext(Dispatchers.IO) {
|
||||
appDao.deleteCookFoodGoodsList(pid, foodId)
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------
|
||||
|
||||
// suspend fun insertGoods(item: CookFoodGoodsEntity) = withContext(Dispatchers.IO) {
|
||||
// appDao.insertGoods(item)
|
||||
// }
|
||||
|
||||
suspend fun insertGoodsList(items: MutableList<CookFoodGoodsEntity>) =
|
||||
withContext(Dispatchers.IO) {
|
||||
appDao.insertGoodsList(items)
|
||||
}
|
||||
|
||||
// suspend fun updateGoods(item: CookFoodGoodsEntity) = withContext(Dispatchers.IO) {
|
||||
// appDao.updateGoods(item)
|
||||
// }
|
||||
|
||||
suspend fun getCookFoodGoodsList(pid:Long, foodId: String) = withContext(Dispatchers.IO) {
|
||||
appDao.getCookFoodGoodsList(pid, foodId)
|
||||
}
|
||||
|
||||
suspend fun getCookFoodGoodsListByType(
|
||||
foodId: String,
|
||||
materialType: Int
|
||||
) = withContext(Dispatchers.IO) {
|
||||
appDao.getCookFoodGoodsListByType(foodId, materialType)
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------
|
||||
|
||||
suspend fun getSeasoningById(id: Long) = withContext(Dispatchers.IO) {
|
||||
appDao.getSeasoningById(id)
|
||||
}
|
||||
|
||||
suspend fun getSeasoningBySort(sort:Int) = withContext(Dispatchers.IO) {
|
||||
appDao.getSeasoningBySort(sort)
|
||||
}
|
||||
|
||||
suspend fun getSeasoningByGoodsId(goodsId: Int) = withContext(Dispatchers.IO) {
|
||||
appDao.getSeasoningByGoodsId(goodsId)
|
||||
}
|
||||
|
||||
suspend fun getAllStream() = withContext(Dispatchers.IO) {
|
||||
appDao.getAllStream()
|
||||
}
|
||||
|
||||
suspend fun search(query: String) = withContext(Dispatchers.IO) {
|
||||
appDao.search(query)
|
||||
}
|
||||
|
||||
suspend fun clearAllSeasoning() = withContext(Dispatchers.IO) {
|
||||
appDao.clearAllSeasoning()
|
||||
}
|
||||
|
||||
suspend fun deleteSeasoningBySort(sort: Int) = withContext(Dispatchers.IO) {
|
||||
appDao.deleteSeasoningBySort(sort)
|
||||
}
|
||||
|
||||
suspend fun insertSeasoningList(items: MutableList<SeasoningEntity>) =
|
||||
withContext(Dispatchers.IO) {
|
||||
appDao.insertSeasoningList(items)
|
||||
}
|
||||
|
||||
suspend fun updateSeasoning(item: SeasoningEntity) = withContext(Dispatchers.IO) {
|
||||
appDao.updateSeasoning(item)
|
||||
}
|
||||
|
||||
suspend fun insertSeasoning(item: SeasoningEntity) = withContext(Dispatchers.IO) {
|
||||
appDao.insertSeasoning(item)
|
||||
}
|
||||
}
|
||||
//
|
||||
//class SeasoningRepository(val seasoningDao: SeasoningDao) {
|
||||
// val seasoningList: Flow<List<SeasoningEntity>> = seasoningDao.getAllStream()
|
||||
//
|
||||
// fun addSeasoning(item: SeasoningEntity) = withContext(Dispatchers.IO) {
|
||||
// seasoningDao.insert(item)
|
||||
// }
|
||||
//
|
||||
// fun searchSeasoning(query: String) = withContext(Dispatchers.IO) {
|
||||
// seasoningDao.search(query)
|
||||
// }
|
||||
//}
|
||||
//
|
||||
//class CookFoodRepository(val cookFoodDao: CookFoodDao) {
|
||||
// fun getCookFood(foodId: String, cookMode:Int = 0) = withContext(Dispatchers.IO) {
|
||||
// cookFoodDao.getCookFoodById(foodId, cookMode)
|
||||
// }
|
||||
//
|
||||
// fun getCookFoodByList(cookMode:Int = 0) = withContext(Dispatchers.IO) {
|
||||
// cookFoodDao.getCookFoodList(cookMode)
|
||||
// }
|
||||
//
|
||||
// fun countCookFood(cookMode:Int = 0)= withContext(Dispatchers.IO) {
|
||||
// cookFoodDao.countCookFood(cookMode)
|
||||
// }
|
||||
//}
|
||||
//
|
||||
//class CookFoodGoodsRepository(val cookFoodGoodsDao: CookFoodGoodsDao) {
|
||||
// fun getFoodGoodsList(foodId: String) = withContext(Dispatchers.IO) {
|
||||
// cookFoodGoodsDao.getCookFoodGoodsList(foodId)
|
||||
// }
|
||||
//
|
||||
//}
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
package com.shuwei.dish.match.db
|
||||
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.db.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.db.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.db.entity.SeasoningSlotEntity
|
||||
import androidx.sqlite.db.SupportSQLiteQuery
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
|
||||
class DbRepository {
|
||||
|
||||
private val db = BaseApp.instance!!.database
|
||||
|
||||
suspend fun insertCookFood(item: CookFoodEntity) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().insertCookFood(item)
|
||||
}
|
||||
|
||||
suspend fun updateCookFood(item: CookFoodEntity) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().updateCookFood(item)
|
||||
}
|
||||
|
||||
suspend fun getCookFoodById(foodId: String, cookMode: Int, dinnerType: String) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().getCookFoodById(BaseApp.canteenId, foodId, cookMode, dinnerType)
|
||||
}
|
||||
|
||||
suspend fun getCookFoodList(cookMode: Int, dinnerType: String) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().getCookFoodList(BaseApp.canteenId, cookMode, dinnerType)
|
||||
}
|
||||
|
||||
suspend fun countCookFood(cookMode: Int) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().countCookFood(BaseApp.canteenId, cookMode)
|
||||
}
|
||||
|
||||
suspend fun deleteCookFood(foodId: String, cookMode: Int, dinnerType: String) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().deleteCookFood(BaseApp.canteenId, foodId, cookMode, dinnerType)
|
||||
}
|
||||
|
||||
/** 接口提交成功后逻辑删除菜品,同时把 submitState 置 1 */
|
||||
suspend fun markSubmittedAndDelete(foodId: String, cookMode: Int, dinnerType: String) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().markSubmittedAndDelete(BaseApp.canteenId, foodId, cookMode, dinnerType)
|
||||
}
|
||||
|
||||
suspend fun deleteCookFoodGoodsList(pid: Long, foodId: String) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodGoodsDao().deleteCookFoodGoodsList(pid, foodId)
|
||||
}
|
||||
|
||||
/** 仅逻辑删除调料行(materialType = 3),主辅材不动 */
|
||||
suspend fun deleteSeasoningOnly(pid: Long, foodId: String) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodGoodsDao().deleteSeasoningOnly(pid, foodId)
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------
|
||||
|
||||
suspend fun insertGoodsList(items: MutableList<CookFoodGoodsEntity>) =
|
||||
withContext(Dispatchers.IO) {
|
||||
db.cookFoodGoodsDao().insertGoodsList(items)
|
||||
}
|
||||
|
||||
suspend fun getCookFoodGoodsList(pid: Long, foodId: String) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodGoodsDao().getCookFoodGoodsList(pid, foodId)
|
||||
}
|
||||
|
||||
suspend fun getCookFoodGoodsListByType(
|
||||
foodId: String,
|
||||
materialType: Int
|
||||
) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodGoodsDao().getCookFoodGoodsListByType(foodId, materialType)
|
||||
}
|
||||
//--------------------------------------------------------------------------------------------
|
||||
|
||||
suspend fun getSeasoningById(id: Long) = withContext(Dispatchers.IO) {
|
||||
db.seasoningDao().getSeasoningById(id)
|
||||
}
|
||||
|
||||
suspend fun getSeasoningBySort(sort: Int) = withContext(Dispatchers.IO) {
|
||||
db.seasoningDao().getSeasoningBySort(sort)
|
||||
}
|
||||
|
||||
suspend fun getSeasoningByGoodsId(goodsId: String) = withContext(Dispatchers.IO) {
|
||||
db.seasoningDao().getSeasoningByGoodsId(goodsId)
|
||||
}
|
||||
|
||||
suspend fun getAllStream() = withContext(Dispatchers.IO) {
|
||||
db.seasoningDao().getAllStream()
|
||||
}
|
||||
|
||||
suspend fun search(query: String) = withContext(Dispatchers.IO) {
|
||||
db.seasoningDao().search(query)
|
||||
}
|
||||
|
||||
suspend fun clearAllSeasoning() = withContext(Dispatchers.IO) {
|
||||
db.seasoningDao().clearAllSeasoning()
|
||||
}
|
||||
|
||||
suspend fun deleteSeasoningBySort(sort: Int) = withContext(Dispatchers.IO) {
|
||||
db.seasoningDao().deleteSeasoningBySort(sort)
|
||||
}
|
||||
|
||||
suspend fun insertSeasoningList(items: MutableList<SeasoningEntity>) =
|
||||
withContext(Dispatchers.IO) {
|
||||
db.seasoningDao().insertSeasoningList(items)
|
||||
}
|
||||
|
||||
suspend fun updateSeasoning(item: SeasoningEntity) = withContext(Dispatchers.IO) {
|
||||
db.seasoningDao().updateSeasoning(item)
|
||||
}
|
||||
|
||||
suspend fun insertSeasoning(item: SeasoningEntity) = withContext(Dispatchers.IO) {
|
||||
db.seasoningDao().insertSeasoning(item)
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 goodsId 查重后 upsert:存在则更新,不存在则插入
|
||||
* 确保同一个 goodsId 在 dm_seasoning 中只有一条记录
|
||||
*/
|
||||
suspend fun upsertSeasoningByGoodsId(item: SeasoningEntity) = withContext(Dispatchers.IO) {
|
||||
val existing = db.seasoningDao().getSeasoningByGoodsId(item.goodsId)
|
||||
if (existing != null) {
|
||||
db.seasoningDao().updateSeasoning(item.also { it.id = existing.id })
|
||||
} else {
|
||||
item.id = 0
|
||||
db.seasoningDao().insertSeasoning(item)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询指定设备是否已配置调料槽位
|
||||
* @param deviceId 目标设备 ID
|
||||
* @return true 表示已有配置,false 表示未配置
|
||||
*/
|
||||
suspend fun hasSeasoningSlotConfig(deviceId: String) = withContext(Dispatchers.IO) {
|
||||
db.seasoningSlotDao().queryByDeviceId(deviceId).isNotEmpty()
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询所有设备的调料槽位配置
|
||||
*/
|
||||
suspend fun getAllSeasoningSlots() = withContext(Dispatchers.IO) {
|
||||
db.seasoningSlotDao().queryAll()
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询指定设备的调料槽位配置
|
||||
* @param deviceId 目标设备 ID
|
||||
*/
|
||||
suspend fun getSeasoningSlotsByDeviceId(deviceId: String) = withContext(Dispatchers.IO) {
|
||||
db.seasoningSlotDao().queryByDeviceId(deviceId)
|
||||
}
|
||||
|
||||
/**
|
||||
* 插入或更新单个调料槽位配置
|
||||
*/
|
||||
suspend fun upsertSeasoningSlot(slot: SeasoningSlotEntity) = withContext(Dispatchers.IO) {
|
||||
db.seasoningSlotDao().upsert(slot)
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量插入或更新调料槽位配置
|
||||
*/
|
||||
suspend fun upsertAllSeasoningSlots(slots: List<SeasoningSlotEntity>) = withContext(Dispatchers.IO) {
|
||||
db.seasoningSlotDao().upsertAll(slots)
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除指定设备的指定槽位配置
|
||||
* @param deviceId 目标设备 ID
|
||||
* @param address 秤硬件地址
|
||||
*/
|
||||
suspend fun deleteSeasoningSlot(deviceId: String, address: Int) = withContext(Dispatchers.IO) {
|
||||
db.seasoningSlotDao().deleteByDeviceIdAndAddress(deviceId, address)
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除指定设备的全部槽位配置
|
||||
* @param deviceId 目标设备 ID
|
||||
*/
|
||||
suspend fun deleteAllSlotsByDeviceId(deviceId: String) = withContext(Dispatchers.IO) {
|
||||
db.seasoningSlotDao().deleteAllByDeviceId(deviceId)
|
||||
}
|
||||
|
||||
// ---- 调试用:查询各表全量数据(含已删除记录)----
|
||||
|
||||
/** 查询 dm_cook_food 全部记录 */
|
||||
suspend fun getAllCookFood() = withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().getAllCookFood()
|
||||
}
|
||||
|
||||
/** 查询 dm_cook_food_goods 全部记录 */
|
||||
suspend fun getAllCookFoodGoods() = withContext(Dispatchers.IO) {
|
||||
db.cookFoodGoodsDao().getAllCookFoodGoods()
|
||||
}
|
||||
|
||||
/** 查询 dm_seasoning 全部记录 */
|
||||
suspend fun getAllSeasoning() = withContext(Dispatchers.IO) {
|
||||
db.seasoningDao().getAllSeasoning()
|
||||
}
|
||||
|
||||
// ---- 调试用:分页查询(含 isDel 过滤)----
|
||||
|
||||
suspend fun getCookFoodPaged(showDel: Boolean, limit: Int, offset: Int) =
|
||||
withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().getCookFoodPaged(if (showDel) 1 else 0, limit, offset)
|
||||
}
|
||||
|
||||
suspend fun countCookFoodAll(showDel: Boolean) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().countCookFoodAll(if (showDel) 1 else 0)
|
||||
}
|
||||
|
||||
suspend fun getCookFoodGoodsPaged(showDel: Boolean, limit: Int, offset: Int) =
|
||||
withContext(Dispatchers.IO) {
|
||||
db.cookFoodGoodsDao().getCookFoodGoodsPaged(if (showDel) 1 else 0, limit, offset)
|
||||
}
|
||||
|
||||
suspend fun countCookFoodGoodsAll(showDel: Boolean) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodGoodsDao().countCookFoodGoodsAll(if (showDel) 1 else 0)
|
||||
}
|
||||
|
||||
suspend fun getSeasoningPaged(showDel: Boolean, limit: Int, offset: Int) =
|
||||
withContext(Dispatchers.IO) {
|
||||
db.seasoningDao().getSeasoningPaged(if (showDel) 1 else 0, limit, offset)
|
||||
}
|
||||
|
||||
suspend fun countSeasoningAll(showDel: Boolean) = withContext(Dispatchers.IO) {
|
||||
db.seasoningDao().countSeasoningAll(if (showDel) 1 else 0)
|
||||
}
|
||||
|
||||
suspend fun getSlotPaged(limit: Int, offset: Int) = withContext(Dispatchers.IO) {
|
||||
db.seasoningSlotDao().getSlotPaged(limit, offset)
|
||||
}
|
||||
|
||||
suspend fun countSlotAll() = withContext(Dispatchers.IO) {
|
||||
db.seasoningSlotDao().countSlotAll()
|
||||
}
|
||||
|
||||
// ---- 调试用:动态条件过滤分页查询 ----
|
||||
|
||||
suspend fun getCookFoodPagedFiltered(query: SupportSQLiteQuery) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().queryPagedFiltered(query)
|
||||
}
|
||||
|
||||
suspend fun countCookFoodFiltered(query: SupportSQLiteQuery) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodDao().countFiltered(query)
|
||||
}
|
||||
|
||||
suspend fun getCookFoodGoodsPagedFiltered(query: SupportSQLiteQuery) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodGoodsDao().queryPagedFiltered(query)
|
||||
}
|
||||
|
||||
suspend fun countCookFoodGoodsFiltered(query: SupportSQLiteQuery) = withContext(Dispatchers.IO) {
|
||||
db.cookFoodGoodsDao().countFiltered(query)
|
||||
}
|
||||
|
||||
suspend fun getSeasoningPagedFiltered(query: SupportSQLiteQuery) = withContext(Dispatchers.IO) {
|
||||
db.seasoningDao().queryPagedFiltered(query)
|
||||
}
|
||||
|
||||
suspend fun countSeasoningFiltered(query: SupportSQLiteQuery) = withContext(Dispatchers.IO) {
|
||||
db.seasoningDao().countFiltered(query)
|
||||
}
|
||||
|
||||
suspend fun getSlotPagedFiltered(query: SupportSQLiteQuery) = withContext(Dispatchers.IO) {
|
||||
db.seasoningSlotDao().queryPagedFiltered(query)
|
||||
}
|
||||
|
||||
suspend fun countSlotFiltered(query: SupportSQLiteQuery) = withContext(Dispatchers.IO) {
|
||||
db.seasoningSlotDao().countFiltered(query)
|
||||
}
|
||||
|
||||
/**
|
||||
* 物理清空全部 4 张表的测试数据
|
||||
* 清除顺序:先删子表(食材),再删主表(菜品),最后删配置表(调料、槽位)
|
||||
*/
|
||||
suspend fun clearAllData() = withContext(Dispatchers.IO) {
|
||||
db.cookFoodGoodsDao().deleteAll()
|
||||
db.cookFoodDao().deleteAll()
|
||||
db.seasoningDao().deleteAll()
|
||||
db.seasoningSlotDao().deleteAll()
|
||||
}
|
||||
}
|
||||
//
|
||||
//class SeasoningRepository(val seasoningDao: SeasoningDao) {
|
||||
// val seasoningList: Flow<List<SeasoningEntity>> = seasoningDao.getAllStream()
|
||||
//
|
||||
// fun addSeasoning(item: SeasoningEntity) = withContext(Dispatchers.IO) {
|
||||
// seasoningDao.insert(item)
|
||||
// }
|
||||
//
|
||||
// fun searchSeasoning(query: String) = withContext(Dispatchers.IO) {
|
||||
// seasoningDao.search(query)
|
||||
// }
|
||||
//}
|
||||
//
|
||||
//class CookFoodRepository(val cookFoodDao: CookFoodDao) {
|
||||
// fun getCookFood(foodId: String, cookMode:Int = 0) = withContext(Dispatchers.IO) {
|
||||
// cookFoodDao.getCookFoodById(foodId, cookMode)
|
||||
// }
|
||||
//
|
||||
// fun getCookFoodByList(cookMode:Int = 0) = withContext(Dispatchers.IO) {
|
||||
// cookFoodDao.getCookFoodList(cookMode)
|
||||
// }
|
||||
//
|
||||
// fun countCookFood(cookMode:Int = 0)= withContext(Dispatchers.IO) {
|
||||
// cookFoodDao.countCookFood(cookMode)
|
||||
// }
|
||||
//}
|
||||
//
|
||||
//class CookFoodGoodsRepository(val cookFoodGoodsDao: CookFoodGoodsDao) {
|
||||
// fun getFoodGoodsList(foodId: String) = withContext(Dispatchers.IO) {
|
||||
// cookFoodGoodsDao.getCookFoodGoodsList(foodId)
|
||||
// }
|
||||
//
|
||||
//}
|
||||
|
||||
@@ -0,0 +1,624 @@
|
||||
package com.shuwei.dish.match.db
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.sqlite.db.SimpleSQLiteQuery
|
||||
import com.shuwei.dish.match.model.CollectedFoodItem
|
||||
import com.shuwei.dish.match.db.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.objbox.ObjectBox
|
||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.db.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.db.entity.SeasoningSlotEntity
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
|
||||
class DbViewModel : ViewModel() {
|
||||
|
||||
private val rep = DbRepository()
|
||||
|
||||
fun updateCookFood(entity: CookFoodEntity) {
|
||||
viewModelScope.launch {
|
||||
rep.updateCookFood(entity)
|
||||
}
|
||||
}
|
||||
|
||||
private val _cookFoodDetailState = MutableStateFlow<CookFoodEntity?>(null)
|
||||
val cookFoodDetailState: StateFlow<CookFoodEntity?> = _cookFoodDetailState.asStateFlow()
|
||||
|
||||
fun getCookFoodById(foodId: String, cookMode: Int, dinnerType: String) {
|
||||
viewModelScope.launch {
|
||||
_cookFoodDetailState.value = rep.getCookFoodById(foodId, cookMode, dinnerType)
|
||||
}
|
||||
}
|
||||
|
||||
private val _cookFoodListState = MutableStateFlow<MutableList<CookFoodEntity>?>(null)
|
||||
val cookFoodListState: StateFlow<MutableList<CookFoodEntity>?> = _cookFoodListState.asStateFlow()
|
||||
fun resetCookFoodList() {
|
||||
_cookFoodListState.value = null
|
||||
}
|
||||
fun getCookFoodList(
|
||||
cookMode: Int,
|
||||
dinnerType: String = "0"
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
_cookFoodListState.value = rep.getCookFoodList(cookMode, dinnerType)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询本地烹饪中数据(回调版本),结果通过 onResult 直接回调,不经过 StateFlow
|
||||
* 适合不需要跨生命周期持续监听的一次性查询场景
|
||||
*/
|
||||
fun getCookFoodListWithCallback(
|
||||
cookMode: Int,
|
||||
dinnerType: String = "0",
|
||||
onResult: (MutableList<CookFoodEntity>?) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onResult(rep.getCookFoodList(cookMode, dinnerType))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接返回本地烹饪中数据,供需要串行等待结果的场景使用(如先查库再发网络请求)
|
||||
*/
|
||||
suspend fun getCookFoodListDirect(
|
||||
cookMode: Int,
|
||||
dinnerType: String = "0"
|
||||
): MutableList<CookFoodEntity>? {
|
||||
return rep.getCookFoodList(cookMode, dinnerType)
|
||||
}
|
||||
|
||||
suspend fun countCookFood(cookMode: Int): Int {
|
||||
return rep.countCookFood(cookMode)
|
||||
}
|
||||
|
||||
// fun saveCookFood(cookMode: Int, entity: CookFoodEntity) {
|
||||
// viewModelScope.launch {
|
||||
// val data = rep.getCookFoodById(entity.foodId, cookMode)
|
||||
// if (data == null) {
|
||||
// rep.insertCookFood(entity)
|
||||
// return@launch
|
||||
// }
|
||||
// rep.updateCookFood(entity)
|
||||
// }
|
||||
// }
|
||||
|
||||
suspend fun saveCookFoodAndGoods(
|
||||
cookMode: Int,
|
||||
entity: CookFoodEntity,
|
||||
list: MutableList<CookFoodGoodsEntity>?
|
||||
) {
|
||||
val data = rep.getCookFoodById(entity.foodId, cookMode, entity.dinnerType ?: "0")
|
||||
if (data == null) {
|
||||
// 首次保存:主表 + 主辅材 + 调料 全量 insert
|
||||
rep.insertCookFood(entity)
|
||||
val newData = rep.getCookFoodById(entity.foodId, cookMode, entity.dinnerType ?: "0")
|
||||
// 回填 id,防止下次调用时 getCookFoodById 查不到而重复插入主辅材
|
||||
newData?.let { entity.id = it.id }
|
||||
list?.let {
|
||||
it.forEach { goods ->
|
||||
goods.id = 0
|
||||
goods.pid = newData?.id ?: 0
|
||||
}
|
||||
rep.insertGoodsList(it)
|
||||
}
|
||||
} else {
|
||||
// 已存在:主表与主辅材保持不变,仅重建调料部分,避免主表/主辅材累积逻辑删除脏数据
|
||||
rep.deleteSeasoningOnly(data.id, entity.foodId)
|
||||
val seasoningList = list?.filter { it.materialType == 3 }?.toMutableList()
|
||||
if (!seasoningList.isNullOrEmpty()) {
|
||||
seasoningList.forEach { goods ->
|
||||
goods.id = 0
|
||||
goods.pid = data.id
|
||||
goods.foodId = entity.foodId
|
||||
}
|
||||
rep.insertGoodsList(seasoningList)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun deleteCookFoodAndGoods(cookMode: Int, foodId: String, dinnerType: String) {
|
||||
val data = rep.getCookFoodById(foodId, cookMode, dinnerType)
|
||||
if (data != null) {
|
||||
rep.deleteCookFood(foodId = foodId, cookMode = cookMode, dinnerType = dinnerType)
|
||||
rep.deleteCookFoodGoodsList(pid = data.id, foodId = foodId)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 接口提交成功后删除本地菜品草稿(异步版本,绑定 viewModelScope)
|
||||
* 与 [markSubmittedAndDelete] 的区别:不是 suspend,内部用 viewModelScope 启动协程,
|
||||
* 不受调用方 Activity 生命周期影响,适合 singleTask 跳转前触发删除的场景
|
||||
*/
|
||||
fun markSubmittedAndDeleteAsync(cookMode: Int, foodId: String, dinnerType: String) {
|
||||
viewModelScope.launch {
|
||||
markSubmittedAndDelete(cookMode, foodId, dinnerType)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 接口提交成功后删除本地菜品草稿
|
||||
* 与 [deleteCookFoodAndGoods] 的区别:主表 submitState 会被置 1,便于审计区分手动删除与接口删除
|
||||
*/
|
||||
suspend fun markSubmittedAndDelete(cookMode: Int, foodId: String, dinnerType: String) {
|
||||
val data = rep.getCookFoodById(foodId, cookMode, dinnerType)
|
||||
if (data != null) {
|
||||
rep.markSubmittedAndDelete(foodId = foodId, cookMode = cookMode, dinnerType = dinnerType)
|
||||
rep.deleteCookFoodGoodsList(pid = data.id, foodId = foodId)
|
||||
}
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------------------------------------
|
||||
|
||||
suspend fun getCookFoodGoodsList(
|
||||
foodId: String,
|
||||
cookMode: Int,
|
||||
dinnerType: String
|
||||
): MutableList<CookFoodGoodsEntity> {
|
||||
val cookFood = rep.getCookFoodById(foodId, cookMode, dinnerType)
|
||||
return if (cookFood != null) rep.getCookFoodGoodsList(pid = cookFood.id, foodId = cookFood.foodId)
|
||||
else mutableListOf()
|
||||
}
|
||||
|
||||
// fun updateGoods(entity: CookFoodGoodsEntity) {
|
||||
// viewModelScope.launch {
|
||||
// rep.updateGoods(entity)
|
||||
// }
|
||||
// }
|
||||
|
||||
// fun saveCookFoodGoods(list: MutableList<CookFoodGoodsEntity>) {
|
||||
// viewModelScope.launch {
|
||||
// val foodId = list[0].foodId
|
||||
// val data: MutableList<CookFoodGoodsEntity>? =
|
||||
// rep.getCookFoodGoodsList(foodId!!)
|
||||
// if (data.isNullOrEmpty()) {
|
||||
// rep.insertGoodsList(list)
|
||||
// return@launch
|
||||
// }
|
||||
// val localDbSeasoningList = rep.getCookFoodGoodsListByType(foodId, 3)
|
||||
// localDbSeasoningList.forEach {
|
||||
// it.isDel = 1
|
||||
// //更新本地调料数据为已删除的状态
|
||||
// rep.updateGoods(it)
|
||||
// }
|
||||
// //筛选出调料数据保存,主辅材不会变更不需要再次处理
|
||||
// val saveSeasoningList = list.filter { it.materialType == 3 }
|
||||
// rep.insertGoodsList(saveSeasoningList.toMutableList())
|
||||
// }
|
||||
// }
|
||||
|
||||
//--------------------------------------------------------------------------------------------------------
|
||||
|
||||
// fun addSeasoning(list: MutableList<SeasoningEntity>, callback: () -> Unit) {
|
||||
// viewModelScope.launch {
|
||||
// rep.deleteBatch()
|
||||
// rep.insertSeasoningList(items = list)
|
||||
// callback()
|
||||
// }
|
||||
// }
|
||||
|
||||
private val loadSeasoningMutex = Mutex()
|
||||
|
||||
/**
|
||||
* 本地调料列表状态流
|
||||
*/
|
||||
private val _seasoningState = MutableStateFlow<MutableList<SeasoningEntity>>(mutableListOf())
|
||||
val seasoningState: StateFlow<MutableList<SeasoningEntity>> = _seasoningState.asStateFlow()
|
||||
|
||||
fun loadSeasoning() {
|
||||
if (loadSeasoningMutex.isLocked) return
|
||||
viewModelScope.launch {
|
||||
loadSeasoningMutex.withLock {
|
||||
_seasoningState.value = rep.getAllStream()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 所有设备调料槽位配置的 UI 状态流
|
||||
*/
|
||||
private val _seasoningSlotState = MutableStateFlow<List<SeasoningSlotEntity>>(emptyList())
|
||||
val seasoningSlotState: StateFlow<List<SeasoningSlotEntity>> = _seasoningSlotState.asStateFlow()
|
||||
|
||||
/**
|
||||
* 查询所有调料槽位配置,更新 seasoningSlotState 并返回结果
|
||||
* 声明为 suspend,调用方可在同一协程中直接使用返回值,无需等待 StateFlow 更新
|
||||
*/
|
||||
suspend fun loadSeasoningSlot(): List<SeasoningSlotEntity> {
|
||||
val slots = rep.getAllSeasoningSlots()
|
||||
_seasoningSlotState.value = slots
|
||||
return slots
|
||||
}
|
||||
|
||||
fun deleteSeasoningBySort(sort: Int) {
|
||||
viewModelScope.launch {
|
||||
rep.deleteSeasoningBySort(sort)
|
||||
}
|
||||
}
|
||||
|
||||
private val _clearAllSeasoningState = MutableStateFlow(false)
|
||||
val clearAllSeasoningState: StateFlow<Boolean> = _clearAllSeasoningState.asStateFlow()
|
||||
|
||||
fun clearAllSeasoning() {
|
||||
viewModelScope.launch {
|
||||
rep.clearAllSeasoning()
|
||||
_clearAllSeasoningState.value = true
|
||||
}
|
||||
}
|
||||
|
||||
private val _hasSeasoningSlotConfigState = MutableStateFlow(false)
|
||||
val hasSeasoningSlotConfigState: StateFlow<Boolean> = _hasSeasoningSlotConfigState.asStateFlow()
|
||||
|
||||
/**
|
||||
* 查询指定设备是否已配置调料槽位
|
||||
* @param deviceId 目标设备 ID
|
||||
*/
|
||||
fun hasSeasoningSlotConfig(deviceId: String) {
|
||||
viewModelScope.launch {
|
||||
_hasSeasoningSlotConfigState.value = rep.hasSeasoningSlotConfig(deviceId)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询指定设备的调料槽位配置
|
||||
*/
|
||||
suspend fun getSeasoningSlotsByDeviceId(deviceId: String) =
|
||||
rep.getSeasoningSlotsByDeviceId(deviceId)
|
||||
|
||||
/**
|
||||
* 插入或更新单个调料槽位配置
|
||||
*/
|
||||
suspend fun upsertSeasoningSlot(slot: SeasoningSlotEntity) =
|
||||
rep.upsertSeasoningSlot(slot)
|
||||
|
||||
/**
|
||||
* 批量插入或更新调料槽位配置
|
||||
*/
|
||||
suspend fun upsertAllSeasoningSlots(slots: List<SeasoningSlotEntity>) =
|
||||
rep.upsertAllSeasoningSlots(slots)
|
||||
|
||||
/**
|
||||
* 删除指定设备的指定槽位配置
|
||||
* @param deviceId 目标设备 ID
|
||||
* @param address 秤硬件地址
|
||||
*/
|
||||
suspend fun deleteSeasoningSlot(deviceId: String, address: Int) =
|
||||
rep.deleteSeasoningSlot(deviceId, address)
|
||||
|
||||
/**
|
||||
* 删除指定设备的全部槽位配置(子设备接收全量广播时先清空再写入)
|
||||
* @param deviceId 目标设备 ID
|
||||
*/
|
||||
suspend fun deleteAllSlotsByDeviceId(deviceId: String) =
|
||||
rep.deleteAllSlotsByDeviceId(deviceId)
|
||||
|
||||
// ---- 数据库调试查看 ----
|
||||
|
||||
/**
|
||||
* 物理清空全部 4 张表的测试数据,完成后通过回调通知 UI
|
||||
* @param onDone 清除完成后在主线程执行的回调
|
||||
*/
|
||||
fun clearAllData(onDone: () -> Unit) {
|
||||
viewModelScope.launch {
|
||||
rep.clearAllData()
|
||||
onDone()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** 每页加载条数 */
|
||||
const val DB_INSPECT_PAGE_SIZE = 50
|
||||
}
|
||||
|
||||
/**
|
||||
* 单条数据库记录的展示模型
|
||||
* @param isDel 是否已逻辑删除
|
||||
* @param fields 字段名-值对列表,按顺序排列
|
||||
* @param columnsPerRow 每行显示的列数,默认 3;槽位表传 1 保持单列
|
||||
*/
|
||||
data class DbRecord(
|
||||
val isDel: Boolean,
|
||||
val fields: List<Pair<String, String>>,
|
||||
val columnsPerRow: Int = 3
|
||||
)
|
||||
|
||||
/**
|
||||
* 数据库调试页面 UI 状态
|
||||
* @param items 当前已加载的记录列表
|
||||
* @param totalCount 当前过滤条件下的总记录数
|
||||
* @param hasMore 是否还有更多数据可加载
|
||||
* @param isLoading 是否正在加载(首次加载或加载更多)
|
||||
* @param filter 当前生效的筛选条件,供"加载更多"复用
|
||||
*/
|
||||
data class DbInspectUiState(
|
||||
val items: List<DbRecord> = emptyList(),
|
||||
val totalCount: Int = 0,
|
||||
val hasMore: Boolean = false,
|
||||
val isLoading: Boolean = false,
|
||||
val filter: DbInspectFilter = DbInspectFilter()
|
||||
)
|
||||
|
||||
/**
|
||||
* 数据库调试页面筛选条件
|
||||
* @param showDel 是否包含已删除记录
|
||||
* @param exactFields 精确匹配字段:列名 → 值
|
||||
* @param likeFields 模糊匹配字段:列名 → 值(自动加 %value%)
|
||||
*/
|
||||
data class DbInspectFilter(
|
||||
val showDel: Boolean = true,
|
||||
val exactFields: Map<String, String> = emptyMap(),
|
||||
val likeFields: Map<String, String> = emptyMap()
|
||||
)
|
||||
|
||||
private val _dbInspectState = MutableStateFlow(DbInspectUiState())
|
||||
val dbInspectState: StateFlow<DbInspectUiState> = _dbInspectState.asStateFlow()
|
||||
|
||||
/**
|
||||
* 加载指定表的第一页数据(切换 Tab / 修改筛选条件时调用)
|
||||
* @param tableIndex 0=菜品 1=食材 2=调料 3=槽位
|
||||
* @param filter 筛选条件,包含 showDel 和各字段过滤值
|
||||
*/
|
||||
fun loadDbInspect(tableIndex: Int, filter: DbInspectFilter) {
|
||||
viewModelScope.launch {
|
||||
// 立即清空旧数据并显示加载状态,避免切换 Tab 时旧数据闪现
|
||||
_dbInspectState.value = DbInspectUiState(isLoading = true, filter = filter)
|
||||
val (items, total) = queryPage(tableIndex, filter, offset = 0)
|
||||
_dbInspectState.value = DbInspectUiState(
|
||||
items = items,
|
||||
totalCount = total,
|
||||
hasMore = items.size < total,
|
||||
isLoading = false,
|
||||
filter = filter
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 追加加载下一页数据(点击"加载更多"时调用)
|
||||
* 筛选条件从当前 state 中复用,无需重新传入
|
||||
* @param tableIndex 0=菜品 1=食材 2=调料 3=槽位
|
||||
*/
|
||||
fun loadMoreDbInspect(tableIndex: Int) {
|
||||
viewModelScope.launch {
|
||||
val current = _dbInspectState.value
|
||||
// 已在加载中或无更多数据时直接返回,防止重复请求
|
||||
if (!current.hasMore || current.isLoading) return@launch
|
||||
_dbInspectState.value = current.copy(isLoading = true)
|
||||
val (newItems, total) = queryPage(tableIndex, current.filter, offset = current.items.size)
|
||||
val merged = current.items + newItems
|
||||
_dbInspectState.value = DbInspectUiState(
|
||||
items = merged,
|
||||
totalCount = total,
|
||||
hasMore = merged.size < total,
|
||||
isLoading = false,
|
||||
filter = current.filter
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行分页查询,返回 DbRecord 列表和总记录数
|
||||
* 通过 buildQueries 将 filter 转换为动态 SQL
|
||||
*/
|
||||
private suspend fun queryPage(
|
||||
tableIndex: Int,
|
||||
filter: DbInspectFilter,
|
||||
offset: Int
|
||||
): Pair<List<DbRecord>, Int> {
|
||||
val limit = DB_INSPECT_PAGE_SIZE
|
||||
return when (tableIndex) {
|
||||
0 -> {
|
||||
val (pageQ, countQ) = buildQueries("dm_cook_food", "createTime DESC", true, filter, limit, offset)
|
||||
val total = rep.countCookFoodFiltered(countQ)
|
||||
val rows = rep.getCookFoodPagedFiltered(pageQ).map { e ->
|
||||
DbRecord(
|
||||
isDel = e.isDel == 1,
|
||||
fields = listOf(
|
||||
"id" to "${e.id}", "foodId" to "${e.foodId}", "foodName" to "${e.foodName}",
|
||||
"canteenId" to "${e.canteenId}", "foodWeight" to "${e.foodWeight}", "cookMode" to "${e.cookMode}",
|
||||
"dinnerType" to "${e.dinnerType}", "isDel" to "${e.isDel}", "submitState" to "${e.submitState}",
|
||||
"createTime" to "${e.createTime}"
|
||||
)
|
||||
)
|
||||
}
|
||||
rows to total
|
||||
}
|
||||
1 -> {
|
||||
val (pageQ, countQ) = buildQueries("dm_cook_food_goods", "createTime DESC", true, filter, limit, offset)
|
||||
val total = rep.countCookFoodGoodsFiltered(countQ)
|
||||
val rows = rep.getCookFoodGoodsPagedFiltered(pageQ).map { e ->
|
||||
DbRecord(
|
||||
isDel = e.isDel == 1,
|
||||
fields = listOf(
|
||||
"id" to "${e.id}", "pid" to "${e.pid}", "goodsId" to "${e.goodsId}",
|
||||
"goodsName" to "${e.goodsName}", "foodId" to "${e.foodId}", "materialType" to "${e.materialType}",
|
||||
"relateionType" to "${e.relateionType}", "allEdible" to "${e.allEdible}", "useWeight" to "${e.useWeight}",
|
||||
"sort" to "${e.sort}", "zjmCode" to "${e.zjmCode}", "materId" to "${e.materId}",
|
||||
"isDel" to "${e.isDel}", "createTime" to "${e.createTime}"
|
||||
)
|
||||
)
|
||||
}
|
||||
rows to total
|
||||
}
|
||||
2 -> {
|
||||
val (pageQ, countQ) = buildQueries("dm_seasoning", "sort ASC", true, filter, limit, offset)
|
||||
val total = rep.countSeasoningFiltered(countQ)
|
||||
val rows = rep.getSeasoningPagedFiltered(pageQ).map { e ->
|
||||
DbRecord(
|
||||
isDel = e.isDel == 1,
|
||||
fields = listOf(
|
||||
"id" to "${e.id}", "goodsId" to "${e.goodsId}", "goodsName" to "${e.goodsName}",
|
||||
"sort" to "${e.sort}", "materialType" to "${e.materialType}", "useWeight" to "${e.useWeight}",
|
||||
"zjmCode" to "${e.zjmCode}", "materId" to "${e.materId}", "isDel" to "${e.isDel}",
|
||||
"createTime" to "${e.createTime}"
|
||||
)
|
||||
)
|
||||
}
|
||||
rows to total
|
||||
}
|
||||
3 -> {
|
||||
val (pageQ, countQ) = buildQueries("dm_seasoning_slot", "deviceId ASC, address ASC", false, filter, limit, offset)
|
||||
val total = rep.countSlotFiltered(countQ)
|
||||
val rows = rep.getSlotPagedFiltered(pageQ).map { e ->
|
||||
DbRecord(
|
||||
isDel = false,
|
||||
fields = listOf(
|
||||
"deviceId" to e.deviceId, "address" to "${e.address}",
|
||||
"goodsId" to e.goodsId, "goodsName" to e.goodsName
|
||||
),
|
||||
columnsPerRow = 1
|
||||
)
|
||||
}
|
||||
rows to total
|
||||
}
|
||||
else -> emptyList<DbRecord>() to 0
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据筛选条件动态构建分页查询和计数查询的 SQL
|
||||
* @param tableName 表名
|
||||
* @param orderBy ORDER BY 子句(不含关键字)
|
||||
* @param hasIsDel 是否有 isDel 字段,无则忽略 showDel 参数
|
||||
* @param filter 筛选条件
|
||||
* @param limit 分页大小
|
||||
* @param offset 偏移量
|
||||
* @return Pair<分页查询, 计数查询>
|
||||
*/
|
||||
private fun buildQueries(
|
||||
tableName: String,
|
||||
orderBy: String,
|
||||
hasIsDel: Boolean,
|
||||
filter: DbInspectFilter,
|
||||
limit: Int,
|
||||
offset: Int
|
||||
): Pair<SimpleSQLiteQuery, SimpleSQLiteQuery> {
|
||||
val conditions = mutableListOf<String>()
|
||||
val args = mutableListOf<Any>()
|
||||
|
||||
if (hasIsDel && !filter.showDel) {
|
||||
conditions.add("isDel = 0")
|
||||
}
|
||||
filter.exactFields.forEach { (col, value) ->
|
||||
if (value.isNotBlank()) {
|
||||
conditions.add("$col = ?")
|
||||
args.add(value)
|
||||
}
|
||||
}
|
||||
filter.likeFields.forEach { (col, value) ->
|
||||
if (value.isNotBlank()) {
|
||||
conditions.add("$col LIKE ?")
|
||||
args.add("%$value%")
|
||||
}
|
||||
}
|
||||
|
||||
val where = if (conditions.isEmpty()) "" else "WHERE ${conditions.joinToString(" AND ")}"
|
||||
val pageQuery = SimpleSQLiteQuery(
|
||||
"SELECT * FROM $tableName $where ORDER BY $orderBy LIMIT ? OFFSET ?",
|
||||
(args + limit + offset).toTypedArray()
|
||||
)
|
||||
val countQuery = SimpleSQLiteQuery(
|
||||
"SELECT COUNT(*) FROM $tableName $where",
|
||||
args.toTypedArray()
|
||||
)
|
||||
return pageQuery to countQuery
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------------------------------------
|
||||
|
||||
// viewModelScope.launch {
|
||||
// list.forEach {
|
||||
// rep.updateSeasoning(it)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
fun saveSeasoning(entity: SeasoningEntity, block: () -> Unit) {
|
||||
viewModelScope.launch {
|
||||
val list = rep.getSeasoningBySort(entity.sort)
|
||||
val size = list?.size?:0
|
||||
if (size == 1) {
|
||||
rep.updateSeasoning(entity.also { it.id = list!![0].id })
|
||||
block()
|
||||
return@launch
|
||||
}
|
||||
if (size > 1) {
|
||||
list?.forEach {
|
||||
rep.deleteSeasoningBySort(it.sort)
|
||||
}
|
||||
}
|
||||
entity.id = 0
|
||||
val id = rep.insertSeasoning(entity)
|
||||
entity.id = id
|
||||
block()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 goodsId 查重后 upsert 调料数据,确保同一 goodsId 只有一条记录
|
||||
*/
|
||||
suspend fun upsertSeasoningByGoodsId(entity: SeasoningEntity) {
|
||||
rep.upsertSeasoningByGoodsId(entity)
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 goodsId 查询调料详情
|
||||
*/
|
||||
suspend fun getSeasoningByGoodsId(goodsId: String): SeasoningEntity? {
|
||||
return rep.getSeasoningByGoodsId(goodsId)
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 已采集食材列表 UI 状态流
|
||||
* 元素为按名称分组后的(名称,数量)数据
|
||||
*/
|
||||
private val _collectedFoodListState = MutableStateFlow<List<CollectedFoodItem>>(emptyList())
|
||||
val collectedFoodListState: StateFlow<List<CollectedFoodItem>> = _collectedFoodListState.asStateFlow()
|
||||
|
||||
/**
|
||||
* 加载已采集食材列表,按名称分组统计数量
|
||||
* 使用属性查询只读 name 字段,不加载 foodVector,节省内存
|
||||
* @param nameFilter 名称过滤关键词,为空时加载全部
|
||||
*/
|
||||
fun loadCollectedFoodList(nameFilter: String? = null) {
|
||||
viewModelScope.launch {
|
||||
val result = ObjectBox.queryFoodNameCounts(nameFilter)
|
||||
_collectedFoodListState.value = result.map { (name, count) ->
|
||||
CollectedFoodItem(foodName = name, collectCount = count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除指定名称的所有采集记录,删除完成后刷新列表
|
||||
* @param foodName 食材名称
|
||||
* @param nameFilter 当前搜索关键词,用于删除后刷新列表
|
||||
*/
|
||||
fun removeCollectedFood(foodName: String, nameFilter: String? = null) {
|
||||
viewModelScope.launch {
|
||||
ObjectBox.remove(foodName)
|
||||
loadCollectedFoodList(nameFilter)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除所有向量采集数据,完成后刷新列表
|
||||
* @param onDone 清除完成后在主线程执行的回调
|
||||
*/
|
||||
fun clearAllCollectedFood(onDone: (() -> Unit)? = null) {
|
||||
viewModelScope.launch {
|
||||
ObjectBox.removeAll()
|
||||
loadCollectedFoodList()
|
||||
onDone?.invoke()
|
||||
}
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------------------------------------
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package com.shuwei.dish.match.db.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Update
|
||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
interface AppDao {
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertCookFood(item: CookFoodEntity): Long
|
||||
|
||||
@Update
|
||||
suspend fun updateCookFood(item: CookFoodEntity)
|
||||
|
||||
@Query("SELECT * FROM dm_cook_food WHERE isDel = 0 AND canteenId = :canteenId AND foodId = :foodId AND cookMode = :cookMode")
|
||||
suspend fun getCookFoodById(canteenId:String, foodId: String, cookMode: Int): CookFoodEntity?
|
||||
|
||||
@Query("SELECT * FROM dm_cook_food WHERE isDel = 0 AND canteenId = :canteenId AND cookMode = :cookMode AND dinnerType = :dinnerType ORDER BY createTime DESC")
|
||||
suspend fun getCookFoodList(canteenId:String, cookMode: Int, dinnerType:String): MutableList<CookFoodEntity>?
|
||||
|
||||
@Query("SELECT count(1) FROM dm_cook_food WHERE isDel = 0 AND canteenId = :canteenId AND cookMode = :cookMode")
|
||||
suspend fun countCookFood(canteenId:String, cookMode: Int): Int
|
||||
|
||||
@Query("DELETE FROM dm_cook_food WHERE canteenId = :canteenId AND foodId = :foodId AND cookMode = :cookMode")
|
||||
suspend fun deleteCookFood(canteenId:String, foodId: String, cookMode: Int)
|
||||
|
||||
//--------------------------------------------------------------------------------------------
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertGoods(item: CookFoodGoodsEntity): Long
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertGoodsList(items: MutableList<CookFoodGoodsEntity>): Array<Long>
|
||||
|
||||
@Update
|
||||
suspend fun updateGoods(item: CookFoodGoodsEntity)
|
||||
|
||||
@Query("SELECT * FROM dm_cook_food_goods WHERE isDel = 0 AND pid = :pid AND foodId = :foodId")
|
||||
suspend fun getCookFoodGoodsList(pid:Long, foodId: String): MutableList<CookFoodGoodsEntity>
|
||||
|
||||
@Query("SELECT * FROM dm_cook_food_goods WHERE isDel = 0 AND foodId = :foodId AND materialType = :materialType")
|
||||
suspend fun getCookFoodGoodsListByType(
|
||||
foodId: String,
|
||||
materialType: Int
|
||||
): MutableList<CookFoodGoodsEntity>
|
||||
|
||||
@Query("DELETE FROM dm_cook_food_goods WHERE pid = :pid AND foodId = :foodId")
|
||||
suspend fun deleteCookFoodGoodsList(pid:Long, foodId: String)
|
||||
|
||||
//--------------------------------------------------------------------------------------------
|
||||
|
||||
@Query("SELECT * FROM dm_seasoning WHERE isDel = 0 AND id = :id")
|
||||
suspend fun getSeasoningById(id: Long): SeasoningEntity?
|
||||
|
||||
@Query("SELECT * FROM dm_seasoning WHERE isDel = 0 AND sort = :sort")
|
||||
suspend fun getSeasoningBySort(sort: Int): MutableList<SeasoningEntity>?
|
||||
|
||||
@Query("SELECT * FROM dm_seasoning WHERE isDel = 0 AND goodsId = :goodsId")
|
||||
suspend fun getSeasoningByGoodsId(goodsId: Int): SeasoningEntity?
|
||||
|
||||
// @Query("SELECT * FROM dm_seasoning WHERE isDel = 0 AND goodsId != -1 AND goodsName != '' ORDER BY sort ASC")
|
||||
// fun getAllStream(): Flow<MutableList<SeasoningEntity>>
|
||||
|
||||
@Query("SELECT * FROM dm_seasoning WHERE isDel = 0 AND goodsId != -1 AND goodsName != '' ORDER BY sort ASC")
|
||||
fun getAllStream(): MutableList<SeasoningEntity>
|
||||
|
||||
@Query("SELECT * FROM dm_seasoning WHERE isDel = 0 AND goodsName LIKE '%' || :query || '%'")
|
||||
suspend fun search(query: String): MutableList<SeasoningEntity>
|
||||
|
||||
@Query("DELETE FROM dm_seasoning WHERE isDel = 0 AND sort = :sort")
|
||||
suspend fun deleteSeasoningBySort(sort:Int): Int
|
||||
|
||||
@Query("DELETE FROM dm_seasoning WHERE isDel = 0")
|
||||
suspend fun clearAllSeasoning(): Int
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertSeasoningList(items: MutableList<SeasoningEntity>): Array<Long>
|
||||
|
||||
@Update
|
||||
suspend fun updateSeasoning(item: SeasoningEntity)
|
||||
|
||||
@Insert
|
||||
suspend fun insertSeasoning(item: SeasoningEntity): Long
|
||||
//--------------------------------------------------------------------------------------------
|
||||
}
|
||||
@@ -1,20 +1,61 @@
|
||||
//package com.shuwei.dish.match.db.dao
|
||||
//
|
||||
//import androidx.room.Dao
|
||||
//import androidx.room.Query
|
||||
//import com.shuwei.dish.match.db.BaseDao
|
||||
//import com.shuwei.dish.match.entity.CookFoodEntity
|
||||
//
|
||||
//@Dao
|
||||
//interface CookFoodDao : BaseDao<CookFoodEntity> {
|
||||
//
|
||||
// @Query("SELECT * FROM dm_cook_food WHERE isDel = 0 AND foodId = :foodId AND cookMode = :cookMode")
|
||||
// suspend fun getCookFoodById(foodId: String, cookMode:Int): CookFoodEntity?
|
||||
//
|
||||
// @Query("SELECT * FROM dm_cook_food WHERE isDel = 0 AND cookMode = :cookMode")
|
||||
// suspend fun getCookFoodList(cookMode:Int): MutableList<CookFoodEntity>?
|
||||
//
|
||||
// @Query("SELECT count(1) FROM dm_cook_food WHERE isDel = 0 AND cookMode = :cookMode")
|
||||
// suspend fun countCookFood(cookMode:Int): Int
|
||||
//
|
||||
//}
|
||||
package com.shuwei.dish.match.db.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.RawQuery
|
||||
import androidx.room.Update
|
||||
import androidx.sqlite.db.SupportSQLiteQuery
|
||||
import com.shuwei.dish.match.db.entity.CookFoodEntity
|
||||
|
||||
@Dao
|
||||
interface CookFoodDao {
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertCookFood(item: CookFoodEntity): Long
|
||||
|
||||
@Update
|
||||
suspend fun updateCookFood(item: CookFoodEntity)
|
||||
|
||||
@Query("SELECT * FROM dm_cook_food WHERE isDel = 0 AND canteenId = :canteenId AND foodId = :foodId AND cookMode = :cookMode AND dinnerType = :dinnerType")
|
||||
suspend fun getCookFoodById(canteenId: String, foodId: String, cookMode: Int, dinnerType: String): CookFoodEntity?
|
||||
|
||||
@Query("SELECT * FROM dm_cook_food WHERE isDel = 0 AND canteenId = :canteenId AND cookMode = :cookMode AND dinnerType = :dinnerType ORDER BY createTime DESC")
|
||||
suspend fun getCookFoodList(canteenId: String, cookMode: Int, dinnerType: String): MutableList<CookFoodEntity>?
|
||||
|
||||
@Query("SELECT count(1) FROM dm_cook_food WHERE isDel = 0 AND canteenId = :canteenId AND cookMode = :cookMode")
|
||||
suspend fun countCookFood(canteenId: String, cookMode: Int): Int
|
||||
|
||||
// @Query("DELETE FROM dm_cook_food WHERE canteenId = :canteenId AND foodId = :foodId AND cookMode = :cookMode")
|
||||
@Query("UPDATE dm_cook_food SET isDel = 1 WHERE isDel = 0 AND canteenId = :canteenId AND foodId = :foodId AND cookMode = :cookMode AND dinnerType = :dinnerType")
|
||||
suspend fun deleteCookFood(canteenId: String, foodId: String, cookMode: Int, dinnerType: String)
|
||||
|
||||
/** 接口提交成功后逻辑删除菜品,同时把 submitState 置 1 以便在数据库审计中区分手动删除 */
|
||||
@Query("UPDATE dm_cook_food SET isDel = 1, submitState = 1 WHERE isDel = 0 AND canteenId = :canteenId AND foodId = :foodId AND cookMode = :cookMode AND dinnerType = :dinnerType")
|
||||
suspend fun markSubmittedAndDelete(canteenId: String, foodId: String, cookMode: Int, dinnerType: String)
|
||||
|
||||
/** 查询全部菜品记录(含已删除),用于数据库调试查看 */
|
||||
@Query("SELECT * FROM dm_cook_food ORDER BY createTime DESC")
|
||||
suspend fun getAllCookFood(): MutableList<CookFoodEntity>
|
||||
|
||||
/** 分页查询菜品记录,showDel=true 时包含已删除记录 */
|
||||
@Query("SELECT * FROM dm_cook_food WHERE (:showDel = 1 OR isDel = 0) ORDER BY createTime DESC LIMIT :limit OFFSET :offset")
|
||||
suspend fun getCookFoodPaged(showDel: Int, limit: Int, offset: Int): List<CookFoodEntity>
|
||||
|
||||
/** 统计菜品记录总数,showDel=true 时包含已删除记录 */
|
||||
@Query("SELECT COUNT(*) FROM dm_cook_food WHERE (:showDel = 1 OR isDel = 0)")
|
||||
suspend fun countCookFoodAll(showDel: Int): Int
|
||||
|
||||
/** 物理清空全表,用于清除测试数据 */
|
||||
@Query("DELETE FROM dm_cook_food")
|
||||
suspend fun deleteAll()
|
||||
|
||||
/** 动态条件分页查询菜品记录,由 ViewModel 构建 SQL */
|
||||
@RawQuery
|
||||
suspend fun queryPagedFiltered(query: SupportSQLiteQuery): List<CookFoodEntity>
|
||||
|
||||
/** 动态条件统计菜品记录总数,由 ViewModel 构建 SQL */
|
||||
@RawQuery
|
||||
suspend fun countFiltered(query: SupportSQLiteQuery): Int
|
||||
}
|
||||
|
||||
@@ -1,29 +1,61 @@
|
||||
//package com.shuwei.dish.match.db.dao
|
||||
//
|
||||
//import androidx.room.Dao
|
||||
//import androidx.room.Query
|
||||
//import com.shuwei.dish.match.db.BaseDao
|
||||
//import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
//
|
||||
//@Dao
|
||||
//interface CookFoodGoodsDao : BaseDao<CookFoodGoodsEntity> {
|
||||
//
|
||||
// @Query("SELECT * FROM dm_cook_food_goods WHERE isDel = 0 AND foodId = :foodId")
|
||||
// suspend fun getCookFoodGoodsList(foodId: String): MutableList<CookFoodGoodsEntity>
|
||||
//
|
||||
// @Query("SELECT * FROM dm_cook_food_goods WHERE isDel = 0 AND foodId = :foodId AND materialType = :materialType")
|
||||
// suspend fun getCookFoodGoodsListByType(foodId: String, materialType:Int): MutableList<CookFoodGoodsEntity>
|
||||
//
|
||||
//// @Query(
|
||||
//// """
|
||||
//// UPDATE dm_cook_food_goods
|
||||
//// SET goodsName=:entity.goodsName, foodId=:entity.foodId, relateionType=:entity.relateionType, sort=:entity.sort
|
||||
//// allEdible=:entity.allEdible, useWeight=:entity.useWeight, isDel=:entity.isDel, createTime=:entity.createTime
|
||||
//// WHERE isDel = 0
|
||||
//// AND foodId=:entity.foodId
|
||||
//// AND goodsId=:goodsId
|
||||
//// """
|
||||
//// )
|
||||
//// fun updateByGoodsId(entity: CookFoodGoodsEntity)
|
||||
//
|
||||
//}
|
||||
package com.shuwei.dish.match.db.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.RawQuery
|
||||
import androidx.room.Update
|
||||
import androidx.sqlite.db.SupportSQLiteQuery
|
||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||
|
||||
@Dao
|
||||
interface CookFoodGoodsDao {
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertGoods(item: CookFoodGoodsEntity): Long
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertGoodsList(items: MutableList<CookFoodGoodsEntity>): Array<Long>
|
||||
|
||||
@Update
|
||||
suspend fun updateGoods(item: CookFoodGoodsEntity)
|
||||
|
||||
@Query("SELECT * FROM dm_cook_food_goods WHERE isDel = 0 AND pid = :pid AND foodId = :foodId")
|
||||
suspend fun getCookFoodGoodsList(pid: Long, foodId: String): MutableList<CookFoodGoodsEntity>
|
||||
|
||||
@Query("SELECT * FROM dm_cook_food_goods WHERE isDel = 0 AND foodId = :foodId AND materialType = :materialType")
|
||||
suspend fun getCookFoodGoodsListByType(foodId: String, materialType: Int): MutableList<CookFoodGoodsEntity>
|
||||
|
||||
// @Query("DELETE FROM dm_cook_food_goods WHERE pid = :pid AND foodId = :foodId")
|
||||
@Query("UPDATE dm_cook_food_goods SET isDel = 1 WHERE isDel = 0 AND pid = :pid AND foodId = :foodId")
|
||||
suspend fun deleteCookFoodGoodsList(pid: Long, foodId: String)
|
||||
|
||||
/** 仅逻辑删除调料行(materialType = 3),主辅材不动,用于 cook 时只重建调料部分 */
|
||||
@Query("UPDATE dm_cook_food_goods SET isDel = 1 WHERE isDel = 0 AND pid = :pid AND foodId = :foodId AND materialType = 3")
|
||||
suspend fun deleteSeasoningOnly(pid: Long, foodId: String)
|
||||
|
||||
/** 查询全部食材记录(含已删除),用于数据库调试查看 */
|
||||
@Query("SELECT * FROM dm_cook_food_goods ORDER BY createTime DESC")
|
||||
suspend fun getAllCookFoodGoods(): MutableList<CookFoodGoodsEntity>
|
||||
|
||||
/** 分页查询食材记录,showDel=true 时包含已删除记录 */
|
||||
@Query("SELECT * FROM dm_cook_food_goods WHERE (:showDel = 1 OR isDel = 0) ORDER BY createTime DESC LIMIT :limit OFFSET :offset")
|
||||
suspend fun getCookFoodGoodsPaged(showDel: Int, limit: Int, offset: Int): List<CookFoodGoodsEntity>
|
||||
|
||||
/** 统计食材记录总数,showDel=true 时包含已删除记录 */
|
||||
@Query("SELECT COUNT(*) FROM dm_cook_food_goods WHERE (:showDel = 1 OR isDel = 0)")
|
||||
suspend fun countCookFoodGoodsAll(showDel: Int): Int
|
||||
|
||||
/** 物理清空全表,用于清除测试数据 */
|
||||
@Query("DELETE FROM dm_cook_food_goods")
|
||||
suspend fun deleteAll()
|
||||
|
||||
/** 动态条件分页查询食材记录,由 ViewModel 构建 SQL */
|
||||
@RawQuery
|
||||
suspend fun queryPagedFiltered(query: SupportSQLiteQuery): List<CookFoodGoodsEntity>
|
||||
|
||||
/** 动态条件统计食材记录总数,由 ViewModel 构建 SQL */
|
||||
@RawQuery
|
||||
suspend fun countFiltered(query: SupportSQLiteQuery): Int
|
||||
}
|
||||
|
||||
@@ -1,25 +1,70 @@
|
||||
//package com.shuwei.dish.match.db.dao
|
||||
//
|
||||
//import androidx.room.Dao
|
||||
//import androidx.room.Query
|
||||
//import com.shuwei.dish.match.db.BaseDao
|
||||
//import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
//import kotlinx.coroutines.flow.Flow
|
||||
//
|
||||
//@Dao
|
||||
//interface SeasoningDao : BaseDao<SeasoningEntity> {
|
||||
//
|
||||
//// @Query("SELECT * FROM dm_seasoning WHERE isDel = 0 AND id = :id")
|
||||
//// suspend fun getSeasoningById(id: Long): SeasoningEntity?
|
||||
////
|
||||
//// @Query("SELECT * FROM dm_seasoning WHERE isDel = 0 ORDER BY sort ASC")
|
||||
//// fun getAllStream(): Flow<MutableList<SeasoningEntity>>
|
||||
////
|
||||
//// @Query("SELECT * FROM dm_seasoning WHERE isDel = 0 AND name LIKE '%' || :query || '%'")
|
||||
//// suspend fun search(query: String): MutableList<SeasoningEntity>
|
||||
////
|
||||
//// @Query("DELETE FROM dm_seasoning WHERE rowid IN " +
|
||||
//// "(SELECT rowid FROM dm_seasoning LIMIT 1000)")
|
||||
//// suspend fun deleteBatch(): Int
|
||||
//
|
||||
//}
|
||||
package com.shuwei.dish.match.db.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.RawQuery
|
||||
import androidx.room.Update
|
||||
import androidx.sqlite.db.SupportSQLiteQuery
|
||||
import com.shuwei.dish.match.db.entity.SeasoningEntity
|
||||
|
||||
@Dao
|
||||
interface SeasoningDao {
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertSeasoning(item: SeasoningEntity): Long
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertSeasoningList(items: MutableList<SeasoningEntity>): Array<Long>
|
||||
|
||||
@Update
|
||||
suspend fun updateSeasoning(item: SeasoningEntity)
|
||||
|
||||
@Query("SELECT * FROM dm_seasoning WHERE isDel = 0 AND id = :id")
|
||||
suspend fun getSeasoningById(id: Long): SeasoningEntity?
|
||||
|
||||
@Query("SELECT * FROM dm_seasoning WHERE isDel = 0 AND sort = :sort")
|
||||
suspend fun getSeasoningBySort(sort: Int): MutableList<SeasoningEntity>?
|
||||
|
||||
@Query("SELECT * FROM dm_seasoning WHERE isDel = 0 AND goodsId = :goodsId")
|
||||
suspend fun getSeasoningByGoodsId(goodsId: String): SeasoningEntity?
|
||||
|
||||
@Query("SELECT * FROM dm_seasoning WHERE isDel = 0 AND goodsId != -1 AND goodsName != '' ORDER BY sort ASC")
|
||||
fun getAllStream(): MutableList<SeasoningEntity>
|
||||
|
||||
@Query("SELECT * FROM dm_seasoning WHERE isDel = 0 AND goodsName LIKE '%' || :query || '%'")
|
||||
suspend fun search(query: String): MutableList<SeasoningEntity>
|
||||
|
||||
// @Query("DELETE FROM dm_seasoning WHERE isDel = 0 AND sort = :sort")
|
||||
@Query("UPDATE dm_seasoning SET isDel = 1 WHERE isDel = 0 AND sort = :sort")
|
||||
suspend fun deleteSeasoningBySort(sort: Int): Int
|
||||
|
||||
// @Query("DELETE FROM dm_seasoning WHERE isDel = 0")
|
||||
@Query("UPDATE dm_seasoning SET isDel = 1 WHERE isDel = 0")
|
||||
suspend fun clearAllSeasoning(): Int
|
||||
|
||||
/** 查询全部调料记录(含已删除),用于数据库调试查看 */
|
||||
@Query("SELECT * FROM dm_seasoning ORDER BY sort ASC")
|
||||
suspend fun getAllSeasoning(): MutableList<SeasoningEntity>
|
||||
|
||||
/** 分页查询调料记录,showDel=true 时包含已删除记录 */
|
||||
@Query("SELECT * FROM dm_seasoning WHERE (:showDel = 1 OR isDel = 0) ORDER BY sort ASC LIMIT :limit OFFSET :offset")
|
||||
suspend fun getSeasoningPaged(showDel: Int, limit: Int, offset: Int): List<SeasoningEntity>
|
||||
|
||||
/** 统计调料记录总数,showDel=true 时包含已删除记录 */
|
||||
@Query("SELECT COUNT(*) FROM dm_seasoning WHERE (:showDel = 1 OR isDel = 0)")
|
||||
suspend fun countSeasoningAll(showDel: Int): Int
|
||||
|
||||
/** 物理清空全表,用于清除测试数据(比 clearAllSeasoning 的逻辑删除更彻底) */
|
||||
@Query("DELETE FROM dm_seasoning")
|
||||
suspend fun deleteAll()
|
||||
|
||||
/** 动态条件分页查询调料记录,由 ViewModel 构建 SQL */
|
||||
@RawQuery
|
||||
suspend fun queryPagedFiltered(query: SupportSQLiteQuery): List<SeasoningEntity>
|
||||
|
||||
/** 动态条件统计调料记录总数,由 ViewModel 构建 SQL */
|
||||
@RawQuery
|
||||
suspend fun countFiltered(query: SupportSQLiteQuery): Int
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.shuwei.dish.match.db.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.RawQuery
|
||||
import androidx.sqlite.db.SupportSQLiteQuery
|
||||
import com.shuwei.dish.match.db.entity.SeasoningSlotEntity
|
||||
|
||||
/**
|
||||
* 调料槽位配置 DAO
|
||||
* 以 (deviceId, address) 为主键做 upsert,保证同一槽位只保留最新配置
|
||||
*/
|
||||
@Dao
|
||||
interface SeasoningSlotDao {
|
||||
|
||||
/**
|
||||
* 插入或更新单个槽位配置(主键冲突时覆盖)
|
||||
*/
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsert(slot: SeasoningSlotEntity)
|
||||
|
||||
/**
|
||||
* 批量插入或更新槽位配置(主设备广播全量时使用)
|
||||
*/
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertAll(slots: List<SeasoningSlotEntity>)
|
||||
|
||||
/**
|
||||
* 查询指定设备的全部槽位配置
|
||||
* @param deviceId 目标设备 ID
|
||||
*/
|
||||
@Query("SELECT * FROM dm_seasoning_slot WHERE deviceId = :deviceId")
|
||||
suspend fun queryByDeviceId(deviceId: String): List<SeasoningSlotEntity>
|
||||
|
||||
/**
|
||||
* 查询所有设备的全部槽位配置(主设备广播时使用)
|
||||
*/
|
||||
@Query("SELECT * FROM dm_seasoning_slot")
|
||||
suspend fun queryAll(): List<SeasoningSlotEntity>
|
||||
|
||||
/** 分页查询槽位记录(槽位表无 isDel,showDel 参数忽略) */
|
||||
@Query("SELECT * FROM dm_seasoning_slot ORDER BY deviceId ASC, address ASC LIMIT :limit OFFSET :offset")
|
||||
suspend fun getSlotPaged(limit: Int, offset: Int): List<SeasoningSlotEntity>
|
||||
|
||||
/** 统计槽位记录总数 */
|
||||
@Query("SELECT COUNT(*) FROM dm_seasoning_slot")
|
||||
suspend fun countSlotAll(): Int
|
||||
|
||||
/**
|
||||
* 删除指定设备的指定槽位配置
|
||||
* @param deviceId 目标设备 ID
|
||||
* @param address 秤硬件地址
|
||||
*/
|
||||
@Query("DELETE FROM dm_seasoning_slot WHERE deviceId = :deviceId AND address = :address")
|
||||
suspend fun deleteByDeviceIdAndAddress(deviceId: String, address: Int)
|
||||
|
||||
/**
|
||||
* 删除指定设备的全部槽位配置(子设备接收全量广播时先清空再写入)
|
||||
* @param deviceId 目标设备 ID
|
||||
*/
|
||||
@Query("DELETE FROM dm_seasoning_slot WHERE deviceId = :deviceId")
|
||||
suspend fun deleteAllByDeviceId(deviceId: String)
|
||||
|
||||
/** 物理清空全表,用于清除测试数据 */
|
||||
@Query("DELETE FROM dm_seasoning_slot")
|
||||
suspend fun deleteAll()
|
||||
|
||||
/** 动态条件分页查询槽位记录,由 ViewModel 构建 SQL */
|
||||
@RawQuery
|
||||
suspend fun queryPagedFiltered(query: SupportSQLiteQuery): List<SeasoningSlotEntity>
|
||||
|
||||
/** 动态条件统计槽位记录总数,由 ViewModel 构建 SQL */
|
||||
@RawQuery
|
||||
suspend fun countFiltered(query: SupportSQLiteQuery): Int
|
||||
}
|
||||
+5
-3
@@ -1,4 +1,4 @@
|
||||
package com.shuwei.dish.match.entity
|
||||
package com.shuwei.dish.match.db.entity
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Ignore
|
||||
@@ -18,11 +18,13 @@ data class CookFoodEntity(
|
||||
//0-制作模式,1-采样模式,2-品控模式
|
||||
var cookMode:Int = 0,
|
||||
var isDel: Int = 0,
|
||||
/** 接口提交状态:0-未提交(本地草稿或手动删除),1-接口提交成功后删除 */
|
||||
var submitState: Int = 0,
|
||||
var createTime: String = DateTimeUtil.formatDateTime(LocalDateTime.now()),
|
||||
var dinnerType: String? = "0",
|
||||
) : BaseEntity {
|
||||
@Ignore
|
||||
var stFoodInfoConstituteList: MutableList<CookFoodGoodsEntity>? = null
|
||||
// @Ignore
|
||||
// var stFoodInfoConstituteList: MutableList<CookFoodGoodsEntity>? = null
|
||||
@Ignore
|
||||
var matchingConstituteInfoList: MutableList<CookFoodGoodsEntity>? = null
|
||||
@Ignore
|
||||
+30
-21
@@ -1,9 +1,9 @@
|
||||
package com.shuwei.dish.match.entity
|
||||
package com.shuwei.dish.match.db.entity
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Ignore
|
||||
import androidx.room.PrimaryKey
|
||||
import com.shuwei.dish.match.db.BaseEntity
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
import com.shuwei.dish.match.utils.DateTimeUtil
|
||||
import java.io.Serializable
|
||||
import java.time.LocalDateTime
|
||||
@@ -63,27 +63,36 @@ class CookFoodGoodsEntity(
|
||||
|
||||
var relateionType_dictText: String? = "",
|
||||
|
||||
var zjmCode: String? = "",
|
||||
|
||||
var materId: String? = "",
|
||||
|
||||
/** 物料编码 */
|
||||
var goodsCode: String? = "",
|
||||
|
||||
/** 净材种类 */
|
||||
var rawMaterialsType: String? = null,
|
||||
|
||||
var isDel: Int = 0,
|
||||
var createTime: String = DateTimeUtil.formatDateTime(LocalDateTime.now())
|
||||
) : BaseEntity, Serializable {
|
||||
constructor() : this(goodsId = "") // 必需的空构造,
|
||||
constructor() : this(goodsId = "") // 必需的空构造
|
||||
|
||||
@Ignore
|
||||
var isSetFinished: Boolean = false
|
||||
|
||||
@Ignore
|
||||
var isItemClicked: Boolean = false
|
||||
|
||||
@Ignore
|
||||
var isSamplingPage: Boolean = false
|
||||
|
||||
@Ignore
|
||||
var isNewDishType: Boolean = false
|
||||
|
||||
@Ignore
|
||||
var isClicked: Boolean = false
|
||||
|
||||
//true-原始数据,false-非原始数据
|
||||
@Ignore
|
||||
var isOriginalData: Boolean = true
|
||||
/**
|
||||
* 转换为 GoodsItem,用于 UI 层(DishPartAdapter、PrepareFoodActivity 等)
|
||||
*/
|
||||
fun toGoodsItem(): GoodsItem = GoodsItem(
|
||||
goodsId = goodsId,
|
||||
goodsName = goodsName,
|
||||
popularName = popularName,
|
||||
zjmCode = zjmCode,
|
||||
materId = materId,
|
||||
materCode = goodsCode,
|
||||
materialType = materialType,
|
||||
useWeight = useWeight,
|
||||
relateionType = relateionType,
|
||||
allEdible = allEdible,
|
||||
goodsOrRelationCode = goodsOrRelationCode,
|
||||
rawMaterialsType = rawMaterialsType
|
||||
)
|
||||
}
|
||||
+11
-8
@@ -1,7 +1,6 @@
|
||||
package com.shuwei.dish.match.entity
|
||||
package com.shuwei.dish.match.db.entity
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Ignore
|
||||
import androidx.room.PrimaryKey
|
||||
import com.shuwei.dish.match.db.BaseEntity
|
||||
import com.shuwei.dish.match.utils.DateTimeUtil
|
||||
@@ -55,6 +54,16 @@ data class SeasoningEntity(
|
||||
|
||||
var relateionType_dictText: String? = "",
|
||||
|
||||
var zjmCode: String? = "",
|
||||
|
||||
var materId: String? = "",
|
||||
|
||||
/** 物料编码 */
|
||||
var goodsCode: String? = "",
|
||||
|
||||
/** 净材种类 */
|
||||
var rawMaterialsType: String? = null,
|
||||
|
||||
var sort: Int = 9999,
|
||||
/**
|
||||
* isDel表示数据是否已删除,1-已删除,为无效数据,0-正常使用,有效数据
|
||||
@@ -62,11 +71,5 @@ data class SeasoningEntity(
|
||||
var isDel: Int = 0,
|
||||
var createTime: String = DateTimeUtil.formatDateTime(LocalDateTime.now())
|
||||
) : BaseEntity {
|
||||
@Ignore
|
||||
var pageType: Int = 0
|
||||
|
||||
@Ignore
|
||||
var isClicked: Boolean = false
|
||||
|
||||
constructor() : this(goodsId = "") // 必需的空构造
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.shuwei.dish.match.db.entity
|
||||
|
||||
import androidx.room.Entity
|
||||
|
||||
/**
|
||||
* 调料槽位配置表,记录每个格子对应哪种调料
|
||||
* 主键为 (deviceId, address) 组合,唯一标识一个物理秤槽位
|
||||
*
|
||||
* @param deviceId 所属设备 ID,用于区分 22格/18格 设备
|
||||
* @param address 秤硬件地址,对应 ScaleDeviceConfig.SCALE_ORDER_22/18 中的值
|
||||
* @param goodsId 调料 ID
|
||||
* @param goodsName 调料名称,用于 adapter 展示
|
||||
*/
|
||||
@Entity(
|
||||
tableName = "dm_seasoning_slot",
|
||||
primaryKeys = ["deviceId", "address"]
|
||||
)
|
||||
data class SeasoningSlotEntity(
|
||||
val deviceId: String,
|
||||
val address: Int,
|
||||
val goodsId: String,
|
||||
val goodsName: String
|
||||
)
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.shuwei.dish.match.dialog
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Dialog
|
||||
import android.content.Context
|
||||
import android.graphics.drawable.ColorDrawable
|
||||
@@ -8,13 +7,13 @@ import android.os.Bundle
|
||||
import android.view.View
|
||||
import android.view.Window
|
||||
import android.widget.LinearLayout
|
||||
import androidx.annotation.StyleRes
|
||||
import android.widget.TextView
|
||||
import androidx.core.view.updateLayoutParams
|
||||
import com.shuwei.dish.match.base.DeviceRole
|
||||
import com.shuwei.dish.match.base.GlobalData
|
||||
import com.shuwei.dish.match.databinding.DialogCommonBinding
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import java.lang.ref.WeakReference
|
||||
import com.shuwei.dish.match.R
|
||||
|
||||
open class CommonDialog(
|
||||
context: Context
|
||||
@@ -23,62 +22,137 @@ open class CommonDialog(
|
||||
private lateinit var binding: DialogCommonBinding
|
||||
|
||||
private var titleText: String? = null
|
||||
private var contentText: 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
|
||||
private var positiveClick: (() -> Unit)? = null
|
||||
// 返回 true 时关闭弹窗,返回 false 时保持弹窗显示(用于校验不通过的场景)
|
||||
private var positiveClick: (() -> Boolean)? = null
|
||||
private var neutralClick: (() -> Unit)? = null
|
||||
private var singleClick: (() -> Unit)? = null
|
||||
private var dismissCallback: (() -> Unit)? = null
|
||||
// 待添加到 llContent 的自定义 View,在 onCreate 后挂载
|
||||
private var pendingContentView: View? = null
|
||||
// pendingContentView 非空时对 tvContent 的灵活控制回调(可调整可见性、间距等)
|
||||
private var tvContentConfigurator: ((TextView) -> Unit)? = null
|
||||
|
||||
/** 设置标题,为空时隐藏 */
|
||||
fun setTitle(text: String): CommonDialog = apply { titleText = text }
|
||||
|
||||
/** 设置内容,为空时隐藏 */
|
||||
fun setContent(text: String): CommonDialog = apply { contentText = 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?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
requestWindowFeature(Window.FEATURE_NO_TITLE)
|
||||
binding = DialogCommonBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
// 弹窗不允许点击外部关闭
|
||||
setCancelable(false)
|
||||
val isMaster = GlobalData.deviceRole == DeviceRole.MASTER
|
||||
window?.run {
|
||||
val screenWidth = context.resources.displayMetrics.widthPixels
|
||||
val isMaster = GlobalData.deviceRole == DeviceRole.MASTER
|
||||
attributes = attributes.apply {
|
||||
width = if (isMaster) (screenWidth * 0.72f).toInt() else (screenWidth * 0.60f).toInt()
|
||||
}
|
||||
// 透明背景,让 shape_dialog_bg 的阴影层正常显示
|
||||
setBackgroundDrawable(ColorDrawable())
|
||||
setCancelable(false)
|
||||
// 应用缩放+淡入淡出动画
|
||||
setWindowAnimations(R.style.CommonDialogAnimation)
|
||||
}
|
||||
val verticalMargin = if (GlobalData.deviceRole == DeviceRole.MASTER) 35.dp else 20.dp
|
||||
// 主/从设备边距微调:主设备内容区域更大,适当增加上下留白
|
||||
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 {
|
||||
positiveClick?.invoke()
|
||||
// 回调返回 false 时阻止关闭,null 或 true 时正常关闭
|
||||
if (positiveClick?.invoke() != false) dismiss()
|
||||
}
|
||||
|
||||
// 3按钮点击事件(negativeClick/positiveClick 与2按钮模式共用)
|
||||
binding.btnTop.setOnClickListener {
|
||||
negativeClick?.invoke()
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
override fun show() {
|
||||
@@ -87,18 +161,25 @@ open class CommonDialog(
|
||||
binding.tvContent.text = contentText
|
||||
binding.tvTitle.visibility = if (titleText.isNullOrEmpty()) View.GONE else View.VISIBLE
|
||||
binding.tvContent.visibility = if (contentText.isNullOrEmpty()) View.GONE else View.VISIBLE
|
||||
binding.btnLeft.text = negativeText
|
||||
binding.btnRight.text = positiveText
|
||||
}
|
||||
}
|
||||
|
||||
open class SafeDialog(activity: Activity, @StyleRes themeResId: Int) :
|
||||
Dialog(activity, themeResId) {
|
||||
private val weakContext = WeakReference(activity)
|
||||
val hasThreeButtons = !neutralText.isNullOrEmpty()
|
||||
val hasSingleButton = !singleText.isNullOrEmpty()
|
||||
binding.btnSingle.visibility = if (hasSingleButton) View.VISIBLE else View.GONE
|
||||
binding.layoutButtonsHorizontal.visibility = if (!hasSingleButton && !hasThreeButtons) View.VISIBLE else View.GONE
|
||||
binding.layoutButtonsVertical.visibility = if (hasThreeButtons) View.VISIBLE else View.GONE
|
||||
|
||||
override fun show() {
|
||||
weakContext.get()?.let {
|
||||
if (!it.isFinishing && !it.isDestroyed) super.show()
|
||||
if (hasSingleButton) {
|
||||
// 单按钮模式
|
||||
binding.btnSingle.text = singleText
|
||||
} else if (hasThreeButtons) {
|
||||
// 3按钮模式:顶部=取消,中间=中立,底部=确认
|
||||
binding.btnTop.text = negativeText
|
||||
binding.btnMiddle.text = neutralText
|
||||
binding.btnBottom.text = positiveText
|
||||
} else {
|
||||
// 2按钮模式
|
||||
binding.btnLeft.text = negativeText
|
||||
binding.btnRight.text = positiveText
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.shuwei.dish.match.dialog
|
||||
|
||||
import android.content.Context
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import com.shuwei.dish.match.base.GlobalData
|
||||
import com.shuwei.dish.match.databinding.DialogEnvSwitchContentBinding
|
||||
import com.shuwei.dish.match.utils.SpTool
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
|
||||
/**
|
||||
* 环境切换弹窗
|
||||
*
|
||||
* 基于 [CommonDialog] 实现,通过 addContentView 注入 RadioGroup 内容区。
|
||||
* 提供 TEST / UAT / PROD 三套环境的切换功能,初始化时自动根据
|
||||
* [GlobalData.appBaseUrl] 选中当前环境,确认后更新 [GlobalData.appBaseUrl]
|
||||
* 并通过 [onEnvChanged] 回调通知外部。
|
||||
*
|
||||
* @param context 上下文
|
||||
* @param onEnvChanged 确认切换后的回调,参数为新的 baseUrl
|
||||
*/
|
||||
class EnvSwitchDialog(
|
||||
context: Context,
|
||||
private val onEnvChanged: (newBaseUrl: String) -> Unit = {}
|
||||
) {
|
||||
|
||||
private val contentBinding = DialogEnvSwitchContentBinding.inflate(LayoutInflater.from(context))
|
||||
|
||||
private val dialog = CommonDialog(context)
|
||||
.setTitle("切换环境")
|
||||
.addContentView(contentBinding.root) { tvContent ->
|
||||
// 内容区已由 RadioGroup 承载,隐藏默认文本
|
||||
tvContent.visibility = View.GONE
|
||||
}
|
||||
.setNegativeButton("取消")
|
||||
.setPositiveButtonInterceptable("确认") {
|
||||
// 未选中任何选项时提示并阻止关闭
|
||||
if (contentBinding.rgEnv.checkedRadioButtonId == -1) {
|
||||
context.toast("请选择环境")
|
||||
return@setPositiveButtonInterceptable false
|
||||
}
|
||||
val newUrl = when (contentBinding.rgEnv.checkedRadioButtonId) {
|
||||
contentBinding.rbTest.id -> GlobalData.TEST_BASE_URL
|
||||
contentBinding.rbUat.id -> GlobalData.UAT_BASE_URL
|
||||
contentBinding.rbProd.id -> GlobalData.PROD_BASE_URL
|
||||
else -> return@setPositiveButtonInterceptable false
|
||||
}
|
||||
GlobalData.appBaseUrl = newUrl
|
||||
SpTool.baseUrl = newUrl
|
||||
onEnvChanged(newUrl)
|
||||
true
|
||||
}
|
||||
|
||||
init {
|
||||
// 根据当前 appBaseUrl 预选对应 RadioButton
|
||||
when (GlobalData.appBaseUrl) {
|
||||
GlobalData.TEST_BASE_URL -> contentBinding.rbTest.isChecked = true
|
||||
GlobalData.UAT_BASE_URL -> contentBinding.rbUat.isChecked = true
|
||||
GlobalData.PROD_BASE_URL -> contentBinding.rbProd.isChecked = true
|
||||
}
|
||||
}
|
||||
|
||||
/** 显示弹窗 */
|
||||
fun show() = dialog.show()
|
||||
|
||||
/** 关闭弹窗 */
|
||||
fun dismiss() = dialog.dismiss()
|
||||
}
|
||||
@@ -1,62 +1,62 @@
|
||||
package com.shuwei.dish.match.dialog
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.LayoutInflater
|
||||
import androidx.recyclerview.widget.GridLayoutManager
|
||||
import com.google.android.material.bottomsheet.BottomSheetDialog
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.GoodsInfoSearchAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.databinding.DialogFoodRecognizeBinding
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
|
||||
/**
|
||||
* 菜品识别结果弹窗,继承 BottomSheetDialog 确保只初始化一次
|
||||
* @param activity 宿主 Activity
|
||||
* @param onDismiss 弹窗关闭时的额外回调(可选)
|
||||
* @param onItemSelected 用户点击某一菜品时的回调
|
||||
*/
|
||||
class FoodRecognizeDialog(
|
||||
private val activity: BaseActivity,
|
||||
private val onDismiss: (() -> Unit)? = null,
|
||||
private val onItemSelected: (item: CookFoodGoodsEntity) -> Unit
|
||||
) : BottomSheetDialog(activity, R.style.BottomSheet) {
|
||||
|
||||
private val binding = DialogFoodRecognizeBinding.inflate(LayoutInflater.from(activity))
|
||||
private val list = mutableListOf<CookFoodGoodsEntity>()
|
||||
private val adapter = GoodsInfoSearchAdapter(list).apply {
|
||||
setOnItemClickListener { _, _, position ->
|
||||
list[position].isClicked = true
|
||||
notifyItemChanged(position)
|
||||
Handler(Looper.getMainLooper()).postDelayed({
|
||||
onItemSelected(list[position])
|
||||
dismiss()
|
||||
}, 300)
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
setContentView(binding.root)
|
||||
setCancelable(true)
|
||||
behavior.skipCollapsed = false
|
||||
setOnDismissListener { activity.hideStatusBar(); onDismiss?.invoke() }
|
||||
binding.recyclerView.run {
|
||||
layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
||||
adapter = this@FoodRecognizeDialog.adapter
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载识别结果数据并显示弹窗
|
||||
* @param items 识别到的菜品列表
|
||||
*/
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
fun loadData(items: List<CookFoodGoodsEntity>) {
|
||||
list.clear()
|
||||
list.addAll(items)
|
||||
adapter.notifyDataSetChanged()
|
||||
if (!isShowing) show()
|
||||
}
|
||||
}
|
||||
//package com.shuwei.dish.match.dialog
|
||||
//
|
||||
//import android.annotation.SuppressLint
|
||||
//import android.os.Handler
|
||||
//import android.os.Looper
|
||||
//import android.view.LayoutInflater
|
||||
//import androidx.recyclerview.widget.GridLayoutManager
|
||||
//import com.google.android.material.bottomsheet.BottomSheetDialog
|
||||
//import com.shuwei.dish.match.R
|
||||
//import com.shuwei.dish.match.adapter.FoodAdapter
|
||||
//import com.shuwei.dish.match.base.BaseActivity
|
||||
//import com.shuwei.dish.match.databinding.DialogFoodRecognizeBinding
|
||||
//import com.shuwei.dish.match.entity.GoodsItem
|
||||
//
|
||||
///**
|
||||
// * 菜品识别结果弹窗,继承 BottomSheetDialog 确保只初始化一次
|
||||
// * @param activity 宿主 Activity
|
||||
// * @param onDismiss 弹窗关闭时的额外回调(可选)
|
||||
// * @param onItemSelected 用户点击某一菜品时的回调
|
||||
// */
|
||||
//class FoodRecognizeDialog(
|
||||
// private val activity: BaseActivity,
|
||||
// private val onDismiss: (() -> Unit)? = null,
|
||||
// private val onItemSelected: (item: GoodsItem) -> Unit
|
||||
//) : BottomSheetDialog(activity, R.style.BottomSheet) {
|
||||
//
|
||||
// private val binding = DialogFoodRecognizeBinding.inflate(LayoutInflater.from(activity))
|
||||
// private val list = mutableListOf<GoodsItem>()
|
||||
// private val adapter = FoodAdapter(list).apply {
|
||||
// setOnItemClickListener { _, _, position ->
|
||||
// list[position].isClicked = true
|
||||
// notifyItemChanged(position)
|
||||
// Handler(Looper.getMainLooper()).postDelayed({
|
||||
// onItemSelected(list[position])
|
||||
// dismiss()
|
||||
// }, 300)
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// init {
|
||||
// setContentView(binding.root)
|
||||
// setCancelable(true)
|
||||
// behavior.skipCollapsed = false
|
||||
// setOnDismissListener { activity.hideStatusBar(); onDismiss?.invoke() }
|
||||
// binding.recyclerView.run {
|
||||
// layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
||||
// adapter = this@FoodRecognizeDialog.adapter
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 加载识别结果数据并显示弹窗
|
||||
// * @param items 识别到的菜品列表
|
||||
// */
|
||||
// @SuppressLint("NotifyDataSetChanged")
|
||||
// fun loadData(items: List<GoodsItem>) {
|
||||
// list.clear()
|
||||
// list.addAll(items)
|
||||
// adapter.notifyDataSetChanged()
|
||||
// if (!isShowing) show()
|
||||
// }
|
||||
//}
|
||||
|
||||
@@ -1,25 +1,33 @@
|
||||
package com.shuwei.dish.match.dialog
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.graphics.Rect
|
||||
import android.text.Editable
|
||||
import android.view.KeyboardShortcutGroup
|
||||
import android.view.LayoutInflater
|
||||
import android.view.Menu
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import androidx.core.view.isEmpty
|
||||
import android.view.Window
|
||||
import android.widget.FrameLayout
|
||||
import androidx.core.widget.addTextChangedListener
|
||||
import androidx.recyclerview.widget.GridLayoutManager
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import com.chad.library.adapter4.util.setOnDebouncedItemClick
|
||||
import com.google.android.material.bottomsheet.BottomSheetDialog
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.GoodsInfoSearchAdapter
|
||||
import com.shuwei.dish.match.adapter.FoodAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.databinding.DialogFoodSearchBinding
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
import com.shuwei.dish.match.model.MaterSearchItem
|
||||
import com.shuwei.dish.match.net.UiState
|
||||
import com.shuwei.dish.match.utils.KeyboardUtil
|
||||
import com.shuwei.dish.match.utils.showRawMaterialsDialog
|
||||
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* 食材搜索弹窗,继承 BottomSheetDialog 确保只初始化一次
|
||||
@@ -30,25 +38,47 @@ import com.shuwei.dish.match.utils.ext.toast
|
||||
class FoodSearchDialog(
|
||||
private val activity: BaseActivity,
|
||||
private val defGoodsName: String? = null,
|
||||
private val onItemSelected: (item: CookFoodGoodsEntity) -> Unit
|
||||
private val onItemSelected: (item: GoodsItem) -> Unit
|
||||
) : BottomSheetDialog(activity, R.style.BottomSheet) {
|
||||
|
||||
companion object {
|
||||
const val PAGE_SIZE = 50
|
||||
}
|
||||
|
||||
private val binding = DialogFoodSearchBinding.inflate(LayoutInflater.from(activity))
|
||||
private val list = mutableListOf<CookFoodGoodsEntity>()
|
||||
private val adapter = GoodsInfoSearchAdapter(list).apply {
|
||||
setOnItemClickListener { _, _, position ->
|
||||
list[position].isClicked = true
|
||||
private val list = mutableListOf<GoodsItem>()
|
||||
|
||||
private val adapter = FoodAdapter(list).apply {
|
||||
isStateViewEnable = true
|
||||
setOnDebouncedItemClick { _, _, position ->
|
||||
val item = list.getOrNull(position) ?: return@setOnDebouncedItemClick
|
||||
item.isClicked = true
|
||||
notifyItemChanged(position)
|
||||
Handler(Looper.getMainLooper()).postDelayed({
|
||||
onItemSelected(list[position])
|
||||
dismiss()
|
||||
}, 300)
|
||||
// mater-search 不返回净材种类,rawMaterialsTypes 为空时直接选中返回,避免卡在净材弹窗
|
||||
if (item.rawMaterialsTypes.isNullOrBlank()) {
|
||||
binding.root.postDelayed({
|
||||
onItemSelected(item)
|
||||
dismiss()
|
||||
}, 300)
|
||||
return@setOnDebouncedItemClick
|
||||
}
|
||||
// 有净材种类时弹出单选弹窗,确认后再回调并关闭弹窗
|
||||
showRawMaterialsDialog(
|
||||
context = activity,
|
||||
types = item.rawMaterialsTypes,
|
||||
checkedType = item.rawMaterialsType
|
||||
) { selectedType ->
|
||||
item.rawMaterialsType = selectedType
|
||||
binding.root.postDelayed({
|
||||
onItemSelected(item)
|
||||
dismiss()
|
||||
}, 300)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var goodsName: String? = null
|
||||
private var pageNo = 1
|
||||
private val pageSize = 50
|
||||
|
||||
init {
|
||||
setContentView(binding.root)
|
||||
@@ -73,34 +103,74 @@ class FoodSearchDialog(
|
||||
addOnActionSearchListener { searchGoods(this) }
|
||||
}
|
||||
|
||||
// RecyclerView 初始化及滑动冲突处理
|
||||
// RecyclerView 初始化
|
||||
binding.recyclerView.run {
|
||||
layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
||||
adapter = this@FoodSearchDialog.adapter
|
||||
addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
||||
override fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) {
|
||||
super.onScrolled(rv, dx, dy)
|
||||
// 解决 RecyclerView 与 SmartRefreshLayout 滑动冲突
|
||||
val topRowVerticalPosition = if (rv.isEmpty()) 0 else rv.getChildAt(0).top
|
||||
binding.refreshLayout.setNestedScrollingEnabled(topRowVerticalPosition >= 0)
|
||||
}
|
||||
})
|
||||
// addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
||||
// override fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) {
|
||||
// super.onScrolled(rv, dx, dy)
|
||||
// // 解决 RecyclerView 与 SmartRefreshLayout 滑动冲突
|
||||
// val topRowVerticalPosition = if (rv.isEmpty()) 0 else rv.getChildAt(0).top
|
||||
// binding.refreshLayout.setNestedScrollingEnabled(topRowVerticalPosition >= 0)
|
||||
// }
|
||||
// })
|
||||
}
|
||||
|
||||
binding.refreshLayout.run {
|
||||
setEnableRefresh(false)
|
||||
setEnableRefresh(true)
|
||||
setEnableLoadMore(false)
|
||||
setOnRefreshListener { pageNo = 1; getGoodsList() }
|
||||
setOnLoadMoreListener { getGoodsList() }
|
||||
}
|
||||
|
||||
binding.ivSearch.setOnClickListener { searchGoods(it) }
|
||||
binding.root.setOnClickListener { KeyboardUtil.hideKeyboard(it.context, it) }
|
||||
binding.root.setOnClickListener { KeyboardUtil.hideKeyboard(it) }
|
||||
|
||||
// 若有默认食材名称,自动填充并触发搜索
|
||||
if (!defGoodsName.isNullOrBlank()) {
|
||||
binding.etSheetInput.setText(defGoodsName)
|
||||
searchGoods(binding.etSheetInput)
|
||||
//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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,50 +184,108 @@ class FoodSearchDialog(
|
||||
}
|
||||
pageNo = 1
|
||||
getGoodsList()
|
||||
KeyboardUtil.hideKeyboard(v.context, v)
|
||||
KeyboardUtil.hideKeyboard(v)
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求食材列表
|
||||
* 请求食材列表(采样模式新配比秤接口 mater-search,回调版本)
|
||||
*/
|
||||
private fun getGoodsList() {
|
||||
val param = mutableMapOf<String, Any>(
|
||||
"goodsType" to "0",
|
||||
"placeId" to BaseApp.canteenId,
|
||||
"pageNum" to pageNo,
|
||||
"pageSize" to pageSize
|
||||
activity.netViewModel.materSearch(
|
||||
keyword = goodsName.takeUnless { it.isNullOrBlank() },
|
||||
pageNum = pageNo,
|
||||
pageSize = PAGE_SIZE,
|
||||
onResult = { state ->
|
||||
when (state) {
|
||||
is UiState.Success -> loadGoodsList(state.data)
|
||||
is UiState.Error -> {
|
||||
activity.toast(state.msg)
|
||||
finishRefresh()
|
||||
if (pageNo == 1) loadEmptyView()
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
)
|
||||
if (!goodsName.isNullOrBlank()) {
|
||||
param["goodsName"] = goodsName!!
|
||||
}
|
||||
activity.queryGoodsList(param = param, onSuccess = {
|
||||
loadGoodsList(it)
|
||||
}, onFailure = { _, msg ->
|
||||
activity.toast(msg)
|
||||
finishRefresh()
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 将返回数据填充到列表
|
||||
*/
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun loadGoodsList(records: MutableList<CookFoodGoodsEntity>?) {
|
||||
private fun loadGoodsList(records: List<MaterSearchItem>?) {
|
||||
finishRefresh()
|
||||
if (records.isNullOrEmpty()) {
|
||||
activity.toast("暂未搜索到食材信息")
|
||||
if (pageNo == 1) {
|
||||
loadEmptyView()
|
||||
}
|
||||
return
|
||||
}
|
||||
// 仅当当前不是 GridLayoutManager 时才重新赋值(空态切回网格时)
|
||||
binding.recyclerView.run {
|
||||
if (layoutManager !is GridLayoutManager) {
|
||||
layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
||||
}
|
||||
}
|
||||
if (pageNo == 1) list.clear()
|
||||
list.addAll(records)
|
||||
// mater-search 不返回净材种类,rawMaterialsTypes 保持 null,点击时直接选中返回
|
||||
val goodsItems = records.map { it.toGoodsItem() }
|
||||
list.addAll(goodsItems)
|
||||
adapter.notifyDataSetChanged()
|
||||
val isLoadMoreEnable = records.size >= pageSize
|
||||
val isLoadMoreEnable = records.size >= PAGE_SIZE
|
||||
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
|
||||
if (isLoadMoreEnable) pageNo++
|
||||
}
|
||||
|
||||
/**
|
||||
* MaterSearchItem → GoodsItem 映射
|
||||
* id 即食材id,同时作为 goodsId 和 materId(提交 sample/save 时使用)
|
||||
*/
|
||||
private fun MaterSearchItem.toGoodsItem() = GoodsItem(
|
||||
goodsId = id,
|
||||
materId = id,
|
||||
goodsName = materName,
|
||||
materCode = materCode,
|
||||
popularName = alias
|
||||
)
|
||||
|
||||
private fun finishRefresh() {
|
||||
if (pageNo == 1) binding.refreshLayout.finishRefresh()
|
||||
else binding.refreshLayout.finishLoadMore()
|
||||
}
|
||||
|
||||
private var emptyViewBinding: LayoutEmptyViewBinding? = null
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun loadEmptyView() {
|
||||
try {
|
||||
binding.refreshLayout.setEnableRefresh(true)
|
||||
binding.refreshLayout.setEnableLoadMore(false)
|
||||
list.clear()
|
||||
adapter.notifyDataSetChanged()
|
||||
if (emptyViewBinding == null) {
|
||||
emptyViewBinding = LayoutEmptyViewBinding.inflate(
|
||||
LayoutInflater.from(activity),
|
||||
binding.recyclerView,
|
||||
false
|
||||
)
|
||||
}
|
||||
emptyViewBinding?.let {
|
||||
it.tvContent.text = "暂无数据"
|
||||
it.tvSubContent.text = "未查询到食材信息,请联系管理员添加"
|
||||
// it.root.setOnClickListener { loadGoodsList(buildMockGoodsList().toMutableList()) }
|
||||
it.root.layoutParams = FrameLayout.LayoutParams(
|
||||
FrameLayout.LayoutParams.MATCH_PARENT,
|
||||
FrameLayout.LayoutParams.MATCH_PARENT
|
||||
)
|
||||
binding.recyclerView.layoutManager = LinearLayoutManager(activity)
|
||||
binding.recyclerView.post {
|
||||
it.root.minimumHeight = binding.recyclerView.height
|
||||
adapter.stateView = it.root
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.shuwei.dish.match.dialog
|
||||
|
||||
import android.graphics.Rect
|
||||
import android.view.KeyboardShortcutGroup
|
||||
import android.view.LayoutInflater
|
||||
import android.view.Menu
|
||||
import android.view.MotionEvent
|
||||
import android.view.ViewGroup
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import com.google.android.material.bottomsheet.BottomSheetDialog
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.GoodsPreviewAdapter
|
||||
import com.shuwei.dish.match.databinding.DialogGoodsPreviewBinding
|
||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
|
||||
/**
|
||||
* 用料明细预览弹窗,以 BottomSheetDialog 形式展示当前 goodsList
|
||||
* @param context 宿主 Context(Activity)
|
||||
* @param goodsList 需要展示的物品列表
|
||||
*/
|
||||
class GoodsPreviewDialog(
|
||||
context: android.content.Context,
|
||||
private val goodsList: List<CookFoodGoodsEntity>
|
||||
) : BottomSheetDialog(context, R.style.BottomSheet) {
|
||||
|
||||
private val binding = DialogGoodsPreviewBinding.inflate(LayoutInflater.from(context))
|
||||
|
||||
init {
|
||||
setContentView(binding.root)
|
||||
setCancelable(true)
|
||||
window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
|
||||
|
||||
binding.rvGoodsList.run {
|
||||
layoutManager = LinearLayoutManager(context)
|
||||
adapter = GoodsPreviewAdapter(goodsList)
|
||||
}
|
||||
// foodId 对同一菜品所有条目相同,统一显示在列表上方
|
||||
val foodId = goodsList.firstOrNull()?.foodId.orEmpty()
|
||||
binding.tvFoodId.text = "菜品ID:${foodId.ifEmpty { "-" }}"
|
||||
if (goodsList.isEmpty()) {
|
||||
binding.rvGoodsList.gone()
|
||||
binding.tvEmpty.visible()
|
||||
}
|
||||
}
|
||||
|
||||
/** 弹出时注入 Window.Callback,解决 RecyclerView 与 BottomSheet 拖拽的滑动冲突 */
|
||||
override fun show() {
|
||||
super.show()
|
||||
val originalCallback = window?.callback ?: return
|
||||
window?.callback = object : android.view.Window.Callback by originalCallback {
|
||||
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
val rect = Rect()
|
||||
binding.rvGoodsList.getGlobalVisibleRect(rect)
|
||||
behavior.isDraggable = !rect.contains(event.rawX.toInt(), event.rawY.toInt())
|
||||
}
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
behavior.isDraggable = true
|
||||
}
|
||||
}
|
||||
return originalCallback.dispatchTouchEvent(event)
|
||||
}
|
||||
|
||||
override fun onPointerCaptureChanged(hasCapture: Boolean) {
|
||||
originalCallback.onPointerCaptureChanged(hasCapture)
|
||||
}
|
||||
|
||||
override fun onProvideKeyboardShortcuts(
|
||||
data: List<KeyboardShortcutGroup?>?,
|
||||
menu: Menu?,
|
||||
deviceId: Int
|
||||
) {
|
||||
originalCallback.onProvideKeyboardShortcuts(data, menu, deviceId)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,28 @@
|
||||
package com.shuwei.dish.match.dialog
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.Dialog
|
||||
import android.content.Context
|
||||
import android.graphics.Color
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.LayoutInflater
|
||||
import android.view.WindowManager
|
||||
import androidx.core.graphics.drawable.toDrawable
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.databinding.DialogLoadingBinding
|
||||
|
||||
@SuppressLint("StaticFieldLeak")
|
||||
object Loading {
|
||||
|
||||
/** 默认超时兜底时长(毫秒):业务方未传值时使用 */
|
||||
const val DEFAULT_TIMEOUT_MS = 15_000L
|
||||
|
||||
private var dialog: LoadingDialog? = null
|
||||
/** 当前持有 Loading 的 context,用于隔离 Activity 销毁时的误关 */
|
||||
private var owner: Context? = null
|
||||
private val timeoutHandler = Handler(Looper.getMainLooper())
|
||||
private val timeoutRunnable = Runnable { dismiss() }
|
||||
|
||||
fun isShowing(): Boolean {
|
||||
return dialog != null && dialog!!.isShowing
|
||||
@@ -22,30 +33,71 @@ object Loading {
|
||||
dialog!!.updateContent(content)
|
||||
}
|
||||
|
||||
fun show(context: Context, message: String = "加载中……", onDismiss: () -> Unit = {}) {
|
||||
/**
|
||||
* 显示 Loading 弹窗
|
||||
*
|
||||
* @param context 上下文
|
||||
* @param message 提示文案
|
||||
* @param timeoutMs 超时兜底时长(毫秒):到期自动 dismiss;传 0 关闭兜底,由业务方自己负责
|
||||
* @param onDismiss 关闭回调
|
||||
*/
|
||||
fun show(
|
||||
context: Context,
|
||||
message: String = "加载中……",
|
||||
timeoutMs: Long = DEFAULT_TIMEOUT_MS,
|
||||
onDismiss: () -> Unit = {}
|
||||
) {
|
||||
try {
|
||||
// 节流:已显示中只更新文案 + 重置超时,不重新 attach 窗口
|
||||
// 避免反复触发 FocusEvent 在主线程繁忙时引发 ANR
|
||||
if (dialog?.isShowing == true) {
|
||||
dialog?.dismiss()
|
||||
}
|
||||
if (dialog == null) {
|
||||
dialog = LoadingDialog(context = context, message = message, onDismiss = onDismiss)
|
||||
dialog?.updateContent(message)
|
||||
owner = context // 同一弹窗最后一次 show 决定 owner
|
||||
resetTimeout(timeoutMs)
|
||||
return
|
||||
}
|
||||
dialog = LoadingDialog(context = context, message = message, onDismiss = onDismiss)
|
||||
owner = context
|
||||
dialog?.show()
|
||||
resetTimeout(timeoutMs)
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
fun dismiss() {
|
||||
timeoutHandler.removeCallbacks(timeoutRunnable)
|
||||
try {
|
||||
dialog?.let {
|
||||
if (it.isShowing) {
|
||||
it.dismiss()
|
||||
}
|
||||
}
|
||||
dialog = null
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
} finally {
|
||||
dialog = null
|
||||
owner = null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Activity 销毁专用:只关闭自己持有的 Loading,防止跨 Activity 误关
|
||||
* 单例 Loading 在多 Activity 共享时,若每个 Activity 的 onDestroy 都无脑 dismiss,
|
||||
* 会误关后启动 Activity 弹出的 Loading;由本方法做 owner 校验后才允许关闭
|
||||
*/
|
||||
fun dismissIfOwnedBy(context: Context) {
|
||||
if (owner === context) dismiss()
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置超时兜底定时器
|
||||
* @param timeoutMs <=0 表示不安排定时器(关闭兜底)
|
||||
*/
|
||||
private fun resetTimeout(timeoutMs: Long) {
|
||||
timeoutHandler.removeCallbacks(timeoutRunnable)
|
||||
if (timeoutMs > 0) {
|
||||
timeoutHandler.postDelayed(timeoutRunnable, timeoutMs)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,237 +1,259 @@
|
||||
package com.shuwei.dish.match.dialog
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.graphics.Typeface
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.text.SpannableStringBuilder
|
||||
import android.text.style.AbsoluteSizeSpan
|
||||
import android.text.style.ForegroundColorSpan
|
||||
import android.text.style.LineHeightSpan
|
||||
import android.text.style.StyleSpan
|
||||
import android.util.Log
|
||||
import android.view.Gravity
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.view.WindowManager
|
||||
import androidx.core.graphics.toColorInt
|
||||
import androidx.core.view.isEmpty
|
||||
import androidx.core.widget.addTextChangedListener
|
||||
import androidx.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.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
|
||||
|
||||
/**
|
||||
* 调料搜索弹窗,继承 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.run {
|
||||
layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
||||
adapter = this@SeasoningSearchDialog.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(false)
|
||||
setEnableLoadMore(false)
|
||||
setOnRefreshListener { pageNo = 1; getGoodsList() }
|
||||
setOnLoadMoreListener { getGoodsList() }
|
||||
}
|
||||
|
||||
binding.ivSearch.setOnClickListener { searchGoods(it) }
|
||||
binding.root.setOnClickListener { KeyboardUtil.hideKeyboard(it.context, 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)
|
||||
|
||||
// 若有默认调料名称,自动填充并触发搜索
|
||||
if (!clickName.isNullOrBlank()) {
|
||||
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 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.querySeasoningList(param = param, onSuccess = {
|
||||
loadGoodsList(it)
|
||||
}, onFailure = { _, msg ->
|
||||
activity.toast(msg)
|
||||
finishRefresh()
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 将返回数据填充到列表
|
||||
*/
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun loadGoodsList(records: MutableList<SeasoningEntity>?) {
|
||||
finishRefresh()
|
||||
if (records.isNullOrEmpty()) {
|
||||
activity.toast("暂未搜索到调料信息")
|
||||
return
|
||||
}
|
||||
if (pageNo == 1) list.clear()
|
||||
list.addAll(records)
|
||||
adapter.notifyDataSetChanged()
|
||||
val isLoadMoreEnable = records.size >= pageSize
|
||||
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
|
||||
if (isLoadMoreEnable) pageNo++
|
||||
}
|
||||
|
||||
private fun finishRefresh() {
|
||||
if (pageNo == 1) binding.refreshLayout.finishRefresh()
|
||||
else binding.refreshLayout.finishLoadMore()
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成重量显示的富文本:数值大字加粗,单位小字灰色
|
||||
*/
|
||||
fun getTextSpan(weight: Double): SpannableStringBuilder {
|
||||
val topWeight = if (weight >= 1000) "${(weight / 1000).roundedDecimalPlace(3)}" else "$weight"
|
||||
val bottomUnit = if (weight >= 1000) "千克" else "克"
|
||||
return buildSpannableString {
|
||||
appendText(
|
||||
topWeight,
|
||||
ForegroundColorSpan("#000000".toColorInt()),
|
||||
StyleSpan(Typeface.BOLD),
|
||||
AbsoluteSizeSpan(72, true),
|
||||
LineHeightSpan { _, _, _, _, _, fm -> fm.descent += 10.dp }
|
||||
)
|
||||
append("\n")
|
||||
appendText(
|
||||
bottomUnit,
|
||||
ForegroundColorSpan("#999999".toColorInt()),
|
||||
AbsoluteSizeSpan(30, true)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
//package com.shuwei.dish.match.dialog
|
||||
//
|
||||
//import android.annotation.SuppressLint
|
||||
//import android.graphics.Typeface
|
||||
//import android.os.Handler
|
||||
//import android.os.Looper
|
||||
//import android.text.SpannableStringBuilder
|
||||
//import android.text.style.AbsoluteSizeSpan
|
||||
//import android.text.style.ForegroundColorSpan
|
||||
//import android.text.style.LineHeightSpan
|
||||
//import android.text.style.StyleSpan
|
||||
//import android.util.Log
|
||||
//import android.view.Gravity
|
||||
//import android.view.LayoutInflater
|
||||
//import android.view.View
|
||||
//import android.view.ViewGroup
|
||||
//import android.view.WindowManager
|
||||
//import androidx.core.graphics.toColorInt
|
||||
//import androidx.core.view.isEmpty
|
||||
//import androidx.core.widget.addTextChangedListener
|
||||
//import androidx.lifecycle.Lifecycle
|
||||
//import androidx.lifecycle.lifecycleScope
|
||||
//import androidx.lifecycle.repeatOnLifecycle
|
||||
//import androidx.recyclerview.widget.GridLayoutManager
|
||||
//import androidx.recyclerview.widget.RecyclerView
|
||||
//import com.google.android.material.bottomsheet.BottomSheetDialog
|
||||
//import com.shuwei.dish.match.R
|
||||
//import com.shuwei.dish.match.adapter.SeasoningSearchAdapter
|
||||
//import com.shuwei.dish.match.base.BaseActivity
|
||||
//import com.shuwei.dish.match.base.BaseApp
|
||||
//import com.shuwei.dish.match.databinding.DialogSeasoningSearchBinding
|
||||
//import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
//import com.shuwei.dish.match.net.UiState
|
||||
//import com.shuwei.dish.match.utils.KeyboardUtil
|
||||
//import com.shuwei.dish.match.utils.WeightUtil
|
||||
//import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
||||
//import com.shuwei.dish.match.utils.ext.appendText
|
||||
//import com.shuwei.dish.match.utils.ext.buildSpannableString
|
||||
//import com.shuwei.dish.match.utils.ext.dp
|
||||
//import com.shuwei.dish.match.utils.ext.roundedDecimalPlace
|
||||
//import com.shuwei.dish.match.utils.ext.toast
|
||||
//import kotlinx.coroutines.launch
|
||||
//
|
||||
///**
|
||||
// * 调料搜索弹窗,继承 BottomSheetDialog 确保只初始化一次
|
||||
// * @param activity 宿主 Activity
|
||||
// * @param weighIndex 秤的索引
|
||||
// * @param weighAddress 秤的地址,用于监听重量和去皮
|
||||
// * @param clickName 默认填充的调料名称(可选)
|
||||
// * @param onItemSelected 用户点击某一调料时的回调,携带当前重量
|
||||
// */
|
||||
//class SeasoningSearchDialog(
|
||||
// private val activity: BaseActivity,
|
||||
// private val weighIndex: Int,
|
||||
// private val weighAddress: Int,
|
||||
// private val clickName: String? = null,
|
||||
// private val onItemSelected: (item: SeasoningEntity) -> Unit
|
||||
//) : BottomSheetDialog(activity, R.style.BottomSheet) {
|
||||
//
|
||||
// companion object {
|
||||
// const val TAG = "BottomDialog2"
|
||||
// }
|
||||
//
|
||||
// private val binding = DialogSeasoningSearchBinding.inflate(LayoutInflater.from(activity))
|
||||
// private val list = mutableListOf<SeasoningEntity>()
|
||||
// private val adapter = SeasoningSearchAdapter(list).apply {
|
||||
// setOnItemClickListener { _, _, position ->
|
||||
// list[position].isClicked = true
|
||||
// notifyItemChanged(position)
|
||||
// Handler(Looper.getMainLooper()).postDelayed({
|
||||
// onItemSelected(list[position].also { it.useWeight = currentWeight })
|
||||
// dismiss()
|
||||
// }, 300)
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private var goodsName: String? = null
|
||||
// private var currentWeight = 0.0
|
||||
// private var pageNo = 1
|
||||
// private val pageSize = 50
|
||||
//
|
||||
// init {
|
||||
// setContentView(binding.root)
|
||||
// setCancelable(true)
|
||||
// behavior.skipCollapsed = false
|
||||
// window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
|
||||
// window?.setGravity(Gravity.BOTTOM)
|
||||
// window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
|
||||
// window?.setWindowAnimations(R.style.DialogSoftInputAnimation)
|
||||
// window?.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
|
||||
//
|
||||
// setOnDismissListener {
|
||||
// // 弹窗关闭时移除重量监听,避免内存泄漏
|
||||
// WeightUtil.removeWeightListener(TAG)
|
||||
// activity.hideStatusBar()
|
||||
// }
|
||||
//
|
||||
// // 输入框:清空时重置列表
|
||||
// binding.etSheetInput.run {
|
||||
// hint = "输入调料名称"
|
||||
// addTextChangedListener(
|
||||
// onTextChanged = { text, _, _, _ -> goodsName = text.toString() },
|
||||
// afterTextChanged = {
|
||||
// if (it.isNullOrBlank()) {
|
||||
// list.clear()
|
||||
// adapter.notifyDataSetChanged()
|
||||
// }
|
||||
// }
|
||||
// )
|
||||
// addOnActionSearchListener { searchGoods(this) }
|
||||
// }
|
||||
//
|
||||
// // RecyclerView 初始化及滑动冲突处理
|
||||
// binding.recyclerView.let {
|
||||
// it.layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
|
||||
// it.adapter = adapter
|
||||
// it.addOnScrollListener(object : RecyclerView.OnScrollListener() {
|
||||
// override fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) {
|
||||
// super.onScrolled(rv, dx, dy)
|
||||
// // 解决 RecyclerView 与 SmartRefreshLayout 滑动冲突
|
||||
// val topRowVerticalPosition = if (rv.isEmpty()) 0 else rv.getChildAt(0).top
|
||||
// binding.refreshLayout.setNestedScrollingEnabled(topRowVerticalPosition >= 0)
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
//
|
||||
// binding.refreshLayout.run {
|
||||
// setEnableRefresh(false)
|
||||
// setEnableLoadMore(false)
|
||||
// setOnRefreshListener { pageNo = 1; getGoodsList() }
|
||||
// setOnLoadMoreListener { getGoodsList() }
|
||||
// }
|
||||
//
|
||||
// binding.ivSearch.setOnClickListener { searchGoods(it) }
|
||||
// binding.root.setOnClickListener { KeyboardUtil.hideKeyboard(it) }
|
||||
//
|
||||
// // 去皮按钮
|
||||
// binding.tvClear.setOnClickListener {
|
||||
// Log.d(TAG, "tareTwo: weighAddress=$weighAddress")
|
||||
// WeightUtil.tareTwo(weighAddress)
|
||||
// }
|
||||
//
|
||||
// // 监听对应秤的重量变化
|
||||
// WeightUtil.addWeightListener(
|
||||
// weightKey = TAG,
|
||||
// getWeight = { address, _, weight ->
|
||||
// if (weighAddress == address) {
|
||||
// currentWeight = weight.toDouble()
|
||||
// binding.tvWeight.text = getTextSpan(weight)
|
||||
// }
|
||||
// }
|
||||
// )
|
||||
// binding.tvWeight.text = getTextSpan(0.0)
|
||||
//
|
||||
// initObserver()
|
||||
//
|
||||
// // 若有默认调料名称,自动填充并触发搜索
|
||||
// if (!clickName.isNullOrBlank()) {
|
||||
// binding.etSheetInput.setText(clickName.trim())
|
||||
// pageNo = 1
|
||||
// getGoodsList()
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 收集 seasoningListState,统一处理 Loading / Success / Error 状态
|
||||
// */
|
||||
// private fun initObserver() {
|
||||
// activity.lifecycleScope.launch {
|
||||
// activity.repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
// activity.netViewModel.seasoningListState.collect { state ->
|
||||
// when (state) {
|
||||
// is UiState.Success -> loadGoodsList(state.data)
|
||||
// is UiState.Error -> {
|
||||
// activity.toast(state.msg)
|
||||
// finishRefresh()
|
||||
// }
|
||||
// else -> {}
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 触发搜索:校验输入、隐藏键盘、发起请求
|
||||
// */
|
||||
// private fun searchGoods(v: View) {
|
||||
// if (goodsName.isNullOrBlank()) {
|
||||
// activity.toast("请${binding.etSheetInput.hint}")
|
||||
// return
|
||||
// }
|
||||
// pageNo = 1
|
||||
// getGoodsList()
|
||||
// KeyboardUtil.hideKeyboard(v)
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 请求调料列表
|
||||
// */
|
||||
// private fun getGoodsList() {
|
||||
// val param = mutableMapOf<String, Any>(
|
||||
// "goodsType" to "1",
|
||||
// "placeId" to BaseApp.canteenId,
|
||||
// "pageNum" to pageNo,
|
||||
// "pageSize" to pageSize
|
||||
// )
|
||||
// if (!goodsName.isNullOrBlank()) {
|
||||
// param["goodsName"] = goodsName!!
|
||||
// }
|
||||
// activity.netViewModel.querySeasoningList(param)
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 将返回数据填充到列表
|
||||
// */
|
||||
// @SuppressLint("NotifyDataSetChanged")
|
||||
// private fun loadGoodsList(records: MutableList<SeasoningEntity>?) {
|
||||
// finishRefresh()
|
||||
// if (records.isNullOrEmpty()) {
|
||||
// activity.toast("暂未搜索到调料信息")
|
||||
// return
|
||||
// }
|
||||
// if (pageNo == 1) list.clear()
|
||||
// list.addAll(records)
|
||||
// adapter.notifyDataSetChanged()
|
||||
// val isLoadMoreEnable = records.size >= pageSize
|
||||
// binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
|
||||
// if (isLoadMoreEnable) pageNo++
|
||||
// }
|
||||
//
|
||||
// private fun finishRefresh() {
|
||||
// if (pageNo == 1) binding.refreshLayout.finishRefresh()
|
||||
// else binding.refreshLayout.finishLoadMore()
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 生成重量显示的富文本:数值大字加粗,单位小字灰色
|
||||
// */
|
||||
// fun getTextSpan(weight: Double): SpannableStringBuilder {
|
||||
// val topWeight = if (weight >= 1000) "${(weight / 1000).roundedDecimalPlace(3)}" else "$weight"
|
||||
// val bottomUnit = if (weight >= 1000) "千克" else "克"
|
||||
// return buildSpannableString {
|
||||
// appendText(
|
||||
// topWeight,
|
||||
// ForegroundColorSpan("#000000".toColorInt()),
|
||||
// StyleSpan(Typeface.BOLD),
|
||||
// AbsoluteSizeSpan(72, true),
|
||||
// LineHeightSpan { _, _, _, _, _, fm -> fm.descent += 10.dp }
|
||||
// )
|
||||
// append("\n")
|
||||
// appendText(
|
||||
// bottomUnit,
|
||||
// ForegroundColorSpan("#999999".toColorInt()),
|
||||
// AbsoluteSizeSpan(30, true)
|
||||
// )
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
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.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.model.SeasoningSearchItem
|
||||
import com.shuwei.dish.match.net.UiState
|
||||
import com.shuwei.dish.match.utils.KeyboardUtil
|
||||
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
/**
|
||||
* 调料选择弹窗,不含重量显示,继承 BottomSheetDialog 确保只初始化一次
|
||||
* @param activity 宿主 Activity
|
||||
* @param 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
|
||||
|
||||
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 {
|
||||
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()
|
||||
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.querySeasoningSearch(
|
||||
keyword = goodsName.takeUnless { it.isNullOrBlank() },
|
||||
pageNum = pageNo,
|
||||
pageSize = PAGE_SIZE,
|
||||
onResult = { state ->
|
||||
when (state) {
|
||||
is UiState.Success -> loadGoodsList(state.data)
|
||||
is UiState.Error -> {
|
||||
activity.toast(state.msg)
|
||||
finishRefresh()
|
||||
if (pageNo == 1) loadEmptyView()
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载本地模拟数据,仅用于联调时点击空布局快速验证 UI
|
||||
*/
|
||||
private fun loadMockData() {
|
||||
val nameList = listOf(
|
||||
"盐", "白砂糖", "冰糖", "鸡精", "味精", "陈醋", "老抽", "生抽", "番茄酱", "胡椒粉", "孜然", "十三香",
|
||||
"料酒", "白醋", "蚝油", "辣椒面", "辣椒酱", "豆瓣酱", "淀粉", "葱", "蒜", "姜", "香菜", "油"
|
||||
)
|
||||
val mockData = nameList.mapIndexed { index, name ->
|
||||
val padString = "${index + 1}".padStart(2, '0')
|
||||
SeasoningSearchItem(id = "1000$padString", materName = name)
|
||||
}
|
||||
pageNo = 1
|
||||
loadGoodsList(mockData)
|
||||
}
|
||||
|
||||
/**
|
||||
* 将新接口返回的 SeasoningSearchItem 映射为 GoodsItem 并填充到列表
|
||||
* 新接口的 id 即食材id,同时用作 goodsId 和 materId,无需再交换
|
||||
*/
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun loadGoodsList(records: List<SeasoningSearchItem>?) {
|
||||
finishRefresh()
|
||||
if (records.isNullOrEmpty()) {
|
||||
if (pageNo == 1) {
|
||||
loadEmptyView()
|
||||
}
|
||||
return
|
||||
}
|
||||
binding.recyclerView.layoutManager = GridLayoutManager(activity, 3, GridLayoutManager.VERTICAL, false)
|
||||
if (pageNo == 1) list.clear()
|
||||
val goodsItems = records.map { it.toGoodsItem() }
|
||||
list.addAll(goodsItems)
|
||||
adapter.notifyDataSetChanged()
|
||||
val isLoadMoreEnable = records.size >= PAGE_SIZE
|
||||
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
|
||||
if (isLoadMoreEnable) pageNo++
|
||||
}
|
||||
|
||||
/**
|
||||
* SeasoningSearchItem → GoodsItem 映射
|
||||
* id 既是食材id也是提交时的 goodsId,不需要 oldGoodsId 交换
|
||||
*/
|
||||
private fun SeasoningSearchItem.toGoodsItem() = GoodsItem(
|
||||
goodsId = id,
|
||||
materId = id,
|
||||
goodsName = materName,
|
||||
materCode = materCode,
|
||||
popularName = alias
|
||||
)
|
||||
|
||||
private fun finishRefresh() {
|
||||
if (pageNo == 1) binding.refreshLayout.finishRefresh()
|
||||
else binding.refreshLayout.finishLoadMore()
|
||||
}
|
||||
|
||||
|
||||
private var emptyViewBinding: LayoutEmptyViewBinding? = null
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun loadEmptyView() {
|
||||
try {
|
||||
binding.refreshLayout.setEnableRefresh(true)
|
||||
binding.refreshLayout.setEnableLoadMore(false)
|
||||
list.clear()
|
||||
adapter.notifyDataSetChanged()
|
||||
if (emptyViewBinding == null) {
|
||||
emptyViewBinding = LayoutEmptyViewBinding.inflate(
|
||||
LayoutInflater.from(activity),
|
||||
binding.recyclerView,
|
||||
false
|
||||
)
|
||||
}
|
||||
emptyViewBinding?.let {
|
||||
it.tvContent.text = "暂无数据"
|
||||
it.tvSubContent.text = "未查询到调料信息,请联系管理员添加"
|
||||
// 点击空布局加载本地模拟数据,方便联调时验证 UI
|
||||
//it.root.setOnClickListener { loadMockData() }
|
||||
it.root.layoutParams = FrameLayout.LayoutParams(
|
||||
FrameLayout.LayoutParams.MATCH_PARENT,
|
||||
FrameLayout.LayoutParams.MATCH_PARENT
|
||||
)
|
||||
binding.recyclerView.layoutManager = LinearLayoutManager(activity)
|
||||
binding.recyclerView.post {
|
||||
it.root.minimumHeight = binding.recyclerView.height
|
||||
adapter.stateView = it.root
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
package com.shuwei.dish.match.entity
|
||||
|
||||
data class HomeModeBean(
|
||||
|
||||
var modeName: String = "",
|
||||
var modeDesc: String = "",
|
||||
var modeIconId: Int = 0,
|
||||
var isLocked: Boolean = false,
|
||||
|
||||
var onClick: (() -> Unit)? = null
|
||||
)
|
||||
|
||||
data class FoodRecordBean(
|
||||
var records: MutableList<FoodRecord>? = null,
|
||||
var total: Int,
|
||||
var size: Int,
|
||||
var current: Int,
|
||||
var page: Int
|
||||
)
|
||||
|
||||
data class GoodsRecordBean(
|
||||
var records: MutableList<CookFoodGoodsEntity>? = null,
|
||||
var total: Int,
|
||||
var size: Int,
|
||||
var current: Int,
|
||||
var page: Int
|
||||
)
|
||||
|
||||
data class SeasoningRecordBean(
|
||||
var records: MutableList<SeasoningEntity>? = null,
|
||||
var total: Int,
|
||||
var size: Int,
|
||||
var current: Int,
|
||||
var page: Int
|
||||
)
|
||||
|
||||
data class ResetReasoningRecord(
|
||||
val list: MutableList<SeasoningEntity>
|
||||
)
|
||||
|
||||
//data class DishDetailEntity(
|
||||
// var foodId: String? = null,
|
||||
// var foodWeight: Double? = null,
|
||||
// var foodRealWeight: Double? = null,
|
||||
// var voList: List<DishPartEntity>? = null
|
||||
//)
|
||||
|
||||
//data class DishPartEntity(
|
||||
// var foodId: String? = null,
|
||||
// var foodName: String? = null,
|
||||
// var foodWeight: Int? = null,
|
||||
// var useWeight: Int? = null,
|
||||
// var useRealWeight: Int? = null,
|
||||
// var goodsId: Int? = null,
|
||||
// var goodsName: String? = null,
|
||||
// var materialType: Int? = null,
|
||||
// var isSetFinished: Boolean = false,
|
||||
// var isItemClicked: Boolean = false,
|
||||
// var isSamplingPage: Boolean = false
|
||||
//)
|
||||
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
package com.shuwei.dish.match.entity
|
||||
|
||||
import androidx.room.ColumnInfo
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
import com.shuwei.dish.match.db.BaseEntity
|
||||
|
||||
//@Entity(tableName = "dm_dish")
|
||||
//data class DishEntity (
|
||||
// /**
|
||||
// * 菜品id
|
||||
// */
|
||||
// @PrimaryKey var id: Long,
|
||||
// /**
|
||||
// * 菜品名称
|
||||
// */
|
||||
// var name: String? = "",
|
||||
// /**
|
||||
// * 菜品重量
|
||||
// */
|
||||
// var weight: Int? = 0,
|
||||
//
|
||||
// var sort: Int = 0,
|
||||
// @ColumnInfo(name = "create_time") val createTime: Long = System.currentTimeMillis()
|
||||
//): BaseEntity
|
||||
@@ -1,38 +0,0 @@
|
||||
//package com.shuwei.dish.match.entity
|
||||
//
|
||||
//import androidx.room.Ignore
|
||||
//import androidx.room.PrimaryKey
|
||||
//import com.shuwei.dish.match.db.BaseEntity
|
||||
//
|
||||
//data class GoodsInfoEntity(
|
||||
// @PrimaryKey(autoGenerate = true) var id: Long = 0,
|
||||
// var goodsId: Int,
|
||||
// var goodsName: String? = "",
|
||||
// var popularName: String? = "",
|
||||
// var canteenId: String? = "",
|
||||
// var goodsOrRelationCode: String? = "",
|
||||
// var relateionType: Int? = -1,
|
||||
// var relateionType_dictText: String? = "",
|
||||
//
|
||||
// var sort: Int = 0,
|
||||
//
|
||||
// var swMaterBaseMaterial: String? = "",
|
||||
// var preMaterClass: String? = "",
|
||||
// var preUseWeight: Int? = 0,
|
||||
// var preWeight: Int? = 0,
|
||||
// var oil: String? = "",
|
||||
// var sugar: String? = "",
|
||||
// /**
|
||||
// * isDel表示数据是否已删除,1-已删除,为无效数据,0-正常使用,有效数据
|
||||
// */
|
||||
// var isDel: Int = 0,
|
||||
// val createTime: Long = System.currentTimeMillis()
|
||||
//) : BaseEntity {
|
||||
// @Ignore
|
||||
// var pageType: Int = 0
|
||||
//
|
||||
// @Ignore
|
||||
// var isClicked: Boolean = false
|
||||
//
|
||||
// constructor() : this(id = -1, goodsId = -1) // 必需的空构造
|
||||
//}
|
||||
@@ -1,70 +0,0 @@
|
||||
//package com.shuwei.dish.match.http
|
||||
//
|
||||
//import android.annotation.SuppressLint
|
||||
//import android.util.Log
|
||||
//import okhttp3.Call
|
||||
//import okhttp3.Interceptor
|
||||
//import okhttp3.OkHttpClient
|
||||
//import okhttp3.Request
|
||||
//import okhttp3.Response
|
||||
//import java.util.concurrent.TimeUnit
|
||||
//
|
||||
//import javax.net.ssl.*
|
||||
//import java.security.SecureRandom
|
||||
//import java.security.cert.X509Certificate
|
||||
//
|
||||
//class HttpClient private constructor() {
|
||||
// private val client: OkHttpClient by lazy {
|
||||
// OkHttpClient.Builder()
|
||||
// .apply {
|
||||
// connectTimeout(15, TimeUnit.SECONDS)
|
||||
// readTimeout(30, TimeUnit.SECONDS)
|
||||
// writeTimeout(15, TimeUnit.SECONDS)
|
||||
// sslSocketFactory(createSSLSocketFactory(), TrustAllCerts())
|
||||
// hostnameVerifier { _, _ -> true }
|
||||
// //if (BuildConfig.Debug) {
|
||||
// addInterceptor(LoggingInterceptor())
|
||||
// // }
|
||||
// }
|
||||
// .build()
|
||||
// }
|
||||
//
|
||||
// companion object {
|
||||
// val instance by lazy { HttpClient() }
|
||||
// }
|
||||
//
|
||||
// fun newCall(request: Request): Call = client.newCall(request)
|
||||
//
|
||||
// inner class LoggingInterceptor : Interceptor {
|
||||
// override fun intercept(chain: Interceptor.Chain): Response {
|
||||
// val request = chain.request()
|
||||
// // 打印请求日志
|
||||
// Log.d("OkHttp", "--> ${request.method} ${request.url}")
|
||||
//
|
||||
// val response = chain.proceed(request)
|
||||
// // 打印响应日志
|
||||
// Log.d("OkHttp", "<-- ${response.code} ${response.request.url}")
|
||||
//
|
||||
// return response
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // 信任所有证书的TrustManager实现
|
||||
// @SuppressLint("CustomX509TrustManager")
|
||||
// class TrustAllCerts : X509TrustManager {
|
||||
// @SuppressLint("TrustAllX509TrustManager")
|
||||
// override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {}
|
||||
// @SuppressLint("TrustAllX509TrustManager")
|
||||
// override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {}
|
||||
// override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
|
||||
// }
|
||||
//
|
||||
// // 创建信任所有证书的SSLSocketFactory
|
||||
// fun createSSLSocketFactory(): SSLSocketFactory {
|
||||
// val sslContext = SSLContext.getInstance("TLS").apply {
|
||||
// init(null, arrayOf(TrustAllCerts()), SecureRandom())
|
||||
// }
|
||||
// return sslContext.socketFactory
|
||||
// }
|
||||
//
|
||||
//}
|
||||
@@ -1,199 +0,0 @@
|
||||
//package com.shuwei.dish.match.http
|
||||
//
|
||||
//import android.os.Handler
|
||||
//import android.os.Looper
|
||||
//import android.util.Log
|
||||
//import com.google.gson.reflect.TypeToken
|
||||
//import com.shuwei.dish.match.base.BaseApp
|
||||
//import com.shuwei.dish.match.base.BaseReq
|
||||
//import com.shuwei.dish.match.utils.SpTool
|
||||
//import com.shuwei.dish.match.utils.ext.toType
|
||||
//import okhttp3.Call
|
||||
//import okhttp3.Callback
|
||||
//import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||
//import okhttp3.Request
|
||||
//import okhttp3.RequestBody.Companion.toRequestBody
|
||||
//import okhttp3.Response
|
||||
//import java.io.IOException
|
||||
//import java.util.concurrent.Executors
|
||||
//import java.util.concurrent.TimeUnit
|
||||
//
|
||||
//
|
||||
//object HttpUtil {
|
||||
//
|
||||
// var loopGetToken = true
|
||||
//
|
||||
// fun runMainThread(action: () -> Unit) {
|
||||
// Handler(Looper.getMainLooper()).post {
|
||||
// action()
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // GET请求(HTTPS)
|
||||
// fun get(
|
||||
// url: String,
|
||||
// header: Map<String, String>?=null,
|
||||
// doSuccess: (data: Any) -> Unit,
|
||||
// doFailure: (code: Int?, msg: String?) -> Unit
|
||||
// ) {
|
||||
// val request = Request.Builder()
|
||||
// .url(if (url.isHttpApi()) url else UrlConfig.BASE_URL + url)
|
||||
// .apply {
|
||||
// if (header != null) {
|
||||
// header.forEach {
|
||||
// addHeader(it.key, it.value)
|
||||
// }
|
||||
// } else {
|
||||
// val token = getToken()
|
||||
// if (token.isNotBlank()) {
|
||||
// addHeader("X-Access-Token", token)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// .get()
|
||||
// .build()
|
||||
// HttpClient.instance.newCall(request).enqueue(CallbackImpl(doSuccess, doFailure))
|
||||
// }
|
||||
////
|
||||
//// fun get(
|
||||
//// isHttps: Boolean = false,
|
||||
//// host: String = "vip.shuziweidao.com",
|
||||
//// pathSegmentList: List<String>,
|
||||
//// queryParams: Map<String, String>,
|
||||
//// doSuccess: (data: Any) -> Unit,
|
||||
//// doFailure: (code: Int?, msg: String?) -> Unit
|
||||
//// ) {
|
||||
//// val token = getToken()
|
||||
//// val url = HttpUrl.Builder()
|
||||
//// .scheme(if (isHttps) "https" else "http")
|
||||
//// .host(host)
|
||||
//// .apply {
|
||||
//// pathSegmentList.forEach { addPathSegment(it) }
|
||||
//// queryParams.forEach { (key, value) -> addQueryParameter(key, value) }
|
||||
//// }
|
||||
//// .build()
|
||||
//// val request = Request.Builder()
|
||||
//// .url(url)
|
||||
//// .apply {
|
||||
//// if (token.isNotBlank()) {
|
||||
//// addHeader("Authorization", token)
|
||||
//// }
|
||||
//// }
|
||||
//// .get()
|
||||
//// .build()
|
||||
//// HttpClient.instance.newCall(request).enqueue(CallbackImpl(doSuccess, doFailure))
|
||||
//// }
|
||||
//
|
||||
// // POST表单(HTTPS)
|
||||
//// fun postForm(url: String, params: Map<String, String>, callback: Callback) {
|
||||
//// val formBody = FormBody.Builder().apply {
|
||||
//// params.forEach { (k, v) -> add(k, v) }
|
||||
//// }.build()
|
||||
////
|
||||
//// Request.Builder()
|
||||
//// .url(url)
|
||||
//// .post(formBody)
|
||||
//// .build().let { HttpClient.instance.newCall(it).enqueue(callback) }
|
||||
//// }
|
||||
//
|
||||
// // POST JSON(HTTPS)
|
||||
// fun postJson(
|
||||
// url: String,
|
||||
// json: String,
|
||||
// doSuccess: (data: Any) -> Unit,
|
||||
// doFailure: (code: Int?, msg: String?) -> Unit
|
||||
// ) {
|
||||
// val body = json
|
||||
// .toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
|
||||
// val token = getToken()
|
||||
// Request.Builder()
|
||||
// .url(if (url.isHttpApi()) url else UrlConfig.BASE_URL + url)
|
||||
// .apply {
|
||||
// if (token.isNotBlank()) {
|
||||
// addHeader("X-Access-Token", token)
|
||||
// }
|
||||
// }
|
||||
// .post(body)
|
||||
// .build()
|
||||
// .let { HttpClient.instance.newCall(it).enqueue(CallbackImpl(doSuccess, doFailure)) }
|
||||
// }
|
||||
//
|
||||
//
|
||||
// val executor = Executors.newSingleThreadScheduledExecutor()
|
||||
// var getTokenIsRunning = false
|
||||
// private fun exeTokenThread() {
|
||||
// if (getTokenIsRunning.not()) {
|
||||
// executor.scheduleWithFixedDelay(
|
||||
// task, 0, 1, TimeUnit.MINUTES
|
||||
// )
|
||||
// getTokenIsRunning = true
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// val task = Runnable {
|
||||
// if (BaseApp.token.isNullOrBlank()) {
|
||||
// getAppToken()
|
||||
// } else {
|
||||
// executor.shutdown()
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// fun getToken() = SpTool.getString(SpTool.TOKEN)
|
||||
////BaseApp.instance?.token ?:""
|
||||
////BaseApp.getSharedPref()?.getString("token", "") ?: ""
|
||||
//
|
||||
// fun getAppToken() {
|
||||
// val url = "${UrlConfig.GET_TOKEN}?qrcodeId=${SpTool.getString(SpTool.DEVICE_ID)}"
|
||||
//// Log.d(TAG, "getToken: url = $url")
|
||||
// get(url = url, doSuccess = {
|
||||
// SpTool.put(SpTool.TOKEN, it)
|
||||
// BaseApp.token = it.toString()
|
||||
// }) { code, msg ->
|
||||
// //toast(msg)
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// class CallbackImpl(
|
||||
// private val doSuccess: (data: Any) -> Unit,
|
||||
// private val doFailure: (code: Int?, msg: String?) -> Unit
|
||||
// ) :
|
||||
// Callback {
|
||||
// override fun onFailure(call: Call, e: IOException) {
|
||||
// runMainThread {
|
||||
// e.printStackTrace()
|
||||
// doFailure(-1, "服务异常,${e.message}")
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// override fun onResponse(call: Call, response: Response) {
|
||||
// val respData = response.body?.string()
|
||||
// runMainThread {
|
||||
// Log.d("HttpUtil", respData ?: "")
|
||||
// runCatching {
|
||||
// val typeToken = object : TypeToken<BaseReq<Any>>() {}
|
||||
// val baseReq = respData?.toType<BaseReq<Any>>(typeToken = typeToken)
|
||||
// if (baseReq == null) {
|
||||
// doFailure(-1, "查询数据失败")
|
||||
// return@runCatching
|
||||
// }
|
||||
// if (baseReq.code != 200) {
|
||||
// doFailure(baseReq.code, baseReq.message)
|
||||
// //baseReq.code == 500 ||
|
||||
// if (baseReq.code == 401 && loopGetToken) {
|
||||
// exeTokenThread()
|
||||
// }
|
||||
// return@runCatching
|
||||
// }
|
||||
// doSuccess(baseReq.result ?: "")
|
||||
// }.onFailure {
|
||||
// it.printStackTrace()
|
||||
// doFailure(-1, "解析异常")
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// }
|
||||
//
|
||||
//}
|
||||
//
|
||||
//fun String.isHttpApi() = this.startsWith("http://") || this.startsWith("https://")
|
||||
@@ -1,37 +0,0 @@
|
||||
package com.shuwei.dish.match.http
|
||||
|
||||
//import com.shuwei.dish.match.base.BaseApp
|
||||
|
||||
object UrlConfig {
|
||||
// private const val DEVICE_BASE_URL = "http://device.shuziweidao.com:8889"
|
||||
// /**
|
||||
// * device获取token
|
||||
// */
|
||||
// const val DEVICE_TOKEN = "${DEVICE_BASE_URL}/sys/getEquipmentToken"
|
||||
// /**
|
||||
// *获取配置信息
|
||||
// */
|
||||
// const val DEVICE_CONFIG = "${DEVICE_BASE_URL}/equipment/stEquipment/queryByEquipmentCode"
|
||||
|
||||
// const val BASE_URL = "http://vip.shuziweidao.com/shuwei-zhct"
|
||||
// const val DISH_DETAIL = "$BASE_URL/scales/goodsUseList?foodId={foodId}&foodWeight={foodWeight}"
|
||||
// const val DISH_LIST = "$BASE_URL/scales/getRestInfoFoods?eaId=99&type=0&foodName"
|
||||
|
||||
// const val BASE_URL = "http://192.168.1.207:9102"
|
||||
// const val BASE_URL = "https://yyjk.shuziweidao.com/gateway"
|
||||
const val BASE_URL = "https://yyjk.shuziweidao.com/gateway/"
|
||||
// const val DISH_LIST = "$BASE_URL/scales/getRestInfoFoods?eaId=99&type=0&foodName"
|
||||
|
||||
|
||||
// var DISH_DETAIL = "${BaseApp.configUrl}/food/stFoodInfoMatching/queryById"
|
||||
//
|
||||
// // "$BASE_URL/scales/generateToken?deviceId=1111111111111111111111111111"
|
||||
//
|
||||
// var GET_TOKEN = "${BaseApp.configUrl}/restaurant/equipment/stEquipment/getEquipmentToken"
|
||||
// var SUBMIT_DISH = "${BaseApp.configUrl}/food/stFoodInfoMatching/saveoredit"
|
||||
//
|
||||
// var QUERY_GOODS_LIST = "${BaseApp.configUrl}/food/stFoodInfoMatching/queryGoodsInfoList"
|
||||
// var QUERY_FOOD_LIST = "${BaseApp.configUrl}/food/stFoodInfoMatching/list"
|
||||
// var SAMPLING_LIST = "${BaseApp.configUrl}/food/stFoodInfoMatching/queryHistorical/goodsInfoList"
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.shuwei.dish.match.model
|
||||
|
||||
/**
|
||||
* 已采集食材列表项数据模型
|
||||
* @param foodName 食材名称
|
||||
* @param collectCount 已采集数量
|
||||
*/
|
||||
data class CollectedFoodItem(
|
||||
val foodName: String = "",
|
||||
val collectCount: Int = 0
|
||||
)
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.shuwei.dish.match.model
|
||||
|
||||
import com.shuwei.dish.match.db.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||
import java.io.Serializable
|
||||
|
||||
/**
|
||||
* 菜品详情接口传输对象(DTO),不依赖 Room
|
||||
* 对应接口:getConstituteByFoodId / saveConstitute
|
||||
*/
|
||||
data class CookFoodDTO(
|
||||
var foodId: String = "",
|
||||
var foodName: String? = null,
|
||||
var canteenId: String? = null,
|
||||
var foodWeight: Double = 0.0,
|
||||
// 0-制作模式,1-采样模式,2-品控模式
|
||||
var cookMode: Int = 0,
|
||||
var dinnerType: String? = "0",
|
||||
// 接口返回的食材构成列表
|
||||
var matchingConstituteInfoList: MutableList<CookFoodGoodsDTO>? = null,
|
||||
var foodConstituteList: MutableList<CookFoodGoodsDTO>? = null
|
||||
) : Serializable {
|
||||
|
||||
/**
|
||||
* 转换为 Room 实体,用于写入本地数据库
|
||||
* id/isDel/createTime 由 Room 自行管理,不从 DTO 携带
|
||||
*/
|
||||
fun toEntity(): CookFoodEntity = CookFoodEntity(
|
||||
foodId = foodId,
|
||||
foodName = foodName,
|
||||
canteenId = canteenId,
|
||||
foodWeight = foodWeight,
|
||||
cookMode = cookMode,
|
||||
dinnerType = dinnerType
|
||||
).also { entity ->
|
||||
entity.matchingConstituteInfoList = matchingConstituteInfoList
|
||||
?.map { it.toEntity() }
|
||||
?.toMutableList()
|
||||
entity.foodConstituteList = foodConstituteList
|
||||
?.map { it.toEntity() }
|
||||
?.toMutableList()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package com.shuwei.dish.match.model
|
||||
|
||||
import com.shuwei.dish.match.db.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||
import java.io.Serializable
|
||||
|
||||
/**
|
||||
* 菜品构成(主辅料/调料)接口传输对象(DTO),不依赖 Room
|
||||
* 对应 CookFoodDTO 中 foodConstituteList、matchingConstituteInfoList 的元素
|
||||
*/
|
||||
data class CookFoodGoodsDTO(
|
||||
var goodsId: String = "",
|
||||
var goodsName: String? = null,
|
||||
var foodId: String? = "",
|
||||
var goodsOrRelationCode: String? = "",
|
||||
// 调料数据顺序
|
||||
var sort: Int = 0,
|
||||
// 食材原材料:1,预制品:2
|
||||
var relateionType: Int = 0,
|
||||
// 物品类型:1主料 2辅料 3调料
|
||||
var materialType: Int = 0,
|
||||
// 物品 是否全部可食:true-全部可食,false-部分可食
|
||||
var allEdible: Boolean = true,
|
||||
// 物品 用料重量
|
||||
var useWeight: Double? = 0.0,
|
||||
var popularName: String? = "",
|
||||
var canteenId: String? = "",
|
||||
var relateionType_dictText: String? = "",
|
||||
var zjmCode: String? = "",
|
||||
var materId: String? = "",
|
||||
// 物料编码
|
||||
var goodsCode: String? = "",
|
||||
// 净材种类
|
||||
var rawMaterialsType: String? = null
|
||||
) : Serializable {
|
||||
|
||||
/**
|
||||
* 转换为 GoodsItem,用于 UI 层
|
||||
*/
|
||||
fun toGoodsItem(): GoodsItem = GoodsItem(
|
||||
goodsId = goodsId,
|
||||
goodsName = goodsName,
|
||||
popularName = popularName,
|
||||
zjmCode = zjmCode,
|
||||
materId = materId,
|
||||
materCode = goodsCode,
|
||||
materialType = materialType,
|
||||
useWeight = useWeight,
|
||||
relateionType = relateionType,
|
||||
allEdible = allEdible,
|
||||
goodsOrRelationCode = goodsOrRelationCode,
|
||||
rawMaterialsType = rawMaterialsType
|
||||
)
|
||||
|
||||
/**
|
||||
* 转换为 Room 实体,用于写入本地数据库
|
||||
* id/pid/isDel/createTime 由 Room 自行管理,不从 DTO 携带
|
||||
*/
|
||||
fun toEntity(): CookFoodGoodsEntity = CookFoodGoodsEntity(
|
||||
goodsId = goodsId,
|
||||
goodsName = goodsName,
|
||||
foodId = foodId,
|
||||
goodsOrRelationCode = goodsOrRelationCode,
|
||||
sort = sort,
|
||||
relateionType = relateionType,
|
||||
materialType = materialType,
|
||||
allEdible = allEdible,
|
||||
useWeight = useWeight,
|
||||
popularName = popularName,
|
||||
canteenId = canteenId,
|
||||
relateionType_dictText = relateionType_dictText,
|
||||
zjmCode = zjmCode,
|
||||
materId = materId,
|
||||
goodsCode = goodsCode,
|
||||
rawMaterialsType = rawMaterialsType
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Room 实体 → DTO 反向映射,用于将本地数据转为接口提交格式
|
||||
* id/pid/isDel/createTime 为本地数据库字段,不参与提交
|
||||
*/
|
||||
fun CookFoodGoodsEntity.toDTO(): CookFoodGoodsDTO = CookFoodGoodsDTO(
|
||||
goodsId = goodsId,
|
||||
goodsName = goodsName,
|
||||
foodId = foodId,
|
||||
goodsOrRelationCode = goodsOrRelationCode,
|
||||
sort = sort,
|
||||
relateionType = relateionType,
|
||||
materialType = materialType,
|
||||
allEdible = allEdible,
|
||||
useWeight = useWeight,
|
||||
popularName = popularName,
|
||||
canteenId = canteenId,
|
||||
relateionType_dictText = relateionType_dictText,
|
||||
zjmCode = zjmCode,
|
||||
materId = materId,
|
||||
goodsCode = goodsCode,
|
||||
rawMaterialsType = rawMaterialsType
|
||||
)
|
||||
|
||||
/**
|
||||
* Room 实体 → DTO 反向映射,用于将本地数据转为接口提交格式
|
||||
* id/isDel/createTime 为本地数据库字段,不参与提交
|
||||
*/
|
||||
fun CookFoodEntity.toDTO(): CookFoodDTO = CookFoodDTO(
|
||||
foodId = foodId,
|
||||
foodName = foodName,
|
||||
canteenId = canteenId,
|
||||
foodWeight = foodWeight,
|
||||
cookMode = cookMode,
|
||||
dinnerType = dinnerType,
|
||||
matchingConstituteInfoList = matchingConstituteInfoList
|
||||
?.map { it.toDTO() }
|
||||
?.toMutableList(),
|
||||
foodConstituteList = foodConstituteList
|
||||
?.map { it.toDTO() }
|
||||
?.toMutableList()
|
||||
)
|
||||
@@ -0,0 +1,146 @@
|
||||
package com.shuwei.dish.match.model
|
||||
|
||||
/**
|
||||
* 当日烹饪任务列表(按餐次分组)请求参数
|
||||
* 对应接口: POST /neglect/ratio-scale/cook-orders/page
|
||||
*/
|
||||
data class CookOrderPageRequest(
|
||||
/** 计划日期 yyyy-MM-dd,默认当天 */
|
||||
val date: String? = null,
|
||||
/** 餐次筛选: 1=早餐 / 2=午餐 / 3=晚餐 / 4=加餐,不传返回全部 */
|
||||
val mealType: Int? = null,
|
||||
/** 菜品名称模糊搜索 */
|
||||
val keyword: String? = null,
|
||||
/** 保留字段,当前不使用 */
|
||||
val pageNum: Int? = null,
|
||||
/** 保留字段,当前不使用 */
|
||||
val pageSize: Int? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 餐次分组,包含该餐次下的烹制单列表
|
||||
*/
|
||||
data class CookOrderMealGroup(
|
||||
/** 餐次: 1=早餐 / 2=午餐 / 3=晚餐 / 4=加餐 */
|
||||
val mealType: Int = 0,
|
||||
/** 餐次中文名称 */
|
||||
val mealTypeName: String = "",
|
||||
/** 该餐次下的烹制单列表 */
|
||||
val cookOrders: List<CookOrderItem> = emptyList()
|
||||
)
|
||||
|
||||
/**
|
||||
* 单个烹制单,对应接口响应中 cookOrders 数组的条目
|
||||
* 注意: Long 类型字段服务端序列化为 String
|
||||
*/
|
||||
data class CookOrderItem(
|
||||
/** 烹制单id(Long → String) */
|
||||
val cookOrderId: String = "",
|
||||
/** 烹制单号 */
|
||||
val cookNo: String = "",
|
||||
/** 菜品名称 */
|
||||
val dishName: String = "",
|
||||
/** 菜品id(关联 nut_food) */
|
||||
val foodId: String = "",
|
||||
/** 餐次: 1=早餐 / 2=午餐 / 3=晚餐 / 4=加餐 */
|
||||
val mealType: Int = 0,
|
||||
/** 餐次中文名称 */
|
||||
val mealTypeName: String = "",
|
||||
/** 烹制状态: 0=待烹制 / 1=烹制中 / 2=已完成 / 3=异常 */
|
||||
val cookStatus: Int = 0,
|
||||
/** 烹制状态中文 */
|
||||
val cookStatusName: String = "",
|
||||
/** 生重(kg),烹制完成后才有值 */
|
||||
val rawWeight: Double? = null,
|
||||
/** 熟重(kg),烹制完成后才有值 */
|
||||
val cookedWeight: Double? = null,
|
||||
/** 需求份数 */
|
||||
val needPortions: Int = 0,
|
||||
/** 烹制份数,烹制完成后才有值 */
|
||||
val cookedPortions: Int? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 菜品食材构成(主材+辅材),对应接口响应中单个食材
|
||||
* 对应接口: GET /neglect/ratio-scale/cook-orders/{cookOrderId}/composition
|
||||
* 注意: 此接口仅返回主材(ingredientClass=1)和辅材(ingredientClass=2),不含调料
|
||||
*/
|
||||
data class CookOrderCompositionItem(
|
||||
/** 食材id */
|
||||
val materId: String = "",
|
||||
/** 食材名称 */
|
||||
val ingredientName: String = "",
|
||||
/** 食材分类: 1=主材 / 2=辅材 */
|
||||
val ingredientClass: Int = 0,
|
||||
/** 食材分类中文名称 */
|
||||
val ingredientClassName: String = "",
|
||||
/** 标准用量(g) */
|
||||
val useWeight: Double = 0.0,
|
||||
/** 净菜类型id */
|
||||
val vegTypeId: String = ""
|
||||
)
|
||||
|
||||
// ==================== 调料模糊搜索 ====================
|
||||
|
||||
/**
|
||||
* 调料模糊搜索请求参数
|
||||
* 对应接口: POST /neglect/ratio-scale/seasoning-search
|
||||
* 数据源: nut_mater_base 一级分类为 18(糖蜜饯)、19(油脂)、20(调味品)
|
||||
*/
|
||||
data class SeasoningSearchRequest(
|
||||
/** 模糊匹配食材名称和别名,为空时返回全部 */
|
||||
val keyword: String? = null,
|
||||
/** 页码 */
|
||||
val pageNum: Int = 1,
|
||||
/** 每页条数 */
|
||||
val pageSize: Int = 20
|
||||
)
|
||||
|
||||
/**
|
||||
* 调料模糊搜索结果条目
|
||||
* 注意: Long 类型字段服务端序列化为 String
|
||||
*/
|
||||
data class SeasoningSearchItem(
|
||||
/** 食材id(Long → String) */
|
||||
val id: String = "",
|
||||
/** 食材名称 */
|
||||
val materName: String = "",
|
||||
/** 食材编码 */
|
||||
val materCode: String = "",
|
||||
/** 别名 */
|
||||
val alias: String = "",
|
||||
/** 归属食堂id(Long → String) */
|
||||
val canteenId: String = ""
|
||||
)
|
||||
|
||||
// ==================== 烹饪完成 ====================
|
||||
|
||||
/**
|
||||
* 烹饪完成 — 单个食材用量条目
|
||||
* 对应接口: POST /neglect/ratio-scale/cook-orders/complete
|
||||
*/
|
||||
data class CookCompleteItem(
|
||||
/** 食材id */
|
||||
val materId: String = "",
|
||||
/** 实际用量(g) */
|
||||
val actualQty: Double = 0.0,
|
||||
/** 调料首次使用时间 yyyy-MM-dd HH:mm:ss,仅调料需要,主辅材留空 */
|
||||
val putTime: String? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 烹饪完成请求,一次性提交主辅材用量+熟重+调料
|
||||
* 对应接口: POST /neglect/ratio-scale/cook-orders/complete
|
||||
*/
|
||||
data class CookCompleteRequest(
|
||||
/** 烹制单id */
|
||||
val cookOrderId: String = "",
|
||||
/** 烹饪开始时间 yyyy-MM-dd HH:mm:ss,进入提交页面时刻 */
|
||||
val cookStart: String? = null,
|
||||
/** 主辅材实际用量列表,至少1条 */
|
||||
val items: List<CookCompleteItem> = emptyList(),
|
||||
/** 熟重(kg) */
|
||||
val cookedWeight: Double = 0.0,
|
||||
/** 调料用量列表,选填 */
|
||||
val seasonings: List<CookCompleteItem>? = null
|
||||
)
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.shuwei.dish.match.model
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.net.Uri
|
||||
import java.io.File
|
||||
|
||||
data class HomeModeBean(
|
||||
var modeName: String = "",
|
||||
var modeDesc: String = "",
|
||||
var modeIconId: Int = 0,
|
||||
var isLocked: Boolean = false,
|
||||
|
||||
var onClick: (() -> Unit)? = null
|
||||
)
|
||||
|
||||
data class FoodCollectionBean(
|
||||
var imageUri: Uri? = null,
|
||||
var bitmap: Bitmap? = null,
|
||||
var imageFile: File? = null,
|
||||
var imageVector: FloatArray? = null,
|
||||
var isShowCamera: Boolean = false,
|
||||
var isFinish:Boolean = false,
|
||||
var uploadSuccess:Boolean = false
|
||||
) {
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (this === other) return true
|
||||
if (javaClass != other?.javaClass) return false
|
||||
|
||||
other as FoodCollectionBean
|
||||
|
||||
if (isShowCamera != other.isShowCamera) return false
|
||||
if (isFinish != other.isFinish) return false
|
||||
if (uploadSuccess != other.uploadSuccess) return false
|
||||
if (imageUri != other.imageUri) return false
|
||||
if (bitmap != other.bitmap) return false
|
||||
if (imageFile != other.imageFile) return false
|
||||
if (!imageVector.contentEquals(other.imageVector)) return false
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
override fun hashCode(): Int {
|
||||
var result = isShowCamera.hashCode()
|
||||
result = 31 * result + isFinish.hashCode()
|
||||
result = 31 * result + uploadSuccess.hashCode()
|
||||
result = 31 * result + (imageUri?.hashCode() ?: 0)
|
||||
result = 31 * result + (bitmap?.hashCode() ?: 0)
|
||||
result = 31 * result + (imageFile?.hashCode() ?: 0)
|
||||
result = 31 * result + (imageVector?.contentHashCode() ?: 0)
|
||||
return result
|
||||
}
|
||||
}
|
||||
+9
-3
@@ -1,4 +1,4 @@
|
||||
package com.shuwei.dish.match.entity
|
||||
package com.shuwei.dish.match.model
|
||||
|
||||
import java.io.Serializable
|
||||
|
||||
@@ -15,6 +15,12 @@ data class FoodRecord(
|
||||
var dinnerType: String = "0",
|
||||
//true-原始数据,false-非原始数据
|
||||
var isOriginalData: Boolean = true,
|
||||
var sort: Int = 0
|
||||
var sort: Int = 0,
|
||||
// ===== 已提交采样列表(sample-list)扩展字段,制作模式不涉及 =====
|
||||
/** 实验编号(innovNo) */
|
||||
var innovNo: String? = null,
|
||||
/** 实验状态: 1=实验中 / 2=已评测 / 9=已转化 */
|
||||
var status: Int? = null,
|
||||
/** 实验状态中文 */
|
||||
var statusName: String? = null
|
||||
) : Serializable
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.shuwei.dish.match.model
|
||||
|
||||
import com.shuwei.dish.match.db.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.db.entity.SeasoningEntity
|
||||
import java.io.Serializable
|
||||
|
||||
/**
|
||||
* 物品信息接口返回的数据类(DTO),不依赖 Room,同时承载 UI 状态字段
|
||||
* 对应接口:queryGoodsInfoList,食材(goodsType=0)和调料(goodsType=1)共用此结构
|
||||
*/
|
||||
data class GoodsItem(
|
||||
// 接口返回字段
|
||||
var goodsId: String = "",
|
||||
val goodsName: String? = null,
|
||||
val popularName: String? = null,
|
||||
val zjmCode: String? = null,
|
||||
var materId: String? = null,
|
||||
val materCode: String? = null,
|
||||
|
||||
// 从 CookFoodGoodsEntity 迁移的数据字段(DishPartAdapter 显示及转换用)
|
||||
var materialType: Int = 0,
|
||||
var useWeight: Double? = 0.0,
|
||||
var relateionType: Int = 0,
|
||||
var allEdible: Boolean = true,
|
||||
var goodsOrRelationCode: String? = "",
|
||||
|
||||
// 从 CookFoodGoodsEntity @Ignore 迁移的 UI 状态字段
|
||||
var isSetFinished: Boolean = false,
|
||||
// var isItemClicked: Boolean = false,
|
||||
var isSamplingPage: Boolean = false,
|
||||
var isNewDishType: Boolean = false,
|
||||
var isClicked: Boolean = false,
|
||||
// true-原始数据,false-非原始数据(识图新增)
|
||||
var isOriginalData: Boolean = true,
|
||||
// true-用户手动指定了主辅材,updateMaterialTypes 自动分配时跳过
|
||||
var isMaterialTypeManual: Boolean = false,
|
||||
// 识图匹配分数,-1 表示不显示
|
||||
var foodScore: Int = -1,
|
||||
// 净材种类(当前选中值)
|
||||
var rawMaterialsType: String? = null,
|
||||
// 净材种类候选列表(临时字段,逗号分隔,不持久化)
|
||||
var rawMaterialsTypes: String? = null,
|
||||
var oldGoodsId: String? = null
|
||||
) : Serializable {
|
||||
|
||||
/**
|
||||
* 物料编码,与查询接口返回的 materCode 同值,统一对外暴露为 goodsCode 供下游使用
|
||||
*/
|
||||
val goodsCode: String? get() = materCode
|
||||
|
||||
/**
|
||||
* 转换为 CookFoodGoodsEntity,用于写入数据库或传给 SubmitFoodActivity
|
||||
*/
|
||||
fun toCookFoodGoodsEntity(): CookFoodGoodsEntity = CookFoodGoodsEntity(
|
||||
goodsId = goodsId,
|
||||
goodsName = goodsName,
|
||||
popularName = popularName,
|
||||
zjmCode = zjmCode,
|
||||
materId = materId,
|
||||
goodsCode = goodsCode,
|
||||
materialType = materialType,
|
||||
useWeight = useWeight,
|
||||
relateionType = relateionType,
|
||||
allEdible = allEdible,
|
||||
goodsOrRelationCode = goodsOrRelationCode,
|
||||
rawMaterialsType = rawMaterialsType
|
||||
)
|
||||
|
||||
/**
|
||||
* 转换为 SeasoningEntity,用于保存调料完整信息到 dm_seasoning
|
||||
*/
|
||||
fun toSeasoningEntity(): SeasoningEntity = SeasoningEntity(
|
||||
goodsId = goodsId,
|
||||
goodsName = goodsName,
|
||||
popularName = popularName,
|
||||
zjmCode = zjmCode,
|
||||
materId = materId,
|
||||
goodsCode = goodsCode,
|
||||
materialType = materialType,
|
||||
relateionType = relateionType,
|
||||
allEdible = allEdible,
|
||||
goodsOrRelationCode = goodsOrRelationCode,
|
||||
rawMaterialsType = rawMaterialsType
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.shuwei.dish.match.model
|
||||
|
||||
/**
|
||||
* 物品名称批量查询入参 DTO
|
||||
* 用于 queryGoodsInfoList 接口 goodsNames 字段的元素类型
|
||||
* @param goodsName 物品名称
|
||||
* @param rawMaterialsType 净材种类
|
||||
*/
|
||||
data class GoodsNameQueryDTO(
|
||||
val goodsName: String,
|
||||
val rawMaterialsType: String
|
||||
)
|
||||
@@ -0,0 +1,251 @@
|
||||
package com.shuwei.dish.match.model
|
||||
|
||||
/**
|
||||
* 采样与制作模式相关模型,对应配比秤接口(Controller: NutRatioScaleController)
|
||||
* 路径前缀: /neglect/ratio-scale
|
||||
* 序列化规则: Long 字段服务端返回字符串;请求体字段按后端约定(id 类字段用 String 与现有代码一致)
|
||||
*/
|
||||
|
||||
/** 采样实验状态(味养创新 nut_innovation.status) */
|
||||
object SampleStatus {
|
||||
/** 实验中 */
|
||||
const val EXPERIMENTING = 1
|
||||
/** 已评测 */
|
||||
const val EVALUATED = 2
|
||||
/** 已转化 */
|
||||
const val CONVERTED = 9
|
||||
}
|
||||
|
||||
// ==================== 一、食材模糊搜索 ====================
|
||||
|
||||
/**
|
||||
* 食材模糊搜索请求参数
|
||||
* 对应接口: POST /neglect/ratio-scale/mater-search
|
||||
* 数据源: nut_mater_base,限定设备对应食堂
|
||||
*/
|
||||
data class MaterSearchRequest(
|
||||
/** 模糊匹配食材名称和别名,为空时返回全部 */
|
||||
val keyword: String? = null,
|
||||
/** 页码 */
|
||||
val pageNum: Int = 1,
|
||||
/** 每页条数 */
|
||||
val pageSize: Int = 20
|
||||
)
|
||||
|
||||
/**
|
||||
* 食材模糊搜索结果条目
|
||||
* 注意: id / canteenId 为 Long 类型,服务端序列化为 String
|
||||
*/
|
||||
data class MaterSearchItem(
|
||||
/** 食材id(Long → String,提交构成 items.materId 使用) */
|
||||
val id: String = "",
|
||||
/** 食材名称 */
|
||||
val materName: String = "",
|
||||
/** 食材编码(一级+二级+自编码,全局唯一) */
|
||||
val materCode: String = "",
|
||||
/** 别名,可能为 null */
|
||||
val alias: String? = null,
|
||||
/** 食材一级分类 */
|
||||
val materFirstClass: String? = null,
|
||||
/** 食材二级分类 */
|
||||
val materSecondClass: String? = null,
|
||||
/** 食材图片url */
|
||||
val materUrl: String? = null,
|
||||
/** 归属食堂id(Long → String) */
|
||||
val canteenId: String = ""
|
||||
)
|
||||
|
||||
// ==================== 二、搜菜品 ====================
|
||||
|
||||
/**
|
||||
* 搜菜品请求参数(制作模式选已有菜品)
|
||||
* 对应接口: POST /neglect/ratio-scale/food-search
|
||||
* 数据源: nut_food(status=1 上架)
|
||||
*/
|
||||
data class FoodSearchRequest(
|
||||
/** 菜品名称或编号模糊搜索 */
|
||||
val keyword: String? = null,
|
||||
/** 页码 */
|
||||
val pageNum: Int = 1,
|
||||
/** 每页条数 */
|
||||
val pageSize: Int = 20
|
||||
)
|
||||
|
||||
/**
|
||||
* 搜菜品结果条目
|
||||
* 注意: foodId 为 Long 类型,服务端序列化为 String
|
||||
*/
|
||||
data class FoodSearchItem(
|
||||
/** 菜品id(Long → String) */
|
||||
val foodId: String = "",
|
||||
/** 菜品编号 */
|
||||
val foodCode: String = "",
|
||||
/** 菜品名称 */
|
||||
val foodName: String = ""
|
||||
)
|
||||
|
||||
// ==================== 三、查菜品构成 ====================
|
||||
|
||||
/**
|
||||
* 查菜品构成响应 — 单个食材
|
||||
* 对应接口: GET /neglect/ratio-scale/food/{foodId}/composition
|
||||
*/
|
||||
data class FoodCompositionIngredient(
|
||||
/** 食材id(Long → String) */
|
||||
val materId: String = "",
|
||||
/** 食材名称 */
|
||||
val materName: String = "",
|
||||
/** 用量(g) */
|
||||
val useWeight: Double = 0.0,
|
||||
/** 1=主材 / 2=辅材 / 3=调料 */
|
||||
val isMain: Int = 0,
|
||||
/** 分类中文名 */
|
||||
val isMainName: String = ""
|
||||
)
|
||||
|
||||
/**
|
||||
* 查菜品构成响应(主辅料+调料 + 熟重)
|
||||
* 对应接口: GET /neglect/ratio-scale/food/{foodId}/composition
|
||||
*/
|
||||
data class FoodCompositionResponse(
|
||||
/** 菜品id(Long → String) */
|
||||
val foodId: String = "",
|
||||
/** 菜品名称 */
|
||||
val foodName: String = "",
|
||||
/** 熟重(g),从 nut_food_cook.output_weight 反查 */
|
||||
val foodWeight: Double = 0.0,
|
||||
/** 食材构成列表 */
|
||||
val ingredients: List<FoodCompositionIngredient> = emptyList()
|
||||
)
|
||||
|
||||
// ==================== 四、提交采样 ====================
|
||||
|
||||
/**
|
||||
* 提交采样 — 单个食材构成条目
|
||||
* 对应接口: POST /neglect/ratio-scale/constitute/save
|
||||
*/
|
||||
data class ConstituteSaveItem(
|
||||
/** 食材id(nut_mater_base.id) */
|
||||
val materId: String = "",
|
||||
/** 食材称量用量(g),必须 > 0 */
|
||||
val useWeight: Double = 0.0,
|
||||
/** 食材分类: 1=主材 / 2=辅材 / 3=调料 */
|
||||
val isMain: Int = 0
|
||||
)
|
||||
|
||||
/**
|
||||
* 提交采样请求(落库味养创新实验,status=1 实验中)
|
||||
* 对应接口: POST /neglect/ratio-scale/constitute/save
|
||||
* 制作模式已废弃本接口,统一为提交采样,不再传 cookMode/foodId
|
||||
*/
|
||||
data class ConstituteSaveRequest(
|
||||
/** 菜品名称 */
|
||||
val foodName: String? = null,
|
||||
/** 熟重(g),必须 > 0 */
|
||||
val foodWeight: Double = 0.0,
|
||||
/** 食材构成列表,至少 1 条 */
|
||||
val items: List<ConstituteSaveItem> = emptyList()
|
||||
)
|
||||
|
||||
// ==================== 五、已提交采样列表 ====================
|
||||
|
||||
/**
|
||||
* 已提交采样列表查询请求参数
|
||||
* 对应接口: POST /neglect/ratio-scale/sample-list
|
||||
* 数据源: nut_innovation(source=2 配比秤采样),按提交时间倒序,不分日期
|
||||
*/
|
||||
data class SampleHistoryRequest(
|
||||
/** 页码 */
|
||||
val pageNum: Int = 1,
|
||||
/** 每页条数 */
|
||||
val pageSize: Int = 10
|
||||
)
|
||||
|
||||
/**
|
||||
* 已提交采样列表结果条目
|
||||
* 注意: innovId 为 Long 类型,服务端序列化为 String
|
||||
*/
|
||||
data class SampleHistoryItem(
|
||||
/** 味养创新实验id(Long → String) */
|
||||
val innovId: String = "",
|
||||
/** 实验编号 */
|
||||
val innovNo: String = "",
|
||||
/** 餐品名称 */
|
||||
val foodName: String = "",
|
||||
/** 熟重(g) */
|
||||
val foodWeight: Double = 0.0,
|
||||
/** 状态: 1=实验中 / 2=已评测 / 9=已转化 */
|
||||
val status: Int = 0,
|
||||
/** 状态中文 */
|
||||
val statusName: String = "",
|
||||
/** 提交时间 */
|
||||
val createTime: String = ""
|
||||
)
|
||||
|
||||
// ==================== 六、制作历史 ====================
|
||||
|
||||
/**
|
||||
* 制作历史查询请求参数
|
||||
* 对应接口: POST /neglect/ratio-scale/make/history
|
||||
* 数据源: nut_food_matching_use,按设备过滤
|
||||
*/
|
||||
data class MakeHistoryRequest(
|
||||
/** 页码 */
|
||||
val pageNum: Int = 1,
|
||||
/** 每页条数 */
|
||||
val pageSize: Int = 10,
|
||||
/** 制作日期 yyyy-MM-dd,不传查全部 */
|
||||
val day: String? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 制作历史结果条目
|
||||
* 注意: id / foodId 为 Long 类型,服务端序列化为 String
|
||||
*/
|
||||
data class MakeHistoryItem(
|
||||
/** 制作记录id(Long → String) */
|
||||
val id: String = "",
|
||||
/** 菜品id(Long → String) */
|
||||
val foodId: String = "",
|
||||
/** 菜品名称 */
|
||||
val foodName: String = "",
|
||||
/** 熟重(g) */
|
||||
val foodWeight: Double = 0.0,
|
||||
/** 餐次: 1=早餐/2=午餐/3=晚餐/4=加餐 */
|
||||
val mealType: Int = 0,
|
||||
/** 餐次中文 */
|
||||
val mealTypeName: String = "",
|
||||
/** 制作日期 */
|
||||
val day: String = "",
|
||||
/** 制作时间 */
|
||||
val createTime: String = ""
|
||||
)
|
||||
|
||||
// ==================== 七、制作历史图表 ====================
|
||||
|
||||
/**
|
||||
* 制作历史图表 — 横轴项
|
||||
* 对应接口: GET /neglect/ratio-scale/make/history/{foodId}
|
||||
*/
|
||||
data class MakeHistoryChartAxis(
|
||||
/** 食材id(时间/熟重项为空字符串) */
|
||||
val goodId: String = "",
|
||||
/** 项名称(时间/熟重/食材名称) */
|
||||
val goodName: String = ""
|
||||
)
|
||||
|
||||
/**
|
||||
* 制作历史图表 — 纵轴值
|
||||
* value 为 String(时间项) 或 Double(数值项)
|
||||
*/
|
||||
data class MakeHistoryChartValue(
|
||||
val value: Any? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* 制作历史图表 — 单条记录(xAxes 与 yAxes 一一对应)
|
||||
*/
|
||||
data class MakeHistoryChartRow(
|
||||
val xAxes: List<MakeHistoryChartAxis> = emptyList(),
|
||||
val yAxes: List<MakeHistoryChartValue> = emptyList()
|
||||
)
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.shuwei.dish.match.model
|
||||
|
||||
/**
|
||||
* 设置页面的列表项实体类
|
||||
*
|
||||
* @param type 菜单项类型,用于唯一标识每一项
|
||||
* @param title 主标题文字
|
||||
* @param subtitle 副标题文字,仅部分项目(如菜品模式)有值
|
||||
* @param isHidden 是否为隐藏项,隐藏项需触发开发者模式后才显示
|
||||
* @param onClick 点击回调,初始化时直接注入对应的业务逻辑
|
||||
*/
|
||||
data class SettingItem(
|
||||
val type: Type,
|
||||
val title: String,
|
||||
val subtitle: String? = null,
|
||||
val isHidden: Boolean = false,
|
||||
val onClick: () -> Unit
|
||||
) {
|
||||
/** 设置菜单项类型枚举 */
|
||||
enum class Type {
|
||||
/** 菜品模式切换 */
|
||||
COOK_MODE,
|
||||
/** 调料区设置 */
|
||||
SEASONING_CONFIG,
|
||||
/** 食材采集 */
|
||||
FOOD_COLLECT,
|
||||
/** 减重配置 */
|
||||
WEIGHT_CONFIG,
|
||||
/** 数据库查看(隐藏项) */
|
||||
DB_INSPECT,
|
||||
/** 秤数据监控(隐藏项) */
|
||||
SCALE_OBSERVE,
|
||||
/** 切换环境(隐藏项) */
|
||||
ENV_SWITCH,
|
||||
/** 数据清除(隐藏项) */
|
||||
CLEAR_DATA,
|
||||
/** 测试调料拿取(隐藏项) */
|
||||
TEST_SEASONING,
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,7 @@ import java.net.UnknownHostException
|
||||
* @param onSuccess 成功回调
|
||||
* @param onFailure 自定义错误回调(可选,不传则用默认提示)
|
||||
*/
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
suspend fun <T> request(
|
||||
onRequest: suspend () -> ApiResponse<T>,
|
||||
onSuccess: (T) -> Unit,
|
||||
@@ -73,6 +74,7 @@ data class CodeMsg(
|
||||
var msg: String? = null
|
||||
)
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
fun getApiException(e: Exception): ApiException {
|
||||
// 捕获各类网络异常并转换为自定义异常
|
||||
return when (e) {
|
||||
@@ -116,7 +118,7 @@ fun httpException2ApiException(e: HttpException): ApiException {
|
||||
val body = e.response()?.errorBody()?.string()
|
||||
val codeMsg: CodeMsg? = try {
|
||||
body?.toObject<CodeMsg>()
|
||||
} catch (ex: Exception) {
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
return ApiException(
|
||||
|
||||
@@ -1,13 +1,35 @@
|
||||
package com.shuwei.dish.match.net
|
||||
|
||||
import com.shuwei.dish.match.base.GlobalData
|
||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.entity.FoodRecord
|
||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.model.CookFoodDTO
|
||||
import com.shuwei.dish.match.model.CookOrderCompositionItem
|
||||
import com.shuwei.dish.match.model.CookOrderMealGroup
|
||||
import com.shuwei.dish.match.model.CookOrderPageRequest
|
||||
import com.shuwei.dish.match.model.FoodRecord
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
import com.shuwei.dish.match.model.ConstituteSaveRequest
|
||||
import com.shuwei.dish.match.model.CookCompleteRequest
|
||||
import com.shuwei.dish.match.model.FoodCompositionResponse
|
||||
import com.shuwei.dish.match.model.FoodSearchItem
|
||||
import com.shuwei.dish.match.model.FoodSearchRequest
|
||||
import com.shuwei.dish.match.model.MakeHistoryChartRow
|
||||
import com.shuwei.dish.match.model.MakeHistoryItem
|
||||
import com.shuwei.dish.match.model.MakeHistoryRequest
|
||||
import com.shuwei.dish.match.model.MaterSearchItem
|
||||
import com.shuwei.dish.match.model.MaterSearchRequest
|
||||
import com.shuwei.dish.match.model.SampleHistoryItem
|
||||
import com.shuwei.dish.match.model.SampleHistoryRequest
|
||||
import com.shuwei.dish.match.model.SeasoningSearchItem
|
||||
import com.shuwei.dish.match.model.SeasoningSearchRequest
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
import retrofit2.http.Body
|
||||
import retrofit2.http.GET
|
||||
import retrofit2.http.Multipart
|
||||
import retrofit2.http.POST
|
||||
import retrofit2.http.Part
|
||||
import retrofit2.http.PartMap
|
||||
import retrofit2.http.Path
|
||||
import retrofit2.http.Query
|
||||
import retrofit2.http.Url
|
||||
|
||||
@@ -18,9 +40,9 @@ interface ApiService {
|
||||
*/
|
||||
@GET
|
||||
suspend fun getFoodDetail(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/getConstituteByFoodId",
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/matching/app/getConstituteByFoodId",
|
||||
@Query("foodId") foodId: String
|
||||
): ApiResponse<CookFoodEntity?>
|
||||
): ApiResponse<CookFoodDTO?>
|
||||
|
||||
|
||||
/**
|
||||
@@ -28,16 +50,16 @@ interface ApiService {
|
||||
*/
|
||||
@POST
|
||||
suspend fun submitCookFood(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/saveConstitute",
|
||||
@Body param: CookFoodEntity
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/matching/app/saveConstitute",
|
||||
@Body param: CookFoodDTO
|
||||
): ApiResponse<Any?>
|
||||
|
||||
/**
|
||||
* 搜索菜品
|
||||
* 搜索菜品(旧接口,采样模式仍在使用)
|
||||
*/
|
||||
@POST
|
||||
suspend fun searchFoodList(
|
||||
@Url url:String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/queryPageList",
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/matching/app/queryPageList",
|
||||
@Body param: MutableMap<String, Any>
|
||||
): ApiResponse<MutableList<FoodRecord>?>
|
||||
|
||||
@@ -46,68 +68,129 @@ interface ApiService {
|
||||
*/
|
||||
@POST
|
||||
suspend fun getSamplingList(
|
||||
@Url url:String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/queryHistoryGoodsInfoList",
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/matching/app/queryHistoryGoodsInfoList",
|
||||
@Body param: MutableMap<String, Any>
|
||||
): ApiResponse<MutableList<FoodRecord>?>
|
||||
|
||||
/**
|
||||
* 物品信息
|
||||
* 物品信息(食材 goodsType=0,调料 goodsType=1 共用此接口)
|
||||
*/
|
||||
@POST
|
||||
suspend fun queryGoodsList(
|
||||
@Url url:String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/queryGoodsInfoList",
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/matching/app/queryGoodsInfoList",
|
||||
@Body param: MutableMap<String, Any>
|
||||
): ApiResponse<MutableList<CookFoodGoodsEntity>?>
|
||||
): ApiResponse<MutableList<GoodsItem>?>
|
||||
|
||||
/**
|
||||
* 调料信息
|
||||
* 提交采集图片数据
|
||||
*/
|
||||
@Multipart
|
||||
@POST
|
||||
suspend fun uploadFoodVectorData(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/matching/app/addWeighingCollectionData",
|
||||
@PartMap params: MutableMap<String, RequestBody>,
|
||||
@Part foodPics: List<MultipartBody.Part>
|
||||
): ApiResponse<List<String>?>
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 查询当日烹饪任务列表(按餐次分组),新配比秤接口
|
||||
*/
|
||||
@POST
|
||||
suspend fun querySeasoningList(
|
||||
@Url url:String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/queryGoodsInfoList",
|
||||
@Body param: MutableMap<String, Any>
|
||||
): ApiResponse<MutableList<SeasoningEntity>?>
|
||||
suspend fun getCookOrderPage(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/ratio-scale/cook-orders/list",
|
||||
@Body request: CookOrderPageRequest
|
||||
): ApiResponse<List<CookOrderMealGroup>?>
|
||||
|
||||
/**
|
||||
* 查询菜品食材构成(主材+辅材,不含调料),新配比秤接口
|
||||
*/
|
||||
@GET("nutrition/neglect/ratio-scale/cook-orders/{cookOrderId}/composition")
|
||||
suspend fun getCookOrderComposition(
|
||||
@Path("cookOrderId") cookOrderId: String
|
||||
): ApiResponse<List<CookOrderCompositionItem>?>
|
||||
|
||||
/**
|
||||
* 调料模糊搜索,新配比秤接口
|
||||
* 数据源: nut_mater_base 一级分类为 18(糖蜜饯)、19(油脂)、20(调味品)
|
||||
*/
|
||||
@POST
|
||||
suspend fun getSeasoningSearch(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/ratio-scale/seasoning-search",
|
||||
@Body request: SeasoningSearchRequest
|
||||
): ApiResponse<List<SeasoningSearchItem>?>
|
||||
|
||||
/**
|
||||
* 烹饪完成:提交主辅材用量+熟重+调料,一次性完成烹制
|
||||
* 新配比秤接口,替代旧 saveConstitute
|
||||
*/
|
||||
@POST
|
||||
suspend fun cookOrderComplete(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/ratio-scale/cook-orders/complete",
|
||||
@Body request: CookCompleteRequest
|
||||
): ApiResponse<Any?>
|
||||
|
||||
/**
|
||||
* 食材模糊搜索(采样/制作通用,称量前检索食材)
|
||||
* 数据源: nut_mater_base,限定设备对应食堂,模糊匹配名称和别名
|
||||
*/
|
||||
@POST
|
||||
suspend fun materSearch(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/ratio-scale/mater-search",
|
||||
@Body request: MaterSearchRequest
|
||||
): ApiResponse<MutableList<MaterSearchItem>?>
|
||||
|
||||
/**
|
||||
* 搜菜品(制作模式选已有上架菜品)
|
||||
*/
|
||||
@POST
|
||||
suspend fun foodSearch(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/ratio-scale/food-search",
|
||||
@Body request: FoodSearchRequest
|
||||
): ApiResponse<MutableList<FoodSearchItem>?>
|
||||
|
||||
/**
|
||||
* 查菜品构成(制作模式查看已有菜品主辅料+调料 + 熟重)
|
||||
*/
|
||||
@GET("nutrition/neglect/ratio-scale/food/{foodId}/composition")
|
||||
suspend fun getFoodComposition(
|
||||
@Path("foodId") foodId: String
|
||||
): ApiResponse<FoodCompositionResponse?>
|
||||
|
||||
// /**
|
||||
// *获取配置信息
|
||||
// */
|
||||
// @GET("/equipment/stEquipment/queryByEquipmentCode")
|
||||
// suspend fun getDeviceInfo(
|
||||
// @Query("equipmentCode") equipmentCode: String,
|
||||
// @Query("appVersion") appVersion: String = App.appVersion
|
||||
// ): ApiResponse<DeviceConfigInfo>
|
||||
//
|
||||
// @GET
|
||||
// suspend fun getAccessToken(
|
||||
// @Url url: String = UrlConfig.GET_ACCESS_TOKEN,
|
||||
// @Query("qrcodeId") qrcodeId: String
|
||||
// ): ApiResponse<String?>
|
||||
//
|
||||
// @GET
|
||||
// suspend fun getShelfList(
|
||||
// @Url url: String = UrlConfig.GET_SHELF_LIST,
|
||||
// @Query("deviceId") deviceId: String
|
||||
// ): ApiResponse<ShelfResult>
|
||||
//
|
||||
// @GET
|
||||
// suspend fun getGoodsList(
|
||||
// @Url url: String = UrlConfig.GET_GOODS_LIST,
|
||||
// @Query("canteenId") canteenId: String = "0",
|
||||
// @Query("goodsName") goodsName: String? = null,
|
||||
// @Query("pageNo") pageNo: Int = 1,
|
||||
// @Query("pageSize") pageSize: Int = 50
|
||||
// ): ApiResponse<MutableList<GoodsModel>?>
|
||||
//
|
||||
// @POST
|
||||
// suspend fun saveShelfGoodsList(
|
||||
// @Url url: String = UrlConfig.SAVE_SHELF_GOODS_LIST,
|
||||
// @Body body: ShelfBody
|
||||
// ): ApiResponse<Any?>
|
||||
/**
|
||||
* 提交采样(落库味养创新实验,制作模式已废弃本接口)
|
||||
*/
|
||||
@POST
|
||||
suspend fun constituteSave(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/ratio-scale/constitute/save",
|
||||
@Body request: ConstituteSaveRequest
|
||||
): ApiResponse<Any?>
|
||||
|
||||
/**
|
||||
* 已提交采样列表(本食堂 source=2,按提交时间倒序,不分日期)
|
||||
*/
|
||||
@POST
|
||||
suspend fun sampleHistory(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/ratio-scale/sample-list",
|
||||
@Body request: SampleHistoryRequest
|
||||
): ApiResponse<MutableList<SampleHistoryItem>?>
|
||||
|
||||
/**
|
||||
* 制作历史(本设备,按日期可选过滤)
|
||||
*/
|
||||
@POST
|
||||
suspend fun makeHistory(
|
||||
@Url url: String = "${GlobalData.appBaseUrl}/nutrition/neglect/ratio-scale/make/history",
|
||||
@Body request: MakeHistoryRequest
|
||||
): ApiResponse<MutableList<MakeHistoryItem>?>
|
||||
|
||||
/**
|
||||
* 制作历史图表(按菜品id)
|
||||
*/
|
||||
@GET("nutrition/neglect/ratio-scale/make/history/{foodId}")
|
||||
suspend fun makeHistoryChart(
|
||||
@Path("foodId") foodId: String
|
||||
): ApiResponse<MutableList<MakeHistoryChartRow>?>
|
||||
|
||||
}
|
||||
@@ -2,7 +2,7 @@ package com.shuwei.dish.match.net
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.util.Log
|
||||
import com.shuwei.dish.match.http.UrlConfig
|
||||
import com.shuwei.dish.match.base.GlobalData
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.logging.HttpLoggingInterceptor
|
||||
import retrofit2.Retrofit
|
||||
@@ -16,7 +16,7 @@ import kotlin.apply
|
||||
import kotlin.jvm.java
|
||||
|
||||
val apiService: ApiService = Retrofit.Builder()
|
||||
.baseUrl(UrlConfig.BASE_URL)
|
||||
.baseUrl(GlobalData.appBaseUrl)
|
||||
// .baseUrl(UrlConfig.DEVICE_BASE_URL)
|
||||
.client(HttpManager.instance.client)
|
||||
.addConverterFactory(GsonConverterFactory.create())
|
||||
|
||||
@@ -2,110 +2,487 @@ package com.shuwei.dish.match.net
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.entity.FoodRecord
|
||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.model.CookFoodDTO
|
||||
import com.shuwei.dish.match.model.CookOrderCompositionItem
|
||||
import com.shuwei.dish.match.model.CookOrderMealGroup
|
||||
import com.shuwei.dish.match.model.CookOrderPageRequest
|
||||
import com.shuwei.dish.match.model.FoodRecord
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
import com.shuwei.dish.match.model.GoodsNameQueryDTO
|
||||
import com.shuwei.dish.match.model.ConstituteSaveRequest
|
||||
import com.shuwei.dish.match.model.CookCompleteRequest
|
||||
import com.shuwei.dish.match.model.FoodCompositionResponse
|
||||
import com.shuwei.dish.match.model.FoodSearchItem
|
||||
import com.shuwei.dish.match.model.FoodSearchRequest
|
||||
import com.shuwei.dish.match.model.MakeHistoryChartRow
|
||||
import com.shuwei.dish.match.model.MakeHistoryItem
|
||||
import com.shuwei.dish.match.model.MakeHistoryRequest
|
||||
import com.shuwei.dish.match.model.MaterSearchItem
|
||||
import com.shuwei.dish.match.model.MaterSearchRequest
|
||||
import com.shuwei.dish.match.model.SampleHistoryItem
|
||||
import com.shuwei.dish.match.model.SampleHistoryRequest
|
||||
import com.shuwei.dish.match.model.SeasoningSearchItem
|
||||
import com.shuwei.dish.match.model.SeasoningSearchRequest
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.RequestBody.Companion.asRequestBody
|
||||
import java.io.File
|
||||
|
||||
class NetViewModel : ViewModel() {
|
||||
/**
|
||||
* 网络请求 ViewModel,所有网络操作通过 RemoteRepository 发起,不直接依赖 apiService
|
||||
* @param repository 网络数据仓库,默认使用单例实例
|
||||
*/
|
||||
class NetViewModel(
|
||||
private val repository: RemoteRepository = RemoteRepository()
|
||||
) : ViewModel() {
|
||||
|
||||
fun submitCookFood(
|
||||
entity: CookFoodEntity,
|
||||
onSuccess: (Any?) -> Unit,
|
||||
onFailure: (String, String) -> Unit
|
||||
) {
|
||||
/**
|
||||
* 提交制作菜品的 UI 状态流,UI 层通过 collect 监听
|
||||
*/
|
||||
private val _submitCookFoodState = MutableStateFlow<UiState<Any?>>(UiState.Idle)
|
||||
val submitCookFoodState: StateFlow<UiState<Any?>> = _submitCookFoodState.asStateFlow()
|
||||
|
||||
/**
|
||||
* 提交制作菜品
|
||||
*/
|
||||
fun submitCookFood(entity: CookFoodDTO) {
|
||||
viewModelScope.launch {
|
||||
request(
|
||||
onRequest = {
|
||||
apiService.submitCookFood(param = entity)
|
||||
},
|
||||
onSuccess = onSuccess,
|
||||
onFailure = onFailure
|
||||
)
|
||||
_submitCookFoodState.value = UiState.Loading
|
||||
_submitCookFoodState.value = repository.submitCookFood(entity)
|
||||
}
|
||||
}
|
||||
|
||||
fun getFoodDetail(
|
||||
foodId: String,
|
||||
onSuccess: (CookFoodEntity?) -> Unit,
|
||||
onFailure: (String, String) -> Unit
|
||||
) {
|
||||
/**
|
||||
* 查询菜品详情的 UI 状态流,UI 层通过 collect 监听
|
||||
*/
|
||||
private val _foodDetailState = MutableStateFlow<UiState<CookFoodDTO?>>(UiState.Idle)
|
||||
val foodDetailState: StateFlow<UiState<CookFoodDTO?>> = _foodDetailState.asStateFlow()
|
||||
|
||||
/**
|
||||
* 查询菜品详情
|
||||
*/
|
||||
fun getFoodDetail(foodId: String) {
|
||||
viewModelScope.launch {
|
||||
request(
|
||||
onRequest = {
|
||||
apiService.getFoodDetail(foodId = foodId)
|
||||
},
|
||||
onSuccess = onSuccess,
|
||||
onFailure = onFailure
|
||||
)
|
||||
_foodDetailState.value = UiState.Loading
|
||||
_foodDetailState.value = repository.getFoodDetail(foodId)
|
||||
}
|
||||
}
|
||||
|
||||
fun resetFoodDetailState() {
|
||||
_foodDetailState.value = UiState.Idle
|
||||
}
|
||||
|
||||
fun searchFoodList(
|
||||
/**
|
||||
* 查询菜品食材构成的 UI 状态流(新配比秤接口),UI 层通过 collect 监听
|
||||
*/
|
||||
private val _cookOrderCompositionState = MutableStateFlow<UiState<List<CookOrderCompositionItem>?>>(UiState.Idle)
|
||||
val cookOrderCompositionState: StateFlow<UiState<List<CookOrderCompositionItem>?>> = _cookOrderCompositionState.asStateFlow()
|
||||
|
||||
/**
|
||||
* 查询菜品食材构成(新配比秤接口,仅返回主材+辅材)
|
||||
* @param cookOrderId 烹制单 ID
|
||||
*/
|
||||
fun getCookOrderComposition(cookOrderId: String) {
|
||||
viewModelScope.launch {
|
||||
_cookOrderCompositionState.value = UiState.Loading
|
||||
_cookOrderCompositionState.value = repository.getCookOrderComposition(cookOrderId)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索菜品列表的 UI 状态流。
|
||||
* 使用 replay=1 保证 Fragment 重建后能收到最近一次结果;
|
||||
* emit 时包一层 Event wrapper 打破 equals 去重,确保相同数据也能触发 collect。
|
||||
*/
|
||||
private val _searchFoodState = MutableSharedFlow<UiState<MutableList<FoodRecord>?>>(
|
||||
replay = 1,
|
||||
extraBufferCapacity = 1
|
||||
)
|
||||
val searchFoodState: SharedFlow<UiState<MutableList<FoodRecord>?>> = _searchFoodState.asSharedFlow()
|
||||
|
||||
/**
|
||||
* 搜索菜品列表
|
||||
*/
|
||||
fun searchFoodList(param: MutableMap<String, Any>) {
|
||||
viewModelScope.launch {
|
||||
// pageNum=1 时先 emit Idle 重置 replay 缓存,防止相同数据导致 SharedFlow 去重不触发
|
||||
if (param["pageNum"] == 1) {
|
||||
_searchFoodState.emit(UiState.Idle)
|
||||
}
|
||||
_searchFoodState.emit(UiState.Loading)
|
||||
_searchFoodState.emit(repository.searchFoodList(param))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜索菜品列表(回调版本),结果通过 onResult 直接回调,不经过 StateFlow/SharedFlow
|
||||
* 适合需要每次都能触发的场景(下拉刷新、上拉加载更多)
|
||||
*/
|
||||
fun searchFoodListWithCallback(
|
||||
param: MutableMap<String, Any>,
|
||||
onSuccess: (MutableList<FoodRecord>?) -> Unit,
|
||||
onFailure: (String, String) -> Unit
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<MutableList<FoodRecord>?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
request(
|
||||
onRequest = {
|
||||
apiService.searchFoodList(param = param)
|
||||
},
|
||||
onSuccess = onSuccess,
|
||||
onFailure = onFailure
|
||||
)
|
||||
onLoading()
|
||||
onResult(repository.searchFoodList(param))
|
||||
}
|
||||
}
|
||||
|
||||
fun getSamplingList(
|
||||
/**
|
||||
* 当日烹饪任务列表的 UI 状态流(新配比秤接口),UI 层通过 collect 监听
|
||||
* 使用 SharedFlow(replay=1) 保证 Fragment 重建后收到最近一次结果
|
||||
*/
|
||||
private val _cookOrderPageState = MutableSharedFlow<UiState<List<CookOrderMealGroup>?>>(
|
||||
replay = 1,
|
||||
extraBufferCapacity = 1
|
||||
)
|
||||
val cookOrderPageState: SharedFlow<UiState<List<CookOrderMealGroup>?>> = _cookOrderPageState.asSharedFlow()
|
||||
|
||||
/**
|
||||
* 查询当日烹饪任务列表(新配比秤接口,StateFlow 版本)
|
||||
* 适合 FoodSearchActivity 等通过 collect 监听结果的场景
|
||||
*/
|
||||
fun getCookOrderPage(request: CookOrderPageRequest) {
|
||||
viewModelScope.launch {
|
||||
_cookOrderPageState.emit(UiState.Loading)
|
||||
_cookOrderPageState.emit(repository.getCookOrderPage(request))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询当日烹饪任务列表(新配比秤接口,回调版本)
|
||||
* 适合 FoodListFragment 下拉刷新、Tab 切换等需要每次都能触发的场景
|
||||
*/
|
||||
fun getCookOrderPageWithCallback(
|
||||
request: CookOrderPageRequest,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<List<CookOrderMealGroup>?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.getCookOrderPage(request))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*/
|
||||
private val _samplingListState = MutableStateFlow<UiState<MutableList<FoodRecord>?>>(UiState.Idle)
|
||||
val samplingListState: StateFlow<UiState<MutableList<FoodRecord>?>> = _samplingListState.asStateFlow()
|
||||
fun resetSamplingListState() {
|
||||
_samplingListState.value = UiState.Idle
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询采样数据列表
|
||||
*/
|
||||
fun getSamplingList(param: MutableMap<String, Any>) {
|
||||
viewModelScope.launch {
|
||||
_samplingListState.value = UiState.Loading
|
||||
_samplingListState.value = repository.getSamplingList(param)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询采样数据列表(回调版本),结果通过 onResult 直接回调,不经过 StateFlow
|
||||
* 适合不需要跨生命周期持续监听的一次性查询场景
|
||||
*/
|
||||
fun getSamplingListWithCallback(
|
||||
param: MutableMap<String, Any>,
|
||||
onSuccess: (MutableList<FoodRecord>?) -> Unit,
|
||||
onFailure: (String, String) -> Unit
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<MutableList<FoodRecord>?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
request(
|
||||
onRequest = {
|
||||
apiService.getSamplingList(param = param)
|
||||
},
|
||||
onSuccess = onSuccess,
|
||||
onFailure = onFailure
|
||||
)
|
||||
onLoading()
|
||||
onResult(repository.getSamplingList(param))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询物品信息列表的 UI 状态流(食材/调料共用),UI 层通过 collect 监听
|
||||
*/
|
||||
private val _goodsListState = MutableStateFlow<UiState<MutableList<GoodsItem>?>>(UiState.Idle)
|
||||
val goodsListState: StateFlow<UiState<MutableList<GoodsItem>?>> = _goodsListState.asStateFlow()
|
||||
|
||||
/**
|
||||
* 食材搜索弹窗专用的 UI 状态流,与 goodsListState 隔离,避免弹窗请求影响其他页面
|
||||
*/
|
||||
private val _foodSearchGoodsListState = MutableStateFlow<UiState<MutableList<GoodsItem>?>>(UiState.Idle)
|
||||
val foodSearchGoodsListState: StateFlow<UiState<MutableList<GoodsItem>?>> = _foodSearchGoodsListState.asStateFlow()
|
||||
|
||||
fun resetGoodsListState() {
|
||||
_goodsListState.value = UiState.Idle
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询物品信息列表(食材 goodsType=0,调料 goodsType=1 共用)
|
||||
* @param goodsType 物品类型:0=食材,1=调料
|
||||
* @param placeId 场所 ID,默认取当前食堂 ID
|
||||
* @param pageNum 页码,默认第 1 页
|
||||
* @param pageSize 每页条数,默认 50
|
||||
* @param goodsName 按名称模糊搜索,为 null 时不传该字段
|
||||
* @param goodsNames 按名称+净材种类列表批量查询,为 null 时不传该字段
|
||||
*/
|
||||
fun queryGoodsList(
|
||||
param: MutableMap<String, Any>,
|
||||
onSuccess: (MutableList<CookFoodGoodsEntity>?) -> Unit,
|
||||
onFailure: (String, String) -> Unit
|
||||
goodsType: String,
|
||||
placeId: String = BaseApp.canteenId,
|
||||
pageNum: Int = 1,
|
||||
pageSize: Int = 50,
|
||||
goodsName: String? = null,
|
||||
goodsNames: List<GoodsNameQueryDTO>? = null
|
||||
) {
|
||||
val param = mutableMapOf<String, Any>(
|
||||
"goodsType" to goodsType,
|
||||
"placeId" to placeId,
|
||||
"pageNum" to pageNum,
|
||||
"pageSize" to pageSize
|
||||
)
|
||||
goodsName?.let { param["goodsName"] = it }
|
||||
goodsNames?.let { param["goodsNames"] = it }
|
||||
viewModelScope.launch {
|
||||
request(
|
||||
onRequest = {
|
||||
apiService.queryGoodsList(param = param)
|
||||
},
|
||||
onSuccess = onSuccess,
|
||||
onFailure = onFailure
|
||||
)
|
||||
_goodsListState.value = UiState.Loading
|
||||
_goodsListState.value = repository.queryGoodsList(param)
|
||||
}
|
||||
}
|
||||
|
||||
fun querySeasoningList(
|
||||
param: MutableMap<String, Any>,
|
||||
onSuccess: (MutableList<SeasoningEntity>?) -> Unit,
|
||||
onFailure: (String, String) -> Unit
|
||||
/**
|
||||
* 食材搜索弹窗专用的查询方法,结果写入 foodSearchGoodsListState,不影响 goodsListState
|
||||
* @param goodsType 物品类型:0=食材,1=调料
|
||||
* @param placeId 场所 ID,默认取当前食堂 ID
|
||||
* @param pageNum 页码,默认第 1 页
|
||||
* @param pageSize 每页条数,默认 50
|
||||
* @param goodsName 按名称模糊搜索,为 null 时不传该字段
|
||||
* @param goodsNames 按名称+净材种类列表批量查询,为 null 时不传该字段
|
||||
*/
|
||||
fun queryFoodSearchGoodsList(
|
||||
goodsType: String,
|
||||
placeId: String = BaseApp.canteenId,
|
||||
pageNum: Int = 1,
|
||||
pageSize: Int = 50,
|
||||
goodsName: String? = null,
|
||||
goodsNames: List<GoodsNameQueryDTO>? = null
|
||||
) {
|
||||
val param = mutableMapOf<String, Any>(
|
||||
"goodsType" to goodsType,
|
||||
"placeId" to placeId,
|
||||
"pageNum" to pageNum,
|
||||
"pageSize" to pageSize
|
||||
)
|
||||
goodsName?.let { param["goodsName"] = it }
|
||||
goodsNames?.let { param["goodsNames"] = it }
|
||||
viewModelScope.launch {
|
||||
request(
|
||||
onRequest = {
|
||||
apiService.querySeasoningList(param = param)
|
||||
},
|
||||
onSuccess = onSuccess,
|
||||
onFailure = onFailure
|
||||
)
|
||||
_foodSearchGoodsListState.value = UiState.Loading
|
||||
_foodSearchGoodsListState.value = repository.queryGoodsList(param)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 调料模糊搜索(新配比秤接口,回调版本)
|
||||
* 替代旧 queryGoodsList(goodsType=1) 调用
|
||||
* @param keyword 模糊匹配食材名称和别名,为 null 时不传该字段
|
||||
* @param pageNum 页码,默认第 1 页
|
||||
* @param pageSize 每页条数,默认 50
|
||||
* @param onLoading 请求发起前的回调
|
||||
* @param onResult 结果回调,直接接收 UiState<List<SeasoningSearchItem>?>
|
||||
*/
|
||||
fun querySeasoningSearch(
|
||||
keyword: String? = null,
|
||||
pageNum: Int = 1,
|
||||
pageSize: Int = 50,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<List<SeasoningSearchItem>?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.getSeasoningSearch(
|
||||
SeasoningSearchRequest(keyword = keyword, pageNum = pageNum, pageSize = pageSize)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 烹饪完成(新配比秤接口,回调版本),替代旧 submitCookFood
|
||||
* 仅在制作模式下 cookOrderId 可用的场景调用
|
||||
*/
|
||||
fun cookOrderComplete(
|
||||
request: CookCompleteRequest,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<Any?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.cookOrderComplete(request))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 食材模糊搜索(回调版本)
|
||||
* @param keyword 模糊匹配食材名称和别名,为 null 时不传该字段
|
||||
* @param pageNum 页码,默认第 1 页
|
||||
* @param pageSize 每页条数,默认 20
|
||||
*/
|
||||
fun materSearch(
|
||||
keyword: String? = null,
|
||||
pageNum: Int = 1,
|
||||
pageSize: Int = 20,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<MutableList<MaterSearchItem>?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.materSearch(
|
||||
MaterSearchRequest(keyword = keyword, pageNum = pageNum, pageSize = pageSize)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 搜菜品(回调版本,制作模式选已有上架菜品)
|
||||
*/
|
||||
fun foodSearch(
|
||||
keyword: String? = null,
|
||||
pageNum: Int = 1,
|
||||
pageSize: Int = 20,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<MutableList<FoodSearchItem>?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.foodSearch(
|
||||
FoodSearchRequest(keyword = keyword, pageNum = pageNum, pageSize = pageSize)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查菜品构成(回调版本,制作模式)
|
||||
*/
|
||||
fun getFoodComposition(
|
||||
foodId: String,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<FoodCompositionResponse?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.getFoodComposition(foodId))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交采样(回调版本,落库味养创新实验,制作模式已废弃本接口)
|
||||
*/
|
||||
fun constituteSave(
|
||||
request: ConstituteSaveRequest,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<Any?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.constituteSave(request))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 已提交采样列表(回调版本,本食堂 source=2,不分日期)
|
||||
* @param pageNum 页码,默认第 1 页
|
||||
* @param pageSize 每页条数,默认 10
|
||||
*/
|
||||
fun sampleHistory(
|
||||
pageNum: Int = 1,
|
||||
pageSize: Int = 10,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<MutableList<SampleHistoryItem>?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.sampleHistory(
|
||||
SampleHistoryRequest(
|
||||
pageNum = pageNum,
|
||||
pageSize = pageSize
|
||||
)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 制作历史(回调版本,本设备按日期可选过滤)
|
||||
*/
|
||||
fun makeHistory(
|
||||
pageNum: Int = 1,
|
||||
pageSize: Int = 10,
|
||||
day: String? = null,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<MutableList<MakeHistoryItem>?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.makeHistory(
|
||||
MakeHistoryRequest(pageNum = pageNum, pageSize = pageSize, day = day)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 制作历史图表(回调版本,按菜品id)
|
||||
*/
|
||||
fun makeHistoryChart(
|
||||
foodId: String,
|
||||
onLoading: () -> Unit = {},
|
||||
onResult: (UiState<MutableList<MakeHistoryChartRow>?>) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
onLoading()
|
||||
onResult(repository.makeHistoryChart(foodId))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传采集菜品信息 UI 状态流,UI 层通过 collect 监听
|
||||
*/
|
||||
private val _uploadCollectState = MutableStateFlow<UiState<List<String>?>>(UiState.Idle)
|
||||
val uploadCollectState: StateFlow<UiState<List<String>?>> = _uploadCollectState.asStateFlow()
|
||||
|
||||
/**
|
||||
* 上传采集菜品信息(触发 StateFlow,适合单次上传场景)
|
||||
*/
|
||||
fun uploadFoodVectorData(
|
||||
fileList: List<File>,
|
||||
params: MutableMap<String, RequestBody>
|
||||
) {
|
||||
val fileParts = fileList.map { file ->
|
||||
file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
|
||||
.let { MultipartBody.Part.createFormData("foodPics", file.name, it) }
|
||||
}
|
||||
viewModelScope.launch {
|
||||
_uploadCollectState.value = UiState.Loading
|
||||
_uploadCollectState.value = repository.uploadFoodVectorData(params, fileParts)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传采集菜品信息(直接返回结果,适合分批循环上传场景)
|
||||
* @param fileList 图片文件列表
|
||||
* @param params 附加参数
|
||||
* @return UiState 包装的结果
|
||||
*/
|
||||
suspend fun uploadFoodVectorDataBatch(
|
||||
fileList: List<File>,
|
||||
params: MutableMap<String, RequestBody>
|
||||
): UiState<List<String>?> {
|
||||
val fileParts = fileList.map { file ->
|
||||
//multipart/form-data image/jpeg
|
||||
file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
|
||||
.let { MultipartBody.Part.createFormData("foodPics", file.name, it) }
|
||||
}
|
||||
return repository.uploadFoodVectorData(params, fileParts)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package com.shuwei.dish.match.net
|
||||
|
||||
import com.shuwei.dish.match.model.CookFoodDTO
|
||||
import com.shuwei.dish.match.model.CookOrderCompositionItem
|
||||
import com.shuwei.dish.match.model.CookOrderMealGroup
|
||||
import com.shuwei.dish.match.model.CookOrderPageRequest
|
||||
import com.shuwei.dish.match.model.FoodRecord
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
import com.shuwei.dish.match.model.ConstituteSaveRequest
|
||||
import com.shuwei.dish.match.model.CookCompleteRequest
|
||||
import com.shuwei.dish.match.model.FoodCompositionResponse
|
||||
import com.shuwei.dish.match.model.FoodSearchItem
|
||||
import com.shuwei.dish.match.model.FoodSearchRequest
|
||||
import com.shuwei.dish.match.model.MakeHistoryChartRow
|
||||
import com.shuwei.dish.match.model.MakeHistoryItem
|
||||
import com.shuwei.dish.match.model.MakeHistoryRequest
|
||||
import com.shuwei.dish.match.model.MaterSearchItem
|
||||
import com.shuwei.dish.match.model.MaterSearchRequest
|
||||
import com.shuwei.dish.match.model.SampleHistoryItem
|
||||
import com.shuwei.dish.match.model.SampleHistoryRequest
|
||||
import com.shuwei.dish.match.model.SeasoningSearchItem
|
||||
import com.shuwei.dish.match.model.SeasoningSearchRequest
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
|
||||
/**
|
||||
* 网络数据仓库,封装所有 ApiService 调用
|
||||
* ViewModel 不直接接触 apiService,统一通过此类发起网络请求
|
||||
*/
|
||||
class RemoteRepository {
|
||||
|
||||
/** 统一封装 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 submitCookFood(entity: CookFoodDTO): UiState<Any?> =
|
||||
safeApiCall { apiService.submitCookFood(param = entity) }
|
||||
|
||||
/** 查询菜品详情 */
|
||||
suspend fun getFoodDetail(foodId: String): UiState<CookFoodDTO?> =
|
||||
safeApiCall { apiService.getFoodDetail(foodId = foodId) }
|
||||
|
||||
/** 查询当日烹饪任务列表(按餐次分组),新配比秤接口 */
|
||||
suspend fun getCookOrderPage(request: CookOrderPageRequest): UiState<List<CookOrderMealGroup>?> =
|
||||
safeApiCall { apiService.getCookOrderPage(request = request) }
|
||||
|
||||
/** 查询菜品食材构成(主材+辅材),新配比秤接口 */
|
||||
suspend fun getCookOrderComposition(cookOrderId: String): UiState<List<CookOrderCompositionItem>?> =
|
||||
safeApiCall { apiService.getCookOrderComposition(cookOrderId = cookOrderId) }
|
||||
|
||||
/** 搜索菜品列表 */
|
||||
suspend fun searchFoodList(param: MutableMap<String, Any>): UiState<MutableList<FoodRecord>?> =
|
||||
safeApiCall { apiService.searchFoodList(param = param) }
|
||||
|
||||
/** 查询采样数据列表 */
|
||||
suspend fun getSamplingList(param: MutableMap<String, Any>): UiState<MutableList<FoodRecord>?> =
|
||||
safeApiCall { apiService.getSamplingList(param = param) }
|
||||
|
||||
/** 查询物品信息列表(食材 goodsType=0,调料 goodsType=1 共用) */
|
||||
suspend fun queryGoodsList(param: MutableMap<String, Any>): UiState<MutableList<GoodsItem>?> =
|
||||
safeApiCall { apiService.queryGoodsList(param = param) }
|
||||
|
||||
/** 调料模糊搜索,新配比秤接口 */
|
||||
suspend fun getSeasoningSearch(request: SeasoningSearchRequest): UiState<List<SeasoningSearchItem>?> =
|
||||
safeApiCall { apiService.getSeasoningSearch(request = request) }
|
||||
|
||||
/** 烹饪完成,新配比秤接口,替代旧 submitCookFood */
|
||||
suspend fun cookOrderComplete(request: CookCompleteRequest): UiState<Any?> =
|
||||
safeApiCall { apiService.cookOrderComplete(request = request) }
|
||||
|
||||
/** 食材模糊搜索 */
|
||||
suspend fun materSearch(request: MaterSearchRequest): UiState<MutableList<MaterSearchItem>?> =
|
||||
safeApiCall { apiService.materSearch(request = request) }
|
||||
|
||||
/** 搜菜品(制作模式选已有上架菜品) */
|
||||
suspend fun foodSearch(request: FoodSearchRequest): UiState<MutableList<FoodSearchItem>?> =
|
||||
safeApiCall { apiService.foodSearch(request = request) }
|
||||
|
||||
/** 查菜品构成(制作模式) */
|
||||
suspend fun getFoodComposition(foodId: String): UiState<FoodCompositionResponse?> =
|
||||
safeApiCall { apiService.getFoodComposition(foodId = foodId) }
|
||||
|
||||
/** 提交采样(落库味养创新实验,制作模式已废弃本接口) */
|
||||
suspend fun constituteSave(request: ConstituteSaveRequest): UiState<Any?> =
|
||||
safeApiCall { apiService.constituteSave(request = request) }
|
||||
|
||||
/** 已提交采样列表(本食堂 source=2,按提交时间倒序,不分日期) */
|
||||
suspend fun sampleHistory(request: SampleHistoryRequest): UiState<MutableList<SampleHistoryItem>?> =
|
||||
safeApiCall { apiService.sampleHistory(request = request) }
|
||||
|
||||
/** 制作历史(本设备,按日期可选过滤) */
|
||||
suspend fun makeHistory(request: MakeHistoryRequest): UiState<MutableList<MakeHistoryItem>?> =
|
||||
safeApiCall { apiService.makeHistory(request = request) }
|
||||
|
||||
/** 制作历史图表(按菜品id) */
|
||||
suspend fun makeHistoryChart(foodId: String): UiState<MutableList<MakeHistoryChartRow>?> =
|
||||
safeApiCall { apiService.makeHistoryChart(foodId = foodId) }
|
||||
|
||||
/** 上传采集数据 */
|
||||
suspend fun uploadFoodVectorData(
|
||||
params: MutableMap<String, RequestBody>,
|
||||
foodPics: List<MultipartBody.Part>
|
||||
): UiState<List<String>?> =
|
||||
safeApiCall { apiService.uploadFoodVectorData(params = params, foodPics = foodPics) }
|
||||
|
||||
}
|
||||
@@ -13,6 +13,7 @@ class RequestInterceptor : Interceptor {
|
||||
val requestBuilder = originalRequest.newBuilder()
|
||||
.header("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjYW50ZWVuSWQiOiJiZTE1NDgzMS0zNDY2LTNiYTItYTJlYS01NzY1MmM5MTlmZWQiLCJ0eXBlIjoiNCIsInVzZXJJZCI6IjAwMDAwMDAwMDAwMDAwMDAwMDEifQ.sN40cOC-O5WQFrF4IDUs8fFlkNdUKLbJt_rHyTsgYYM")
|
||||
.header("X-DEVICE-CODE", GlobalData.deviceId)
|
||||
.header("X-DEVICE-TOKEN", GlobalData.deviceId)
|
||||
.header("authorization", "57ee87183f2a4fa59683ec9ef41c8f5d")
|
||||
|
||||
val newRequest = requestBuilder.build()
|
||||
|
||||
@@ -3,7 +3,10 @@ package com.shuwei.dish.match.net
|
||||
data class ApiResponse<T>(
|
||||
val code: String,
|
||||
val msg: String? = "",
|
||||
val data: T? = null
|
||||
val data: T? = null,
|
||||
/** 分页总条数,仅新配比秤接口返回(如 seasoning-search),旧接口为 null */
|
||||
val total: Int? = null
|
||||
) {
|
||||
fun isSuccess() = code == "00000"
|
||||
/** 兼容旧接口成功码 "00000" 和新配比秤接口成功码 "200" */
|
||||
fun isSuccess() = code == "00000" || code == "200"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.shuwei.dish.match.net
|
||||
|
||||
/**
|
||||
* 统一 UI 状态模型,用于 ViewModel 向 UI 层传递请求状态
|
||||
* Idle — 初始状态,未发起请求
|
||||
* Loading — 请求进行中
|
||||
* Success — 请求成功,携带数据
|
||||
* Error — 请求失败,携带错误码和错误信息
|
||||
*/
|
||||
sealed class UiState<out T> {
|
||||
object Idle : UiState<Nothing>()
|
||||
object Loading : UiState<Nothing>()
|
||||
data class Success<T>(val data: T) : UiState<T>()
|
||||
data class Error(val code: String, val msg: String) : UiState<Nothing>()
|
||||
}
|
||||
@@ -1,68 +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>
|
||||
)
|
||||
|
||||
data class FoodCollectionBean(
|
||||
var imageUri: Uri? = null,
|
||||
var bitmap: Bitmap? = null,
|
||||
var imageFile: File? = null,
|
||||
var imageVector: FloatArray? = null,
|
||||
var isShowCamera: Boolean = false,
|
||||
var isFinish:Boolean = false,
|
||||
var uploadSuccess:Boolean = false
|
||||
)
|
||||
|
||||
data class ReceiptGoodsInfo(
|
||||
var goodsId: String? = "",
|
||||
var goodsName: String? = "",
|
||||
var procurementUnit: String? = "",
|
||||
var procurementCount: Int? = 0,
|
||||
var procurementPrice: Double? = 0.0,
|
||||
var procurementAmount: Double? = 0.0,
|
||||
var receiptCount: Int? = 0,
|
||||
var goodsWeight: Int? = 0,
|
||||
var goodsState: String? = "",
|
||||
var isSelected: Boolean = false,
|
||||
var isLocalGoods: Boolean = false
|
||||
)
|
||||
|
||||
//data class DropdownInfo(
|
||||
// var id: String,
|
||||
// var name: String
|
||||
//)
|
||||
|
||||
//data class RecognizeResult(
|
||||
// var name: String? = null,
|
||||
// var image: String? = null,
|
||||
// var isSelected: Boolean = false
|
||||
//)
|
||||
|
||||
//data class GoodsSearchInfo(
|
||||
// var id: String? = null,
|
||||
// var name: String? = null,
|
||||
// var isSelected: Boolean = false
|
||||
//)
|
||||
|
||||
data class OperateBean(
|
||||
var obj: Any? = null,
|
||||
var typeList: MutableList<OperateType> = mutableListOf(),
|
||||
var isSelected: Boolean = false,
|
||||
var isLocalGoods: Boolean = false,
|
||||
var isReceiptPage: Boolean = true
|
||||
)
|
||||
|
||||
data class OperateType(
|
||||
var value: String = "",
|
||||
var width: Int = 0,
|
||||
var textColor: String = "#FF999999",
|
||||
var isBoldFont: Boolean = false,
|
||||
var isShowIcon: Boolean = false
|
||||
)
|
||||
@@ -11,7 +11,8 @@ data class Food(
|
||||
var name: String? = null,
|
||||
var foodIdx: Int = 0,
|
||||
@HnswIndex(dimensions = 512, distanceType = VectorDistanceType.DOT_PRODUCT)
|
||||
var foodVector: FloatArray? = null
|
||||
var foodVector: FloatArray? = null,
|
||||
var version: String? = null
|
||||
) {
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (this === other) return true
|
||||
@@ -23,6 +24,7 @@ data class Food(
|
||||
if (foodIdx != other.foodIdx) return false
|
||||
if (name != other.name) return false
|
||||
if (!foodVector.contentEquals(other.foodVector)) return false
|
||||
if (version != other.version) return false
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -32,6 +34,8 @@ data class Food(
|
||||
result = 31 * result + foodIdx
|
||||
result = 31 * result + (name?.hashCode() ?: 0)
|
||||
result = 31 * result + (foodVector?.contentHashCode() ?: 0)
|
||||
result = 31 * result + (version?.hashCode() ?: 0)
|
||||
return result
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
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>
|
||||
)
|
||||
|
||||
@@ -22,7 +22,7 @@ import java.io.InputStream
|
||||
|
||||
object FoodModule {
|
||||
|
||||
private lateinit var module_mobile: Module
|
||||
private lateinit var module: Module
|
||||
|
||||
private val NO_MEAN_RGB = floatArrayOf(0.0f, 0.0f, 0.0f)
|
||||
private val NO_STD_RGB = floatArrayOf(1.0f, 1.0f, 1.0f)
|
||||
@@ -37,8 +37,8 @@ object FoodModule {
|
||||
|
||||
suspend fun init(context: Context) {
|
||||
withContext(Dispatchers.IO) {
|
||||
module_mobile = Module.load(copyAssetToCache(context, "best_embedding_model_mobile.pt"))
|
||||
initDefFoodData(context)
|
||||
module = Module.load(copyAssetToCache(context, "best_embedding_model_mobile.pt"))
|
||||
// initDefFoodData(context)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,6 +51,11 @@ object FoodModule {
|
||||
// }
|
||||
|
||||
fun bitmap2FloatArray(originBitmap: Bitmap, isRecycle: Boolean): FloatArray? {
|
||||
// 模型未初始化时直接返回 null,避免 UninitializedPropertyAccessException
|
||||
if (!::module.isInitialized) {
|
||||
logInfo("bitmap2FloatArray: module 尚未初始化,跳过推理")
|
||||
return null
|
||||
}
|
||||
var rgb565Bitmap: Bitmap? = null
|
||||
try {
|
||||
val scaledBitmap = originBitmap.scale(MODEL_INPUT_WIDTH, MODEL_INPUT_HEIGHT)
|
||||
@@ -64,7 +69,7 @@ object FoodModule {
|
||||
NO_MEAN_RGB, // [0.485, 0.456, 0.406] TORCHVISION_NORM_MEAN_RGB
|
||||
NO_STD_RGB // [0.229, 0.224, 0.225] TORCHVISION_NORM_STD_RGB
|
||||
)
|
||||
val outputTensor = module_mobile.forward(IValue.from(inputTensor)).toTensor()
|
||||
val outputTensor = module.forward(IValue.from(inputTensor)).toTensor()
|
||||
return outputTensor.dataAsFloatArray
|
||||
} catch (e: OutOfMemoryError) {
|
||||
e.printStackTrace()
|
||||
@@ -124,7 +129,12 @@ object FoodModule {
|
||||
val nameScoreList = mutableListOf<IdNameScore>()
|
||||
idScoreList.forEach {
|
||||
val name = foodMap[it.id]?.name ?: ""
|
||||
nameScoreList.add(IdNameScore(id = it.id, name = name, score = it.score))
|
||||
val arr = name.split("&&")
|
||||
var rawMaterialsType = ""
|
||||
if (arr.size > 1) {
|
||||
rawMaterialsType = arr[1]
|
||||
}
|
||||
nameScoreList.add(IdNameScore(id = it.id, name = arr[0], score = it.score, rawMaterialsType = rawMaterialsType))
|
||||
}
|
||||
logInfo("queryFood数据:${nameScoreList.toJsonString()}")
|
||||
return nameScoreList
|
||||
@@ -176,7 +186,8 @@ object FoodModule {
|
||||
data class IdNameScore(
|
||||
val id: Long,
|
||||
var name: String,
|
||||
val score: Double
|
||||
val score: Double,
|
||||
val rawMaterialsType: String
|
||||
)
|
||||
|
||||
suspend fun initDefFoodData(context: Context, action: () -> Unit = {}) {
|
||||
|
||||
@@ -213,6 +213,36 @@ object ObjectBox {
|
||||
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" // 备份目录
|
||||
|
||||
@@ -28,7 +28,6 @@ class MdnsDiscoveryManager(private val context: Context) {
|
||||
|
||||
/** 待解析队列,串行处理避免并发解析失败 */
|
||||
private val resolveQueue = LinkedList<NsdServiceInfo>()
|
||||
@Volatile
|
||||
private var isResolving = false
|
||||
|
||||
/**
|
||||
|
||||
@@ -15,5 +15,6 @@ data class ScaleData(
|
||||
val weight: Double,
|
||||
val state: Int,
|
||||
val ts: Long,
|
||||
val ip: String = ""
|
||||
val ip: String = "",
|
||||
val name: String? = null
|
||||
)
|
||||
|
||||
@@ -6,7 +6,7 @@ package com.shuwei.dish.match.scale
|
||||
*/
|
||||
object ScaleDeviceConfig {
|
||||
|
||||
const val DEVICE_ID_2 = "8fc2ab34-2137-3112-acca-f884ea8736d4"
|
||||
const val DEVICE_ID_2 = "0bd74d78-c221-3182-b5ee-55d86dd79283"//测试0bd74d78-c221-3182-b5ee-55d86dd79283 正式8fc2ab34-2137-3112-acca-f884ea8736d4
|
||||
const val DEVICE_ID_22 = "a46fa55c-113c-3511-bb1f-41e5eff77c4b"
|
||||
const val DEVICE_ID_18 = "1038da9f-c6eb-326e-a1d9-d6d3af978b22"
|
||||
const val DEVICE_ID_1 = "7cc0f6ea-f13d-3013-a867-fc998eb554ac"
|
||||
@@ -17,6 +17,9 @@ object ScaleDeviceConfig {
|
||||
/** 18个秤的显示顺序(按物理位置排列) */
|
||||
val SCALE_ORDER_18 = listOf(6, 5, 4, 3, 2, 1, 12, 11, 10, 9, 8, 7, 18, 17, 16, 15, 14, 13)
|
||||
|
||||
/** 1个秤的地址列表 */
|
||||
val SCALE_ORDER_1 = listOf(1)
|
||||
|
||||
/** 设备在列表中的显示顺序 */
|
||||
val DEVICE_ORDER = listOf(DEVICE_ID_2, DEVICE_ID_22, DEVICE_ID_18, DEVICE_ID_1)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
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"
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,17 @@ 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
|
||||
|
||||
/**
|
||||
* 秤服务统一门面(单例)
|
||||
@@ -29,6 +36,9 @@ object ScaleServiceManager {
|
||||
|
||||
private const val TAG = "ScaleServiceManager"
|
||||
|
||||
@Volatile private var isStarted = false
|
||||
private var serviceScope: CoroutineScope? = null
|
||||
|
||||
private var mdnsRegister: MdnsRegisterManager? = null
|
||||
private var wsServer: ScaleWebSocketServer? = null
|
||||
private var udpSender: UdpBroadcastSender? = null
|
||||
@@ -46,6 +56,74 @@ object ScaleServiceManager {
|
||||
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() 之后设置才能生效
|
||||
@@ -62,6 +140,9 @@ object ScaleServiceManager {
|
||||
* 启动所有秤服务,在 Application.onCreate() 中调用
|
||||
*/
|
||||
fun start(context: Context) {
|
||||
if (isStarted) return
|
||||
isStarted = true
|
||||
serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
val deviceId = GlobalData.deviceId
|
||||
val role = GlobalData.deviceRole
|
||||
Log.d(TAG, "启动秤服务, deviceId=$deviceId, role=$role")
|
||||
@@ -73,9 +154,8 @@ object ScaleServiceManager {
|
||||
if (role == DeviceRole.MASTER) {
|
||||
startMasterServices(context, deviceId)
|
||||
} else {
|
||||
// 子设备:启动 UDP 广播,作为 mDNS 的兜底发现机制
|
||||
val localIp = getLocalIp(context)
|
||||
udpSender = UdpBroadcastSender(deviceId, localIp).also { it.start() }
|
||||
// 子设备:启动 UDP 广播,作为 mDNS 的兜底发现机制;每次广播时动态获取 IP,避免启动时网络未就绪导致 IP 为空
|
||||
udpSender = UdpBroadcastSender(deviceId = deviceId, ipProvider = { getLocalIp(context) }).also { it.start() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,7 +180,25 @@ object ScaleServiceManager {
|
||||
// WebSocket 客户端
|
||||
val client = ScaleWebSocketClient().also {
|
||||
it.onScaleData = { data -> aggregator?.onRemoteScaleData(data) }
|
||||
it.onDeviceDisconnected = { remoteId -> aggregator?.removeDevice(remoteId) }
|
||||
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
|
||||
|
||||
@@ -144,7 +242,7 @@ object ScaleServiceManager {
|
||||
*/
|
||||
fun sendTare(deviceId: String, address: Int): Boolean {
|
||||
return if (deviceId == GlobalData.deviceId) {
|
||||
com.shuwei.dish.match.utils.WeightUtil.tareTwo(address)
|
||||
WeightUtil.tareTwo(address)
|
||||
true
|
||||
} else {
|
||||
val cmd = ScaleCommand(ScaleCommand.CMD_TARE, deviceId, address)
|
||||
@@ -156,6 +254,9 @@ object ScaleServiceManager {
|
||||
* 停止所有秤服务,在 Application.onTerminate() 或退出时调用
|
||||
*/
|
||||
fun stop() {
|
||||
serviceScope?.cancel()
|
||||
serviceScope = null
|
||||
isStarted = false
|
||||
mdnsDiscovery?.stopDiscovery()
|
||||
udpReceiver?.stop()
|
||||
udpSender?.stop()
|
||||
|
||||
@@ -43,15 +43,26 @@ class ScaleWebSocketClient {
|
||||
private val reconnectDelays = ConcurrentHashMap<String, Long>()
|
||||
/** 已主动移除的设备集合,不对其触发重连 */
|
||||
private val removedDevices = ConcurrentHashMap.newKeySet<String>()
|
||||
/**
|
||||
* 各设备的连接版本号,每次调用 connect() 时递增
|
||||
* doConnect 执行前校验版本,版本不匹配说明已有更新的连接请求,直接放弃本次连接
|
||||
*/
|
||||
private val connectVersions = ConcurrentHashMap<String, Int>()
|
||||
|
||||
private val scheduler: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()
|
||||
|
||||
/** 收到秤数据时的回调,在子线程调用 */
|
||||
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
|
||||
@@ -60,12 +71,24 @@ class ScaleWebSocketClient {
|
||||
*/
|
||||
fun connect(deviceId: String, host: String, port: Int) {
|
||||
removedDevices.remove(deviceId)
|
||||
// 取消旧重连任务,防止 IP 变化时新旧任务并发竞争
|
||||
reconnectTasks.remove(deviceId)?.cancel(false)
|
||||
reconnectDelays[deviceId] = RECONNECT_BASE_MS
|
||||
doConnect(deviceId, host, port)
|
||||
// 递增版本号:doConnect 执行前会校验版本,旧任务版本不匹配时直接放弃
|
||||
val version = (connectVersions[deviceId] ?: 0) + 1
|
||||
connectVersions[deviceId] = version
|
||||
doConnect(deviceId, host, port, version)
|
||||
}
|
||||
|
||||
private fun doConnect(deviceId: String, host: String, port: Int) {
|
||||
val url = "ws://$host:$port"
|
||||
private fun doConnect(deviceId: String, host: String, port: Int, version: Int = connectVersions[deviceId] ?: 0) {
|
||||
// 版本校验:若当前版本已被更新的 connect() 调用覆盖,放弃本次连接
|
||||
if (connectVersions[deviceId] != version) {
|
||||
Log.d(TAG, "放弃过期连接任务: $deviceId, version=$version")
|
||||
return
|
||||
}
|
||||
// IPv6 地址在 URL 中需用方括号包裹,否则 OkHttp 会将冒号后内容误解析为端口
|
||||
val formattedHost = if (host.contains(':')) "[$host]" else host
|
||||
val url = "ws://$formattedHost:$port"
|
||||
val request = Request.Builder().url(url).build()
|
||||
|
||||
val ws = httpClient.newWebSocket(request, object : WebSocketListener() {
|
||||
@@ -74,47 +97,67 @@ class ScaleWebSocketClient {
|
||||
connections[deviceId] = webSocket
|
||||
reconnectDelays[deviceId] = RECONNECT_BASE_MS
|
||||
reconnectTasks.remove(deviceId)?.cancel(false)
|
||||
onDeviceConnected?.invoke(deviceId)
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, text: String) {
|
||||
try {
|
||||
val data = gson.fromJson(text, ScaleData::class.java)
|
||||
onScaleData?.invoke(data)
|
||||
// 通过 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}")
|
||||
Log.w(TAG, "解析消息失败: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
|
||||
Log.w(TAG, "连接子设备失败: $deviceId, ${t.message}")
|
||||
connections.remove(deviceId)
|
||||
onDeviceDisconnected?.invoke(deviceId)
|
||||
scheduleReconnect(deviceId, host, port)
|
||||
// 使用 remove(key, value) 确保只移除自己的实例
|
||||
// 避免旧连接超时触发时误删新连接引用,导致 aggregator 错误清空新连接数据
|
||||
val removed = connections.remove(deviceId, webSocket)
|
||||
if (removed) {
|
||||
onDeviceDisconnected?.invoke(deviceId)
|
||||
scheduleReconnect(deviceId, host, port)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
|
||||
Log.d(TAG, "子设备连接已关闭: $deviceId, reason=$reason")
|
||||
connections.remove(deviceId)
|
||||
onDeviceDisconnected?.invoke(deviceId)
|
||||
scheduleReconnect(deviceId, host, port)
|
||||
// 同上:只有移除的是自己,才触发断线回调和重连
|
||||
val removed = connections.remove(deviceId, webSocket)
|
||||
if (removed) {
|
||||
onDeviceDisconnected?.invoke(deviceId)
|
||||
scheduleReconnect(deviceId, host, port)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
connections[deviceId] = ws
|
||||
// 写入新连接前先关闭旧连接,避免 IP 变化时旧 ws 对象悬空造成 TCP 资源泄漏
|
||||
connections.put(deviceId, ws)?.close(1000, "新连接替换")
|
||||
}
|
||||
|
||||
/**
|
||||
* 指数退避重连
|
||||
* 入口不拦截 removedDevices,仅在延迟任务执行前检查,
|
||||
* 确保 disconnect() 后已入队的任务不执行,但新断线事件始终能进入重连流程
|
||||
* scheduler 已关闭(shutdown 后)时直接跳过,避免 RejectedExecutionException
|
||||
*/
|
||||
private fun scheduleReconnect(deviceId: String, host: String, port: Int) {
|
||||
if (scheduler.isShutdown) return
|
||||
val delay = reconnectDelays[deviceId] ?: RECONNECT_BASE_MS
|
||||
Log.d(TAG, "将在 ${delay}ms 后重连子设备: $deviceId")
|
||||
// 记录当前版本,延迟任务执行时再次校验,防止期间有新的 connect() 调用
|
||||
val version = connectVersions[deviceId] ?: 0
|
||||
|
||||
val future = scheduler.schedule({
|
||||
if (!removedDevices.contains(deviceId)) {
|
||||
doConnect(deviceId, host, port)
|
||||
doConnect(deviceId, host, port, version)
|
||||
}
|
||||
}, delay, TimeUnit.MILLISECONDS)
|
||||
|
||||
@@ -136,6 +179,31 @@ class ScaleWebSocketClient {
|
||||
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
|
||||
@@ -145,6 +213,7 @@ class ScaleWebSocketClient {
|
||||
reconnectTasks.remove(deviceId)?.cancel(false)
|
||||
connections.remove(deviceId)?.close(1000, "设备离线")
|
||||
reconnectDelays.remove(deviceId)
|
||||
connectVersions.remove(deviceId)
|
||||
Log.d(TAG, "已断开子设备: $deviceId")
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,11 @@ import org.java_websocket.WebSocket
|
||||
import org.java_websocket.handshake.ClientHandshake
|
||||
import org.java_websocket.server.WebSocketServer
|
||||
import java.net.InetSocketAddress
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.ScheduledFuture
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
* 秤数据 WebSocket 服务端(主设备和子设备均运行)
|
||||
@@ -20,23 +25,36 @@ class ScaleWebSocketServer(private val deviceId: String, private val context: Co
|
||||
private const val TAG = "ScaleWebSocketServer"
|
||||
/** 节流间隔:两次推送之间的最小间隔(毫秒) */
|
||||
private const val THROTTLE_MS = 100L
|
||||
/** latestData 为空时延迟补推的时间(毫秒),给 WeightUtil 时间产生第一次读数 */
|
||||
private const val RETRY_PUSH_DELAY_MS = 3_000L
|
||||
}
|
||||
|
||||
private val gson = Gson()
|
||||
private var server: InternalServer? = null
|
||||
/** 延迟补推任务的调度器 */
|
||||
private val scheduler = Executors.newSingleThreadScheduledExecutor()
|
||||
|
||||
/** 主设备连接状态变化回调:true=已连接,false=已断开;在主线程外调用,需自行切换线程 */
|
||||
var onConnectionChanged: ((connected: Boolean) -> Unit)? = null
|
||||
|
||||
/** 收到主设备下发的调料配置同步事件时的回调,在子线程调用 */
|
||||
var onSeasoningConfig: ((event: ScaleEvent) -> Unit)? = null
|
||||
|
||||
/** 收到主设备下发的清除数据事件时的回调,在子线程调用 */
|
||||
var onClearData: ((event: ScaleEvent) -> Unit)? = null
|
||||
|
||||
/** 当前是否有主设备连接 */
|
||||
val isConnected: Boolean
|
||||
get() = server?.connections?.isNotEmpty() == true
|
||||
|
||||
/** 每个秤地址的最近一次推送时间,用于节流 */
|
||||
private val lastPushTime = mutableMapOf<Int, Long>()
|
||||
private val lastPushTime = ConcurrentHashMap<Int, Long>()
|
||||
|
||||
/** 缓存各秤最新数据,新客户端连接时立即同步当前状态 */
|
||||
private val latestData = mutableMapOf<Int, ScaleData>()
|
||||
private val latestData = ConcurrentHashMap<Int, ScaleData>()
|
||||
|
||||
/** 节流窗口内的延迟推送任务,key=address;保证窗口结束时最新数据被推送 */
|
||||
private val pendingPushTasks = ConcurrentHashMap<Int, ScheduledFuture<*>>()
|
||||
|
||||
/**
|
||||
* 启动 WebSocket 服务器,并注册 WeightUtil 回调
|
||||
@@ -49,11 +67,12 @@ class ScaleWebSocketServer(private val deviceId: String, private val context: Co
|
||||
|
||||
// 注册本机秤数据监听
|
||||
WeightUtil.addWeightListener(TAG) { address, state, weight ->
|
||||
Log.d(TAG, "WebSocket 设备${deviceId}推送数据, address=$address, state=$state, weight=$weight")
|
||||
val now = System.currentTimeMillis()
|
||||
// 节流:同一地址 100ms 内只推送一次
|
||||
if (now - (lastPushTime[address] ?: 0L) < THROTTLE_MS) return@addWeightListener
|
||||
// 数据未变化时直接跳过,避免无效推送
|
||||
val last = latestData[address]
|
||||
if (last?.weight == weight && last.state == state) return@addWeightListener
|
||||
|
||||
lastPushTime[address] = now
|
||||
val data = ScaleData(
|
||||
deviceId = deviceId,
|
||||
address = address,
|
||||
@@ -62,8 +81,28 @@ class ScaleWebSocketServer(private val deviceId: String, private val context: Co
|
||||
ts = now,
|
||||
ip = NetworkUtil.getLocalIpAddress(context)
|
||||
)
|
||||
// 始终更新 latestData,保证最新一帧不丢失
|
||||
latestData[address] = data
|
||||
broadcast(gson.toJson(data))
|
||||
|
||||
val lastPush = lastPushTime[address] ?: 0L
|
||||
if (now - lastPush >= THROTTLE_MS) {
|
||||
// 窗口已过:立即推送,并取消可能存在的延迟任务
|
||||
lastPushTime[address] = now
|
||||
pendingPushTasks.remove(address)?.cancel(false)
|
||||
broadcast(gson.toJson(data))
|
||||
} else if (pendingPushTasks[address] == null) {
|
||||
// 窗口内首次触发:安排 trailing 推送,保证窗口末尾推最新值
|
||||
val delay = THROTTLE_MS - (now - lastPush)
|
||||
if (!scheduler.isShutdown) {
|
||||
pendingPushTasks[address] = scheduler.schedule({
|
||||
val latest = latestData[address] ?: return@schedule
|
||||
lastPushTime[address] = System.currentTimeMillis()
|
||||
pendingPushTasks.remove(address)
|
||||
broadcast(gson.toJson(latest))
|
||||
}, delay, TimeUnit.MILLISECONDS)
|
||||
}
|
||||
}
|
||||
// 窗口内且已安排过 trailing 任务:仅更新 latestData,等 trailing 触发时推送
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,6 +111,10 @@ class ScaleWebSocketServer(private val deviceId: String, private val context: Co
|
||||
*/
|
||||
fun stop() {
|
||||
WeightUtil.removeWeightListener(TAG)
|
||||
onConnectionChanged = null
|
||||
onSeasoningConfig = null
|
||||
onClearData = null
|
||||
scheduler.shutdownNow()
|
||||
try {
|
||||
server?.stop(1000)
|
||||
} catch (e: Exception) {
|
||||
@@ -80,9 +123,19 @@ class ScaleWebSocketServer(private val deviceId: String, private val context: Co
|
||||
server = null
|
||||
latestData.clear()
|
||||
lastPushTime.clear()
|
||||
pendingPushTasks.values.forEach { it.cancel(false) }
|
||||
pendingPushTasks.clear()
|
||||
Log.d(TAG, "WebSocket 服务端已停止")
|
||||
}
|
||||
|
||||
/**
|
||||
* 向所有已连接的主设备广播秤事件(如调料添加通知)
|
||||
* @param event 要广播的事件
|
||||
*/
|
||||
fun broadcastEvent(event: ScaleEvent) {
|
||||
broadcast(gson.toJson(event))
|
||||
}
|
||||
|
||||
/**
|
||||
* 向所有已连接客户端广播消息
|
||||
*/
|
||||
@@ -104,40 +157,77 @@ class ScaleWebSocketServer(private val deviceId: String, private val context: Co
|
||||
private inner class InternalServer(port: Int) :
|
||||
WebSocketServer(InetSocketAddress(port)) {
|
||||
|
||||
/** 当前活跃连接计数,用于替代 connections.isNullOrEmpty() 避免竞态 */
|
||||
private val connectionCount = AtomicInteger(0)
|
||||
|
||||
override fun onOpen(conn: WebSocket, handshake: ClientHandshake) {
|
||||
connectionCount.incrementAndGet()
|
||||
Log.d(TAG, "主设备已连接: ${conn.remoteSocketAddress}")
|
||||
onConnectionChanged?.invoke(true)
|
||||
|
||||
// 新客户端连接后,立即推送所有秤的最新数据
|
||||
latestData.values.forEach { data ->
|
||||
try {
|
||||
conn.send(gson.toJson(data))
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "初始推送失败: ${e.message}")
|
||||
if (latestData.isNotEmpty()) {
|
||||
latestData.values.forEach { data ->
|
||||
try {
|
||||
conn.send(gson.toJson(data))
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "初始推送失败: ${e.message}")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// latestData 为空说明刚重启,WeightUtil 还未产生读数
|
||||
// 延迟 3 秒后补推一次,确保主设备能看到本机秤
|
||||
Log.d(TAG, "latestData 为空,${RETRY_PUSH_DELAY_MS}ms 后补推")
|
||||
scheduler.schedule({
|
||||
if (conn.isOpen && latestData.isNotEmpty()) {
|
||||
latestData.values.forEach { data ->
|
||||
try {
|
||||
conn.send(gson.toJson(data))
|
||||
Log.d(TAG, "补推数据: address=${data.address}, weight=${data.weight}")
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "补推失败: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}, RETRY_PUSH_DELAY_MS, TimeUnit.MILLISECONDS)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onClose(conn: WebSocket, code: Int, reason: String, remote: Boolean) {
|
||||
Log.d(TAG, "主设备已断开: ${conn.remoteSocketAddress}, reason=$reason")
|
||||
// 若已无任何连接,通知子设备 UI 更新为未连接状态
|
||||
if (server?.connections.isNullOrEmpty()) {
|
||||
// 用计数器判断是否还有活跃连接,避免依赖 connections 集合的移除时机导致竞态
|
||||
if (connectionCount.decrementAndGet() <= 0) {
|
||||
connectionCount.set(0)
|
||||
onConnectionChanged?.invoke(false)
|
||||
}
|
||||
}
|
||||
|
||||
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) return
|
||||
if (cmd.deviceId != deviceId) {
|
||||
Log.d(TAG, "收到清零指令, 但设备号不正确, deviceId=${cmd.deviceId}")
|
||||
return
|
||||
}
|
||||
when (cmd.cmd) {
|
||||
ScaleCommand.CMD_TARE -> {
|
||||
Log.d(TAG, "收到清零指令, address=${cmd.address}")
|
||||
com.shuwei.dish.match.utils.WeightUtil.tareTwo(cmd.address)
|
||||
WeightUtil.tareTwo(cmd.address)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "解析指令失败: ${e.message}")
|
||||
Log.w(TAG, "收到消息, 解析失败: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,10 +13,12 @@ import java.util.concurrent.TimeUnit
|
||||
* UDP 广播发送器(子设备运行)
|
||||
* 每隔固定间隔向局域网广播本机的 deviceId、IP、WebSocket 端口
|
||||
* 作为 mDNS 的兜底发现机制,确保主设备能可靠发现子设备
|
||||
*
|
||||
* @param ipProvider 动态获取本机 IP 的函数,每次广播时调用;返回空字符串时跳过本次广播
|
||||
*/
|
||||
class UdpBroadcastSender(
|
||||
private val deviceId: String,
|
||||
private val localIp: String,
|
||||
private val ipProvider: () -> String,
|
||||
private val wsPort: Int = MdnsRegisterManager.WS_PORT
|
||||
) {
|
||||
|
||||
@@ -43,12 +45,18 @@ class UdpBroadcastSender(
|
||||
task = scheduler.scheduleWithFixedDelay({
|
||||
sendBroadcast()
|
||||
}, 0, INTERVAL_SEC, TimeUnit.SECONDS)
|
||||
Log.d(TAG, "UDP 广播已启动, deviceId=$deviceId, ip=$localIp, port=$wsPort")
|
||||
Log.d(TAG, "UDP 广播已启动, deviceId=$deviceId, port=$wsPort")
|
||||
}
|
||||
|
||||
private fun sendBroadcast() {
|
||||
try {
|
||||
val payload = gson.toJson(Payload(deviceId, localIp, wsPort))
|
||||
val ip = ipProvider()
|
||||
// 网络未就绪时跳过本次广播,等待下一个周期重试
|
||||
if (ip.isEmpty()) {
|
||||
Log.d(TAG, "IP 未就绪,跳过本次广播")
|
||||
return
|
||||
}
|
||||
val payload = gson.toJson(Payload(deviceId, ip, wsPort))
|
||||
val data = payload.toByteArray(Charsets.UTF_8)
|
||||
DatagramSocket().use { socket ->
|
||||
socket.broadcast = true
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
package com.shuwei.dish.match.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.graphics.Color
|
||||
import android.graphics.Typeface
|
||||
import android.os.Bundle
|
||||
import android.text.style.ForegroundColorSpan
|
||||
import android.text.style.StyleSpan
|
||||
import android.view.LayoutInflater
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import androidx.core.widget.addTextChangedListener
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.CollectedFoodAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.databinding.ActivityCollectedFoodBinding
|
||||
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.model.CollectedFoodItem
|
||||
import com.shuwei.dish.match.utils.KeyboardUtil
|
||||
import com.shuwei.dish.match.utils.ext.appendText
|
||||
import com.shuwei.dish.match.utils.ext.buildSpannableString
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.collections.getOrNull
|
||||
|
||||
/**
|
||||
* 已采集食材列表页面
|
||||
* 展示所有已采集的食材及其采集数量,支持搜索和删除
|
||||
*/
|
||||
class CollectedFoodActivity : BaseActivity() {
|
||||
|
||||
private lateinit var binding: ActivityCollectedFoodBinding
|
||||
|
||||
private val foodList = mutableListOf<CollectedFoodItem>()
|
||||
|
||||
private var emptyViewBinding: LayoutEmptyViewBinding? = null
|
||||
|
||||
private val adapter by lazy {
|
||||
CollectedFoodAdapter(foodList).apply {
|
||||
isStateViewEnable = true
|
||||
// 点击删除按钮,移除对应食材
|
||||
addOnItemChildClickListener(R.id.ivDelete) { _, _, position ->
|
||||
val item = foodList.getOrNull(position) ?: return@addOnItemChildClickListener
|
||||
showDeleteDialog(item.foodName)
|
||||
}
|
||||
setOnItemClickListener { _, _, _ ->
|
||||
hideKeyboard()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除所有采集数据确认弹窗
|
||||
*/
|
||||
private fun showClearAllDialog() {
|
||||
CommonDialog(this)
|
||||
.setTitle("清除提示")
|
||||
.setContent("清除后无法恢复,确认要清除所有采集数据吗?")
|
||||
.setNegativeButton("取消")
|
||||
.setPositiveButton("确认") {
|
||||
dbViewModel.clearAllCollectedFood {
|
||||
toast("已清除所有采集数据")
|
||||
}
|
||||
}
|
||||
.show()
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除弹窗
|
||||
*/
|
||||
private fun showDeleteDialog(foodName: String) {
|
||||
val showFoodName = foodName.split("WP").first()
|
||||
val separator = if (showFoodName.length <= 10) "\n" else ""
|
||||
val content = buildSpannableString {
|
||||
appendText("食材:")
|
||||
appendText(showFoodName, StyleSpan(Typeface.BOLD), ForegroundColorSpan(Color.BLACK))
|
||||
appendText(" 删除后无法恢复,${separator}确认要删除吗?")
|
||||
}
|
||||
CommonDialog(this)
|
||||
.setTitle("删除提示")
|
||||
.setContent(content)
|
||||
.setNegativeButton("取消")
|
||||
.setPositiveButton("确认") {
|
||||
dbViewModel.removeCollectedFood(
|
||||
foodName = foodName,
|
||||
nameFilter = binding.editSearch.text.toString()
|
||||
)
|
||||
}
|
||||
.show()
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
statusBarDarkFont(enable = true)
|
||||
binding = ActivityCollectedFoodBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
setHeaderBackground()
|
||||
binding.root.setOnClickListener { v ->
|
||||
hideKeyboard()
|
||||
}
|
||||
setTitleBar(titleBarAction = {
|
||||
it.visible()
|
||||
it.setOnClickListener { v ->
|
||||
hideKeyboard()
|
||||
}
|
||||
}, titleAction = {
|
||||
it.text = "已采集食材"
|
||||
}, rightIconAction = {
|
||||
it.visible()
|
||||
it.setPaddingRelative(25.dp ,0 ,25.dp ,0)
|
||||
it.setImageResource(R.drawable.ic_trash_white)
|
||||
it.setOnClickListener {
|
||||
showClearAllDialog()
|
||||
}
|
||||
}, backAction = {
|
||||
it.visible()
|
||||
it.setOnClickListener {
|
||||
finish()
|
||||
}
|
||||
})
|
||||
initRecyclerView()
|
||||
initSearch()
|
||||
initObserver()
|
||||
loadCollectedFoodList()
|
||||
}
|
||||
|
||||
private fun loadCollectedFoodList(name: String = "") {
|
||||
dbViewModel.loadCollectedFoodList(nameFilter = name)
|
||||
}
|
||||
|
||||
/**
|
||||
* 收集 searchFoodState,统一处理 Loading / Success / Error 状态
|
||||
*/
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun initObserver() {
|
||||
lifecycleScope.launch {
|
||||
repeatOnLifecycle(Lifecycle.State.STARTED) {
|
||||
dbViewModel.collectedFoodListState.collect { items ->
|
||||
foodList.clear()
|
||||
foodList.addAll(items)
|
||||
adapter.notifyDataSetChanged()
|
||||
if (items.isEmpty()) {
|
||||
loadEmptyView()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 展示空视图 */
|
||||
private fun loadEmptyView() {
|
||||
if (emptyViewBinding == null) {
|
||||
emptyViewBinding = LayoutEmptyViewBinding.inflate(
|
||||
LayoutInflater.from(this), binding.rvCollectedFood, false
|
||||
)
|
||||
}
|
||||
emptyViewBinding!!.tvContent.text = "暂无数据"
|
||||
emptyViewBinding!!.tvSubContent.text = "未查询到食材信息"
|
||||
adapter.stateView = emptyViewBinding!!.root
|
||||
}
|
||||
|
||||
/** 初始化列表 */
|
||||
private fun initRecyclerView() {
|
||||
binding.rvCollectedFood.run {
|
||||
layoutManager = LinearLayoutManager(this@CollectedFoodActivity)
|
||||
adapter = this@CollectedFoodActivity.adapter
|
||||
}
|
||||
}
|
||||
|
||||
/** 初始化搜索栏交互 */
|
||||
private fun initSearch() {
|
||||
binding.btnSearch.setOnClickListener { v ->
|
||||
performSearch {
|
||||
toast(binding.editSearch.hint.toString())
|
||||
}
|
||||
hideKeyboard()
|
||||
}
|
||||
binding.editSearch.run {
|
||||
addTextChangedListener {
|
||||
performSearch {
|
||||
loadCollectedFoodList()
|
||||
}
|
||||
}
|
||||
setOnEditorActionListener { v, actionId, _ ->
|
||||
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
|
||||
performSearch {
|
||||
toast(binding.editSearch.hint.toString())
|
||||
}
|
||||
hideKeyboard()
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 根据关键词过滤食材列表 */
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun performSearch(action: () -> Unit) {
|
||||
val keyword = binding.editSearch.text.toString().trim()
|
||||
if (keyword.isEmpty()) {
|
||||
action()
|
||||
return
|
||||
}
|
||||
// 根据关键词从数据库查询并刷新列表
|
||||
loadCollectedFoodList(keyword)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package com.shuwei.dish.match.ui
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import androidx.activity.addCallback
|
||||
import androidx.core.widget.addTextChangedListener
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import kotlinx.coroutines.launch
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.databinding.ActivityCookingModeBinding
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.ui.fragment.FoodListFragment
|
||||
import com.shuwei.dish.match.utils.KeyboardUtil
|
||||
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.startActivity
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
|
||||
/**
|
||||
* 制作模式
|
||||
*/
|
||||
class CookingModeActivity : BaseActivity() {
|
||||
|
||||
companion object {
|
||||
const val IS_COOKING = "isCooking"
|
||||
const val DINNER_TYPE = "dinnerType"
|
||||
const val IS_CONFIG_PAGE = "isConfigPage"
|
||||
}
|
||||
|
||||
private val binding by lazy { ActivityCookingModeBinding.inflate(layoutInflater) }
|
||||
|
||||
private var dinnerType: String = "1"
|
||||
|
||||
private val fragmentList = mutableListOf<FoodListFragment>().apply {
|
||||
add(FoodListFragment.instance("1"))
|
||||
add(FoodListFragment.instance("2"))
|
||||
add(FoodListFragment.instance("3"))
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContentView(binding.root)
|
||||
setHeaderBackground()
|
||||
setTitleBar(titleBarAction = {
|
||||
it.visible()
|
||||
}, titleAction = {
|
||||
it.text = "选择菜品"
|
||||
}, rightIconAction = {
|
||||
it.visible()
|
||||
it.setImageResource(R.drawable.ic_setting)
|
||||
it.setOnClickListener {
|
||||
startActivity<SettingActivity>()
|
||||
}
|
||||
}, backAction = {
|
||||
it.gone()
|
||||
})
|
||||
addViewListener()
|
||||
loadFragment()
|
||||
onBackPressedDispatcher.addCallback(this) {}
|
||||
}
|
||||
|
||||
|
||||
fun getCookFoodList() {
|
||||
dbViewModel.getCookFoodList(cookMode = 0, dinnerType = dinnerType)
|
||||
}
|
||||
|
||||
private var configFinished = false
|
||||
|
||||
fun judgeDeviceConfig(block: () -> Unit) {
|
||||
// if (configFinished) {
|
||||
// block()
|
||||
// return
|
||||
// }
|
||||
// dbViewModel.loadSeasoning {
|
||||
// if (it.isEmpty()) {
|
||||
// showDeviceConfigDialog()
|
||||
// return@loadSeasoning
|
||||
// }
|
||||
// configFinished = true
|
||||
// block()
|
||||
// }
|
||||
block()
|
||||
}
|
||||
|
||||
private fun showDeviceConfigDialog() {
|
||||
CommonDialog(this)
|
||||
.setTitle("配置提示")
|
||||
.setContent("请先在设备配置页面进行调料设置")
|
||||
.setNegativeButton("取消")
|
||||
.setPositiveButton("去设置") { startActivity<SettingActivity>() }
|
||||
.show()
|
||||
}
|
||||
|
||||
/** 切换餐次时清空输入框,用此标志跳过 afterTextChanged 的查询触发 */
|
||||
private var isClearingByTabSwitch = false
|
||||
|
||||
private fun addViewListener() {
|
||||
binding.tvBreakfast.setOnClickListener { selectTab("1") }
|
||||
binding.tvLunch.setOnClickListener { selectTab("2") }
|
||||
binding.tvDinner.setOnClickListener { selectTab("3") }
|
||||
binding.etInputDish.addOnActionSearchListener {
|
||||
jumpSearch()
|
||||
}
|
||||
binding.ivDishSearch.setOnClickListener {
|
||||
jumpSearch()
|
||||
}
|
||||
// 输入框清空时自动查询全部数据(切换餐次触发的清空除外,由 loadFragment 负责刷新)
|
||||
binding.etInputDish.addTextChangedListener(afterTextChanged = { text ->
|
||||
if (!isClearingByTabSwitch && text.isNullOrBlank()) {
|
||||
currentFragment()?.getDishList(pageNo = 1, dinnerType = dinnerType)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换餐次 Tab:更新选中态、清空搜索框、切换 Fragment
|
||||
* 由点击事件调用,不触发额外的 getDishList(),由 onHiddenChanged 负责刷新
|
||||
*/
|
||||
private fun selectTab(type: String) {
|
||||
if (dinnerType == type) return
|
||||
dinnerType = type
|
||||
binding.tvBreakfast.isChecked = type == "1"
|
||||
binding.tvLunch.isChecked = type == "2"
|
||||
binding.tvDinner.isChecked = type == "3"
|
||||
clearSearchText()
|
||||
loadFragment()
|
||||
}
|
||||
|
||||
/** 获取当前显示的 FoodListFragment */
|
||||
private fun currentFragment(): FoodListFragment? {
|
||||
return runCatching { fragmentList[dinnerType.toInt() - 1] }.getOrNull()
|
||||
}
|
||||
|
||||
private fun jumpSearch() {
|
||||
val searchText = binding.etInputDish.text.toString().trim()
|
||||
if (searchText.isBlank()) {
|
||||
toast(binding.etInputDish.hint.toString())
|
||||
return
|
||||
}
|
||||
currentFragment()?.getDishList(pageNo = 1, dinnerType = dinnerType, foodName = searchText)
|
||||
hideKeyboard()
|
||||
}
|
||||
|
||||
private fun loadFragment() {
|
||||
runCatching {
|
||||
val target = fragmentList[dinnerType.toInt() - 1]
|
||||
supportFragmentManager.beginTransaction().apply {
|
||||
fragmentList.forEach { fragment ->
|
||||
if (fragment.isAdded) {
|
||||
if (fragment == target) show(fragment) else hide(fragment)
|
||||
} else {
|
||||
if (fragment == target) add(R.id.flSubPage, fragment)
|
||||
}
|
||||
}
|
||||
commit()
|
||||
}
|
||||
}.onFailure {
|
||||
it.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteCookFoodAndGoods(foodId: String, dinnerType: String, action: () -> Unit) {
|
||||
lifecycleScope.launch {
|
||||
dbViewModel.deleteCookFoodAndGoods(cookMode = 0, foodId = foodId, dinnerType = dinnerType)
|
||||
action()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
runCatching {
|
||||
val isConfigPage = intent.getBooleanExtra(IS_CONFIG_PAGE, false)
|
||||
if (isConfigPage) {
|
||||
return
|
||||
}
|
||||
val lastDinnerType = intent.getStringExtra(DINNER_TYPE) ?: "0"
|
||||
if (lastDinnerType !in listOf("1", "2", "3")) return
|
||||
if (lastDinnerType == dinnerType) {
|
||||
// 同一 Tab:onHiddenChanged 不会触发,直接刷新
|
||||
clearSearchText()
|
||||
currentFragment()?.getDishList(1, lastDinnerType)
|
||||
} else {
|
||||
// 不同 Tab:selectTab → loadFragment → show → onHiddenChanged 负责刷新,无需直接调用
|
||||
selectTab(lastDinnerType)
|
||||
}
|
||||
}.onFailure {
|
||||
it.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
private var isVisible = false
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
isVisible = true
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
isVisible = false
|
||||
}
|
||||
|
||||
fun clearSearchText() {
|
||||
isClearingByTabSwitch = true
|
||||
binding.etInputDish.text?.clear()
|
||||
isClearingByTabSwitch = false
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,345 +1,345 @@
|
||||
package com.shuwei.dish.match.ui
|
||||
|
||||
import android.graphics.Typeface
|
||||
import android.os.Bundle
|
||||
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.util.SparseArray
|
||||
import android.widget.FrameLayout
|
||||
import androidx.core.graphics.toColorInt
|
||||
import androidx.core.view.forEach
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.db.AppRepository
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
import com.shuwei.dish.match.entity.ResetReasoningRecord
|
||||
import com.shuwei.dish.match.utils.AddressUtil
|
||||
import com.shuwei.dish.match.utils.JsonAssetsLoader
|
||||
import com.shuwei.dish.match.utils.MultiClickDetector
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
import com.shuwei.dish.match.utils.ext.appendText
|
||||
import com.shuwei.dish.match.utils.ext.buildSpannableString
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import com.shuwei.dish.match.utils.ext.startActivity
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
import com.shuwei.dish.match.viewmodel.AppViewModel
|
||||
import com.shuwei.dish.match.viewmodel.factory.AppFactory
|
||||
import com.shuwei.dish.match.adapter.TextCellAdapter
|
||||
import com.shuwei.dish.match.databinding.ActivityDeviceConfigBinding
|
||||
import com.shuwei.dish.match.dialog.SeasoningSearchDialog
|
||||
import com.shuwei.dish.match.utils.SpTool
|
||||
import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
|
||||
class DeviceConfigActivity : BaseActivity() {
|
||||
|
||||
companion object {
|
||||
|
||||
const val TAG = "DeviceConfigActivity"
|
||||
|
||||
const val COOK_MODE = "cookMode"
|
||||
|
||||
val modeList = listOf<ModeBean>(
|
||||
ModeBean("制作模式", "菜品快速制作,记录熟重"),
|
||||
ModeBean("采样模式", "菜品快速制作,记录熟重"),
|
||||
ModeBean("品控模式", "菜品快速制作,记录熟重")
|
||||
)
|
||||
}
|
||||
|
||||
data class ModeBean(
|
||||
var modeName: String,
|
||||
var modeDesc: String
|
||||
)
|
||||
|
||||
private lateinit var binding: ActivityDeviceConfigBinding
|
||||
|
||||
private lateinit var appViewModel: AppViewModel
|
||||
|
||||
private var cookMode: Int = 0
|
||||
// private val weightArray = SparseIntArray()
|
||||
private val weightArray = SparseArray<Double>()
|
||||
private val addressArray = AddressUtil.getWeighAddressArray()
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
binding = ActivityDeviceConfigBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
cookMode = intent.getIntExtra(COOK_MODE, 0)
|
||||
initViewModel()
|
||||
setHeaderBackground()
|
||||
setTitleBar(titleBarAction = {
|
||||
it.visible()
|
||||
}, titleAction = {
|
||||
it.text = "设备配置"
|
||||
}, rightIconActon = {
|
||||
it.gone()
|
||||
// it.alpha = 0.0F
|
||||
// it.setImageResource(R.drawable.ic_setting)
|
||||
// it.setOnClickListener {_->
|
||||
// detector.setOnDelayedMultiClickListener(it) {
|
||||
// defaultDataSettingDialog()
|
||||
// }
|
||||
//package com.shuwei.dish.match.ui
|
||||
//
|
||||
//import android.graphics.Typeface
|
||||
//import android.os.Bundle
|
||||
//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.util.SparseArray
|
||||
//import android.widget.FrameLayout
|
||||
//import androidx.core.graphics.toColorInt
|
||||
//import androidx.core.view.forEach
|
||||
//import androidx.lifecycle.ViewModelProvider
|
||||
//import com.shuwei.dish.match.base.BaseActivity
|
||||
//import com.shuwei.dish.match.base.BaseApp
|
||||
//import com.shuwei.dish.match.db.DbRepository
|
||||
//import com.shuwei.dish.match.dialog.CommonDialog
|
||||
//import com.shuwei.dish.match.entity.SeasoningEntity
|
||||
//import com.shuwei.dish.match.entity.ResetReasoningRecord
|
||||
//import com.shuwei.dish.match.utils.AddressUtil
|
||||
//import com.shuwei.dish.match.utils.JsonAssetsLoader
|
||||
//import com.shuwei.dish.match.utils.MultiClickDetector
|
||||
//import com.shuwei.dish.match.utils.WeightUtil
|
||||
//import com.shuwei.dish.match.utils.ext.appendText
|
||||
//import com.shuwei.dish.match.utils.ext.buildSpannableString
|
||||
//import com.shuwei.dish.match.utils.ext.dp
|
||||
//import com.shuwei.dish.match.utils.ext.startActivity
|
||||
//import com.shuwei.dish.match.utils.ext.toast
|
||||
//import com.shuwei.dish.match.utils.ext.visible
|
||||
//import com.shuwei.dish.match.adapter.TextCellAdapter
|
||||
//import com.shuwei.dish.match.databinding.ActivityDeviceConfigBinding
|
||||
//import com.shuwei.dish.match.dialog.SeasoningSearchDialog
|
||||
//import com.shuwei.dish.match.utils.SpTool
|
||||
//import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
||||
//import com.shuwei.dish.match.utils.ext.gone
|
||||
//import com.shuwei.dish.match.utils.ext.toJsonString
|
||||
//
|
||||
//class DeviceConfigActivity : BaseActivity() {
|
||||
//
|
||||
// companion object {
|
||||
//
|
||||
// const val TAG = "DeviceConfigActivity"
|
||||
//
|
||||
// const val COOK_MODE = "cookMode"
|
||||
//
|
||||
// val modeList = listOf<ModeBean>(
|
||||
// ModeBean("制作模式", "菜品快速制作,记录熟重"),
|
||||
// ModeBean("采样模式", "菜品快速制作,记录熟重"),
|
||||
// ModeBean("品控模式", "菜品快速制作,记录熟重")
|
||||
// )
|
||||
// }
|
||||
//
|
||||
// data class ModeBean(
|
||||
// var modeName: String,
|
||||
// var modeDesc: String
|
||||
// )
|
||||
//
|
||||
// private lateinit var binding: ActivityDeviceConfigBinding
|
||||
//
|
||||
// private lateinit var appViewModel: DbViewModel
|
||||
//
|
||||
// private var cookMode: Int = 0
|
||||
//// private val weightArray = SparseIntArray()
|
||||
// private val weightArray = SparseArray<Double>()
|
||||
// private val addressArray = AddressUtil.getWeighAddressArray()
|
||||
//
|
||||
// override fun onCreate(savedInstanceState: Bundle?) {
|
||||
// super.onCreate(savedInstanceState)
|
||||
// binding = ActivityDeviceConfigBinding.inflate(layoutInflater)
|
||||
// setContentView(binding.root)
|
||||
// cookMode = intent.getIntExtra(COOK_MODE, 0)
|
||||
// initViewModel()
|
||||
// setHeaderBackground()
|
||||
// setTitleBar(titleBarAction = {
|
||||
// it.visible()
|
||||
// }, titleAction = {
|
||||
// it.text = "设备配置"
|
||||
// }, rightIconAction = {
|
||||
// it.gone()
|
||||
//// it.alpha = 0.0F
|
||||
//// it.setImageResource(R.drawable.ic_setting)
|
||||
//// it.setOnClickListener {_->
|
||||
//// detector.setOnDelayedMultiClickListener(it) {
|
||||
//// defaultDataSettingDialog()
|
||||
//// }
|
||||
//// }
|
||||
// })
|
||||
//
|
||||
// loadQualitySpan(isEnable = false)
|
||||
// when (cookMode) {
|
||||
// 1 -> {
|
||||
// binding.rbModeCook.isChecked = true
|
||||
// binding.rbModeSampling.isChecked = false
|
||||
// loadCookSpan(isClicked = true)
|
||||
// loadSamplingSpan()
|
||||
// }
|
||||
})
|
||||
|
||||
loadQualitySpan(isEnable = false)
|
||||
when (cookMode) {
|
||||
1 -> {
|
||||
binding.rbModeCook.isChecked = true
|
||||
binding.rbModeSampling.isChecked = false
|
||||
loadCookSpan(isClicked = true)
|
||||
loadSamplingSpan()
|
||||
}
|
||||
|
||||
2 -> {
|
||||
binding.rbModeCook.isChecked = false
|
||||
binding.rbModeSampling.isChecked = true
|
||||
loadCookSpan()
|
||||
loadSamplingSpan(isClicked = true)
|
||||
}
|
||||
|
||||
else -> {
|
||||
binding.rbModeCook.isChecked = true
|
||||
binding.rbModeSampling.isChecked = false
|
||||
loadCookSpan(isClicked = true)
|
||||
loadSamplingSpan()
|
||||
}
|
||||
}
|
||||
|
||||
binding.rbModeCook.setOnClickListener {
|
||||
SpTool.put(SpTool.LAUNCH_PAGE_TYPE, 0)
|
||||
binding.rbModeCook.isChecked = true
|
||||
binding.rbModeSampling.isChecked = false
|
||||
loadCookSpan(isClicked = true)
|
||||
loadSamplingSpan()
|
||||
startActivity<SelectDishActivity> {
|
||||
putExtra(SelectDishActivity.IS_CONFIG_PAGE, true)
|
||||
}
|
||||
finish()
|
||||
}
|
||||
binding.rbModeSampling.setOnClickListener {
|
||||
SpTool.put(SpTool.LAUNCH_PAGE_TYPE, 1)
|
||||
binding.rbModeCook.isChecked = false
|
||||
binding.rbModeSampling.isChecked = true
|
||||
loadCookSpan()
|
||||
loadSamplingSpan(isClicked = true)
|
||||
startActivity<SamplingListActivity> {
|
||||
putExtra(SamplingListActivity.IS_CONFIG_PAGE, true) }
|
||||
finish()
|
||||
}
|
||||
addWeighListener()
|
||||
addGridItemListener()
|
||||
loadSeasoning()
|
||||
}
|
||||
|
||||
private fun addWeighListener() {
|
||||
WeightUtil.addWeightListener(
|
||||
weightKey = TAG,
|
||||
getWeight = { address, state, weight ->
|
||||
Log.d(TAG, "addWeighListener: address=$address,stat=$state,weight=$weight")
|
||||
weightArray.put(address, weight)
|
||||
val item = seasoningItems.firstOrNull { address == addressArray[it.sort] }
|
||||
item?.let {
|
||||
it.useWeight = weight.toDouble()
|
||||
updateGridData(it)
|
||||
}
|
||||
Log.d(TAG, "addWeighListener: update-----------------------")
|
||||
})
|
||||
}
|
||||
|
||||
private var seasoningItems = mutableListOf<SeasoningEntity>()
|
||||
private fun addGridItemListener() {
|
||||
binding.include.root.forEach { child ->
|
||||
child.clickWithDebounce {
|
||||
val sort = child.tag.toString().toInt()
|
||||
val entity = seasoningItems.firstOrNull { it.sort == sort } ?: SeasoningEntity()
|
||||
clickGridItem(sort, entity)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val detector = MultiClickDetector(targetCount = 10, intervalMs = 800)
|
||||
|
||||
private fun defaultDataSettingDialog() {
|
||||
CommonDialog(this)
|
||||
.setTitle("温馨提示")
|
||||
.setContent("您好,使用默认配置作为您的调料数据,则已有配置将被清除,确认吗?")
|
||||
.setNegativeButton("取消")
|
||||
.setPositiveButton("确认") { resetList() }
|
||||
.setOnDismissCallback { hideStatusBar() }
|
||||
.show()
|
||||
}
|
||||
|
||||
private fun resetList() {
|
||||
runCatching {
|
||||
val record = JsonAssetsLoader.parseJsonFromAssets<ResetReasoningRecord>(
|
||||
this,
|
||||
"default_seasoning_list.json"
|
||||
)
|
||||
// val weightArray = WeightUtil.weightArray
|
||||
appViewModel.clearAllSeasoning {
|
||||
record?.list?.forEach { entity ->
|
||||
entity.useWeight = weightArray[addressArray[entity.sort]].toDouble()
|
||||
appViewModel.saveSeasoning(entity) {
|
||||
updateGridData(entity)
|
||||
}
|
||||
}
|
||||
// loadSeasoning()
|
||||
}
|
||||
}.onFailure { it.printStackTrace() }
|
||||
}
|
||||
|
||||
private fun initViewModel() {
|
||||
val db = BaseApp.instance!!.database
|
||||
val factory =
|
||||
AppFactory(AppRepository(db.appDao()))
|
||||
appViewModel =
|
||||
ViewModelProvider(this, factory)[AppViewModel::class.java]
|
||||
}
|
||||
|
||||
private fun loadSeasoning() {
|
||||
appViewModel.loadSeasoning {
|
||||
seasoningItems.clear()
|
||||
seasoningItems.addAll(it)
|
||||
initConfigData()
|
||||
setGridData(seasoningItems)
|
||||
}
|
||||
}
|
||||
|
||||
private fun initConfigData() {
|
||||
repeat(12) { num ->
|
||||
val firstOne = seasoningItems.firstOrNull { it.sort == num }
|
||||
if (firstOne == null) {
|
||||
seasoningItems.add(SeasoningEntity().also { it.sort = num })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun setGridData(list: MutableList<SeasoningEntity>) {
|
||||
val gridLayout = binding.include.root
|
||||
list.forEach { entity ->
|
||||
val tag = entity.sort.toString()
|
||||
val frameLayout = gridLayout.findViewWithTag<FrameLayout>(tag)
|
||||
TextCellAdapter.loadLayout(frameLayout, entity)
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateGridData(entity: SeasoningEntity) {
|
||||
val gridLayout = binding.include.root
|
||||
val tag = entity.sort.toString()
|
||||
val frameLayout = gridLayout.findViewWithTag<FrameLayout>(tag)
|
||||
TextCellAdapter.loadLayout(frameLayout, entity)
|
||||
}
|
||||
|
||||
private fun clickGridItem(sort: Int, entity: SeasoningEntity) {
|
||||
val currentAddress = AddressUtil.getWeighAddressArray().get(sort)
|
||||
// val seasoningEntity = list.first{it.sort == sort}
|
||||
SeasoningSearchDialog(
|
||||
activity = this,
|
||||
weighIndex = sort,
|
||||
weighAddress = currentAddress,
|
||||
clickName = entity.goodsName
|
||||
) { item ->
|
||||
syncItem(entity, item)
|
||||
//3-调料
|
||||
entity.materialType = 3
|
||||
entity.sort = sort
|
||||
saveSeasoning(entity) {
|
||||
val tag = sort.toString()
|
||||
val gridLayout = binding.include.root
|
||||
val frameLayout = gridLayout.findViewWithTag<FrameLayout>(tag)
|
||||
TextCellAdapter.loadLayout(frameLayout, entity)
|
||||
}
|
||||
}.show()
|
||||
}
|
||||
|
||||
private fun syncItem(oldItem: SeasoningEntity, newItem: SeasoningEntity) {
|
||||
oldItem.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
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadQualitySpan(isClicked: Boolean = false, isEnable: Boolean = true) {
|
||||
binding.rbModeQuality.text =
|
||||
getModeTextSpan(
|
||||
topText = modeList[2].modeName,
|
||||
bottomText = modeList[2].modeDesc,
|
||||
topColor = if (isEnable) if (isClicked) "#00BC71" else "#000000" else "#B4B4B4",
|
||||
bottomColor = if (isEnable) "#8B8B8B" else "#B4B4B4"
|
||||
)
|
||||
}
|
||||
|
||||
private fun loadSamplingSpan(isClicked: Boolean = false, isEnable: Boolean = true) {
|
||||
binding.rbModeSampling.text =
|
||||
getModeTextSpan(
|
||||
topText = modeList[1].modeName,
|
||||
bottomText = modeList[1].modeDesc,
|
||||
topColor = if (isEnable) if (isClicked) "#00BC71" else "#000000" else "#B4B4B4",
|
||||
bottomColor = if (isEnable) "#8B8B8B" else "#B4B4B4"
|
||||
)
|
||||
}
|
||||
|
||||
private fun loadCookSpan(isClicked: Boolean = false, isEnable: Boolean = true) {
|
||||
binding.rbModeCook.text =
|
||||
getModeTextSpan(
|
||||
topText = modeList[0].modeName,
|
||||
bottomText = modeList[0].modeDesc,
|
||||
topColor = if (isEnable) if (isClicked) "#00BC71" else "#000000" else "#B4B4B4",
|
||||
bottomColor = if (isEnable) "#8B8B8B" else "#B4B4B4"
|
||||
)
|
||||
}
|
||||
|
||||
private fun getModeTextSpan(
|
||||
topText: String,
|
||||
topColor: String,
|
||||
bottomText: String,
|
||||
bottomColor: String
|
||||
): SpannableStringBuilder {
|
||||
|
||||
|
||||
return buildSpannableString {
|
||||
appendText(
|
||||
topText,
|
||||
ForegroundColorSpan(topColor.toColorInt()),
|
||||
StyleSpan(Typeface.BOLD),
|
||||
AbsoluteSizeSpan(36, true),
|
||||
LineHeightSpan { text, start, end, spanstartv, v, fm ->
|
||||
fm.descent += 10.dp // 增加行间距
|
||||
}
|
||||
)
|
||||
append("\n")
|
||||
appendText(
|
||||
bottomText,
|
||||
ForegroundColorSpan(bottomColor.toColorInt()),
|
||||
AbsoluteSizeSpan(26, true)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun saveSeasoning(entity: SeasoningEntity, action: () -> Unit = {}) {
|
||||
appViewModel.saveSeasoning(entity) {
|
||||
action()
|
||||
toast("保存成功")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
//
|
||||
// 2 -> {
|
||||
// binding.rbModeCook.isChecked = false
|
||||
// binding.rbModeSampling.isChecked = true
|
||||
// loadCookSpan()
|
||||
// loadSamplingSpan(isClicked = true)
|
||||
// }
|
||||
//
|
||||
// else -> {
|
||||
// binding.rbModeCook.isChecked = true
|
||||
// binding.rbModeSampling.isChecked = false
|
||||
// loadCookSpan(isClicked = true)
|
||||
// loadSamplingSpan()
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// binding.rbModeCook.setOnClickListener {
|
||||
// SpTool.put(SpTool.LAUNCH_PAGE_TYPE, 0)
|
||||
// binding.rbModeCook.isChecked = true
|
||||
// binding.rbModeSampling.isChecked = false
|
||||
// loadCookSpan(isClicked = true)
|
||||
// loadSamplingSpan()
|
||||
// startActivity<SelectDishActivity> {
|
||||
// putExtra(SelectDishActivity.IS_CONFIG_PAGE, true)
|
||||
// }
|
||||
// finish()
|
||||
// }
|
||||
// binding.rbModeSampling.setOnClickListener {
|
||||
// SpTool.put(SpTool.LAUNCH_PAGE_TYPE, 1)
|
||||
// binding.rbModeCook.isChecked = false
|
||||
// binding.rbModeSampling.isChecked = true
|
||||
// loadCookSpan()
|
||||
// loadSamplingSpan(isClicked = true)
|
||||
// startActivity<SamplingListActivity> {
|
||||
// putExtra(SamplingListActivity.IS_CONFIG_PAGE, true) }
|
||||
// finish()
|
||||
// }
|
||||
// addWeighListener()
|
||||
// addGridItemListener()
|
||||
// loadSeasoning()
|
||||
// }
|
||||
//
|
||||
// private fun addWeighListener() {
|
||||
// WeightUtil.addWeightListener(
|
||||
// weightKey = TAG,
|
||||
// getWeight = { address, state, weight ->
|
||||
// Log.d(TAG, "addWeighListener: address=$address,stat=$state,weight=$weight")
|
||||
// weightArray.put(address, weight)
|
||||
// val item = seasoningItems.firstOrNull { address == addressArray[it.sort] }
|
||||
// item?.let {
|
||||
// it.useWeight = weight.toDouble()
|
||||
// updateGridData(it)
|
||||
// }
|
||||
// Log.d(TAG, "addWeighListener: update-----------------------")
|
||||
// })
|
||||
// }
|
||||
//
|
||||
// private var seasoningItems = mutableListOf<SeasoningEntity>()
|
||||
// private fun addGridItemListener() {
|
||||
// binding.include.root.forEach { child ->
|
||||
// child.clickWithDebounce {
|
||||
// val sort = child.tag.toString().toInt()
|
||||
// val entity = seasoningItems.firstOrNull { it.sort == sort } ?: SeasoningEntity()
|
||||
// clickGridItem(sort, entity)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// val detector = MultiClickDetector(targetCount = 10, intervalMs = 800)
|
||||
//
|
||||
// private fun defaultDataSettingDialog() {
|
||||
// CommonDialog(this)
|
||||
// .setTitle("温馨提示")
|
||||
// .setContent("您好,使用默认配置作为您的调料数据,则已有配置将被清除,确认吗?")
|
||||
// .setNegativeButton("取消")
|
||||
// .setPositiveButton("确认") { resetList() }
|
||||
// .setOnDismissCallback { hideStatusBar() }
|
||||
// .show()
|
||||
// }
|
||||
//
|
||||
// private fun resetList() {
|
||||
// runCatching {
|
||||
// val record = JsonAssetsLoader.parseJsonFromAssets<ResetReasoningRecord>(
|
||||
// this,
|
||||
// "default_seasoning_list.json"
|
||||
// )
|
||||
//// val weightArray = WeightUtil.weightArray
|
||||
// appViewModel.clearAllSeasoning {
|
||||
// record?.list?.forEach { entity ->
|
||||
// entity.useWeight = weightArray[addressArray[entity.sort]].toDouble()
|
||||
// appViewModel.saveSeasoning(entity) {
|
||||
// updateGridData(entity)
|
||||
// }
|
||||
// }
|
||||
//// loadSeasoning()
|
||||
// }
|
||||
// }.onFailure { it.printStackTrace() }
|
||||
// }
|
||||
//
|
||||
// private fun initViewModel() {
|
||||
// val db = BaseApp.instance!!.database
|
||||
// val factory =
|
||||
// AppFactory(DbRepository(db.appDao()))
|
||||
// appViewModel =
|
||||
// ViewModelProvider(this, factory)[DbViewModel::class.java]
|
||||
// }
|
||||
//
|
||||
// private fun loadSeasoning() {
|
||||
// appViewModel.loadSeasoning {
|
||||
// seasoningItems.clear()
|
||||
// seasoningItems.addAll(it)
|
||||
// initConfigData()
|
||||
// setGridData(seasoningItems)
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private fun initConfigData() {
|
||||
// repeat(12) { num ->
|
||||
// val firstOne = seasoningItems.firstOrNull { it.sort == num }
|
||||
// if (firstOne == null) {
|
||||
// seasoningItems.add(SeasoningEntity().also { it.sort = num })
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private fun setGridData(list: MutableList<SeasoningEntity>) {
|
||||
// Log.d(TAG, "setGridData: ${list.toJsonString()}")
|
||||
// val gridLayout = binding.include.root
|
||||
// list.forEach { entity ->
|
||||
// val tag = entity.sort.toString()
|
||||
// val frameLayout = gridLayout.findViewWithTag<FrameLayout>(tag)
|
||||
// TextCellAdapter.loadLayout(frameLayout, entity)
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private fun updateGridData(entity: SeasoningEntity) {
|
||||
// val gridLayout = binding.include.root
|
||||
// val tag = entity.sort.toString()
|
||||
// val frameLayout = gridLayout.findViewWithTag<FrameLayout>(tag)
|
||||
// TextCellAdapter.loadLayout(frameLayout, entity)
|
||||
// }
|
||||
//
|
||||
// private fun clickGridItem(sort: Int, entity: SeasoningEntity) {
|
||||
// val currentAddress = AddressUtil.getWeighAddressArray().get(sort)
|
||||
//// val seasoningEntity = list.first{it.sort == sort}
|
||||
// SeasoningSearchDialog(
|
||||
// activity = this,
|
||||
// weighIndex = sort,
|
||||
// weighAddress = currentAddress,
|
||||
// clickName = entity.goodsName
|
||||
// ) { item ->
|
||||
// syncItem(entity, item)
|
||||
// //3-调料
|
||||
// entity.materialType = 3
|
||||
// entity.sort = sort
|
||||
// saveSeasoning(entity) {
|
||||
// val tag = sort.toString()
|
||||
// val gridLayout = binding.include.root
|
||||
// val frameLayout = gridLayout.findViewWithTag<FrameLayout>(tag)
|
||||
// TextCellAdapter.loadLayout(frameLayout, entity)
|
||||
// }
|
||||
// }.show()
|
||||
// }
|
||||
//
|
||||
// private fun syncItem(oldItem: SeasoningEntity, newItem: SeasoningEntity) {
|
||||
// oldItem.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
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private fun loadQualitySpan(isClicked: Boolean = false, isEnable: Boolean = true) {
|
||||
// binding.rbModeQuality.text =
|
||||
// getModeTextSpan(
|
||||
// topText = modeList[2].modeName,
|
||||
// bottomText = modeList[2].modeDesc,
|
||||
// topColor = if (isEnable) if (isClicked) "#00BC71" else "#000000" else "#B4B4B4",
|
||||
// bottomColor = if (isEnable) "#8B8B8B" else "#B4B4B4"
|
||||
// )
|
||||
// }
|
||||
//
|
||||
// private fun loadSamplingSpan(isClicked: Boolean = false, isEnable: Boolean = true) {
|
||||
// binding.rbModeSampling.text =
|
||||
// getModeTextSpan(
|
||||
// topText = modeList[1].modeName,
|
||||
// bottomText = modeList[1].modeDesc,
|
||||
// topColor = if (isEnable) if (isClicked) "#00BC71" else "#000000" else "#B4B4B4",
|
||||
// bottomColor = if (isEnable) "#8B8B8B" else "#B4B4B4"
|
||||
// )
|
||||
// }
|
||||
//
|
||||
// private fun loadCookSpan(isClicked: Boolean = false, isEnable: Boolean = true) {
|
||||
// binding.rbModeCook.text =
|
||||
// getModeTextSpan(
|
||||
// topText = modeList[0].modeName,
|
||||
// bottomText = modeList[0].modeDesc,
|
||||
// topColor = if (isEnable) if (isClicked) "#00BC71" else "#000000" else "#B4B4B4",
|
||||
// bottomColor = if (isEnable) "#8B8B8B" else "#B4B4B4"
|
||||
// )
|
||||
// }
|
||||
//
|
||||
// private fun getModeTextSpan(
|
||||
// topText: String,
|
||||
// topColor: String,
|
||||
// bottomText: String,
|
||||
// bottomColor: String
|
||||
// ): SpannableStringBuilder {
|
||||
//
|
||||
//
|
||||
// return buildSpannableString {
|
||||
// appendText(
|
||||
// topText,
|
||||
// ForegroundColorSpan(topColor.toColorInt()),
|
||||
// StyleSpan(Typeface.BOLD),
|
||||
// AbsoluteSizeSpan(36, true),
|
||||
// LineHeightSpan { text, start, end, spanstartv, v, fm ->
|
||||
// fm.descent += 10.dp // 增加行间距
|
||||
// }
|
||||
// )
|
||||
// append("\n")
|
||||
// appendText(
|
||||
// bottomText,
|
||||
// ForegroundColorSpan(bottomColor.toColorInt()),
|
||||
// AbsoluteSizeSpan(26, true)
|
||||
// )
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// fun saveSeasoning(entity: SeasoningEntity, action: () -> Unit = {}) {
|
||||
// appViewModel.saveSeasoning(entity) {
|
||||
// action()
|
||||
// toast("保存成功")
|
||||
// }
|
||||
// }
|
||||
//
|
||||
//}
|
||||
@@ -1,304 +0,0 @@
|
||||
package com.shuwei.dish.match.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import android.view.View
|
||||
import androidx.activity.addCallback
|
||||
import androidx.activity.viewModels
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import androidx.recyclerview.widget.ItemTouchHelper
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.DishPartAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.databinding.ActivityDishSamplingBinding
|
||||
import com.shuwei.dish.match.db.AppRepository
|
||||
import com.shuwei.dish.match.dialog.FoodSearchDialog
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.entity.CookFoodEntity
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.entity.FoodRecord
|
||||
import com.shuwei.dish.match.net.NetViewModel
|
||||
import com.shuwei.dish.match.utils.AddressUtil
|
||||
import com.shuwei.dish.match.utils.KeyboardUtil
|
||||
import com.shuwei.dish.match.utils.SwipeCallback
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
||||
import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.startActivity
|
||||
import com.shuwei.dish.match.utils.ext.toJsonString
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
import com.shuwei.dish.match.viewmodel.AppViewModel
|
||||
import com.shuwei.dish.match.viewmodel.factory.AppFactory
|
||||
import java.io.Serializable
|
||||
|
||||
class DishSamplingActivity : BaseActivity() {
|
||||
|
||||
private lateinit var binding: ActivityDishSamplingBinding
|
||||
|
||||
var foodName: String? = null
|
||||
|
||||
private var foodId: String? = null
|
||||
|
||||
companion object {
|
||||
private const val TAG = "DishSamplingActivity"
|
||||
public const val FOOD_NAME = "foodName"
|
||||
public const val PAGE_FROM = "pageFrom"
|
||||
public const val HOME = "home"
|
||||
}
|
||||
|
||||
private var pageFrom: String? = null
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
binding = ActivityDishSamplingBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
pageFrom = intent.getStringExtra(PAGE_FROM)
|
||||
setTitleBar()
|
||||
setHeaderBackground()
|
||||
addViewClickListener()
|
||||
initViewModel()
|
||||
foodName = intent.getStringExtra(FOOD_NAME)
|
||||
binding.etInputDish.setText(foodName)
|
||||
|
||||
WeightUtil.addWeightListener(
|
||||
weightKey = TAG,
|
||||
getWeight = { address, state, weight ->
|
||||
//Log.d(TAG, "addViewClickListener: address=$address,state=$state,weight=$weight")
|
||||
if (address == AddressUtil.ONE) {
|
||||
tempDishEntity?.useWeight = weight.toDouble()
|
||||
binding.tvDishPartWeight.text = "${weight}"
|
||||
}
|
||||
})
|
||||
addBackKeyListener()
|
||||
}
|
||||
|
||||
private fun setTitleBar() {
|
||||
setTitleBar(titleBarAction = {
|
||||
it.visible()
|
||||
}, titleAction = {
|
||||
it.text = "菜品采集"
|
||||
}, rightIconActon = {
|
||||
it.gone()
|
||||
it.setImageResource(R.drawable.ic_setting)
|
||||
it.setOnClickListener {
|
||||
//startActivity<DeviceSettingActivity>()
|
||||
}
|
||||
}, backAction = {
|
||||
it.visible()
|
||||
it.setOnClickListener {
|
||||
onBackPressedDispatcher.onBackPressed()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private lateinit var appViewModel: AppViewModel
|
||||
|
||||
private fun initViewModel() {
|
||||
val db = BaseApp.instance!!.database
|
||||
val factory =
|
||||
AppFactory(AppRepository(db.appDao()))
|
||||
appViewModel =
|
||||
ViewModelProvider(this, factory)[AppViewModel::class.java]
|
||||
}
|
||||
|
||||
fun getCookFoodList(action: (MutableList<CookFoodEntity>?) -> Unit) {
|
||||
appViewModel.getCookFoodList(cookMode = 1) { action(it) }
|
||||
}
|
||||
|
||||
/**
|
||||
* 监听返回键
|
||||
*/
|
||||
fun addBackKeyListener() {
|
||||
onBackPressedDispatcher.addCallback(this) {
|
||||
if (list.isEmpty().not()) {
|
||||
//说明有新增的食材
|
||||
saveDataRemindDialog()
|
||||
return@addCallback
|
||||
}
|
||||
if (pageFrom == HOME) {
|
||||
startActivity<SamplingListActivity>()
|
||||
}
|
||||
onBackPressedDispatcher.onBackPressed()
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveDataRemindDialog() {
|
||||
CommonDialog(this)
|
||||
.setTitle("温馨提示")
|
||||
.setContent("您好,当前页面存在未保存的数据,确认返回吗?")
|
||||
.setNegativeButton("取消")
|
||||
.setPositiveButton("确认") {
|
||||
if (pageFrom == HOME) {
|
||||
startActivity<SamplingListActivity>()
|
||||
}
|
||||
finish()
|
||||
}
|
||||
.setOnDismissCallback { hideStatusBar() }
|
||||
.show()
|
||||
}
|
||||
|
||||
|
||||
val list: MutableList<CookFoodGoodsEntity> = mutableListOf()
|
||||
|
||||
private var tempDishEntity: CookFoodGoodsEntity? = null
|
||||
|
||||
private var dishMaterialType = 1
|
||||
|
||||
private val dishAdapter by lazy {
|
||||
DishPartAdapter(list).apply {
|
||||
addOnItemChildClickListener(R.id.ivOperateIcon) { _, _, position ->
|
||||
//删除操作
|
||||
list.removeAt(position)
|
||||
notifyItemRemoved(position)
|
||||
notifyItemRangeChanged(position, list.size - position)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun addViewClickListener() {
|
||||
binding.rvDishPartList.run {
|
||||
layoutManager =
|
||||
LinearLayoutManager(this@DishSamplingActivity, LinearLayoutManager.VERTICAL, false)
|
||||
adapter = dishAdapter
|
||||
val itemTouchHelper = ItemTouchHelper(SwipeCallback(dishAdapter) { position ->
|
||||
list.removeAt(position)
|
||||
dishAdapter.notifyItemRemoved(position)
|
||||
dishAdapter.notifyItemRangeChanged(position, list.size - position)
|
||||
toast("已删除")
|
||||
})
|
||||
itemTouchHelper.attachToRecyclerView(this)
|
||||
}
|
||||
binding.etInputDishType.addOnActionSearchListener {
|
||||
searchDishType()
|
||||
}
|
||||
binding.ivDishTypeSearch.setOnClickListener {
|
||||
searchDishType()
|
||||
}
|
||||
|
||||
binding.ivWeightClear.setOnClickListener {
|
||||
WeightUtil.tareTwo(AddressUtil.ONE)
|
||||
}
|
||||
binding.ivWeightAdd.setOnClickListener {
|
||||
if (tempDishEntity == null) {
|
||||
toast("请输入食材名称")
|
||||
return@setOnClickListener
|
||||
}
|
||||
if (binding.rgSampling.checkedRadioButtonId == -1) {
|
||||
toast("请选择主辅材类型")
|
||||
return@setOnClickListener
|
||||
}
|
||||
val realWeight = tempDishEntity!!.useWeight ?: 0.0
|
||||
if (realWeight <= 0.toDouble()) {
|
||||
toast("食材用量需要大于0")
|
||||
return@setOnClickListener
|
||||
}
|
||||
if (tempDishEntity?.goodsName != binding.etInputDishType.text.toString().trim()) {
|
||||
toast("所选择的食材名称与输入框内容不一致")
|
||||
return@setOnClickListener
|
||||
}
|
||||
tempDishEntity!!.apply {
|
||||
isSamplingPage = true
|
||||
materialType = dishMaterialType
|
||||
}
|
||||
val result = list.firstOrNull { it.goodsId == tempDishEntity!!.goodsId }
|
||||
if (result != null) {
|
||||
toast("${result.goodsName}食材已添加,请勿重复操作")
|
||||
return@setOnClickListener
|
||||
}
|
||||
list.add(tempDishEntity!!)
|
||||
dishAdapter.notifyDataSetChanged()
|
||||
tempDishEntity = null
|
||||
binding.etInputDishType.setText("")
|
||||
binding.rgSampling.clearCheck()
|
||||
}
|
||||
binding.rgSampling.setOnCheckedChangeListener { group, checkedId ->
|
||||
dishMaterialType = if (checkedId == R.id.rbDishTypeFirst) 1 else 2
|
||||
}
|
||||
binding.ivDishSearch.setOnClickListener { v ->
|
||||
jumpSearch(v)
|
||||
}
|
||||
binding.btnCook.clickWithDebounce {
|
||||
val showFoodName = binding.etInputDish.text.toString().trim()
|
||||
if (showFoodName.isBlank()) {
|
||||
toast("菜品名称为空")
|
||||
return@clickWithDebounce
|
||||
}
|
||||
if (list.isEmpty()) {
|
||||
toast("菜品构成信息未设置")
|
||||
return@clickWithDebounce
|
||||
}
|
||||
val food = FoodRecord()
|
||||
binding.etInputDish.let {
|
||||
if (it.tag != null && it.tag.toString() == it.text.toString()) {
|
||||
food.foodId = foodId
|
||||
}
|
||||
}
|
||||
food.foodName = showFoodName
|
||||
food.cookMode = 1
|
||||
Log.d(TAG, "goToSubmit: goodsList:${list.toJsonString()}")
|
||||
// startActivity<SubmitDishActivity> {
|
||||
startActivity<SubmitFoodActivity> {
|
||||
putExtra(SubmitFoodActivity.GOODS_LIST, list as java.io.Serializable)
|
||||
putExtra(SubmitFoodActivity.FOOD_ITEM, food as Serializable)
|
||||
}
|
||||
}
|
||||
binding.etInputDish.let { v ->
|
||||
v.addOnActionSearchListener {
|
||||
jumpSearch(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun jumpSearch(v: View) {
|
||||
val intent = Intent(this, FoodSearchActivity::class.java).apply {
|
||||
putExtra(FoodSearchActivity.FOOD_NAME, binding.etInputDish.text.toString().trim())
|
||||
}
|
||||
startActivity(intent) {
|
||||
foodId = it?.getStringExtra(FoodSearchActivity.FOOD_ID)
|
||||
foodName = it?.getStringExtra(FoodSearchActivity.FOOD_NAME)
|
||||
binding.etInputDish.run {
|
||||
setText(foodName)
|
||||
tag = foodName
|
||||
setSelection(text.length)
|
||||
}
|
||||
}
|
||||
KeyboardUtil.hideKeyboard(v.context, v)
|
||||
}
|
||||
|
||||
private fun searchDishType() {
|
||||
val inputText = binding.etInputDishType.text.toString().trim()
|
||||
FoodSearchDialog(
|
||||
activity = this@DishSamplingActivity,
|
||||
defGoodsName = inputText
|
||||
) { item ->
|
||||
val filterResult = list.firstOrNull { it.goodsName == item.goodsName }
|
||||
if (filterResult != null) {
|
||||
toast("不允许重复添加同一食材")
|
||||
return@FoodSearchDialog
|
||||
}
|
||||
binding.etInputDishType.run {
|
||||
setText(item.goodsName)
|
||||
setSelection(length())
|
||||
}
|
||||
tempDishEntity = CookFoodGoodsEntity().apply {
|
||||
goodsId = item.goodsId
|
||||
goodsName = item.goodsName
|
||||
|
||||
relateionType = item.relateionType ?: 0
|
||||
goodsOrRelationCode = item.goodsOrRelationCode
|
||||
|
||||
isNewDishType = true
|
||||
// TODO: 待定
|
||||
//allEdible = item.allEdible
|
||||
}
|
||||
}.show()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,20 +2,33 @@ package com.shuwei.dish.match.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import androidx.activity.addCallback
|
||||
import androidx.core.content.IntentCompat
|
||||
import androidx.recyclerview.widget.GridLayoutManager
|
||||
import com.shuwei.dish.match.adapter.GoodsInfoSearchAdapter
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
import com.shuwei.dish.match.adapter.FoodAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.databinding.ActivityFoodRecognizeBinding
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.dialog.FoodSearchDialog
|
||||
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
|
||||
import com.shuwei.dish.match.model.GoodsItem
|
||||
import com.shuwei.dish.match.model.GoodsNameQueryDTO
|
||||
import com.shuwei.dish.match.utils.ActivityManager
|
||||
import com.shuwei.dish.match.utils.AddressUtil
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
import com.shuwei.dish.match.utils.ext.clickWithDebounce
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
import androidx.core.net.toUri
|
||||
import androidx.core.view.updateLayoutParams
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import com.shuwei.dish.match.net.UiState
|
||||
import com.shuwei.dish.match.objbox.FoodModule
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import com.shuwei.dish.match.utils.showRawMaterialsDialog
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* 食材识别结果页面
|
||||
@@ -26,32 +39,44 @@ class FoodRecognizeActivity : BaseActivity() {
|
||||
companion object {
|
||||
private const val TAG = "FoodRecognizeActivity"
|
||||
private const val EXTRA_IMAGE_URI = "extra_image_uri"
|
||||
private const val EXTRA_CURRENT_WEIGHT = "extra_current_weight"
|
||||
private const val EXTRA_INITIAL_WEIGHT = "extra_initial_weight"
|
||||
const val EXTRA_SELECTED_ITEM = "extra_selected_item"
|
||||
const val IS_MANUAL_CANCEL = "isManualCancel"
|
||||
|
||||
/** 内存缓存食材列表,避免通过 Intent 序列化传递大数据 */
|
||||
private var pendingGoodsList: ArrayList<CookFoodGoodsEntity>? = null
|
||||
private var recognizeNameList: ArrayList<FoodModule.IdNameScore>? = null
|
||||
|
||||
/**
|
||||
* 启动本页面,通过 onResult 回调返回用户选中的食材
|
||||
* @param activity 宿主 Activity
|
||||
* @param imageUri 食材照片路径(可为空)
|
||||
* @param goodsList 识别到的食材列表
|
||||
* @param onResult 页面关闭后回调,携带用户选中的食材(未选中时为 null)
|
||||
* @param nameScoreList 识别到的食材列表
|
||||
* @param finishCallback 页面关闭后回调,携带用户选中的食材(未选中时为 null)
|
||||
*/
|
||||
fun start(
|
||||
activity: BaseActivity,
|
||||
imageUri: String? = null,
|
||||
goodsList: ArrayList<CookFoodGoodsEntity> = arrayListOf(),
|
||||
onResult: (CookFoodGoodsEntity?) -> Unit = {}
|
||||
currentWeight: Double = 0.0,
|
||||
initialWeight: Double = 0.0,
|
||||
nameScoreList: ArrayList<FoodModule.IdNameScore> = arrayListOf(),
|
||||
finishCallback: (Boolean, GoodsItem?) -> Unit = { _, _ -> }
|
||||
) {
|
||||
pendingGoodsList = goodsList
|
||||
val intent = Intent(activity, FoodRecognizeActivity::class.java).apply {
|
||||
recognizeNameList = nameScoreList
|
||||
val launchIntent = Intent(activity, FoodRecognizeActivity::class.java).apply {
|
||||
putExtra(EXTRA_IMAGE_URI, imageUri)
|
||||
putExtra(EXTRA_CURRENT_WEIGHT, currentWeight)
|
||||
putExtra(EXTRA_INITIAL_WEIGHT, initialWeight)
|
||||
}
|
||||
activity.startActivity(intent) { resultIntent ->
|
||||
@Suppress("DEPRECATION")
|
||||
val item = resultIntent?.getSerializableExtra(EXTRA_SELECTED_ITEM) as? CookFoodGoodsEntity
|
||||
onResult(item)
|
||||
activity.startActivity(launchIntent) { resultIntent ->
|
||||
val isManualCancel = resultIntent?.getBooleanExtra(IS_MANUAL_CANCEL, false) ?: false
|
||||
val entity = resultIntent?.let {
|
||||
IntentCompat.getSerializableExtra(
|
||||
it,
|
||||
EXTRA_SELECTED_ITEM,
|
||||
GoodsItem::class.java
|
||||
)
|
||||
}
|
||||
finishCallback(isManualCancel, entity)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,21 +88,78 @@ class FoodRecognizeActivity : BaseActivity() {
|
||||
ActivityManager.getActivityStack()
|
||||
.filterIsInstance<FoodRecognizeActivity>()
|
||||
.lastOrNull()
|
||||
?.finishWithResult()
|
||||
?.finishWithResult(false)
|
||||
}
|
||||
}
|
||||
|
||||
private lateinit var binding: ActivityFoodRecognizeBinding
|
||||
|
||||
private val list = mutableListOf<CookFoodGoodsEntity>()
|
||||
private val list = mutableListOf<GoodsItem>()
|
||||
|
||||
private val adapter = GoodsInfoSearchAdapter(list).apply {
|
||||
/** 当前选中的列表位置,-1 表示无选中 */
|
||||
private var selectedPosition = -1
|
||||
|
||||
/** 秤1当前实时净重(已减去初始读数) */
|
||||
private var currentWeight = 0.0
|
||||
|
||||
/** 初始秤读数,净重 = 秤读数 - initialWeight */
|
||||
private var initialWeight = 0.0
|
||||
|
||||
/**
|
||||
* 滑动窗口:保存最近 10 条稳定帧净重,用于关闭页面时判断数据是否稳定
|
||||
* 超过 10 条时移除队头,保持最新数据
|
||||
*/
|
||||
private val weightWindow = ArrayDeque<Double>(10)
|
||||
|
||||
/** 右侧自定义滚动指示条最小高度 */
|
||||
private val scrollIndicatorMinHeightPx by lazy { (24 * resources.displayMetrics.density).toInt() }
|
||||
|
||||
/** 食材搜索弹窗,持有引用防止重复打开 */
|
||||
private var foodSearchDialog: FoodSearchDialog? = null
|
||||
|
||||
/** 数据不稳定提示弹窗,持有引用通过 isShowing 防止重复弹出 */
|
||||
private var unstableDialog: CommonDialog? = null
|
||||
|
||||
/** 通过name查询IdNameScore */
|
||||
private val nameScoreMap = mutableMapOf<String, FoodModule.IdNameScore>()
|
||||
|
||||
/** 识别物品名称列表(名称 + 净材种类,用于批量查询接口) */
|
||||
private val goodsNameList = mutableListOf<GoodsNameQueryDTO>()
|
||||
|
||||
private val scrollListener = object : RecyclerView.OnScrollListener() {
|
||||
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
|
||||
updateScrollIndicator()
|
||||
}
|
||||
}
|
||||
|
||||
private val adapter = FoodAdapter(list).apply {
|
||||
setOnItemClickListener { _, _, position ->
|
||||
// 更新选中状态
|
||||
list.forEachIndexed { i, item -> item.isClicked = (i == position) }
|
||||
// rawMaterialsRemind(position)
|
||||
val item = list.getOrNull(position) ?: return@setOnItemClickListener
|
||||
list.forEachIndexed { i, it -> it.isClicked = (i == position) }
|
||||
// 点击选择时记录当前秤重量
|
||||
item.useWeight = currentWeight
|
||||
notifyDataSetChanged()
|
||||
// 同步更新选中食材名称
|
||||
binding.tvSelectedFood.text = list[position].goodsName ?: "-"
|
||||
selectedPosition = position
|
||||
binding.tvSelectedFood.text = item.goodsName ?: "-"
|
||||
}
|
||||
}
|
||||
|
||||
private fun rawMaterialsRemind(position: Int) {
|
||||
val item = list.getOrNull(position) ?: return
|
||||
// 弹出净材种类单选弹窗,确认后再选中该食材
|
||||
showRawMaterialsDialog(
|
||||
context = this@FoodRecognizeActivity,
|
||||
types = item.rawMaterialsTypes,
|
||||
checkedType = item.rawMaterialsType
|
||||
) { selectedType ->
|
||||
item.rawMaterialsType = selectedType
|
||||
list.forEachIndexed { i, it -> it.isClicked = (i == position) }
|
||||
// 点击选择时记录当前秤重量
|
||||
item.useWeight = currentWeight
|
||||
adapter.notifyDataSetChanged()
|
||||
selectedPosition = position
|
||||
binding.tvSelectedFood.text = item.goodsName ?: "-"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,122 +167,354 @@ class FoodRecognizeActivity : BaseActivity() {
|
||||
super.onCreate(savedInstanceState)
|
||||
binding = ActivityFoodRecognizeBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
registerWeightListener()
|
||||
setHeaderBackground()
|
||||
|
||||
// 显示标题栏
|
||||
setTitleBar(titleBarAction = { it.visible() }, titleAction = { it.text = "食材识别" })
|
||||
|
||||
initData()
|
||||
setTitleBar(
|
||||
titleBarAction = { it.visible() },
|
||||
titleAction = { it.text = "食材识别" },
|
||||
backAction = {
|
||||
it.setOnClickListener {
|
||||
manualBack()
|
||||
}
|
||||
}
|
||||
)
|
||||
initRecyclerView()
|
||||
updateRvParentLayoutHeight()
|
||||
initClickListeners()
|
||||
registerWeightListener()
|
||||
|
||||
onBackPressedDispatcher.addCallback(this) {
|
||||
manualBack()
|
||||
}
|
||||
initObserver()
|
||||
initData()
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动返回
|
||||
*/
|
||||
private fun manualBack() {
|
||||
finishWithResult(true)
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Intent 读取数据并初始化页面
|
||||
* Reads data from Intent and initializes the page
|
||||
*/
|
||||
private fun initData() {
|
||||
// 加载食材照片
|
||||
// Load food photo
|
||||
val imageUri = intent.getStringExtra(EXTRA_IMAGE_URI)
|
||||
if (!imageUri.isNullOrBlank()) {
|
||||
binding.ivFoodPhoto.setImageURI(Uri.parse(imageUri))
|
||||
binding.ivFoodPhoto.setImageURI(imageUri.toUri())
|
||||
}
|
||||
currentWeight = intent.getDoubleExtra(EXTRA_CURRENT_WEIGHT, 0.0)
|
||||
initialWeight = intent.getDoubleExtra(EXTRA_INITIAL_WEIGHT, 0.0)
|
||||
binding.tvWeight.text = "${currentWeight}g"
|
||||
recognizeNameList?.apply {
|
||||
forEach {
|
||||
val goodsName = it.name.split("WP").first()
|
||||
val rawMaterialsType = it.rawMaterialsType
|
||||
goodsNameList.add(GoodsNameQueryDTO(goodsName, rawMaterialsType))
|
||||
nameScoreMap.put(goodsName, it)
|
||||
}
|
||||
recognizeNameList = null
|
||||
}
|
||||
|
||||
// 取出内存缓存的食材列表,取用后立即清空
|
||||
val goodsList = pendingGoodsList?.also { pendingGoodsList = null }
|
||||
if (!goodsList.isNullOrEmpty()) {
|
||||
list.addAll(goodsList)
|
||||
// 默认选中第一项
|
||||
list[0].isClicked = true
|
||||
binding.tvSelectedFood.text = list[0].goodsName ?: "-"
|
||||
if (goodsNameList.isNotEmpty()) {
|
||||
netViewModel.queryGoodsList(goodsType = "0", goodsNames = goodsNameList)
|
||||
} else {
|
||||
loadRecognizeList(emptyList())
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildTestData(item: FoodModule.IdNameScore): GoodsItem {
|
||||
var foodName = ""
|
||||
var foodId = ""
|
||||
item.name.split("WP").let {
|
||||
foodName = it[0]
|
||||
foodId = if (it.size > 1) {
|
||||
"WP${it[1]}"
|
||||
} else {
|
||||
item.name
|
||||
}
|
||||
}
|
||||
return GoodsItem(
|
||||
goodsId = foodId,
|
||||
goodsName = foodName
|
||||
).also {
|
||||
it.foodScore = ((1 - item.score) * 10000).toInt()
|
||||
it.isOriginalData = false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private fun initObserver() {
|
||||
lifecycleScope.launch {
|
||||
netViewModel.goodsListState.collect { state ->
|
||||
when (state) {
|
||||
is UiState.Loading -> {
|
||||
showLoading()
|
||||
}
|
||||
|
||||
is UiState.Success -> {
|
||||
delayDismissLoading()
|
||||
loadRecognizeList(state.data)
|
||||
}
|
||||
|
||||
is UiState.Error -> {
|
||||
delayDismissLoading()
|
||||
toast(state.msg)
|
||||
}
|
||||
|
||||
is UiState.Idle -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadRecognizeList(goodsList: List<GoodsItem>?) {
|
||||
if (goodsList.isNullOrEmpty()) {
|
||||
binding.flListContainer.updateLayoutParams {
|
||||
height = 260.dp
|
||||
}
|
||||
binding.rvRecognizeList.gone()
|
||||
binding.tvNoData.visible()
|
||||
return
|
||||
}
|
||||
binding.rvRecognizeList.visible()
|
||||
binding.tvNoData.gone()
|
||||
list.clear()
|
||||
goodsList.forEach { goods ->
|
||||
var foodScore = -1
|
||||
nameScoreMap[goods.goodsName]?.let { food ->
|
||||
foodScore = ((1 - food.score) * 10000).toInt()
|
||||
}
|
||||
//保存原goodsId
|
||||
goods.oldGoodsId = goods.goodsId
|
||||
//PrepareFoodActivity中的goodsId就是materId
|
||||
goods.goodsId = goods.materId ?: ""
|
||||
list.add(goods.also { it.foodScore = foodScore })
|
||||
}
|
||||
adapter.notifyDataSetChanged()
|
||||
updateRvParentLayoutHeight()
|
||||
// 默认选中第一项
|
||||
selectedPosition = 0
|
||||
list[0].isClicked = true
|
||||
list[0].useWeight = currentWeight
|
||||
binding.tvSelectedFood.text = list[0].goodsName ?: "-"
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化 RecyclerView
|
||||
*/
|
||||
private fun initRecyclerView() {
|
||||
binding.recyclerView.run {
|
||||
layoutManager = GridLayoutManager(this@FoodRecognizeActivity, 2)
|
||||
adapter = this@FoodRecognizeActivity.adapter
|
||||
binding.rvRecognizeList.let {
|
||||
it.layoutManager = GridLayoutManager(this@FoodRecognizeActivity, 2)
|
||||
it.adapter = adapter
|
||||
it.isVerticalScrollBarEnabled = false
|
||||
it.removeOnScrollListener(scrollListener)
|
||||
it.addOnScrollListener(scrollListener)
|
||||
it.post { updateScrollIndicator() }
|
||||
}
|
||||
updateListVisibility()
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新RecyclerView父布局高度
|
||||
*/
|
||||
private fun updateRvParentLayoutHeight() {
|
||||
binding.flListContainer.updateLayoutParams {
|
||||
height = if (adapter.items.size > 2) 260.dp else 130.dp
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据列表是否有数据控制 RecyclerView 显隐
|
||||
*/
|
||||
private fun updateListVisibility() {
|
||||
if (list.isEmpty()) {
|
||||
binding.recyclerView.gone()
|
||||
} else {
|
||||
binding.recyclerView.visible()
|
||||
if (list.isNotEmpty()) {
|
||||
binding.rvRecognizeList.post { updateScrollIndicator() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 RecyclerView 滚动状态刷新右侧自定义指示条
|
||||
*/
|
||||
private fun updateScrollIndicator() {
|
||||
val recyclerView = binding.rvRecognizeList
|
||||
val track = binding.vScrollIndicatorTrack
|
||||
val thumb = binding.vScrollIndicatorThumb
|
||||
|
||||
if (!recyclerView.canScrollVertically(1) && !recyclerView.canScrollVertically(-1)) {
|
||||
track.gone()
|
||||
thumb.gone()
|
||||
return
|
||||
}
|
||||
|
||||
val range = recyclerView.computeVerticalScrollRange()
|
||||
val extent = recyclerView.computeVerticalScrollExtent()
|
||||
val offset = recyclerView.computeVerticalScrollOffset()
|
||||
if (range <= 0 || extent <= 0 || range <= extent) {
|
||||
track.gone()
|
||||
thumb.gone()
|
||||
return
|
||||
}
|
||||
|
||||
val trackHeight = track.height.takeIf { it > 0 } ?: recyclerView.height
|
||||
if (trackHeight <= 0) return
|
||||
|
||||
val thumbHeight = ((extent.toFloat() / range) * trackHeight)
|
||||
.toInt()
|
||||
.coerceAtLeast(scrollIndicatorMinHeightPx)
|
||||
.coerceAtMost(trackHeight)
|
||||
|
||||
val maxTop = (trackHeight - thumbHeight).coerceAtLeast(0)
|
||||
val scrollable = (range - extent).coerceAtLeast(1)
|
||||
val thumbTop = ((offset.toFloat() / scrollable) * maxTop).toInt().coerceIn(0, maxTop)
|
||||
|
||||
if (thumb.layoutParams.height != thumbHeight) {
|
||||
thumb.layoutParams = thumb.layoutParams.apply { height = thumbHeight }
|
||||
}
|
||||
thumb.translationY = thumbTop.toFloat()
|
||||
|
||||
track.visible()
|
||||
thumb.visible()
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化按钮点击事件
|
||||
*/
|
||||
private fun initClickListeners() {
|
||||
// 更换食材:打开食材搜索弹窗
|
||||
// 更换食材:打开食材搜索弹窗,已打开时跳过
|
||||
binding.btnChangeFood.clickWithDebounce {
|
||||
val currentName = if (list.isNotEmpty()) list.firstOrNull { it.isClicked }?.goodsName else null
|
||||
FoodSearchDialog(
|
||||
// val currentName = list.getOrNull(selectedPosition)?.goodsName
|
||||
if (foodSearchDialog?.isShowing == true) return@clickWithDebounce
|
||||
foodSearchDialog = FoodSearchDialog(
|
||||
activity = this,
|
||||
defGoodsName = currentName,
|
||||
onItemSelected = { item ->
|
||||
// 用搜索结果替换当前选中食材
|
||||
updateSelectedFood(item)
|
||||
}
|
||||
).show()
|
||||
// defGoodsName = currentName,
|
||||
onItemSelected = { item -> updateSelectedFood(item) }
|
||||
).also { it.show() }
|
||||
}
|
||||
|
||||
// 取消:关闭页面
|
||||
binding.btnCancel.setOnClickListener { finish() }
|
||||
binding.btnCancel.setOnClickListener { manualBack() }
|
||||
}
|
||||
|
||||
/**
|
||||
* 用新食材替换当前选中项(或追加到列表首位)
|
||||
*/
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun updateSelectedFood(item: CookFoodGoodsEntity) {
|
||||
item.isClicked = true
|
||||
val clickedIndex = list.indexOfFirst { it.isClicked && it.goodsId != item.goodsId }
|
||||
if (clickedIndex >= 0) {
|
||||
list[clickedIndex].isClicked = false
|
||||
}
|
||||
// 若列表中已存在则直接选中,否则插入到首位
|
||||
private fun updateSelectedFood(item: GoodsItem) {
|
||||
val existIndex = list.indexOfFirst { it.goodsId == item.goodsId }
|
||||
if (existIndex >= 0) {
|
||||
list.forEachIndexed { i, e -> e.isClicked = (i == existIndex) }
|
||||
selectedPosition = existIndex
|
||||
} else {
|
||||
list.add(0, item)
|
||||
list.forEachIndexed { i, e -> e.isClicked = (i == 0) }
|
||||
selectedPosition = 0
|
||||
}
|
||||
adapter.notifyDataSetChanged()
|
||||
if (list.isNotEmpty()) {
|
||||
binding.rvRecognizeList.visible()
|
||||
binding.tvNoData.gone()
|
||||
}
|
||||
updateRvParentLayoutHeight()
|
||||
binding.tvSelectedFood.text = item.goodsName ?: "-"
|
||||
updateListVisibility()
|
||||
binding.rvRecognizeList.post { updateScrollIndicator() }
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册秤1重量监听
|
||||
* 只有重量高于识别阈值时才更新选中食材的 useWeight,
|
||||
* 低于阈值说明食材已被取走,保留上次有效值等待页面关闭
|
||||
*/
|
||||
private fun registerWeightListener() {
|
||||
WeightUtil.addWeightListener(TAG) { address, _, weight ->
|
||||
if (address == AddressUtil.ONE) {
|
||||
WeightUtil.addWeightListener(TAG) { address, state, weight ->
|
||||
if (address == AddressUtil.ONE && state == WeightUtil.STATE_STABLE) {
|
||||
runOnUiThread {
|
||||
binding.tvWeight.text = "$weight g"
|
||||
// 净重 = 秤读数 - 初始读数
|
||||
val netWeight = weight - initialWeight
|
||||
currentWeight = netWeight
|
||||
binding.tvWeight.run {
|
||||
if (tag != netWeight) {
|
||||
text = "${netWeight}g"
|
||||
tag = netWeight
|
||||
}
|
||||
}
|
||||
// 入队,超过 10 条移除队头
|
||||
if (weightWindow.size >= 10) weightWindow.removeFirst()
|
||||
weightWindow.addLast(netWeight)
|
||||
// 实时更新选中食材重量
|
||||
list.getOrNull(selectedPosition)?.useWeight = netWeight
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 携带当前选中食材关闭页面
|
||||
* 从滑动窗口尾部向前查找连续稳定值:
|
||||
* 跳过尾部不稳定的过渡帧,找到第一段连续相同且大于阈值的序列
|
||||
* 连续条数 >= 3 时返回该值,否则返回 null(数据不稳定)
|
||||
*/
|
||||
private fun finishWithResult() {
|
||||
val selected = list.firstOrNull { it.isClicked }
|
||||
private fun getStableWeightFromWindow(): Double? {
|
||||
val threshold = PrepareFoodActivity.WEIGHT_RECOGNIZE_VALUE
|
||||
var i = weightWindow.indices.last
|
||||
while (i >= 0) {
|
||||
val candidate = weightWindow[i]
|
||||
// 跳过低于阈值的过渡帧
|
||||
if (candidate <= threshold) {
|
||||
i--
|
||||
continue
|
||||
}
|
||||
// 以 candidate 为基准,向前统计连续相同条数
|
||||
var count = 0
|
||||
var j = i
|
||||
while (j >= 0 && weightWindow[j] == candidate) {
|
||||
count++
|
||||
j--
|
||||
}
|
||||
if (count >= 3) return candidate
|
||||
// 不足 3 条,继续向前找
|
||||
i = j
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 携带当前选中食材关闭页面
|
||||
* @param isManualCancel true=用户手动返回;false=被动关闭(重量低于阈值)
|
||||
*/
|
||||
private fun finishWithResult(isManualCancel: Boolean) {
|
||||
val item = list.getOrNull(selectedPosition)
|
||||
if (!isManualCancel && item != null) {
|
||||
// 被动关闭:从窗口取稳定值
|
||||
val stableWeight = getStableWeightFromWindow()
|
||||
if (stableWeight == null) {
|
||||
// 数据不稳定,不关闭页面,弹窗提示(通过 isShowing 防止重复弹出)
|
||||
if (unstableDialog?.isShowing == true) return
|
||||
if (unstableDialog == null) {
|
||||
unstableDialog = CommonDialog(this)
|
||||
.setTitle("提示")
|
||||
.setContent("秤数据不稳定,请放置食材进行重新识别")
|
||||
.setSingleButton("确认") {
|
||||
finishWithResult(true)
|
||||
}
|
||||
}
|
||||
unstableDialog?.show()
|
||||
return
|
||||
}
|
||||
item.useWeight = stableWeight
|
||||
}
|
||||
|
||||
val intent = Intent().apply {
|
||||
selected?.let { putExtra(EXTRA_SELECTED_ITEM, it) }
|
||||
putExtra(IS_MANUAL_CANCEL, isManualCancel)
|
||||
if (!isManualCancel) {
|
||||
item?.let { putExtra(EXTRA_SELECTED_ITEM, it) }
|
||||
}
|
||||
}
|
||||
setResult(RESULT_OK, intent)
|
||||
finish()
|
||||
|
||||
@@ -6,49 +6,44 @@ import android.os.Bundle
|
||||
import android.view.LayoutInflater
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.FoodRecordAdapter
|
||||
import com.shuwei.dish.match.adapter.Food2Adapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.databinding.ActivityFoodSearchBinding
|
||||
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
|
||||
import com.shuwei.dish.match.entity.FoodRecord
|
||||
import com.shuwei.dish.match.model.FoodRecord
|
||||
import com.shuwei.dish.match.model.FoodSearchItem
|
||||
import com.shuwei.dish.match.net.UiState
|
||||
import com.shuwei.dish.match.utils.KeyboardUtil
|
||||
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.startActivity
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
import java.io.Serializable
|
||||
import kotlin.collections.getOrNull
|
||||
|
||||
/**
|
||||
* 菜品搜索页面(采样模式:搜索已有上架菜品作为称量模板)
|
||||
* 数据源: POST /neglect/ratio-scale/food-search
|
||||
*/
|
||||
class FoodSearchActivity : BaseActivity() {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "FoodSearchActivity"
|
||||
const val PAGE_TYPE = "pageType"
|
||||
const val FOOD_ITEM = "foodItem"
|
||||
const val FOOD_ID = "foodId"
|
||||
const val FOOD_NAME = "foodName"
|
||||
const val DINNER_TYPE = "dinnerType"
|
||||
}
|
||||
|
||||
private lateinit var binding: ActivityFoodSearchBinding
|
||||
|
||||
private var list: MutableList<FoodRecord> = mutableListOf()
|
||||
private var pageType = 0
|
||||
private var dinnerType = "1"
|
||||
private val recordAdapter by lazy {
|
||||
FoodRecordAdapter(list).apply {
|
||||
Food2Adapter(list).apply {
|
||||
isStateViewEnable = true
|
||||
setOnItemClickListener { adapter, view, position ->
|
||||
if (pageType == 1) {
|
||||
val jumpItem = list[position].also { it.dinnerType = dinnerType }
|
||||
startActivity<PrepareCookActivity> {
|
||||
putExtra(PrepareCookActivity.FOOD_ITEM, jumpItem as Serializable)
|
||||
}
|
||||
return@setOnItemClickListener
|
||||
}
|
||||
val jumpItem = list.getOrNull(position) ?: return@setOnItemClickListener
|
||||
setResult(RESULT_OK, Intent().apply {
|
||||
putExtra(FOOD_ID, list[position].foodId)
|
||||
putExtra(FOOD_NAME, list[position].foodName)
|
||||
putExtra(FOOD_ITEM, jumpItem as Serializable)
|
||||
})
|
||||
finish()
|
||||
}
|
||||
@@ -61,8 +56,6 @@ class FoodSearchActivity : BaseActivity() {
|
||||
super.onCreate(savedInstanceState)
|
||||
binding = ActivityFoodSearchBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
pageType = intent.getIntExtra(PAGE_TYPE, 0)
|
||||
dinnerType = intent.getStringExtra(DINNER_TYPE) ?: "0"
|
||||
setHeaderBackground()
|
||||
foodName = intent.getStringExtra(FOOD_NAME)
|
||||
binding.etInputDish.setText(foodName)
|
||||
@@ -70,7 +63,7 @@ class FoodSearchActivity : BaseActivity() {
|
||||
it.visible()
|
||||
}, titleAction = {
|
||||
it.text = "菜品搜索"
|
||||
}, rightIconActon = {
|
||||
}, rightIconAction = {
|
||||
it.gone()
|
||||
it.setImageResource(R.drawable.ic_setting)
|
||||
it.setOnClickListener {
|
||||
@@ -89,7 +82,7 @@ class FoodSearchActivity : BaseActivity() {
|
||||
binding.ivDishSearch.setOnClickListener { v ->
|
||||
pageNo = 1
|
||||
getInputAndSearch()
|
||||
KeyboardUtil.hideKeyboard(v.context, v)
|
||||
hideKeyboard()
|
||||
}
|
||||
binding.refreshLayout.setEnableRefresh(true)
|
||||
binding.refreshLayout.setEnableLoadMore(false)
|
||||
@@ -106,13 +99,13 @@ class FoodSearchActivity : BaseActivity() {
|
||||
queryListInfo(foodName!!)
|
||||
}
|
||||
binding.root.setOnClickListener { v ->
|
||||
KeyboardUtil.hideKeyboard(v.context, v)
|
||||
hideKeyboard()
|
||||
}
|
||||
binding.etInputDish.let { v ->
|
||||
v.addOnActionSearchListener {
|
||||
pageNo = 1
|
||||
getInputAndSearch()
|
||||
KeyboardUtil.hideKeyboard(v.context, v)
|
||||
hideKeyboard()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -128,122 +121,65 @@ class FoodSearchActivity : BaseActivity() {
|
||||
}
|
||||
|
||||
private var pageNo = 1
|
||||
private var pageSize = 10
|
||||
fun getDinnerTypeText(): String {
|
||||
return when (dinnerType) {
|
||||
"1" -> "早餐"
|
||||
"2" -> "午餐"
|
||||
"3" -> "晚餐"
|
||||
else -> "早餐"
|
||||
}
|
||||
}
|
||||
private var pageSize = 20
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun queryListInfo(input: String) {
|
||||
showLoading()
|
||||
// val map = mutableMapOf(
|
||||
// "foodName" to input.trim(),
|
||||
// "pageNo" to "$pageNo",
|
||||
// "pageSize" to "$pageSize",
|
||||
// "canteenId" to BaseApp.canteenId
|
||||
// "dinnerType" to getDinnerTypeText()
|
||||
// )
|
||||
// val sb = StringBuilder(UrlConfig.QUERY_FOOD_LIST).apply {
|
||||
// append("?")
|
||||
// map.forEach { (key, value) -> append("$key=$value&") }
|
||||
// }
|
||||
// sb.deleteCharAt(sb.length - 1)
|
||||
// HttpUtil.get(
|
||||
// url = sb.toString(),
|
||||
// doSuccess = {
|
||||
// delayDismissLoading()
|
||||
// finishRefresh()
|
||||
// binding.refreshLayout.run {
|
||||
// setEnableRefresh(true)
|
||||
// }
|
||||
// val json = it.toJsonString()
|
||||
// val recordBean: FoodRecordBean? = json.toObject<FoodRecordBean>()
|
||||
// if (recordBean == null || recordBean.records.isNullOrEmpty()) {
|
||||
//// toast("暂未搜索到相关菜品信息")
|
||||
// if (pageNo == 1) {
|
||||
// loadEmptyView()
|
||||
// }
|
||||
// return@get
|
||||
// }
|
||||
// val records = recordBean.records
|
||||
// if (pageNo == 1) {
|
||||
// list.clear()
|
||||
// }
|
||||
// list.addAll(records!!)
|
||||
// recordAdapter.notifyDataSetChanged()
|
||||
// val isLoadMoreEnable = records.size >= pageSize
|
||||
// binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
|
||||
// if (isLoadMoreEnable) {
|
||||
// pageNo++
|
||||
// }
|
||||
// },
|
||||
// doFailure = { code, msg ->
|
||||
// binding.refreshLayout.run {
|
||||
// setEnableRefresh(true)
|
||||
// }
|
||||
// toast(msg)
|
||||
// delayDismissLoading()
|
||||
// finishRefresh()
|
||||
// if (pageNo == 1) {
|
||||
// loadEmptyView()
|
||||
// }
|
||||
// }
|
||||
// )
|
||||
|
||||
val map = mutableMapOf<String, Any>(
|
||||
"foodName" to input.trim(),
|
||||
"pageNum" to pageNo,
|
||||
"pageSize" to pageSize,
|
||||
"placeId" to BaseApp.canteenId,
|
||||
"dinnerType" to getDinnerTypeText()
|
||||
)
|
||||
netViewModel.searchFoodList(
|
||||
param = map,
|
||||
onSuccess = {
|
||||
delayDismissLoading()
|
||||
finishRefresh()
|
||||
binding.refreshLayout.setEnableRefresh(true)
|
||||
if (it.isNullOrEmpty()) {
|
||||
// toast("暂未搜索到相关菜品信息")
|
||||
if (pageNo == 1) {
|
||||
loadEmptyView()
|
||||
netViewModel.foodSearch(
|
||||
keyword = input.trim(),
|
||||
pageNum = pageNo,
|
||||
pageSize = pageSize,
|
||||
onLoading = { showLoading() },
|
||||
onResult = { state ->
|
||||
when (state) {
|
||||
is UiState.Success -> handleSearchResult(state.data)
|
||||
is UiState.Error -> {
|
||||
delayDismissLoading()
|
||||
finishRefresh()
|
||||
binding.refreshLayout.setEnableRefresh(true)
|
||||
toast(state.msg)
|
||||
if (pageNo == 1) loadEmptyView()
|
||||
}
|
||||
return@searchFoodList
|
||||
else -> {}
|
||||
}
|
||||
if (pageNo == 1) {
|
||||
list.clear()
|
||||
}
|
||||
list.addAll(it)
|
||||
recordAdapter.notifyDataSetChanged()
|
||||
val isLoadMoreEnable = it.size >= pageSize
|
||||
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
|
||||
if (isLoadMoreEnable) {
|
||||
pageNo++
|
||||
}
|
||||
}, onFailure = { code, msg ->
|
||||
binding.refreshLayout.run {
|
||||
setEnableRefresh(true)
|
||||
}
|
||||
toast(msg)
|
||||
delayDismissLoading()
|
||||
finishRefresh()
|
||||
if (pageNo == 1) {
|
||||
loadEmptyView()
|
||||
}
|
||||
})
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* FoodSearchItem → FoodRecord 映射,供 Food2Adapter 展示
|
||||
* 采样模式下返回给 PrepareFoodActivity 作为称量模板
|
||||
*/
|
||||
private fun FoodSearchItem.toFoodRecord(): FoodRecord = FoodRecord(
|
||||
foodId = foodId,
|
||||
foodName = foodName,
|
||||
cookMode = 1
|
||||
)
|
||||
|
||||
/**
|
||||
* 处理搜索结果:FoodSearchItem → FoodRecord 填充列表
|
||||
*/
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
private fun handleSearchResult(items: List<FoodSearchItem>?) {
|
||||
delayDismissLoading()
|
||||
finishRefresh()
|
||||
binding.refreshLayout.setEnableRefresh(true)
|
||||
if (items.isNullOrEmpty()) {
|
||||
if (pageNo == 1) {
|
||||
loadEmptyView()
|
||||
}
|
||||
return
|
||||
}
|
||||
if (pageNo == 1) list.clear()
|
||||
list.addAll(items.map { it.toFoodRecord() })
|
||||
recordAdapter.notifyDataSetChanged()
|
||||
val isLoadMoreEnable = items.size >= pageSize
|
||||
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
|
||||
if (isLoadMoreEnable) pageNo++
|
||||
}
|
||||
|
||||
private fun finishRefresh() {
|
||||
if (pageNo == 1) {
|
||||
binding.refreshLayout.finishRefresh(1200)
|
||||
} else {
|
||||
binding.refreshLayout.finishLoadMore(1200)
|
||||
}
|
||||
binding.refreshLayout.finishRefresh(1200)
|
||||
}
|
||||
|
||||
private var emptyViewBinding: LayoutEmptyViewBinding? = null
|
||||
|
||||
@@ -3,21 +3,23 @@ package com.shuwei.dish.match.ui
|
||||
import android.annotation.SuppressLint
|
||||
import android.os.Bundle
|
||||
import androidx.activity.addCallback
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.recyclerview.widget.LinearLayoutManager
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.HomeModeAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.databinding.ActivityHomeBinding
|
||||
import com.shuwei.dish.match.db.AppRepository
|
||||
import com.shuwei.dish.match.entity.HomeModeBean
|
||||
import com.shuwei.dish.match.model.HomeModeBean
|
||||
import com.shuwei.dish.match.utils.SpTool
|
||||
import com.shuwei.dish.match.utils.ext.startActivity
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import com.shuwei.dish.match.viewmodel.AppViewModel
|
||||
import com.shuwei.dish.match.viewmodel.factory.AppFactory
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlin.collections.getOrNull
|
||||
|
||||
/**
|
||||
* 主页,包括三种模式:制作模式、采样模式、品控模式
|
||||
*/
|
||||
class HomeActivity : BaseActivity() {
|
||||
|
||||
companion object {
|
||||
@@ -32,7 +34,6 @@ class HomeActivity : BaseActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
statusBarDarkFont(enable = true)
|
||||
initViewModel()
|
||||
// // 获取 ANDROID_ID
|
||||
// val deviceId =
|
||||
// Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
|
||||
@@ -42,12 +43,14 @@ class HomeActivity : BaseActivity() {
|
||||
binding = ActivityHomeBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
setHeaderBackground(isHomePage = true)
|
||||
// 根据当前 canteenId 恢复 RadioButton 选中状态
|
||||
binding.radioGroup.check(
|
||||
if (BaseApp.canteenId == "1678234139391512577") R.id.radioSw else R.id.radioZk
|
||||
)
|
||||
binding.radioGroup.setOnCheckedChangeListener { group, checkedId ->
|
||||
if (checkedId == R.id.radioSw) {
|
||||
BaseApp.canteenId = "1678234139391512577"
|
||||
} else {
|
||||
BaseApp.canteenId = "0"
|
||||
}
|
||||
val id = if (checkedId == R.id.radioSw) "1678234139391512577" else "0"
|
||||
SpTool.canteenId = id
|
||||
BaseApp.canteenId = id
|
||||
}
|
||||
onBackPressedDispatcher.addCallback(this) {}
|
||||
// binding.radioGroup.check(R.id.radioZk)
|
||||
@@ -63,18 +66,18 @@ class HomeActivity : BaseActivity() {
|
||||
// startActivity<SamplingListActivity>()
|
||||
// }
|
||||
|
||||
// appViewModel.deleteSeasoningBySort(12)
|
||||
// appViewModel.deleteSeasoningBySort(11)
|
||||
// appViewModel.deleteSeasoningBySort(13)
|
||||
// appViewModel.deleteSeasoningBySort(14)
|
||||
// appViewModel.deleteCookFoodAndGoods(0,"") {}
|
||||
// appViewModel.getCookFoodGoodsList("") {goodsList->
|
||||
// dbViewModel.deleteSeasoningBySort(12)
|
||||
// dbViewModel.deleteSeasoningBySort(11)
|
||||
// dbViewModel.deleteSeasoningBySort(13)
|
||||
// dbViewModel.deleteSeasoningBySort(14)
|
||||
// dbViewModel.deleteCookFoodAndGoods(0,"") {}
|
||||
// dbViewModel.getCookFoodGoodsList("") {goodsList->
|
||||
// goodsList.forEach {
|
||||
// it.foodId = "1594990392084779010"
|
||||
// appViewModel.updateGoods(it)
|
||||
// dbViewModel.updateGoods(it)
|
||||
// }
|
||||
// }
|
||||
// appViewModel.clearAllSeasoning(){}
|
||||
// dbViewModel.clearAllSeasoning(){}
|
||||
|
||||
|
||||
// binding.btnDeviceConfig.setOnClickListener {
|
||||
@@ -95,7 +98,7 @@ class HomeActivity : BaseActivity() {
|
||||
private val modeAdapter by lazy {
|
||||
HomeModeAdapter(modeList).apply {
|
||||
addOnItemChildClickListener(R.id.layoutCard) { adapter, view, position ->
|
||||
modeList[position].onClick?.invoke()
|
||||
modeList.getOrNull(position)?.onClick?.invoke()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -107,8 +110,8 @@ class HomeActivity : BaseActivity() {
|
||||
modeDesc = "菜品快速制作,记录熟重",
|
||||
modeIconId = R.drawable.ic_mode_cook,
|
||||
onClick = {
|
||||
SpTool.put(SpTool.LAUNCH_PAGE_TYPE, 0)
|
||||
startActivity<SelectDishActivity>()
|
||||
SpTool.cookMode = 0
|
||||
startActivity<CookingModeActivity>()
|
||||
finish()
|
||||
})
|
||||
)
|
||||
@@ -118,7 +121,7 @@ class HomeActivity : BaseActivity() {
|
||||
modeDesc = "菜品快速制作,记录熟重",
|
||||
modeIconId = R.drawable.ic_mode_sampling,
|
||||
onClick = {
|
||||
SpTool.put(SpTool.LAUNCH_PAGE_TYPE, 1)
|
||||
SpTool.cookMode = 1
|
||||
goSampling()
|
||||
})
|
||||
)
|
||||
@@ -134,35 +137,29 @@ class HomeActivity : BaseActivity() {
|
||||
)
|
||||
}
|
||||
|
||||
private lateinit var appViewModel: AppViewModel
|
||||
|
||||
private fun initViewModel() {
|
||||
val db = BaseApp.instance!!.database
|
||||
val factory = AppFactory(AppRepository(db.appDao()))
|
||||
appViewModel = ViewModelProvider(this, factory)[AppViewModel::class.java]
|
||||
}
|
||||
|
||||
private fun goSampling() {
|
||||
appViewModel.loadSeasoning {
|
||||
if (it.isEmpty()) {
|
||||
//无调料信息打开采样历史列表页面,点击设置配置调料信息
|
||||
startActivity<SamplingListActivity>()
|
||||
lifecycleScope.launch {
|
||||
val slots = dbViewModel.loadSeasoningSlot()
|
||||
if (slots.isEmpty()) {
|
||||
// 无调料信息,打开采样历史列表页面,点击设置配置调料信息
|
||||
startActivity<SamplingModeActivity>()
|
||||
finish()
|
||||
return@loadSeasoning
|
||||
return@launch
|
||||
}
|
||||
appViewModel.countCookFood(cookMode = 1) { count ->
|
||||
if (count > 0) {
|
||||
//有烹饪中数据打开采样历史列表页面
|
||||
startActivity<SamplingListActivity>()
|
||||
finish()
|
||||
return@countCookFood
|
||||
}
|
||||
//无烹饪数据打开新增采样页面
|
||||
startActivity<DishSamplingActivity> {
|
||||
putExtra(DishSamplingActivity.PAGE_FROM, DishSamplingActivity.HOME)
|
||||
}
|
||||
val count = dbViewModel.countCookFood(cookMode = 1)
|
||||
if (count > 0) {
|
||||
// 有烹饪中数据,打开采样历史列表页面
|
||||
startActivity<SamplingModeActivity>()
|
||||
finish()
|
||||
return@launch
|
||||
}
|
||||
// 无烹饪数据,打开新增采样页面
|
||||
startActivity<PrepareFoodActivity> {
|
||||
putExtra(PrepareFoodActivity.PAGE_FROM, PrepareFoodActivity.HOME)
|
||||
}
|
||||
finish()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,33 +2,27 @@ package com.shuwei.dish.match.ui
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.graphics.Color
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.view.KeyEvent
|
||||
import android.view.animation.RotateAnimation
|
||||
import androidx.activity.addCallback
|
||||
import androidx.core.graphics.toColorInt
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
import com.shuwei.dish.match.base.DeviceRole
|
||||
import com.shuwei.dish.match.base.GlobalData
|
||||
import com.shuwei.dish.match.databinding.ActivityInitBinding
|
||||
import com.shuwei.dish.match.db.AppRepository
|
||||
import com.shuwei.dish.match.objbox.FoodModule
|
||||
import com.shuwei.dish.match.scale.ScaleServiceManager
|
||||
import com.shuwei.dish.match.utils.AddressUtil
|
||||
import com.shuwei.dish.match.utils.AppUtil
|
||||
import com.shuwei.dish.match.utils.NetworkUtils
|
||||
import com.shuwei.dish.match.utils.NetworkUtil
|
||||
import com.shuwei.dish.match.utils.SpTool
|
||||
import com.shuwei.dish.match.utils.Weigher2
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
import com.shuwei.dish.match.utils.ext.gone
|
||||
import com.shuwei.dish.match.utils.ext.startActivity
|
||||
import com.shuwei.dish.match.utils.ext.visible
|
||||
import com.shuwei.dish.match.viewmodel.AppViewModel
|
||||
import com.shuwei.dish.match.viewmodel.factory.AppFactory
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@@ -38,9 +32,37 @@ class InitActivity : BaseActivity() {
|
||||
}
|
||||
|
||||
private lateinit var binding: ActivityInitBinding
|
||||
private lateinit var appViewModel: AppViewModel
|
||||
private var hasNavigated = false // 防止 onResume 多次触发重复路由
|
||||
private var startTime = 0L // 倒计时开始时间
|
||||
private var lastNetworkCheckTime = 0L // 上次检测网络的时间
|
||||
private val countdownHandler = Handler(Looper.getMainLooper())
|
||||
private val countdownTask = object : Runnable {
|
||||
override fun run() {
|
||||
val elapsedTime = SystemClock.elapsedRealtime() - startTime
|
||||
val remainingTime = 60 - (elapsedTime / 1000).toInt()
|
||||
val currentNetworkCheckTime = (elapsedTime / 1000).toInt()
|
||||
|
||||
// 每 10 秒检测一次网络
|
||||
if (currentNetworkCheckTime > 0 && currentNetworkCheckTime % 10 == 0 && currentNetworkCheckTime != lastNetworkCheckTime.toInt()) {
|
||||
lastNetworkCheckTime = currentNetworkCheckTime.toLong()
|
||||
checkNetworkConnection()
|
||||
}
|
||||
|
||||
// 倒计时未结束,继续更新 UI
|
||||
if (remainingTime > 0) {
|
||||
binding.tvCountdown.text = "${remainingTime}秒"
|
||||
countdownHandler.postDelayed(this, 100)
|
||||
} else {
|
||||
// 倒计时结束,最后检测一次网络
|
||||
if (NetworkUtil.isNetworkConnected(this@InitActivity)) {
|
||||
startNextPage()
|
||||
} else {
|
||||
// 网络未连接,显示"连接网络"按钮
|
||||
showNetworkButton()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("HardwareIds")
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
@@ -57,36 +79,29 @@ class InitActivity : BaseActivity() {
|
||||
setHeaderBgVisible(false)
|
||||
BaseApp.appVersion = AppUtil.getAppVersionCode(this).toString()
|
||||
|
||||
BaseApp.canteenId = "0"
|
||||
|
||||
initViewModel()
|
||||
|
||||
WeightUtil.init()
|
||||
WeightUtil.getWeight()
|
||||
WeightUtil.startContinuousRead()
|
||||
BaseApp.canteenId = SpTool.canteenId
|
||||
|
||||
initViews()
|
||||
}
|
||||
|
||||
private fun initViewModel() {
|
||||
val db = BaseApp.instance!!.database
|
||||
val factory = AppFactory(AppRepository(db.appDao()))
|
||||
appViewModel = ViewModelProvider(this, factory)[AppViewModel::class.java]
|
||||
}
|
||||
|
||||
private fun startNextPage(withDelay: Boolean = false) {
|
||||
if (hasNavigated) return
|
||||
hasNavigated = true
|
||||
lifecycleScope.launch {
|
||||
if (withDelay) delay(2000)
|
||||
// 子设备:直接进入小屏专属页面,不走原有大屏业务流程
|
||||
if (GlobalData.deviceRole == DeviceRole.SLAVE) {
|
||||
startActivity<SlaveActivity>()
|
||||
// 延迟到下一帧 finish,避免与 LaunchActivityItem 事务竞态导致
|
||||
// "Activity client record must not be null" 偶发崩溃
|
||||
window.decorView.post { finish() }
|
||||
return@launch
|
||||
}
|
||||
// 主设备:走原有路由逻辑
|
||||
val launchPageType = SpTool.getInt(SpTool.LAUNCH_PAGE_TYPE, -1)
|
||||
when (launchPageType) {
|
||||
when (SpTool.cookMode) {
|
||||
0 -> {
|
||||
startActivity<SelectDishActivity>()
|
||||
startActivity<CookingModeActivity>()
|
||||
}
|
||||
|
||||
1 -> {
|
||||
@@ -97,33 +112,38 @@ class InitActivity : BaseActivity() {
|
||||
startActivity<HomeActivity>()
|
||||
}
|
||||
}
|
||||
// 延迟到下一帧 finish,避免与 LaunchActivityItem 事务竞态导致
|
||||
// "Activity client record must not be null" 偶发崩溃
|
||||
window.decorView.post { finish() }
|
||||
}
|
||||
}
|
||||
|
||||
private fun goSampling() {
|
||||
appViewModel.loadSeasoning {
|
||||
if (it.isEmpty()) {
|
||||
//无调料信息打开采样历史列表页面,点击设置配置调料信息
|
||||
startActivity<SamplingListActivity>()
|
||||
return@loadSeasoning
|
||||
}
|
||||
appViewModel.countCookFood(cookMode = 1) { count ->
|
||||
if (count > 0) {
|
||||
//有烹饪中数据打开采样历史列表页面
|
||||
startActivity<SamplingListActivity>()
|
||||
return@countCookFood
|
||||
}
|
||||
//无烹饪数据打开新增采样页面
|
||||
startActivity<DishSamplingActivity> {
|
||||
putExtra(DishSamplingActivity.PAGE_FROM, DishSamplingActivity.HOME)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 采样模式启动路由:根据本地调料配置和烹饪中数据决定跳转目标
|
||||
* 改为 suspend 后由外层协程串行等待,保证 startActivity 早于 finish() 执行,
|
||||
* 避免内部再嵌一层 lifecycleScope.launch 导致 finish 抢跑、跳转失败
|
||||
*/
|
||||
private suspend fun goSampling() {
|
||||
val slots = dbViewModel.loadSeasoningSlot()
|
||||
if (slots.isEmpty()) {
|
||||
// 无调料信息,打开采样历史列表页面,点击设置配置调料信息
|
||||
startActivity<SamplingModeActivity>()
|
||||
return
|
||||
}
|
||||
val count = dbViewModel.countCookFood(cookMode = 1)
|
||||
if (count > 0) {
|
||||
// 有烹饪中数据,打开采样历史列表页面
|
||||
startActivity<SamplingModeActivity>()
|
||||
return
|
||||
}
|
||||
// 无烹饪数据,打开新增采样页面
|
||||
startActivity<PrepareFoodActivity> {
|
||||
putExtra(PrepareFoodActivity.PAGE_FROM, PrepareFoodActivity.HOME)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
WeightUtil.stopContinuousRead()
|
||||
ScaleServiceManager.stop()
|
||||
countdownHandler.removeCallbacksAndMessages(null)
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
@@ -156,7 +176,7 @@ class InitActivity : BaseActivity() {
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (NetworkUtils.isNetworkConnected(this)) {
|
||||
if (NetworkUtil.isNetworkConnected(this)) {
|
||||
// 有网络时隐藏网络检测区域,直接跳转
|
||||
binding.llNetwork.gone()
|
||||
startNextPage(withDelay = false)
|
||||
@@ -169,7 +189,7 @@ class InitActivity : BaseActivity() {
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
// 页面不可见时停止倒计时
|
||||
handler.removeCallbacksAndMessages(null)
|
||||
countdownHandler.removeCallbacks(countdownTask)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -192,40 +212,17 @@ class InitActivity : BaseActivity() {
|
||||
* 使用 SystemClock.elapsedRealtime() 确保精确计时
|
||||
*/
|
||||
private fun scheduleCountdown() {
|
||||
handler.postDelayed({
|
||||
val elapsedTime = SystemClock.elapsedRealtime() - startTime
|
||||
val remainingTime = 60 - (elapsedTime / 1000).toInt()
|
||||
val currentNetworkCheckTime = (elapsedTime / 1000).toInt()
|
||||
|
||||
// 每 10 秒检测一次网络
|
||||
if (currentNetworkCheckTime > 0 && currentNetworkCheckTime % 10 == 0 && currentNetworkCheckTime != lastNetworkCheckTime.toInt()) {
|
||||
lastNetworkCheckTime = currentNetworkCheckTime.toLong()
|
||||
checkNetworkConnection()
|
||||
}
|
||||
|
||||
// 倒计时未结束,继续更新 UI
|
||||
if (remainingTime > 0) {
|
||||
binding.tvCountdown.text = "${remainingTime}秒"
|
||||
scheduleCountdown()
|
||||
} else {
|
||||
// 倒计时结束,最后检测一次网络
|
||||
if (NetworkUtils.isNetworkConnected(this)) {
|
||||
startNextPage()
|
||||
} else {
|
||||
// 网络未连接,显示"连接网络"按钮
|
||||
showNetworkButton()
|
||||
}
|
||||
}
|
||||
}, 100) // 每 100ms 检查一次,确保精确性
|
||||
countdownHandler.removeCallbacks(countdownTask)
|
||||
countdownHandler.postDelayed(countdownTask, 100)
|
||||
}
|
||||
|
||||
/**
|
||||
* 检测网络连接
|
||||
*/
|
||||
private fun checkNetworkConnection() {
|
||||
if (NetworkUtils.isNetworkConnected(this)) {
|
||||
if (NetworkUtil.isNetworkConnected(this)) {
|
||||
// 网络连接成功,停止倒计时并跳转到 HomeActivity
|
||||
handler.removeCallbacksAndMessages(null)
|
||||
countdownHandler.removeCallbacks(countdownTask)
|
||||
startNextPage()
|
||||
}
|
||||
}
|
||||
@@ -254,4 +251,8 @@ class InitActivity : BaseActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
hasNavigated = false
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,9 @@ package com.shuwei.dish.match.ui
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.os.Bundle
|
||||
import android.view.Gravity
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import androidx.core.view.updateLayoutParams
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.recyclerview.widget.GridLayoutManager
|
||||
import androidx.recyclerview.widget.RecyclerView
|
||||
@@ -18,29 +16,33 @@ import com.google.android.flexbox.FlexDirection
|
||||
import com.google.android.flexbox.FlexWrap
|
||||
import com.google.android.flexbox.FlexboxLayoutManager
|
||||
import com.shuwei.dish.match.R
|
||||
import com.shuwei.dish.match.adapter.Scale18GridAdapter
|
||||
import com.shuwei.dish.match.adapter.Scale22GridAdapter
|
||||
import com.shuwei.dish.match.adapter.Seasoning18GridAdapter
|
||||
import com.shuwei.dish.match.adapter.Seasoning22GridAdapter
|
||||
import com.shuwei.dish.match.base.BaseActivity
|
||||
import com.shuwei.dish.match.base.GlobalData
|
||||
import com.shuwei.dish.match.dialog.CommonDialog
|
||||
import com.shuwei.dish.match.databinding.ActivityMasterScaleBinding
|
||||
import com.shuwei.dish.match.databinding.ListTypeScale1Binding
|
||||
import com.shuwei.dish.match.databinding.ListTypeScale18Binding
|
||||
import com.shuwei.dish.match.databinding.ListTypeScale2Binding
|
||||
import com.shuwei.dish.match.databinding.ListTypeScale22Binding
|
||||
import com.shuwei.dish.match.base.BaseApp
|
||||
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.scale.ScaleServiceManager
|
||||
import com.shuwei.dish.match.utils.NetworkUtil
|
||||
import com.shuwei.dish.match.utils.SizeTool
|
||||
import com.shuwei.dish.match.utils.WeightUtil
|
||||
import com.shuwei.dish.match.utils.ext.dp
|
||||
import com.shuwei.dish.match.utils.ext.toast
|
||||
import kotlinx.coroutines.flow.collectLatest
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
private const val VIEW_TYPE_SCALE2 = 0
|
||||
private const val VIEW_TYPE_SCALE2 = 0
|
||||
private const val VIEW_TYPE_SCALE22 = 1
|
||||
private const val VIEW_TYPE_SCALE18 = 2
|
||||
private const val VIEW_TYPE_SCALE1 = 3
|
||||
private const val VIEW_TYPE_SCALE1 = 3
|
||||
|
||||
/**
|
||||
* 主设备秤数据总览页面
|
||||
@@ -49,6 +51,7 @@ private const val VIEW_TYPE_SCALE1 = 3
|
||||
class MasterScaleActivity : BaseActivity() {
|
||||
|
||||
private lateinit var binding: ActivityMasterScaleBinding
|
||||
private val size by lazy { SizeTool.getFlexLayoutSize(10.dp) }
|
||||
|
||||
private data class DeviceGroup(
|
||||
val deviceId: String,
|
||||
@@ -59,6 +62,9 @@ class MasterScaleActivity : BaseActivity() {
|
||||
private val groupList = mutableListOf<DeviceGroup>()
|
||||
private val adapter = DeviceGroupAdapter(groupList)
|
||||
|
||||
/** key = "$deviceId#$address",value = 调料名称,用于注入 ScaleData.name */
|
||||
private val slotNameMap = mutableMapOf<String, String>()
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
binding = ActivityMasterScaleBinding.inflate(layoutInflater)
|
||||
@@ -70,37 +76,60 @@ class MasterScaleActivity : BaseActivity() {
|
||||
binding.rvScaleList.itemAnimator = null
|
||||
binding.rvScaleList.adapter = adapter
|
||||
|
||||
observeScaleData()
|
||||
loadSlotNames()
|
||||
}
|
||||
|
||||
/** 从 Room 加载槽位配置到 slotNameMap,加载完成后启动数据观测 */
|
||||
private fun loadSlotNames() {
|
||||
lifecycleScope.launch {
|
||||
val slots = dbViewModel.loadSeasoningSlot()
|
||||
slots.forEach { slot ->
|
||||
slotNameMap["${slot.deviceId}#${slot.address}"] = slot.goodsName
|
||||
}
|
||||
observeScaleData()
|
||||
}
|
||||
}
|
||||
|
||||
/** 用 slotNameMap 为 ScaleData 注入名称 */
|
||||
private fun ScaleData.withSlotName(): ScaleData {
|
||||
val name = slotNameMap["$deviceId#$address"]
|
||||
return if (name != null) copy(name = name) else this
|
||||
}
|
||||
|
||||
private fun observeScaleData() {
|
||||
val flow = ScaleServiceManager.allScales ?: return
|
||||
lifecycleScope.launch {
|
||||
flow.collectLatest { scaleMap ->
|
||||
val localId = com.shuwei.dish.match.base.GlobalData.deviceId
|
||||
val localId = GlobalData.deviceId
|
||||
val localIp = NetworkUtil.getLocalIpAddress(this@MasterScaleActivity)
|
||||
val groups = scaleMap.values
|
||||
.groupBy { it.deviceId }
|
||||
.entries
|
||||
.sortedWith(compareBy { entry ->
|
||||
ScaleDeviceConfig.DEVICE_ORDER.indexOf(entry.key).let { if (it == -1) Int.MAX_VALUE else it }
|
||||
ScaleDeviceConfig.DEVICE_ORDER.indexOf(entry.key)
|
||||
.let { if (it == -1) Int.MAX_VALUE else it }
|
||||
})
|
||||
.map { (deviceId, scales) ->
|
||||
DeviceGroup(
|
||||
deviceId = deviceId,
|
||||
ip = if (deviceId == localId) localIp
|
||||
else scales.firstOrNull { it.ip.isNotEmpty() }?.ip ?: "",
|
||||
scales = scales.sortedBy { it.address }
|
||||
else scales.firstOrNull { it.ip.isNotEmpty() }?.ip ?: "",
|
||||
scales = scales.map { it.withSlotName() }.sortedBy { it.address }
|
||||
)
|
||||
}
|
||||
|
||||
val structureChanged = groups.size != groupList.size ||
|
||||
groups.indices.any { groups[it].deviceId != groupList[it].deviceId }
|
||||
groups.indices.any { groups[it].deviceId != groupList[it].deviceId }
|
||||
|
||||
if (structureChanged) {
|
||||
updateList(groups)
|
||||
} else {
|
||||
groups.forEach { group -> adapter.updateScalesForDevice(group.deviceId, group.scales) }
|
||||
groups.forEach { group ->
|
||||
adapter.updateScalesForDevice(
|
||||
group.deviceId,
|
||||
group.scales
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
updateStatusBar(scaleMap)
|
||||
@@ -142,8 +171,8 @@ class MasterScaleActivity : BaseActivity() {
|
||||
private inner class DeviceGroupAdapter(data: MutableList<DeviceGroup>) :
|
||||
BaseMultiItemAdapter<DeviceGroup>(data) {
|
||||
|
||||
private val scale1VHMap = mutableMapOf<String, Scale1VH>()
|
||||
private val scale2VHMap = mutableMapOf<String, Scale2VH>()
|
||||
private val scale1VHMap = mutableMapOf<String, Scale1VH>()
|
||||
private val scale2VHMap = mutableMapOf<String, Scale2VH>()
|
||||
private val scale22VHMap = mutableMapOf<String, Scale22VH>()
|
||||
private val scale18VHMap = mutableMapOf<String, Scale18VH>()
|
||||
|
||||
@@ -155,101 +184,171 @@ class MasterScaleActivity : BaseActivity() {
|
||||
}
|
||||
|
||||
init {
|
||||
addItemType(VIEW_TYPE_SCALE2, object : BaseMultiItemAdapter.OnMultiItemAdapterListener<DeviceGroup, QuickViewHolder> {
|
||||
override fun onCreate(context: Context, parent: ViewGroup, viewType: Int) =
|
||||
QuickViewHolder(ListTypeScale2Binding.inflate(LayoutInflater.from(context), parent, false).root)
|
||||
override fun onBind(holder: QuickViewHolder, position: Int, item: DeviceGroup?) {
|
||||
item ?: return
|
||||
val b = ListTypeScale2Binding.bind(holder.itemView)
|
||||
val vh = Scale2VH(b)
|
||||
scale2VHMap[item.deviceId] = vh
|
||||
vh.bind(item)
|
||||
addItemType(
|
||||
VIEW_TYPE_SCALE2,
|
||||
object :
|
||||
BaseMultiItemAdapter.OnMultiItemAdapterListener<DeviceGroup, QuickViewHolder> {
|
||||
override fun onCreate(context: Context, parent: ViewGroup, viewType: Int) =
|
||||
QuickViewHolder(
|
||||
ListTypeScale2Binding.inflate(
|
||||
LayoutInflater.from(context),
|
||||
parent,
|
||||
false
|
||||
).root
|
||||
)
|
||||
|
||||
override fun onBind(
|
||||
holder: QuickViewHolder,
|
||||
position: Int,
|
||||
item: DeviceGroup?
|
||||
) {
|
||||
item ?: return
|
||||
val b = ListTypeScale2Binding.bind(holder.itemView)
|
||||
val vh = Scale2VH(b)
|
||||
scale2VHMap[item.deviceId] = vh
|
||||
vh.bind(item)
|
||||
}
|
||||
})
|
||||
addItemType(
|
||||
VIEW_TYPE_SCALE22,
|
||||
object :
|
||||
BaseMultiItemAdapter.OnMultiItemAdapterListener<DeviceGroup, QuickViewHolder> {
|
||||
override fun onCreate(context: Context, parent: ViewGroup, viewType: Int) =
|
||||
QuickViewHolder(
|
||||
ListTypeScale22Binding.inflate(
|
||||
LayoutInflater.from(context),
|
||||
parent,
|
||||
false
|
||||
).root
|
||||
)
|
||||
|
||||
override fun onBind(
|
||||
holder: QuickViewHolder,
|
||||
position: Int,
|
||||
item: DeviceGroup?
|
||||
) {
|
||||
item ?: return
|
||||
val b = ListTypeScale22Binding.bind(holder.itemView)
|
||||
// 每次 onBind 时注册/更新 VH 缓存,后续数据更新直接走 VH,不再触发 notify
|
||||
val vh = Scale22VH(b)
|
||||
scale22VHMap[item.deviceId] = vh
|
||||
vh.bind(item)
|
||||
}
|
||||
})
|
||||
addItemType(
|
||||
VIEW_TYPE_SCALE18,
|
||||
object :
|
||||
BaseMultiItemAdapter.OnMultiItemAdapterListener<DeviceGroup, QuickViewHolder> {
|
||||
override fun onCreate(context: Context, parent: ViewGroup, viewType: Int) =
|
||||
QuickViewHolder(
|
||||
ListTypeScale18Binding.inflate(
|
||||
LayoutInflater.from(context),
|
||||
parent,
|
||||
false
|
||||
).root
|
||||
)
|
||||
|
||||
override fun onBind(
|
||||
holder: QuickViewHolder,
|
||||
position: Int,
|
||||
item: DeviceGroup?
|
||||
) {
|
||||
item ?: return
|
||||
val b = ListTypeScale18Binding.bind(holder.itemView)
|
||||
val vh = Scale18VH(b)
|
||||
scale18VHMap[item.deviceId] = vh
|
||||
vh.bind(item)
|
||||
}
|
||||
})
|
||||
addItemType(
|
||||
VIEW_TYPE_SCALE1,
|
||||
object :
|
||||
BaseMultiItemAdapter.OnMultiItemAdapterListener<DeviceGroup, QuickViewHolder> {
|
||||
override fun onCreate(context: Context, parent: ViewGroup, viewType: Int) =
|
||||
QuickViewHolder(
|
||||
ListTypeScale1Binding.inflate(
|
||||
LayoutInflater.from(context),
|
||||
parent,
|
||||
false
|
||||
).root
|
||||
)
|
||||
|
||||
override fun onBind(
|
||||
holder: QuickViewHolder,
|
||||
position: Int,
|
||||
item: DeviceGroup?
|
||||
) {
|
||||
item ?: return
|
||||
val b = ListTypeScale1Binding.bind(holder.itemView)
|
||||
val vh = Scale1VH(b)
|
||||
scale1VHMap[item.deviceId] = vh
|
||||
vh.bind(item)
|
||||
}
|
||||
})
|
||||
onItemViewType { position, list ->
|
||||
when (list.getOrNull(position)?.deviceId) {
|
||||
ScaleDeviceConfig.DEVICE_ID_2 -> VIEW_TYPE_SCALE2
|
||||
ScaleDeviceConfig.DEVICE_ID_22 -> VIEW_TYPE_SCALE22
|
||||
ScaleDeviceConfig.DEVICE_ID_18 -> VIEW_TYPE_SCALE18
|
||||
else -> VIEW_TYPE_SCALE1
|
||||
}
|
||||
})
|
||||
addItemType(VIEW_TYPE_SCALE22, object : BaseMultiItemAdapter.OnMultiItemAdapterListener<DeviceGroup, QuickViewHolder> {
|
||||
override fun onCreate(context: Context, parent: ViewGroup, viewType: Int) =
|
||||
QuickViewHolder(ListTypeScale22Binding.inflate(LayoutInflater.from(context), parent, false).root)
|
||||
override fun onBind(holder: QuickViewHolder, position: Int, item: DeviceGroup?) {
|
||||
item ?: return
|
||||
val b = ListTypeScale22Binding.bind(holder.itemView)
|
||||
// 每次 onBind 时注册/更新 VH 缓存,后续数据更新直接走 VH,不再触发 notify
|
||||
val vh = Scale22VH(b)
|
||||
scale22VHMap[item.deviceId] = vh
|
||||
vh.bind(item)
|
||||
}
|
||||
})
|
||||
addItemType(VIEW_TYPE_SCALE18, object : BaseMultiItemAdapter.OnMultiItemAdapterListener<DeviceGroup, QuickViewHolder> {
|
||||
override fun onCreate(context: Context, parent: ViewGroup, viewType: Int) =
|
||||
QuickViewHolder(ListTypeScale18Binding.inflate(LayoutInflater.from(context), parent, false).root)
|
||||
override fun onBind(holder: QuickViewHolder, position: Int, item: DeviceGroup?) {
|
||||
item ?: return
|
||||
val b = ListTypeScale18Binding.bind(holder.itemView)
|
||||
val vh = Scale18VH(b)
|
||||
scale18VHMap[item.deviceId] = vh
|
||||
vh.bind(item)
|
||||
}
|
||||
})
|
||||
addItemType(VIEW_TYPE_SCALE1, object : BaseMultiItemAdapter.OnMultiItemAdapterListener<DeviceGroup, QuickViewHolder> {
|
||||
override fun onCreate(context: Context, parent: ViewGroup, viewType: Int) =
|
||||
QuickViewHolder(ListTypeScale1Binding.inflate(LayoutInflater.from(context), parent, false).root)
|
||||
override fun onBind(holder: QuickViewHolder, position: Int, item: DeviceGroup?) {
|
||||
item ?: return
|
||||
val b = ListTypeScale1Binding.bind(holder.itemView)
|
||||
val vh = Scale1VH(b)
|
||||
scale1VHMap[item.deviceId] = vh
|
||||
vh.bind(item)
|
||||
}
|
||||
})
|
||||
onItemViewType { position, list -> when (list.getOrNull(position)?.deviceId) {
|
||||
ScaleDeviceConfig.DEVICE_ID_2 -> VIEW_TYPE_SCALE2
|
||||
ScaleDeviceConfig.DEVICE_ID_22 -> VIEW_TYPE_SCALE22
|
||||
ScaleDeviceConfig.DEVICE_ID_18 -> VIEW_TYPE_SCALE18
|
||||
else -> VIEW_TYPE_SCALE1
|
||||
}}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── ViewHolder: 2个秤 ──────────────────────────────────────────────────
|
||||
|
||||
private inner class Scale2VH(val b: ListTypeScale2Binding) : RecyclerView.ViewHolder(b.root) {
|
||||
private lateinit var cells: List<LinearLayout>
|
||||
|
||||
@SuppressLint("SetTextI18n")
|
||||
fun bind(group: DeviceGroup) {
|
||||
b.tvDeviceIp.text = "IP:${group.ip.ifEmpty { "未知" }}"
|
||||
b.tvDeviceLabel.text = "设备:${group.deviceId}"
|
||||
|
||||
if (!::cells.isInitialized) {
|
||||
val cellSize = (resources.displayMetrics.widthPixels - 4 * 4.dp - 10.dp) / 2
|
||||
cells = group.scales.take(2).map { scale ->
|
||||
makeScaleCell(scale, cellSize).also { cell ->
|
||||
cell.setOnClickListener {
|
||||
val s = cell.tag as? ScaleData ?: return@setOnClickListener
|
||||
showTareDialog(deviceId = s.deviceId, ip = s.ip, address = s.address)
|
||||
}
|
||||
}
|
||||
// 两个格子显示秤地址行,隐藏重量/状态(showAddress 通过 visibility 控制)
|
||||
listOf(b.cell1, b.cell2).forEach { cell ->
|
||||
cell.tvAddress.visibility = android.view.View.VISIBLE
|
||||
cell.tvWeight.visibility = android.view.View.VISIBLE
|
||||
cell.tvState.visibility = android.view.View.VISIBLE
|
||||
cell.root.setOnClickListener {
|
||||
val s = cell.root.tag as? ScaleData ?: return@setOnClickListener
|
||||
showTareDialog(deviceId = s.deviceId, ip = s.ip, address = s.address)
|
||||
}
|
||||
b.llScaleContainer.removeAllViews()
|
||||
cells.forEach { b.llScaleContainer.addView(it) }
|
||||
}
|
||||
updateScales(group.scales)
|
||||
}
|
||||
|
||||
fun updateScales(scales: List<ScaleData>) {
|
||||
if (!::cells.isInitialized) return
|
||||
scales.take(2).forEachIndexed { i, scale ->
|
||||
cells.getOrNull(i)?.let { cell ->
|
||||
cell.tag = scale
|
||||
updateScaleCell(cell, scale)
|
||||
}
|
||||
bindCell(b.cell1, scales.getOrNull(0))
|
||||
bindCell(b.cell2, scales.getOrNull(1))
|
||||
}
|
||||
|
||||
@SuppressLint("SetTextI18n")
|
||||
private fun bindCell(cell: ListItemScale22RowBinding, scale: ScaleData?) {
|
||||
cell.root.tag = scale
|
||||
cell.tvAddress.run {
|
||||
text = scale?.let { "秤${it.address}" } ?: ""
|
||||
textSize = 18f
|
||||
}
|
||||
cell.tvName.run {
|
||||
text = if (scale?.address == 1) "净材" else "熟食"
|
||||
textSize = 22f
|
||||
}
|
||||
cell.tvWeight.run {
|
||||
text = scale?.let { "${it.weight}g" } ?: ""
|
||||
textSize = 22f
|
||||
}
|
||||
cell.tvState.run {
|
||||
text = WeightUtil.getStateStr(scale?.state ?: -1)
|
||||
textSize = 22f
|
||||
}
|
||||
cell.root.updateLayoutParams { height = 400.dp }
|
||||
}
|
||||
}
|
||||
|
||||
// ── ViewHolder: 22个秤 ─────────────────────────────────────────────────
|
||||
|
||||
private inner class Scale22VH(val b: ListTypeScale22Binding) : RecyclerView.ViewHolder(b.root) {
|
||||
private var innerAdapter: Scale22GridAdapter? = null
|
||||
private var innerAdapter: Seasoning22GridAdapter? = null
|
||||
|
||||
@SuppressLint("SetTextI18n")
|
||||
fun bind(group: DeviceGroup) {
|
||||
@@ -257,21 +356,25 @@ class MasterScaleActivity : BaseActivity() {
|
||||
b.tvDeviceLabel.text = "设备:${group.deviceId}"
|
||||
|
||||
if (innerAdapter == null) {
|
||||
val screenWidth = resources.displayMetrics.widthPixels
|
||||
val usable = screenWidth - 8 * 4.dp - 10.dp
|
||||
val smallSize = usable / 9
|
||||
val largeSize = (usable - smallSize * 6) / 2
|
||||
val rvHeight = smallSize * 3 + 3 * 4.dp
|
||||
b.rvScales.layoutParams = b.rvScales.layoutParams.also { it.height = rvHeight }
|
||||
b.rvScales.layoutParams = b.rvScales.layoutParams.also { it.height = size.rvHeight }
|
||||
b.rvScales.layoutManager = FlexboxLayoutManager(b.root.context).apply {
|
||||
flexDirection = FlexDirection.COLUMN
|
||||
flexWrap = FlexWrap.WRAP
|
||||
alignItems = AlignItems.FLEX_START
|
||||
}
|
||||
b.rvScales.itemAnimator = null
|
||||
innerAdapter = Scale22GridAdapter(largeSize, smallSize).apply {
|
||||
onItemClick = { scale ->
|
||||
showTareDialog(deviceId = scale.deviceId, ip = scale.ip, address = scale.address)
|
||||
innerAdapter = Seasoning22GridAdapter(
|
||||
size.largeSize,
|
||||
size.smallSize,
|
||||
showNameOnly = false,
|
||||
showAddress = true
|
||||
).apply {
|
||||
onItemClick = { scale, _ ->
|
||||
showTareDialog(
|
||||
deviceId = scale.deviceId,
|
||||
ip = scale.ip,
|
||||
address = scale.address
|
||||
)
|
||||
}
|
||||
}
|
||||
b.rvScales.adapter = innerAdapter
|
||||
@@ -288,7 +391,7 @@ class MasterScaleActivity : BaseActivity() {
|
||||
// ── ViewHolder: 18个秤 ─────────────────────────────────────────────────
|
||||
|
||||
private inner class Scale18VH(val b: ListTypeScale18Binding) : RecyclerView.ViewHolder(b.root) {
|
||||
private var innerAdapter: Scale18GridAdapter? = null
|
||||
private var innerAdapter: Seasoning18GridAdapter? = null
|
||||
|
||||
@SuppressLint("SetTextI18n")
|
||||
fun bind(group: DeviceGroup) {
|
||||
@@ -303,11 +406,16 @@ class MasterScaleActivity : BaseActivity() {
|
||||
}
|
||||
b.rvScales.layoutManager = gridLayoutManager
|
||||
b.rvScales.itemAnimator = null
|
||||
innerAdapter = Scale18GridAdapter().apply {
|
||||
onItemClick = { scale ->
|
||||
showTareDialog(deviceId = scale.deviceId, ip = scale.ip, address = scale.address)
|
||||
innerAdapter =
|
||||
Seasoning18GridAdapter(showNameOnly = false, showAddress = true).apply {
|
||||
onItemClick = { scale, _ ->
|
||||
showTareDialog(
|
||||
deviceId = scale.deviceId,
|
||||
ip = scale.ip,
|
||||
address = scale.address
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
b.rvScales.adapter = innerAdapter
|
||||
}
|
||||
updateScales(group.scales)
|
||||
@@ -341,61 +449,14 @@ class MasterScaleActivity : BaseActivity() {
|
||||
val scale = scales.firstOrNull()
|
||||
b.llScaleContainer.tag = scale
|
||||
b.tvAddr.text = scale?.let { "秤 ${it.address}" } ?: ""
|
||||
b.tvName.text = scale?.name?.takeIf { it.isNotBlank() } ?: "-"
|
||||
b.tvWeight.text = scale?.let { "${it.weight} g" } ?: ""
|
||||
b.tvState.text = stateStr(scale?.state)
|
||||
b.tvState.text = scale?.let { WeightUtil.getStateStr(it.state) } ?: ""
|
||||
}
|
||||
}
|
||||
|
||||
// ── 工具方法 ───────────────────────────────────────────────────────────
|
||||
|
||||
private fun stateStr(state: Int?) = when (state) {
|
||||
WeightUtil.STATE_STABLE -> "稳定"
|
||||
WeightUtil.STATE_UNSTABLE -> "不稳定"
|
||||
WeightUtil.STATE_OVER_WEIGHT -> "超量"
|
||||
null -> ""
|
||||
else -> "$state"
|
||||
}
|
||||
|
||||
/** 创建正方形秤格子(用于 Scale2VH 初始化) */
|
||||
@SuppressLint("SetTextI18n")
|
||||
private fun makeScaleCell(scale: ScaleData, cellSize: Int): LinearLayout {
|
||||
val margin = 2.dp
|
||||
return LinearLayout(this).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
gravity = Gravity.CENTER
|
||||
layoutParams = LinearLayout.LayoutParams(0, cellSize - margin * 2, 1f)
|
||||
.also { it.setMargins(margin, margin, margin, margin) }
|
||||
setPadding(4.dp, 2.dp, 4.dp, 2.dp)
|
||||
setBackgroundResource(R.drawable.shape_scale_cell)
|
||||
val baseSize = ((cellSize - margin * 2) / resources.displayMetrics.density).toInt()
|
||||
addView(makeCellText("秤${scale.address}", (baseSize * 0.16f).coerceIn(9f, 14f).toInt()))
|
||||
addView(makeCellText("${scale.weight}g", (baseSize * 0.22f).coerceIn(12f, 20f).toInt(), bold = true))
|
||||
addView(makeCellText(stateStr(scale.state), (baseSize * 0.14f).coerceIn(8f, 12f).toInt()))
|
||||
tag = scale
|
||||
}
|
||||
}
|
||||
|
||||
/** 仅更新格子内文字,不重建 view(用于 Scale2VH 数据刷新) */
|
||||
@SuppressLint("SetTextI18n")
|
||||
private fun updateScaleCell(cell: LinearLayout, scale: ScaleData) {
|
||||
(cell.getChildAt(0) as? TextView)?.text = "秤${scale.address}"
|
||||
(cell.getChildAt(1) as? TextView)?.text = "${scale.weight}g"
|
||||
(cell.getChildAt(2) as? TextView)?.text = stateStr(scale.state)
|
||||
}
|
||||
|
||||
private fun makeCellText(text: String, spSize: Int, bold: Boolean = false): TextView =
|
||||
TextView(this).apply {
|
||||
this.text = text
|
||||
textSize = spSize.toFloat()
|
||||
if (bold) setTypeface(null, android.graphics.Typeface.BOLD)
|
||||
setTextColor(if (bold) getColor(R.color.home_title) else getColor(R.color.home_sub_title))
|
||||
layoutParams = LinearLayout.LayoutParams(
|
||||
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT
|
||||
)
|
||||
gravity = Gravity.CENTER
|
||||
includeFontPadding = false
|
||||
}
|
||||
|
||||
/**
|
||||
* 弹出清零确认对话框
|
||||
* @param deviceId 目标设备 ID
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user