Author SHA1 Message Date
lvmeng c8383af120 feat(meal): 添加餐品列表下拉刷新和上拉加载功能
- 集成 SmartRefreshLayout 实现下拉刷新和上拉加载更多
- 修改 MealListActivity 添加分页加载逻辑,每页30条数据
- 实现空视图显示功能,当无数据时展示暂无数据提示
- 优化 RecyclerView 点击事件处理,使用 startActivity 扩展函数
- 添加加载状态管理,区分首次加载和后续加载情况
- 实现加载失败时的状态回退和错误处理机制
- 统一网络请求回调处理,优化 Loading 状态显示逻辑
2026-06-05 10:13:05 +08:00
mazengfei 2f18376236 feat(task): 添加任务份数默认值设置
- 在任务详情页面为新任务设置默认份数为1
- 确保任务开始组配前包含正确的份数信息
2026-06-04 18:09:24 +08:00
mazengfei 14ccc39bfd fix(config): 更新应用配置和设备方向设置
- 在InitActivity中添加竖屏显示配置
- 注释掉BaseActivity中的动态屏幕方向逻辑
- 修改应用ID为com.shuwei.dish.match.new
- 将应用名称从菜品配比终端改为配比秤新
- 恢复称重设备端口为/dev/ttyS4
2026-06-04 11:22:03 +08:00
lvmeng 01ff7241cd feat(pack): 重构净菜包装页面并集成食材搜索功能
- 替换重量识别功能为食材选择搜索功能
- 新增 FoodSearchV2Activity 页面实现食材搜索选择
- 添加 InboundIngredientV2Adapter 适配器展示食材列表
- 创建 MaterialTypeTool 工具类统一处理食材类型文本
- 更新 CleanPackActivity 集成食材搜索返回逻辑
- 修改布局文件适配新的食材选择流程
- 调整环境配置中的API地址映射关系
- 优化 RecyclerView 显示和交互逻辑
- 移除原有的重量识别相关界面元素和代码
- 更新提交参数收集逻辑支持新食材数据结构
2026-06-03 16:05:19 +08:00
lvmeng ad9291243f feat(clean-pack): 添加配比秤功能和界面重构
- 新增搜索菜品名称功能和菜品搜索按钮
- 添加用量克数显示和清零重量功能
- 集成配比秤重量监听和显示功能
- 重构主页界面添加配比秤入口
- 新增组配任务按钮和相关页面跳转
- 修改餐品净菜包功能跳转至新的列表页面
- 优化净菜包装表单布局和字段配置
- 移除溯源码自动填充净菜名称功能
- 添加重量校准和去皮功能支持
- 重构提交流程增加重量验证和回调处理
2026-06-03 14:25:31 +08:00
lvmeng c81e2d14bb feat(pack): 优化净菜包页面布局和功能
- 调整 activity_pack.xml 中的边距和按钮布局
- 在 DateTimeUtil.kt 中添加日期格式常量 YYYY_MM_DD
- 优化 list_item_form_field.xml 的输入框样式和字体大小
- 将页面标题从"菜品净菜包"改为"餐品净菜包"
- 修改包装日期格式为 yyyy-MM-dd 并移除操作类型字段
- 将操作类型改为下拉选择框,支持设备自动和人工录入选项
- 将表单列表网格布局从2列改为4列显示
- 在 TaskActivity 中添加页面刷新逻辑
- 任务详情页面提交成功后返回并提示"组配成功"
2026-06-03 09:54:21 +08:00
lvmeng 0cc1d9189c feat(pack): 优化菜品净菜包装界面和功能
- 调整布局间距,移除商品名称和材料类型显示
- 修改开始组配按钮文本为完成组配并设为可见
- 更新API服务接口支持可空参数类型
- 添加餐品净菜包装数据模型字段
- 实现包装数据收集和提交功能
- 添加时间工具类导入和设备码字段
- 优化适配器中材料分类显示逻辑
2026-06-02 19:49:21 +08:00
lvmeng 32ec1d9b74 feat(pack): 添加净菜包装功能和食材追溯界面
- 在activity_pack.xml中新增rvFormList RecyclerView用于表单展示
- 在TaskDetailActivity中实现食材明细的增删改查功能
- 添加InboundIngredientSearchDialog用于食材溯源码搜索
- 更新NetViewModelV2中addComboTask方法参数类型
- 添加NutCleanInboundIngredientVO数据模型用于已入库净菜食材
- 在PackActivity中实现包装表单动态加载和设备选择功能
- 添加用量计算和重量识别相关UI组件
- 优化FormFieldAdapter适配器去除Activity上下文依赖
- 新增formatDecimal扩展函数用于格式化用量字符串
- 实现TaskDetailAdapter中食材项的选中和清除逻辑
- 添加组合约束的API接口定义和数据传输对象修改
- 重构表单字段配置为动态加载模式支持多种输入类型
- 添加删除确认对话框提升用户体验和数据安全性
- 优化布局文件结构调整控件间距和显示效果
- 添加设备选项加载回调机制确保数据实时更新
- 实现重量监听器的生命周期管理防止内存泄漏
- 更新界面跳转逻辑支持餐品选择和详情展示
- 修复多个布局和代码中的空格及格式问题
- 添加必要的依赖导入和常量定义完善功能模块
2026-06-02 18:05:47 +08:00
lvmeng 3fe66b513f feat(task): 添加组配任务功能模块
- 新增组配任务列表页面和详情页面
- 实现组配任务查询、搜索和分页功能
- 添加组配任务详情展示和状态管理
- 集成溯源码获取功能到任务详情页面
- 添加组配任务相关的API接口定义和实现
- 创建组配任务数据模型和适配器
- 在设置页面添加组配任务入口
- 重构食材物料列表项布局和显示逻辑
- 更新应用启动时的设备ID初始化逻辑
- 生成配比秤终端接口文档
2026-06-02 14:21:09 +08:00
lvmeng 9801534aad feat(ui): 新增餐品列表和菜品包装页面
- 创建了 MealListActivity 餐品列表页面,用于展示可选的餐品
- 实现了餐品列表的 RecyclerView 展示和点击跳转功能
- 添加了 PackActivity 菜品包装页面,支持食材构成管理
- 集成了相机预览功能用于食材识别
- 实现了重量识别和食材添加功能
- 添加了侧滑删除菜单和食材重量管理
- 创建了 MealListAdapter 适配器用于餐品列表展示
2026-06-02 11:14:48 +08:00
lvmeng 48d331f05d feat(ui): 添加餐品列表和套餐功能并优化食材显示
- 在 AndroidManifest.xml 中注册 MealListActivity 和 PackActivity
- 在 FoodMaterialAdapter 中添加溯源码显示功能
- 修改 GoodsItem 模型中 goodsName 和 materCode 为可变属性
- 更新 list_item_food_material 布局文件以支持溯源码显示
- 在 NutritionModels 中为 NutFoodComposition 添加 isMain 字段
- 将设置页面中的餐包功能重定向到 MealListActivity
2026-06-02 11:14:24 +08:00
lvmeng c2cf7289b7 feat(setting): 添加净菜包功能并优化设置页面
- 在BaseApp中新增ScaleDeviceConfig、AppUtil等依赖导入
- 恢复InitActivity中的原有路由逻辑,移除HomeV2Activity跳转
- 移除SettingActivity中设置项的硬编码标题,改用枚举默认值
- 新增CLEAN_PACKAGE、MEAL_PACKAGE、MEAL_PACKAGE_TEST三种设置类型
- 为净菜包功能添加对应的页面跳转逻辑
- 隐藏数据库查看、秤数据监控等调试功能项
2026-06-02 09:35:30 +08:00
lvmeng 3884738911 feat(form): 实现餐品选择后自动加载食材功能
- 添加 NutFoodOptionVO 模型导入并增加 foodOptionsData 缓存列表
- 新增 ingredientsField 表单字段用于包含食材动态加载
- 将食材名称字段类型从 DROPDOWN 改为 FIXED 类型并移除固定选项
- 实现餐品选中后根据 position 从 compositions 加载包含食材逻辑
- 在 DictType 中新增 position 属性用于索引定位
- 在 FormField 中新增 onDropdownSelected 回调函数属性
- 更新 FormFieldAdapter 中触发选中回调并在日期字段注释中调整说明
- 修改 IngredientRowAdapter 中根据字段类型区分 FIXED 和其他类型处理
- 添加 extraApiKeys 到 extraValues 映射逻辑并更新下拉选中回调
- 调整 list_item_ingredient_row.xml 中食材名称布局去除右侧边距和下拉箭头
- 注释掉 NetViewModelV2 中的 getFoodOptions 方法(暂未使用)
2026-06-01 20:05:00 +08:00
lvmeng a25ee7d987 feat(clean-pack): 实现净菜包装页面功能完善
- 集成称重功能到应用生命周期管理
- 添加全局用户名配置
- 更新测试环境基础URL地址
- 实现表单字段动态加载和回调机制
- 优化设备选项和字典项加载逻辑
- 修复餐品搜索结果显示问题
- 统一字段值映射关系配置
2026-06-01 19:17:32 +08:00
lvmeng 4a2abf6eec feat(form): 重构净菜包装表单实现动态字段和提交功能
- 移除固定 DTO 类型,改用 Map<String, Any> 接收 API 参数
- 实现动态表单字段配置,支持净菜和餐品两种包装类型
- 添加下拉选项动态加载和自动填充溯源码功能
- 实现表单验证和通用提交逻辑
- 添加回调版本的数据加载方法提高性能
- 优化字段绑定和值映射机制
2026-06-01 16:51:47 +08:00
lvmeng 5d6df58e46 feat(form): 实现餐品净菜包装表单功能
- 新增 CHILDREN 字段类型支持动态子列表
- 实现包含食材的嵌套表单结构
- 添加餐品包装相关字段配置
- 集成下拉选项和日期选择器组件
- 创建食材行适配器处理子列表渲染
- 更新表单布局和样式资源文件
2026-06-01 14:18:16 +08:00
lvmeng c4a2105737 feat(form): 新增净菜包装功能并优化表单字段类型
- 添加 CleanPackActivity 页面用于净菜包装表单
- 将 NUMBER 字段类型拆分为 INTEGER 和 DECIMAL 类型
- 更新 FormFieldAdapter 适配新的字段类型
- 在 HomeV2Activity 中添加跳转到净菜包装页面的功能
- 创建 ApiServiceV2、NetViewModelV2 和 RemoteRepositoryV2 处理新接口
- 添加营养相关模型类和分页组件
- 在 AndroidManifest.xml 中注册新 Activity
2026-06-01 11:21:04 +08:00
lvmeng d7a1b75fef feat(app): 添加 HomeV2Activity 并移除设备角色相关功能
- 在 AndroidManifest.xml 中注册新的 HomeV2Activity 页面
- 移除 BaseApp 中的设备角色判断和秤服务相关初始化代码
- 添加蓝色和橙色渐变按钮背景资源文件
- 修改 InitActivity 默认跳转至 HomeV2Activity 页面
- 移除与设备角色相关的路由逻辑代码
2026-06-01 10:42:47 +08:00
lvmeng 11963b8b12 feat(form): 添加动态表单组件和下拉选择功能
- 新增 FormField 数据模型定义五种字段类型(文本、数字、下拉、日期、固定值)
- 实现 FormFieldAdapter 适配器支持动态表单渲染和数据绑定
- 添加 DropdownPopup 弹窗组件和 DropdownAdapter 适配器
- 新增多个圆角背景资源文件(bg_gray_radius10、bg_white_radius10_stroke 等)
- 在 Common.kt 中添加 hideKeyboard 扩展函数用于隐藏软键盘
- 创建 DictType 数据模型用于字典类型数据传输
- 添加表单项和下拉项的布局文件(list_item_form_field、list_item_dropdown 等)
2026-06-01 10:19:07 +08:00
lvmeng 80d80e7e63 chore(utils): 注释掉 DecimalAdapter 类的实现代码
- 将整个 DecimalAdapter 类及其相关导入语句注释掉
- 包含 write 和 read 方法的完整实现都被注释
- 相关的包声明和使用方式注释也一并被注释掉
2026-05-25 18:01:18 +08:00
lvmengandClaude Sonnet 4.6 2d88ce1479 refactor(scale): 修复线程安全、生命周期与连接管理问题
- ScaleWebSocketServer:三个状态 Map 改为 ConcurrentHashMap,connectionCount 改为 AtomicInteger
- ScaleServiceManager:新增 serviceScope 统一管理协程生命周期,新增 @Volatile isStarted 防重复启动
- ScaleWebSocketClient:doConnect 写入新连接前先 close() 旧连接,防止 TCP 资源泄漏
- MdnsDiscoveryManager:移除 isResolving 上多余的 @Volatile 注解
- MasterScaleActivity:全限定类名改为 import + 短类名
- WeightUtil:删除 WeightListenerImpl 中注释掉的调试代码
- scale包架构分析.md:同步更新架构文档,已修复问题压缩为汇总表

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-25 17:20:15 +08:00
lvmengandClaude Sonnet 4.6 d580040c55 feat(fragment): 上传失败时透传接口错误原因至 toast 提示
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 18:17:26 +08:00
lvmengandClaude Sonnet 4.6 00bf478185 feat(fragment): 新增默认减重配置功能
- SpTool 新增 configWeight 属性,持久化存储默认减重克数
- 新增 WeightConfigFragment 及对应布局,支持数字输入和回填
- SingleFragmentActivity 注册 WEIGHT_CONFIG 页面类型
- SettingActivity 在食材采集下方新增减重配置入口
- PrepareFoodActivity 打开时从 SpTool.configWeight 初始化 initialWeight

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 16:39:38 +08:00
lvmeng ea79e584f3 refactor(utils): 简化 toast 扩展函数实现
- 移除多余的 null 检查代码块
- 删除已注释的旧版 toast 实现
- 简化条件判断语法
- 保留 ToastUtil 统一调用方式
2026-05-19 15:38:52 +08:00
lvmeng 1140d6bf91 refactor(ui): 提取 WeightUtil.getStateStr 统一秤状态文案,量程溢出时红色背景提示 2026-05-19 15:25:03 +08:00
lvmeng f3dbb3fe68 Merge remote-tracking branch 'origin/dev_260316_新设备' into dev_260316_新设备 2026-05-19 14:55:18 +08:00
mazengfei dc91cdfa2e 超量显示改为量程溢出 2026-05-19 14:42:29 +08:00
mazengfei a6ce3a1ed3 超量显示改为量程溢出 2026-05-19 14:41:51 +08:00
lvmeng 292fdade81 feat(ui): 添加用料明细预览功能和清空数据确认对话框
- 在 SubmitFoodActivity 中添加右侧图标显示并实现点击打开用料明细预览弹窗
- 新增 GoodsPreviewDialog 用于展示底部弹出的用料明细列表
- 创建 GoodsPreviewAdapter 和相关布局文件实现用料列表展示
- 添加 ic_list_view 图标用于右上角按钮
- 在 VectorCollectionFragment 中为清空数据按钮添加确认对话框
- 优化 WeightUtil 工具类添加可用性检查避免异常调用
2026-05-19 11:15:33 +08:00
lvmeng aa539d87d0 fix(base): 修复Loading弹窗管理和超时机制
- 添加了Loading超时自动关闭功能,默认15秒超时
- 实现了Activity销毁时只关闭自己的Loading,防止误关其他页面
- 优化了Loading重复显示时的节流处理,避免ANR问题
- 在BaseActivity中增加了showLoading方法的超时参数支持
- 为图片上传等长时间操作添加了60秒超时兜底机制
- 增加了相关日志便于调试Loading的显示和关闭流程
2026-05-18 18:11:26 +08:00
lvmeng e570707216 fix(seasoning): 移除调试用的空布局点击事件
- 注释掉loadMockData()方法调用
- 防止生产环境中误触加载模拟数据功能
2026-05-18 16:12:18 +08:00
lvmeng 87ca6abe1b fix(init): 解决Activity启动时序竞态问题
- 将finish()调用延迟到下一帧执行,避免与LaunchActivityItem事务竞态
- 修复"Activity client record must not be null"偶发崩溃问题
- 将goSampling方法改为suspend函数确保协程串行执行
- 保证startActivity在finish()之前完成,防止页面跳转失败
2026-05-18 16:05:26 +08:00
lvmeng 28784fa7c1 feat(db): 为数据库调试页面添加多字段动态筛选功能
- 在 CookFoodDao、CookFoodGoodsDao、SeasoningDao 和 SeasoningSlotDao 中添加 RawQuery 支持
- 为各数据访问对象添加动态条件分页查询和统计方法
- 在 DbRepository 中扩展动态查询相关方法
- 在 DbViewModel 中实现 DbInspectFilter 数据类和 buildQueries 动态 SQL 构建逻辑
- 更新 DbInspectFragment 添加筛选字段配置和 UI 生成逻辑
- 重构筛选条件收集和查询流程,支持精确匹配和模糊搜索
- 修改刷新按钮为查询按钮,更新 Tab 切换时的筛选框重建逻辑
- 调整设置页面标题从"设备设置"改为"设置"
2026-05-18 15:52:46 +08:00
lvmeng df01312577 feat(resources): 添加网格和列表布局图标资源
- 添加 ic_layout_grid.xml 矢量图标文件
- 添加 ic_layout_list.xml 矢量图标文件
- 配置图标尺寸为 24x24 dp
- 设置视口宽度和高度为 24
- 定义灰色填充颜色 #6666
- 实现网格布局图标的路径数据
- 实现列表布局图标的路径数据
2026-05-18 14:18:32 +08:00
lvmeng 7d3cb27b6e fix(ui): 修复调料列表布局切换功能
- 将布局容器从 LinearLayout 改为 FrameLayout 以支持更好的定位控制
- 调整标题文本的尺寸和对齐方式,设置固定高度 50dp
- 更新切换按钮的内边距并调整其在父容器中的位置
- 更改切换按钮的图标资源名称从 ic_switch_box 为 ic_layout_list
- 优化布局切换逻辑,图标始终显示目标布局样式
- 在切换时动态更新按钮图标以反映当前布局模式
2026-05-18 14:17:59 +08:00
lvmengandClaude Sonnet 4.6 ef6a29ffb0 fix(food): 修复并发竞态、双重刷新及搜索态丢失问题
- FoodListFragment:添加 currentJob 取消机制,防止快速切换时旧请求覆盖新数据
- FoodListFragment:缓存 currentFoodName,返回二级页面后 onResume 复用搜索词
- CookingModeActivity:RadioGroup+RadioButton 替换为 LinearLayout+CheckedTextView
- CookingModeActivity:新增 selectTab() 统一管理选中态,内置幂等保护
- CookingModeActivity:重构 onNewIntent,消除切换餐次时 getDishList 被双重调用的问题
- VectorCollectionFragment:Error/Success 消费后重置 StateFlow,防止 replay 导致 toast 重复弹出

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 12:09:21 +08:00
lvmeng d7f9fb05fb fix(food): 修复菜品列表刷新和净材对话框显示问题
- 在 Fragment 初始化时启用下拉刷新功能
- 将数据加载逻辑移至 onResume 方法中并添加异常处理
- 添加 onHiddenChanged 回调以在 Fragment 显示时重新加载数据
- 更新净材对话框为空时的提示文本和按钮样式
2026-05-18 11:49:57 +08:00
lvmeng d9cfd3007d fix(ui): 修复搜索列表状态管理和界面交互问题
- 添加了 clipToOutline 和 foreground 属性以改善列表项视觉效果
- 修复了 UiState 处理中未重置商品列表状态的问题
- 优化了 searchFood 方法中的状态重置逻辑,避免重复调用
- 修复了空视图点击监听器设置时机,确保在状态视图挂载完成后添加监听器
- 移除了重复的搜索调用,解决因 setText 触发的多次搜索问题
2026-05-18 09:43:42 +08:00
lvmeng c1f52c6337 fix(vector): 解决食材搜索列表状态管理问题
- 添加 resetGoodsListState 方法重置商品列表状态
- 添加 UiState.Error 状态处理并显示错误提示
- 搜索前重置商品列表状态避免状态残留
- 更新空数据显示文本为更明确的提示信息
- 点击空布局时触发重新搜索功能
2026-05-18 09:03:45 +08:00
lvmeng 5723209614 feat(app): 添加测试设备支持和芯片布局优化
- 在 BaseApp 中根据 BuildConfig.IS_TEST_DEVICE 配置设备 ID
- 更新 build.gradle 配置 IS_TEST_DEVICE 构建字段
- 添加 x86_64 架构支持用于 Windows 模拟器调试
- 优化 RawMaterialsDialogUtils 中的 Chip 布局和测量逻辑
- 在 WeightUtil 中添加架构检查避免非 ARM 设备崩溃
- 实现秤 SDK 可用性检测和异常处理机制
2026-05-15 17:16:00 +08:00
lvmeng d080ca0690 refactor(setting): 优化设置页面适配器点击事件处理
- 移除旧的直接点击监听器实现
- 集成防抖动点击事件处理机制
- 使用新的点击事件委托方式提升用户体验
- 改进适配器初始化逻辑结构
2026-05-15 15:21:44 +08:00
lvmengandClaude Sonnet 4.6 1024d82958 refactor(ui): 将设置页面由多个 LinearLayout 重构为 RecyclerView 实现
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 15:18:26 +08:00
lvmeng 8b19da2710 style(ui): 调整收藏食物页面界面样式
- 添加 dp 扩展函数导入用于尺寸转换
- 为删除图标设置左右 25dp 内边距以改善视觉效果
2026-05-15 14:52:28 +08:00
lvmengandClaude Sonnet 4.6 25167829cc feat(ui): 在已采集食材页添加清除全部数据功能
- ObjectBox 新增 removeAll() 方法清除所有向量数据
- DbViewModel 新增 clearAllCollectedFood() 方法并刷新列表
- CollectedFoodActivity 右上角添加垃圾桶图标,点击通过 CommonDialog 二次确认后清除

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 14:38:40 +08:00
lvmeng e38f19ac1b refactor(dialog): 移除食材搜索对话框中的测试代码
- 删除 buildMockGoodsList 扩展函数及相关导入
- 移除 FoodSearchDialog 中的假数据点击事件监听器
- 移除 VectorCollectionFragment 中的假数据填充逻辑
- 优化 RawMaterialsDialogUtils 中的 Chip 样式配置
- 清理相关文件的无用导入声明
2026-05-15 14:28:36 +08:00
lvmeng ada83b64e6 refactor(dialog): 优化 CommonDialog 代码质量
- 修复 setPositiveButton 中 lambda 隐式参数 it 被遮蔽的问题
- 提取 isMaster 为局部变量,消除重复计算
- addContentView 挂载前先 removeAllViews(),防止重复添加
2026-05-15 11:56:50 +08:00
lvmeng d3f02620af refactor(db): 将 entity 包拆分为 db/entity(数据库实体)和 model(数据模型)
- 新建 db/entity 包,迁入 4 个 Room 实体类:CookFoodEntity、CookFoodGoodsEntity、SeasoningEntity、SeasoningSlotEntity
- 新建 model 包,迁入 7 个普通数据模型:FoodRecord、GoodsItem、CookFoodDTO、CookFoodGoodsDTO、GoodsNameQueryDTO、CollectedFoodItem、DataBean
- 删除原 entity 包
- 更新全部引用文件的 import 路径(共 33 个文件)
2026-05-15 11:46:37 +08:00
lvmeng deb03a0c37 refactor(base): 重构基础组件和数据库访问层
- 修复 BaseActivity 中 rightIconActon 方法名拼写错误
- 重命名 appViewModel 为 dbViewModel 以统一数据库访问实例
- 优化 BaseApp 中的共享偏好设置获取逻辑
- 移除 GlobalData 中硬编码的应用ID和SDK密钥
- 重命名 NetworkUtils 为 NetworkUtil 并增强网络连接检测
- 重构 RemoteRepository 中的API调用方法结构
- 在多个Activity和Fragment中统一使用dbViewModel替代appViewModel
- 优化食品列表合并烹饪中条目的逻辑处理
- 调整文件上传时的媒体类型定义
- 清理注释和代码结构以提高可维护性
2026-05-15 11:24:44 +08:00
lvmeng b562694665 fix(ui): 修复子设备调料数据有时不显示的问题
将 observeScaleData 中的 collectLatest 改为 collect,
避免多个秤数据并发到来时 block 被取消导致 ts 已记录但
rawWeightMap 未更新,造成后续数据被永久跳过的竞态问题。
2026-05-15 10:14:48 +08:00
lvmeng 64586175ff fix(ui): 修复烹饪模式页面意图处理问题
- 移除了多余的空值检查操作符以简化代码
- 注释掉未使用的 isCooking 变量
- 使用 getOrNull 安全访问 fragmentList 避免越界异常
- 简化了 getIntentExtra 的调用方式
2026-05-15 09:55:51 +08:00
lvmeng e8431de53d refactor(ui): 将搜索框清空职责从getDishList移至调用方,修复下拉刷新误清输入框问题 2026-05-15 09:55:08 +08:00
lvmeng 4ccd4eaad0 fix(global): 将秤生命周期提升至进程级,修复子设备空白页和秤停止响应问题
- WeightUtil 初始化移至 BaseApp.onCreate(),通过 ActivityLifecycleCallbacks
  在最后一个 Activity 销毁时才调用 stopContinuousRead()
- InitActivity 删除 WeightUtil 的初始化/停止调用
- startNextPage() 跳转完成后执行 finish(),防止 InitActivity 残留任务栈
  导致返回时出现空白页,及被系统回收时触发 onDestroy 意外停止秤读取
2026-05-15 08:43:43 +08:00
lvmeng b44f4aae5a refactor(food): 统一商品数据模型字段映射逻辑
- 在 FoodSearchDialog 中添加 oldGoodsId 字段赋值逻辑
- 在 VectorCollectionFragment 中统一商品 ID 映射处理
- 将 goodsId 字段更新为 materId 的值或空字符串
- 保留原始 goodsId 值到 oldGoodsId 字段用于回溯
- 简化代码中的循环变量引用方式
2026-05-14 15:42:07 +08:00
lvmeng fee9598689 fix(ui): 修复初始化页面导航状态和设置页面跳转逻辑
- 在InitActivity中重写onNewIntent方法以重置导航状态
- 移除SettingActivity中的无用toast导入
- 简化SubmitFoodActivity启动语法
- 将设置页面清除数据后的跳转目标从HomeActivity改为InitActivity
2026-05-14 15:32:39 +08:00
lvmeng b24435744c feat(setting): 添加测试调料拿取功能并优化界面交互
- 在设置页面添加测试调料拿取入口并实现跳转功能
- 优化食材搜索对话框的网格布局管理器初始化逻辑
- 为未识别食材对话框添加重新识别和取消回调处理
- 优化准备食材页面标题文字显示效果
- 修复调料切换按钮点击防抖处理
2026-05-14 15:23:34 +08:00
lvmeng a257b03b9d refactor(sampling): 移除注释代码 2026-05-14 14:37:07 +08:00
lvmeng 89fff7c2b0 refactor(ui): 重构采样模式界面和数据处理逻辑
- 将 RadioButton 替换为 CheckedTextView 并调整布局结构
- 添加安全索引访问避免数组越界异常
- 优化数据库查询方法增加回调版本
- 更新崩溃处理器重启目标页面
- 添加单按钮对话框支持
- 优化采样模式页面数据加载和刷新逻辑
- 调整重量计算和数据处理流程
- 修复页面跳转和数据传递问题
2026-05-14 14:24:25 +08:00
lvmeng 6392b76ac2 fix(cooking): 解决搜索框内容清除和称重逻辑问题
- 在 CookingModeActivity 中添加 clearSearchText 方法用于清除搜索框内容
- 在 FoodListFragment 中添加协程调度器导入并实现空搜索时自动清除功能
- 在 SubmitFoodActivity 中新增初始重量和初始化状态变量
- 修改称重清零逻辑,清零后重置初始重量为 0
- 实现净重计算逻辑,使用秤读数减去初始重量得到实际净重
- 更新重量显示逻辑,使用净重数值进行单位转换和显示
2026-05-14 09:54:56 +08:00
lvmengandClaude Sonnet 4.6 8398bd4fd3 fix(global): App 启动时恢复本地保存的环境地址
- SpTool 新增 baseUrl 属性,统一管理环境地址的持久化读写
- EnvSwitchDialog 改用 SpTool.baseUrl 保存,移除直接调用 SpTool.put
- BaseApp.onCreate 启动时读取 SpTool.baseUrl 并赋值给 GlobalData.appBaseUrl

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 18:13:09 +08:00
lvmengandClaude Sonnet 4.6 535da33aab refactor(fragment): 改用回调方式查询菜品列表,修复刷新卡死问题
- FoodListFragment 改用 searchFoodListWithCallback 替代 SharedFlow collect,
  彻底解决下拉/上拉因数据相同导致不触发的问题
- NetViewModel 新增 searchFoodListWithCallback 回调版本
- CookingModeActivity loadFragment 改为 show/hide 方式,切换餐次不重建 Fragment
- 修复数据为空时未调用 finishRefresh 导致加载动画卡死的问题
- 新增 fragment-ktx 依赖,支持 by viewModels()

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 17:54:59 +08:00
lvmengandClaude Sonnet 4.6 120f5432de refactor(fragment): FoodListFragment 独立持有 NetViewModel
每个 FoodListFragment 通过 by viewModels() 持有独立的 NetViewModel 实例,
searchFoodState 各自隔离,不再共享 Activity 的 netViewModel。

- 删除 pendingDinnerType 字段及餐次过滤逻辑
- initObserver 改为收 Fragment 自身的 netViewModel.searchFoodState
- getDishList 直接调 netViewModel.searchFoodList,不再经由 Activity 中转
- CookingModeActivity 删除 getFoodList() 透传方法

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 17:24:31 +08:00
lvmengandClaude Sonnet 4.6 61d11c6a78 fix/feat: 修复数据不稳定弹窗重复弹出 & 新增切换环境功能
fix: FoodRecognizeActivity 数据不稳定时弹窗会重复弹出
- 持有 unstableDialog 引用,通过 isShowing 防止重复弹出

feat: 新增切换环境功能(测试/UAT/生产)
- GlobalData 新增 KEY_BASE_URL,修正 UAT 端口为 8083
- SettingActivity 开发模式下显示「切换环境」入口
- 新增 EnvSwitchDialog 及其布局文件

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 17:18:30 +08:00
lvmengandClaude Sonnet 4.6 301f470274 fix(fragment): 修复切换餐次时数据串台问题
三个餐次 Fragment 共享同一个 searchFoodState,导致早餐的本地数据会被错误合并到午餐/晚餐列表中。

修复方案:
- 新增 pendingDinnerType 字段记录本次请求对应的餐次
- 响应回来时比对餐次,忽略非本 Fragment 发起的请求结果
- 确保每个 Fragment 只处理自己发起的请求数据

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 17:16:34 +08:00
lvmengandClaude Sonnet 4.6 67d64848de feat(activity): 搜索菜品直接刷新列表,切换餐次自动清空搜索框
- jumpSearch 改为调用 FoodListFragment.getDishList(foodName),不再跳转 FoodSearchActivity
- 切换餐次时清空输入框,用 isClearingByTabSwitch 标志避免重复请求
- 手动清空输入框时自动触发查全部数据
- FoodListFragment.getDishList 新增 foodName 参数,支持按名称过滤

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 16:22:46 +08:00
lvmeng ce7d2da6d8 feat(activity): 优化食材识别重量逻辑,修复主辅材重复保存问题
- PrepareFoodActivity:改为以首次秤读数为基准计算净重,注释清零按钮和测试按钮,修复 foodSelectCallback 中 isClicked 赋值对象错误导致选中状态异常的 bug,修复 getGoodsList 重复调用时主辅材累加的问题,向 FoodRecognizeActivity 传递 initialWeight
- FoodRecognizeActivity:启用秤重量监听,改为净重显示;用滑动窗口(最近10帧)替换延迟更新逻辑,关闭页面时从窗口中提取连续稳定值作为 useWeight,数据不稳定时弹窗提示而非直接关闭
- DbViewModel:saveCookFoodAndGoods 首次插入后回填 entity.id,防止重复进入时主辅材重复插入
- InitActivity:注释启动时自动清零秤的逻辑
- SubmitFoodActivity:将魔法数字 0.5 提取为常量 WEIGHT_THRESHOLD
2026-05-13 16:01:28 +08:00
lvmeng 65958bf637 feat(food): 优化食材识别功能并增加调料选择支持
- 将页面大小从30调整为100以提高加载效率
- 移除食材名称显示中的原始数据判断逻辑
- 在FoodRecognizeActivity中添加goodsId映射处理
- 修改GoodsItem实体类将goodsId和materId设为可变属性
- 新增oldGoodsId字段用于保存原始商品ID
- 创建新的调料搜索适配器和布局文件
- 更新调料选择对话框中的数据处理逻辑
2026-05-13 11:13:18 +08:00
lvmeng 7e72ce413b feat(food): 实现食材识别和净材类型功能
- 在FoodAdapter中添加选中状态背景和文字颜色变化
- 修改FoodMaterialAdapter显示食材名称时包含净材类型
- 在FoodModule中解析食材名称中的净材类型信息
- 移除食材识别页面的净材类型选择弹窗流程
- 优化食材识别结果处理逻辑和数据映射
- 添加未识别到食材时的提示对话框
- 实现向量采集页面的搜索功能和实时监听
- 优化网络请求的文件上传媒体类型设置
- 调整食材列表项的布局约束和样式配置
2026-05-12 18:15:40 +08:00
lvmengandClaude Sonnet 4.6 5745791041 feat(activity): 弹窗食材/调料查询使用独立 StateFlow,新增调料列表双布局切换功能
- NetViewModel 新增 foodSearchGoodsListState 和 queryFoodSearchGoodsList,与 goodsListState 隔离
- FoodSearchDialog、SeasoningSelectDialog 改用弹窗专用 State,避免影响 FoodRecognizeActivity 列表
- SeasoningWeightAdapter 支持 Grid(4列)/List(2列)双布局模式
- SubmitFoodActivity 添加调料列表布局切换按钮
- FoodModule 变量重命名并添加未初始化保护
- 注释掉 mock 食材数据,调整相关布局边距与文字截断

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-12 15:17:54 +08:00
lvmeng d412e03c6e perf(activity): 优化秤数据 StateFlow 重发时的无效遍历,添加 ts 去重跳过未变化帧;ScaleWebSocketServer 改为 trailing 节流并增加数据变化去重 2026-05-12 14:07:22 +08:00
lvmengandClaude Sonnet 4.6 b6389be898 feat(db): 支持早中晚三餐同一菜品独立保存及调料预填充优化
- 修复 getCookFoodById/deleteCookFood/markSubmittedAndDelete 查询条件缺少 dinnerType,
  导致同一 foodId 跨餐次保存时误判已存在、主记录和主辅材数据丢失的问题;
  查询键由三元组(canteenId+foodId+cookMode)升级为四元组(+dinnerType)
- SamplingModeActivity 构建 FoodRecord 时补充 dinnerType,确保删除操作能精确定位餐次
- SubmitFoodActivity 制作中模式下从数据库加载 goodsList 时预填充调料到 adapter,
  isCooking=false 时同样预填充前一页面带入的调料数据
- dm_cook_food 表新增 submitState 字段(DB v13),区分手动删除与接口提交删除
- 提交成功后改用 markSubmittedAndDelete 替代 deleteCookFoodAndGoods,正确置 submitState=1
- InitActivity onDestroy 不再停止秤服务,避免进程存活期间秤数据中断
- GoodsItem.isItemClicked 统一改为 isClicked,PrepareFoodActivity 食材选中逻辑同步更新
- AndroidManifest InitActivity 增加 singleTask 及 configChanges 配置

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-11 18:10:59 +08:00
lvmeng 919e43afba feat(dialog): 添加调料选择对话框的本地模拟数据功能
- 实现 loadMockData 函数用于加载本地模拟调料数据
- 在空布局上添加点击事件监听器,点击时加载模拟数据
- 将原有的 TODO 注释代码转换为正式的模拟数据加载功能
- 优化空布局的初始化逻辑并添加安全调用处理
2026-05-11 15:23:23 +08:00
lvmeng 0b9b3e8988 fix(activity): 修复调料 foodId 为空导致重新打开看不到调料数据 2026-05-11 14:39:12 +08:00
lvmeng 803ae75e40 fix(activity): 修复识图新增食材主辅材类型未显示
foodSelectCallback 新增 GoodsItem 时未将 isOriginalData 置为
false,导致 updateMaterialTypes 跳过计算,列表无法显示主辅材
2026-05-11 13:31:24 +08:00
lvmeng ec4c3f1232 refactor: 提取净材种类弹窗为工具类并统一各页面选择逻辑
- 新增 RawMaterialsDialogUtils,包含 showRawMaterialsDialog、
  buildSingleChoiceChipGroup、buildMockGoodsList 三个顶层函数
- FoodAdapter/list_item_food 新增净材种类选中结果展示
- VectorCollectionFragment、FoodRecognizeActivity、FoodSearchDialog
  的食材点击均改为弹出净材种类单选弹窗后再确认选中
- FoodSearchDialog 空布局补充点击加载测试数据
- setting_border 新增圆角
2026-05-11 12:07:06 +08:00
lvmeng 63911fe432 feat(network): queryGoodsList 入参 goodsNames 改为带净材种类的对象列表 2026-05-11 11:15:27 +08:00
lvmeng 8f15c0efb7 refactor(network): 菜品详情接口改用 DTO 与 Room 实体解耦 2026-05-11 11:10:45 +08:00
lvmeng 879af8426f feat(fragment): 食材采集页改用 ChipGroup 选择净材并新增列表空布局 2026-05-11 10:20:54 +08:00
lvmeng dc947df6e3 fix(network): 修复 uploadFoodVectorData 接口 PartMap 类型导致的 Retrofit 解析异常 2026-05-11 10:20:47 +08:00
lvmeng ef13aa8307 feat(fragment): 新增净材种类选择功能及相关数据结构支持
- 新增 rawMaterialsType 字段至 GoodsItem、CookFoodGoodsEntity、SeasoningEntity,DB 升级至 v12
- VectorCollectionFragment 重构食材搜索,点击食材弹出净材种类单选弹窗
- CommonDialog 新增 addContentView 和可拦截确认按钮(setPositiveButtonInterceptable)能力
- Food3Adapter 和 list_item_food3.xml 支持显示已选净材种类副标签
2026-05-09 18:10:07 +08:00
lvmeng a9663a21f0 style(ui): 调整食物识别页面布局间距和移除测试代码
- 调整 activity_food_recognize.xml 中多个组件的 margin 间距
- 移除 FoodRecognizeActivity.kt 中的测试数据相关注释代码
- 为 list_item_food2.xml 添加可点击背景效果
- 清理 PrepareFoodActivity.kt 中的无用导入和调整常量值
- 优化 PrepareFoodActivity.kt 中的条件判断换行格式
2026-05-09 14:45:18 +08:00
lvmeng d060305417 fix(food): 修复Food类的equals和hashCode方法
- 在equals方法中添加version字段比较
- 在hashCode方法中添加version字段哈希计算
- 确保对象比较的一致性
2026-05-09 13:53:00 +08:00
lvmeng bb319ee4ee feat(network): 新增菜品向量采集数据上传接口及调用链路
- ApiService/RemoteRepository/NetViewModel 新增 uploadFoodVectorData 三层实现,新增 uploadFoodVectorDataBatch 供分批循环调用直接 await 结果
- VectorCollectionFragment 启用 upload() 链路:调用 uploadFoodVectorDataBatch 分批上传,去掉 runBlocking/runOnUiThread,统一在协程主线程更新 UI
- ImageUploader 修正包路径并将 onProgress 改为 suspend lambda
- Food 实体新增 version 字段,同步 ObjectBox model
- SeasoningSelectDialog 切换为真实接口,FoodSearchDialog 注释模拟数据
- 调整删除按钮 drawable 为圆形并对列表 ItemView 增加 tint
2026-05-09 13:51:15 +08:00
lvmeng bb1ecbde43 feat: 新增 goodsCode 字段并同步迁移 DB v11,修复 IPv6 WebSocket 地址格式,重构 VectorCollectionFragment 相机回调为协程 2026-05-09 10:51:43 +08:00
lvmeng 7a03ab8108 refactor(activity): 统一 cook/submit 中调料数据处理逻辑,先清除 materialType==3 再从 adapter 覆盖写入 2026-05-09 10:51:04 +08:00
lvmeng 3b1dc0a03f refactor(activity): 统一各入口传 FoodRecord 跳转 PrepareFoodActivity,重构菜品详情加载逻辑 2026-05-08 18:38:14 +08:00
lvmeng f4d383dfe1 feat(adapter): FoodMaterialAdapter 无重量时 ic_dish_clear 染灰色并将点击转发为 item 选中 2026-05-08 16:12:03 +08:00
lvmengandClaude Sonnet 4.6 a14072af00 chore: 补充 SCALE_ORDER_1 配置、Weigher2 unInit 修复及调料列表模拟数据
- ScaleDeviceConfig:新增 SCALE_ORDER_1 单秤地址列表
- Weigher2:unInit() 补充调用 Weigher.unInit(),确保串口资源正确释放
- SeasoningSelectDialog:getGoodsList 临时改为模拟数据,待联调时切回真实接口

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 15:49:35 +08:00
lvmengandClaude Sonnet 4.6 436de88d73 fix(scale): 修复子设备重启后主设备看不到连接数据的问题,新增清除数据广播功能
- ScaleWebSocketClient:引入版本号机制防止 UDP 触发的新连接与指数退避重连任务并发建立两条连接;onFailure/onClosed 改用 remove(key, value) 原子操作,避免旧连接超时回调误删新连接引用
- ScaleWebSocketServer:新增 latestData 为空时延迟 3 秒补推机制,解决子设备刚重启时 WeightUtil 尚无读数导致主设备看不到数据的问题;新增 onClearData 回调处理清除数据事件;stop() 时同步关闭 scheduler
- ScaleEvent:新增 TYPE_CLEAR_DATA 事件类型
- ScaleServiceManager:新增 onClearData 属性和 sendClearData() 方法
- SlaveActivity:监听 onClearData 事件,收到后清空本机数据并重置 SP 状态;启动时预填空占位格子
- SettingActivity/DbViewModel/DbRepository:clearAllTestData 重命名为 clearAllData,清除完成后通知子设备并跳转 HomeActivity
- scale包架构分析.md:同步更新文档

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 15:48:59 +08:00
lvmengandClaude Sonnet 4.6 a0137d6979 feat(db): 新增测试数据清除功能,物理清空全部 4 张表并重置 SP 状态
- 各 DAO 新增 deleteAll() 物理清空方法
- DbRepository 新增 clearAllTestData(),按顺序删除食材→菜品→调料→槽位
- DbViewModel 暴露 clearAllTestData(onDone) 供 UI 层调用
- SettingActivity 新增「测试数据清除」入口(隐藏,右上角图标触发显示)
- 清除完成后重置 SpTool.cookMode=-1 和 SpTool.canteenId="0"

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-08 11:58:32 +08:00
lvmeng c46264a4cf feat(activity): 新增 canteenId 持久化存储,HomeActivity 切换食堂时同步写入 SpTool 并恢复选中状态 2026-05-08 11:50:22 +08:00
lvmeng 979b93c53d feat(activity): 统一键盘收起逻辑,新增 RecyclerView 侧滑收起键盘支持 2026-05-08 11:10:13 +08:00
lvmeng 9880f2a5a8 feat(activity): 新增识别添加菜品时自动计算 materialType 逻辑 2026-05-08 10:26:13 +08:00
lvmeng 19b5d721a7 style(layout): 优化布局文件结构和属性配置
- 统一调整了 activity_setting.xml 中各个 LinearLayout 的属性顺序
- 为 fragment_seasoning_config.xml 和 fragment_vector_collection.xml
  添加了工具忽略属性
- 重新排列了 list_item_scale22_row.xml 和 list_item_scale_row.xml
  的命名空间和属性顺序
- 在 list_type_scale1.xml 中调整了组件的布局属性顺序
- 为设置页面添加了数据库查看和秤数据监控功能的可见性控制
- 修复了布局文件中的硬编码文本警告问题
2026-05-08 08:44:42 +08:00
lvmeng 0648f458a7 refactor(fragment): DbInspectFragment 改用嵌套 RecyclerView 展示字段,优化已删除记录视觉样式 2026-05-07 18:13:17 +08:00
lvmengandClaude Sonnet 4.6 c17402c3c2 feat(fragment): 新增 DbInspectFragment 本地数据库调试查看功能
- 新增 DbInspectFragment,支持按表切换(菜品/食材/调料/槽位)查看全量数据
- 分页加载(每页 50 条)+ isDel 过滤开关,避免大数据量时内存占用过高
- 切换 Tab 立即清空旧数据防止闪现,loadMoreDbInspect 加并发保护
- 槽位表字段少无 isDel,切换到该 Tab 时自动隐藏 isDel 相关控件
- 菜品/食材/调料表字段改为每行 3 列紧凑布局,槽位表保持逐行显示
- SettingActivity 新增"数据库查看"入口,复用 SingleFragmentActivity 承载
- 4 个 DAO 新增分页查询及计数方法,DbRepository/DbViewModel 同步扩展

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 13:44:03 +08:00
lvmengandClaude Sonnet 4.6 a64a00e099 refactor(seasoning): 调料数据改用 dm_seasoning 存储并统一逻辑删除
- SeasoningSelectDialog/SeasoningSearchAdapter 改用 GoodsItem 替代 SeasoningEntity
- SeasoningConfigFragment 选中调料时同步 upsert 完整信息到 dm_seasoning
- SubmitFoodActivity cook/submit 按 goodsId 查 dm_seasoning 补全调料字段
- SeasoningEntity 删除 @Ignore 的 pageType/isClicked 字段
- GoodsItem.toSeasoningEntity() 补全 materialType/relateionType 等字段映射
- DAO 物理删除改为逻辑删除(isDel=1),getSeasoningByGoodsId 参数改为 String
- AppDatabase version 9→10,删除 dm_cook_food.foodId 唯一索引以支持逻辑删除
- SamplingModeActivity 从 DeviceConfigFragment 返回时刷新本地列表
- ScaleWebSocketClient 修复 scheduler 关闭后重连抛出 RejectedExecutionException

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 10:47:32 +08:00
lvmeng 6595c4bde0 feat(dialog): FoodSearchDialog 新增空页面效果及 Window.Callback 手势冲突修复
- FoodSearchDialog:adapter 启用 isStateViewEnable,新增 loadEmptyView() 通过 adapter.stateView 展示空视图,替换原 toast 提示;覆写 show() 通过 Window.Callback.dispatchTouchEvent 动态控制 behavior.isDraggable,解决列表滑动与 BottomSheet 拖拽的手势冲突;注释旧 addOnScrollListener 方案保留备查
- SeasoningSelectDialog:同步补齐空页面效果,修复网络错误时也触发 loadEmptyView,优化 Handler 为 View.postDelayed
- FoodRecognizeActivity:修复识别结果回填后列表未显示的问题
- 新增 scale包架构分析.md 文档
2026-05-06 17:35:29 +08:00
lvmeng 2de5ec39b5 refactor(activity): 重构食材识别流程,改由接口查询识别结果,queryGoodsList 改为具名参数 2026-05-06 16:41:35 +08:00
lvmengandClaude Sonnet 4.6 e5fc0c265d refactor(entity): 新增 GoodsItem 统一物品数据模型,合并查询接口并迁移 UI 状态字段
- 新增 GoodsItem 纯数据类(DTO),整合接口字段与原 CookFoodGoodsEntity @Ignore UI 状态字段
- ApiService/RemoteRepository/NetViewModel 合并 queryGoodsList 与 querySeasoningList 为统一接口
- GoodsInfoSearchAdapter/FoodSearchAdapter/DishPartAdapter 实体类改为 GoodsItem
- FoodSearchDialog/FoodRecognizeDialog/FoodRecognizeActivity/VectorCollectionFragment 改用 GoodsItem
- PrepareFoodActivity.list 改为 GoodsItem,loadDishDetail 加 toGoodsItem() 转换,采集模式传 SubmitFoodActivity 前转回 CookFoodGoodsEntity
- CookFoodGoodsEntity 删除所有 @Ignore 字段,新增 toGoodsItem() 转换方法

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-06 15:00:32 +08:00
lvmeng 05063ee9de refactor(ui): 更新布局样式和清理无用代码
- 将活动主秤页面背景从颜色改为 drawable 背景
- 调整主秤页面标题的内边距、文字颜色和去除外边距
- 修改返回按钮尺寸并调整内边距为水平方向
- 更新设置页面三个组件的背景 drawable 样式
- 删除 ApiService 中大量注释掉的无用 API 接口代码
- 移除 CommonDialog 中不必要的导入和完整包名引用
- 清理 DataBean 中多个无用的数据类定义
- 新增白色带灰色边框圆角背景 drawable 资源
2026-05-06 11:13:42 +08:00
lvmengandClaude Sonnet 4.6 af737b910c fix(scale): 修复 UdpBroadcastSender 启动时 IP 为空导致广播失效
- UdpBroadcastSender 改为接收 ipProvider 函数替代静态 localIp 参数,每次广播时动态获取 IP
- IP 为空时跳过本次广播并等待下一周期重试,避免设备启动时网络未就绪导致广播携带空 IP
- ScaleServiceManager 更新调用方式,传入 lambda 动态获取 IP

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-06 10:01:26 +08:00
lvmengandClaude Sonnet 4.6 12c6b5cf94 fix(adapter): 修复 ScaleRowAdapter 点击事件偶发失效,改用同步更新替代 submitList
- 新增 updateItem / updateName / removeByAddress 同步更新方法,使用 set/add/removeAt 直接触发 notifyItemChanged
- 新增 onItemClick lambda 属性,点击时通过 bindingAdapterPosition 取最新数据
- SlaveActivity 中所有 submitList 调用替换为对应同步方法,消除 AsyncListDiffer 异步窗口期导致的点击丢失

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-06 10:01:19 +08:00
lvmeng e990652981 fix(scale): 修复子设备断线后重连慢及连接状态竞态问题
- onDeviceDisconnected 时同步清除 UDP 缓存,使子设备 5s 内即可重连,不再等待指数退避
- ScaleWebSocketServer 用 connectionCount 计数器替代 connections.isNullOrEmpty(),消除 onClose 竞态导致子设备 UI 状态不更新的问题
2026-05-06 09:03:40 +08:00
lvmeng 9cfc481cf3 fix(activity): 修复采样页越界崩溃、重复路由及搜索返回清空输入框问题 2026-04-30 15:42:44 +08:00
lvmengandClaude Sonnet 4.6 5e46c21469 fix(ui): 修复空态视图贴顶及刷新动画无法关闭问题
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-30 11:40:05 +08:00
lvmengandClaude Sonnet 4.6 858cc24046 fix(activity): 优化提交页返回未保存判断与采样页按钮样式
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-30 10:55:46 +08:00
lvmeng dc55d3fde5 refactor(swipe): 迁移侧滑删除至 SwipeRecyclerView,移除 SwipeRevealLayout
- 新增 SwipeRecyclerView.aar 及使用说明文档
- 删除 SwipeRevealLayout.java / ViewBinderHelper.java
- DishListFragment、SamplingModeActivity、PrepareFoodActivity 改用 setSwipeMenuCreator API
- FoodListAdapter、DishPartAdapter 移除 ViewBinderHelper 侧滑状态管理代码
- 布局文件将 RecyclerView 替换为 SwipeRecyclerView,item 布局移除 SwipeRevealLayout 根节点
2026-04-30 10:34:44 +08:00
lvmengandClaude Sonnet 4.6 3842391555 fix(fragment): 修复删除本地菜品后网络数据未恢复显示
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-30 09:07:05 +08:00
lvmengandClaude Sonnet 4.6 d1569faa85 feat(swipe): 接入 SwipeRevealLayout 并统一侧滑删除交互
引入 SwipeRevealLayout 替换原有滑动删除方案,修复点击冲突与开合状态问题,并在菜品列表与食材列表中统一删除确认与侧滑行为。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 18:18:32 +08:00
lvmeng a958262dff refactor(adapter): 新增 FoodListAdapter 合并 DishShowAdapter 与 SamplingAdapter 2026-04-29 15:16:59 +08:00
lvmeng fb691c508d refactor(entity): 重构数据实体类结构
- 将 FoodCollectionBean 从 objbox 包移动到 entity 包
- 在 DataBean.kt 中添加必要的 Android 图像处理相关导入
- 更新 VectorCollectionAdapter 中 FoodCollectionBean 的导入路径
- 更新 VectorCollectionFragment 中 FoodCollectionBean 的导入路径
- 重命名 DataBean.kt 为 FoodClassInfo.kt
- 移除 objbox 包中的重复 FoodCollectionBean 定义
2026-04-29 14:32:26 +08:00
lvmeng 8113c1d830 refactor(activity): 重构 BaseActivity 并优化相关页面
- 将 handler 改为 private,onDestroy 统一清理所有待执行任务
- 新增 protected postDelayed 方法供子类安全调度延时任务
- 将 DateTimeFormatter 提取为 companion object 常量,避免每秒重复创建
- setTitleBar 调用时自动显示标题栏
- 拆分 permissionCallback 为单权限和多权限独立回调,避免覆盖
- 将权限 launcher 改为 private,收敛访问入口
- 删除死代码 bgState/useBackground 及注释掉的旧代码
- InitActivity 倒计时改用私有 countdownHandler/countdownTask,解除对父类 handler 的依赖
- PrepareFoodActivity 替换 handler.postDelayed 为 BaseActivity.postDelayed
- FoodRecognizeActivity 持有弹窗引用防止重复打开
- BaseApp 使用 ScaleDeviceConfig.DEVICE_ID_2 替换硬编码设备 ID
2026-04-29 14:23:22 +08:00
lvmeng db839fd596 style(ui): 更新设置页面和调料列表界面样式
- 调整设置页面布局间距和背景样式
- 更换箭头图标资源文件
- 将调料列表改为网格布局显示
- 优化调料项目卡片样式和尺寸
- 修改RecyclerView为4列网格布局
2026-04-29 10:10:57 +08:00
lvmeng c2fd14cb6f fix(ui): 修复界面文本显示和布局问题
- 将"餐品模式"统一修改为"菜品模式"
- 优化列表项布局结构,使用ConstraintLayout替代LinearLayout
- 调整间距属性,将marginTop改为layout_marginVertical
- 重新设置文本和图标的位置约束关系
- 添加多点击检测器用于快速跳转到主页面的临时功能
2026-04-29 09:10:32 +08:00
lvmeng 95895e6390 remove(dish): 删除菜品采样相关功能代码
- 移除 activity_dish_sampling.xml 布局文件及其全部UI组件
- 删除 DishSamplingActivity 类的所有业务逻辑代码
- 移除 BaseReq 基础请求类定义
- 将 loading 图片资源引用从 loading_spinner 更新为 loading
2026-04-29 08:48:12 +08:00
lvmeng 9a0b066490 refactor(ui): 对页面名称进行统一重命名
- 将 SelectDishActivity 重命名为 CookingModeActivity
- 将 PrepareCookActivity 重命名为 PrepareFoodActivity
- 将 SamplingListActivity 重命名为 SamplingModeActivity
- 更新 AndroidManifest.xml 中的活动声明
- 修改 DishListFragment 中的相关引用
- 注释掉 DishSamplingActivity 的完整实现代码
- 更新 DeviceConfigFragment 中的活动跳转逻辑
- 优化 CookingModeActivity 的视图绑定方式
- 更新相关导入包路径和类引用
2026-04-28 18:13:50 +08:00
lvmengandClaude Sonnet 4.6 e8933fa578 fix(activity): 修复采样与菜品列表页异常场景的数据展示
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-28 17:46:19 +08:00
lvmeng 425f485b95 feat(ui): 将加载动画图标替换为 VectorDrawable,清理无用代码 2026-04-28 11:56:28 +08:00
lvmeng 264198463c style(ui): 优化界面布局和颜色配置
- 修改 RecyclerView 高度设置以改进布局
- 更新颜色值,移除 alpha 通道简化颜色定义
- 重构调味配置界面布局,提升视觉效果
- 调整项目条目样式,包括文字颜色和字体粗细
- 更新分割线为 Material Divider 组件
- 统一调整文本颜色和大小以增强可读性
- 优化调味网格适配器中的文字颜色显示
- 调整布局间距和尺寸参数以改善界面美观
- 优化重量数据显示,增加小数位数控制功能
2026-04-28 10:49:10 +08:00
lvmeng 89fa681722 style(ui): 优化食材识别页面界面布局和交互体验
- 将内边距设置从统一padding改为水平和底部独立设置
- 增加卡片圆角大小从8dp到12dp提升视觉效果
- 为商品列表添加白色圆角背景提升美观性
- 调整滚动条垂直边距和顶部间距
- 将选中食材和重量显示区域包裹在圆角容器中
- 添加食材名称文本的最大行数和省略效果
- 统一按钮边距使用水平和垂直边距设置
- 动态调整RecyclerView父容器高度适配内容
- 注释掉食材搜索弹窗的默认商品名称传递
- 在食材搜索弹窗中预设测试数据便于调试
2026-04-28 09:25:31 +08:00
lvmeng 7a75e943db fix(ui): 优化菜品制作界面布局和称重功能
- 调整 activity_prepare_cook.xml 中的边距和布局参数
- 更新称重显示文本为“称重:0g”并调整样式
- 在 BaseActivity 中将 loading 显示和隐藏操作移到主线程执行
- 为称重按钮添加防抖点击监听器和清零功能
- 在食物识别过程中添加加载提示和调试日志
- 修复食物识别流程中的加载框显示和隐藏逻辑
- 添加识别结果页面加载功能和取消判断
2026-04-27 14:32:03 +08:00
lvmeng 634f23a76a style(ui): 优化食物识别界面布局和对话框标题
- 将食物照片区域包装在 CardView 中并调整样式
- 为食材列表容器添加滚动指示条功能
- 替换 RecyclerView 的滚动条为自定义指示条
- 更新多个对话框的标题文本以提高一致性
- 在准备烹饪界面添加重量显示文本
- 优化适配器数据更新和列表滚动逻辑
- 防止 StateFlow 重放导致的重复数据加载
- 添加新的滚动条绘制资源文件
2026-04-27 13:50:56 +08:00
lvmeng b110cc97a0 refactor(collect): 重构食材采集功能界面和适配器
- 将按钮组件替换为TextView以支持更好的交互效果
- 添加selectableItemBackground实现点击反馈效果
- 重命名食材采样为食材采集保持术语一致性
- 替换FoodCollectionAdapter为VectorCollectionAdapter适配器
- 更新列表项布局从list_item_food_collection到list_item_vector_collection
- 添加FoodSearchAdapter适配器用于食材搜索功能
- 重构CollectFragment中的数据绑定和UI逻辑
- 修改相机容器布局位置优化界面结构
- 更新资源文件名和颜色定义提升代码可读性
- 调整保存按钮样式增强视觉效果
- 修改提示对话框内容精确表达功能意图
2026-04-27 10:21:37 +08:00
lvmeng fda88fff33 feat(ui): 添加地址显示功能到调味品网格适配器
- 在 Seasoning22GridAdapter 中启用地址显示
- 在 Seasoning18GridAdapter 中启用地址显示
- 更新点击事件以显示地址对话框
- 为网格项目添加地址显示支持
2026-04-27 08:57:30 +08:00
lvmeng c4fbf9dcd6 feat(ui): 优化通用弹窗样式并修复初始化清零逻辑
- 重构 CommonDialog 弹窗视觉效果:新增带阴影投影的背景、缩放淡入淡出动画、取消/确认按钮主次色区分
- 修复 setCancelable 调用位置错误(原写在 window.run 内不生效)
- 新增弹窗按钮圆角 ripple drawable,防止涟漪溢出圆角
- InitActivity 启动时对净材秤和熟食秤执行清零操作
- PrepareCookActivity 弹窗补充内容文案
- 修正 activity_dish_sampling.xml 中 MaterialDivider 颜色属性写法
2026-04-24 18:03:43 +08:00
lvmeng a2f8fb903a refactor(http): 移除旧的HTTP客户端配置并整合到网络管理器中
- 删除了废弃的HttpClient.kt文件中的自定义HTTP客户端实现
- 将基础URL配置从UrlConfig迁移到GlobalData统一管理
- 更新HttpManager使用GlobalData.appBaseUrl作为基础URL
- 移除了HttpUtil.kt文件中的遗留HTTP工具类
- 简化了网络层架构,移除重复的配置类
2026-04-24 17:23:27 +08:00
lvmengandClaude Sonnet 4.6 13fc7c7e0f fix(ui): 修复22格高宽比调整后列表高度显示不全
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 17:14:19 +08:00
lvmeng fed161b088 style(adapter): 更新网格适配器高亮样式
- 将 setBackgroundColor 替换为 setBackgroundResource 使用形状资源
- 为 Seasoning18GridAdapter 和 Seasoning22GridAdapter 统一高亮样式
- 添加 shape_scale_cell_highlight.xml 定义圆角橙色背景
- 移除硬编码颜色值,提高样式可维护性
2026-04-24 16:23:15 +08:00
lvmengandClaude Sonnet 4.6 594c551a98 fix(activity): 修复调料配置删除后子设备未同步问题
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 11:28:59 +08:00
lvmeng 617ccfb456 feat(dialog): 调料选择对话框增加滑动冲突处理和重量传递功能
- 修改 dialog_seasoning_select.xml 布局高度为 match_parent 并添加标题文本
- 调整 SmartRefreshLayout 高度限制并移除 RecyclerView 内边距
- 在 FoodRecognizeActivity 中新增 currentWeight 参数传递机制
- 移除 WeightUtil 监听器相关代码并初始化当前重量值
- 在 PrepareCookActivity 中传递当前重量到识别页面
- 从 SeasoningConfigFragment 和 SeasoningSelectDialog 中移除无用参数
- 添加 Window.Callback 触摸事件拦截解决 RecyclerView 滑动冲突
- 实现触摸点位置检测动态控制 BottomSheet 拖拽行为
2026-04-24 10:07:11 +08:00
lvmengandClaude Sonnet 4.6 f3d57177b8 feat(activity): 制作/提交按钮增加二次确认弹窗,调整弹窗标题颜色及列表项背景属性
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 17:41:26 +08:00
lvmengandClaude Sonnet 4.6 267628411a fix(viewmodel): 修复切换 tab 返回后数据消失及 loading 不消失的问题
切换 tab 时重置对方的 StateFlow 状态为初始值,避免 repeatOnLifecycle
重启后 replay 残留状态导致 UI 异常覆盖或 loading 无法关闭

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 17:41:12 +08:00
lvmeng 58fb78c7bd feat(activity): 新增已采集食材列表页,支持搜索、删除及空视图展示 2026-04-23 16:51:57 +08:00
lvmeng 9f0671410f feat(ui): 将采集页红色主题图标统一替换为绿色 2026-04-23 14:39:49 +08:00
lvmengandClaude Sonnet 4.6 0243fe0dc8 refactor(viewmodel): 将回调方式统一改为 StateFlow + UiState,消除竞态问题
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 14:01:24 +08:00
lvmengandClaude Sonnet 4.6 df0580d68f refactor(viewmodel): 统一 DbViewModel 初始化并拆分 DAO 结构
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 11:58:14 +08:00
lvmengandClaude Sonnet 4.6 deab289747 refactor(rename): 将 AppRepository 重命名为 DbRepository,AppViewModel 重命名为 DbViewModel
- DatabaseRepository.kt → DbRepository.kt,类名 AppRepository → DbRepository
- AppViewModel.kt → DbViewModel.kt,类名 AppViewModel → DbViewModel
- VMFactory 构造参数与创建类型同步更新
- 所有引用文件(UI 层、Fragment、ViewModel 工厂)批量更新 import 与使用处

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 11:06:59 +08:00
lvmeng debc7a0740 refactor(viewmodel): 封装调料槽位读写至 AppViewModel,消除页面直接调用 DAO 的情况 2026-04-23 10:54:59 +08:00
lvmeng 441cffe4da fix(submit): 移除调料数据为空的检查限制
- 注释掉调味料数据为空时的验证逻辑
- 允许在没有调料信息的情况下继续提交流程
- 保持原有的数据转换和追加功能不变
2026-04-23 10:31:02 +08:00
lvmeng 3581975ab0 refactor(viewmodel): 新增 seasoningSlotState 替代 loadSeasoning,将 getSamplingList 迁移至 StateFlow 2026-04-23 10:29:17 +08:00
lvmeng 9e99e6ef6d refactor(viewmodel): 将 searchFoodList/getCookFoodList 迁移至 StateFlow,DishListFragment 改用 combine 并行合并数据并修复分页本地数据混入问题 2026-04-23 09:54:34 +08:00
lvmengandClaude Sonnet 4.6 16fe64e9fe refactor(viewmodel): 修复 loadSeasoning 防重入缺陷并移除 BaseActivity 网络包装方法
- AppViewModel.loadSeasoning 用 Mutex 替换 isProcessing 标志位,避免异常时状态永久锁死
- 删除 BaseActivity 中 queryGoodsList / querySeasoningList 包装方法,减少隐式依赖
- FoodSearchDialog / SeasoningSearchDialog 改为直接调用 activity.netViewModel.xxx()

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 08:56:13 +08:00
lvmengandClaude Sonnet 4.6 75830b9204 refactor(network): 引入 RemoteRepository 隔离网络层,AppRepository 支持调料槽位查询
- 新增 RemoteRepository,将 NetViewModel 中直接调用 apiService 的逻辑下沉至仓库层
- NetViewModel 改为依赖注入 RemoteRepository,不再直接接触 apiService
- AppRepository 构造函数增加 SeasoningSlotDao 参数,新增 hasSeasoningSlotConfig() 方法
- AppViewModel 新增 hasSeasoningSlotConfig() 方法,明确区分"调料数据"与"槽位配置"语义
- 同步更新 6 个 Activity 的 AppFactory 构造调用,传入 seasoningSlotDao

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 18:31:38 +08:00
lvmeng 0498501b33 style(ui): 统一界面组件样式并优化设置页面交互
- 为所有列表项和设置面板应用统一的白色圆角背景样式
- 为可点击区域添加波纹效果提升用户体验
- 修复布局文件中ID命名不规范的问题
- 在设置页面添加右上角功能按钮并实现跳转逻辑
- 导入页面跳转扩展函数支持快速导航到主秤配置页面
- 优化布局参数确保界面元素正确显示和交互响应
2026-04-22 17:35:26 +08:00
lvmeng 8c709a3f5f fix(fragment): 修复 CollectFragment 首次打开相机预览不显示的问题 2026-04-22 17:09:33 +08:00
lvmeng 9ba6443f4f refactor(setting): 重构设置页面界面和功能结构
- 将底部导航菜单替换为三个独立的功能卡片布局
- 添加餐品模式、调料区设置和食材采样功能入口
- 移除原有的Fragment容器和标签页切换逻辑
- 更新CollectFragment以使用新的SingleFragmentActivity架构
- 修改相机权限检查逻辑并添加权限拒绝提示对话框
- 简化DeviceConfigFragment和SeasoningConfigFragment的依赖导入
- 在设置页面添加当前模式显示和跳转功能
- 重构调料配置页面的日志记录和高亮逻辑
2026-04-22 14:55:09 +08:00
lvmeng 04e4efe1fc feat(activity): 新增 SingleFragmentActivity 通用 Fragment 容器页 2026-04-22 13:39:52 +08:00
lvmengandClaude Sonnet 4.6 bce9675b0f feat(activity): SubmitFoodActivity 支持制作中菜品调料历史数据加载与新增叠加
- SeasoningWeightAdapter 改继承 BaseQuickAdapter
- item_seasoning_weight 左右间距改为 32dp
- isCooking=true 时从数据库查询 goodsList 并预填充调料历史数据
- refreshAdapterByName 叠加历史用量,修复新增用量覆盖历史数据问题
- 返回键拦截,弹窗提示保存数据

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 11:47:13 +08:00
lvmeng f25108360b feat(ui): CommonDialog 支持垂直3按钮布局(iOS风格) 2026-04-22 11:39:37 +08:00
lvmeng 4ec02ac2bc feat(MasterScaleActivity): 添加秤名称显示功能
- 在UI界面上增加tvName文本视图用于显示秤的名称
- 当秤名称不为空时显示实际名称,否则显示默认值"-"
- 优化了秤信息展示的完整性,补充了名称字段的显示逻辑
2026-04-22 09:34:04 +08:00
lvmeng 97b357850c refactor(layout): 优化布局尺寸计算逻辑并提取公共工具类
- 添加 SizeTool 工具类统一管理 Flexbox 布局尺寸计算
- 在 MasterScaleActivity 中使用 SizeTool 替代硬编码计算
- 在 SeasoningConfigFragment 中使用 SizeTool 重构尺寸计算
- 在 SlaveActivity 中应用统一的尺寸计算方法
- 更新 Seasoning18GridAdapter 和 Seasoning22GridAdapter 使用现代化布局参数设置
- 调整 fragment_seasoning_config.xml 中的边距和内边距数值
- 为布局文件添加 tools:itemCount 属性支持预览功能
2026-04-22 09:28:07 +08:00
lvmengandClaude Sonnet 4.6 b6b5088107 feat(ui): 新增油盆配置区,子设备1调料名改为动态配置
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 18:18:22 +08:00
lvmeng bbdebc0c9c feat(activity): 新增同名调料用量聚合合并展示逻辑
- SubmitFoodActivity 新增 rawWeightMap 记录各秤槽位原始用量
- 每次秤数据更新后按 goodsName 聚合求和,同名调料只展示一条
- SeasoningWeightAdapter 改为按 goodsName 作为唯一标识匹配更新/移除
- SlaveActivity 简化高亮触发条件判断
2026-04-21 17:50:02 +08:00
lvmeng 0a90a8b368 feat(activity): 重构 SubmitFoodActivity 调料展示,改用子设备实时秤数据 2026-04-21 17:08:34 +08:00
lvmeng 07eb626e12 feat(layout): 更新秤数据列表项布局样式
- 将布局高度从120dp增加到340dp
- 调整布局方向为垂直排列并居中对齐
- 添加商品名称显示文本框
- 调整字体大小和颜色配置
- 修改权重布局为包裹内容模式
- 更新内边距设置以优化显示效果
2026-04-21 16:57:55 +08:00
lvmeng 736e4820dd fix(fragment): 修复 triggerHighlight 因设备判断用 != 导致主设备秤误触发调料格子高亮 2026-04-21 16:52:23 +08:00
lvmengandClaude Sonnet 4.6 3fc54d5f52 refactor(ui): 重构 Scale2VH 使用 XML 布局,优化秤总览界面样式
- list_type_scale2.xml 替换动态格子为 include list_item_scale22_row,Scale2VH 删除 makeScaleCell/updateScaleCell/makeCellText
- list_type_scale1.xml 布局调整为垂直居中,新增 tvName 展示调料名称
- list_type_scale18/22.xml 移除分割线
- SeasoningSelectDialog 搜索列表改为3列,扩充模拟调料数据

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 15:54:04 +08:00
lvmengandClaude Sonnet 4.6 b16d7d19cd feat(scale): 实现调料槽位配置持久化及主从设备数据同步
- 新增 SeasoningSlotEntity / SeasoningSlotDao,独立存储格子调料配置
- AppDatabase 升级至版本 8,添加 MIGRATION_7_8
- ScaleEvent 新增 TYPE_SEASONING_CONFIG 和 SlotConfig,用于主从同步
- SeasoningConfigFragment 选择调料后写 Room 并通过 wsClient 推送给子设备
- ScaleWebSocketClient 新增 sendToAllSlaves / sendToDevice / onDeviceConnected
- ScaleWebSocketServer 扩展 onMessage 支持接收主设备下发的配置事件
- ScaleServiceManager 暴露 sendSeasoningConfig / onSeasoningConfig;子设备连接时自动推送全量配置
- MasterScaleActivity 启动时从 Room 加载 slotNameMap,注入 ScaleData.name 展示调料名
- SlaveActivity 新增 slotNameMap 防止重量回调覆盖调料名;监听 onSeasoningConfig 写 Room 并刷新 adapter
- Adapter 新增 tvAddress 和 showAddress 参数,仅 MasterScaleActivity 显示秤地址行;tvName 空值统一显示"-"

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 15:27:28 +08:00
lvmengandClaude Sonnet 4.6 a81e914b63 refactor(adapter): 合并 Scale18/22GridAdapter 为 Seasoning18/22GridAdapter,统一支持调料配置和秤总览双模式
- ScaleData 新增可空 name 字段,用于承载调料名称
- Seasoning18/22GridAdapter 改用 ScaleData,新增 showNameOnly 参数区分页面模式
- showNameOnly=true(调料配置):仅显示名称,无名称显示"-"
- showNameOnly=false(秤总览):显示名称+重量+状态,无名称显示秤地址编号
- update() 恢复差量更新逻辑,避免 submitList 动画期间点击失效
- MasterScaleActivity、SlaveActivity 改用新 Adapter,删除旧 Scale18/22GridAdapter
- 删除 Scale22GridActivity 及其布局和 Manifest 注册
- list_item_scale22_row.xml 中 tvAddr 重命名为 tvName

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 11:59:59 +08:00
lvmeng ffdf364ee8 style(ui): 调料配置界面布局优化
- 添加了整体容器的圆角背景样式
- 新增了顶部标题区域,包含主标题和操作提示文字
- 统一调整了上下层调料区标题的文字大小为28sp
- 优化了RecyclerView的边距设置
- 改善了整体界面的视觉层次和用户体验
2026-04-21 10:51:34 +08:00
lvmengandClaude Sonnet 4.6 6d3bb96d61 fix(activity): 修复 SlaveActivity 负值清零后误触发高亮的问题
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 10:41:42 +08:00
lvmengandClaude Sonnet 4.6 da712ed25a fix(activity): 修复 FoodRecognizeActivity 称重更新导致 useWeight 异常的问题
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 10:11:10 +08:00
lvmeng 6b312ec689 fix(prepareCook): 修复食材选择和数据处理逻辑
- 修复了食材选择回调中的变量命名问题,统一使用 entity 替代 item
- 改进了食材名称解析逻辑,正确提取 WP 标识符和食材名称
- 为食材 ID 提取添加了边界情况处理,避免数组越界异常
- 添加了调试日志以便追踪食材查询结果
- 优化了食材列表数据结构的构建过程
2026-04-21 09:46:15 +08:00
lvmeng e175893790 refactor(FoodRecognizeActivity): 重构食材识别页面返回逻辑和数据传递机制
- 移除废弃的 Uri 导入并添加 Activity 兼容性支持
- 新增手动取消标识常量 IS_MANUAL_CANCEL 用于区分正常选择和手动取消
- 将启动方法参数 onResult 重命名为 finishCallback 并支持取消状态回调
- 使用 IntentCompat 替代已弃用的 getSerializableExtra 方法
- 在标题栏和返回键添加手动返回功能,统一处理页面关闭逻辑
- 修改 finishWithResult 方法支持传递取消状态,仅在非取消状态下传递选中数据
- 更新 PrepareCookActivity 中的重量阈值从 5 改为 15
- 重构识别控制变量,使用 showRecognizePage 和 manualCancelFlag 替代原有变量
- 调整页面生命周期中的识别启用逻辑,确保正确的状态管理
- 修改食材识别启动回调,集成手动取消状态处理机制
2026-04-21 09:29:26 +08:00
lvmengandClaude Sonnet 4.6 82217b4fb1 feat(activity): 合并采集功能至 PrepareCookActivity 并优化识别页重量处理逻辑
- 将 DishSamplingActivity 逻辑合并至 PrepareCookActivity,根据 cookMode 区分采集/制作模式
- 布局替换:activity_prepare_cook 第一子 View 改为搜索栏(etInputDish + ivDishSearch),删除第二个子 LinearLayout
- InitActivity / HomeActivity / SamplingListActivity 改用 PrepareCookActivity 替代 DishSamplingActivity
- FoodRecognizeActivity 新增 selectedPosition 字段,避免通过 isClicked 线性查找索引
- 优化重量更新逻辑:重量增加立即同步,重量减少延迟 3 秒更新,防止关页前误覆盖用量
- foodSelectCallback 改为累加同 goodsId 的 useWeight,不再限制重复添加

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-20 18:26:20 +08:00
lvmengandClaude Sonnet 4.6 72ecc8fcd6 fix(scale): 修复 RS485 多联秤地址 ≥ 10 时清零命令发送到错误设备的问题
- 新增 FixedSensorScale 继承 SensorScale,通过反射重写 zeroTwo/tareTwo
- 修复根因:SDK 将 int 地址直接拼接为十进制字符串再按十六进制解析,
  导致地址 10 发送字节 0x10(=16号秤)而非 0x0A(=10号秤)
- 修复方式:String.format("%02X", address) 确保正确的十六进制编码
- Weigher2 替换 mSensorScale 字段类型为 FixedSensorScale
- WeightUtil.tareTwo 移除 isTaring 防重复逻辑,简化为直接调用 zeroTwo

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-20 14:58:27 +08:00
lvmeng 99d670390a fix(scale): 解决称重设备清零功能问题
- 修复了ScaleServiceManager中的WeightUtil引用路径错误
- 添加了WebSocket服务器中设备ID验证失败的日志记录
- 修复了Weigher2中字符串比较的错误写法,使用equals方法替代==
- 更新了WeightUtil中清零操作的日志记录和异常处理机制
2026-04-20 10:01:05 +08:00
lvmeng d3b69c4e46 fix(fragment): 修复 weightSnapshot key 因 Int 溢出导致主设备高亮失效的问题
将 snapshotKey 从 Int(address + hashCode*1000 易溢出)改为 String(deviceId#address),
避免不同设备的基准值互相覆盖,导致 delta 永远无法正确计算
2026-04-20 09:08:50 +08:00
lvmeng 193acff1e0 feat(activity): 为子设备 SlaveActivity 添加调料秤重量增加高亮提醒功能
检测本机秤稳定后重量增加超过10g,高亮对应格子(红底白字),15秒后自动恢复
2026-04-20 09:08:44 +08:00
lvmeng 87bf11454c feat(fragment): 实现调料秤重量增加高亮提醒功能
主设备订阅 allScales StateFlow 检测所有子设备秤重量变化,
超过10g且秤稳定时高亮对应格子,15秒后自动恢复
2026-04-17 16:56:36 +08:00
lvmengandClaude Sonnet 4.6 768bde79a1 feat(fragment): 新增调料选择弹窗并绑定格子点击交互
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-17 15:43:11 +08:00
lvmeng c61b1c8ef7 feat(seasoning): 添加调料配置网格适配器功能
- 创建调料配置格子布局文件,仅显示调料名称
- 实现调料配置下层18格网格适配器,使用GridLayoutManager排列
- 实现调料配置上层22格网格适配器,使用FlexboxLayoutManager排列
- 添加不同行列的边距控制和字体大小自适应
- 实现按预设顺序更新数据的功能,空位用哨兵填充
- 预留点击回调接口,暂不处理点击事件
2026-04-17 14:23:57 +08:00
lvmeng 77df4a4d82 refactor(ui): 移除设备配置页面并重构调料配置界面
- 移除 DeviceConfigActivity 页面及相关 AndroidManifest 注册
- 将调料配置从单页网格改为上下两层 RecyclerView 结构
- 上层使用 FlexboxLayoutManager 显示 22 格调料位
- 下层使用 GridLayoutManager 显示 18 格调料位
- 更新存储工具类 SpTool 中烹饪模式的访问方式
- 修改首页和初始化页面中烹饪模式的读取逻辑
- 更新 WebSocket 客户端连接逻辑中的重复连接处理
2026-04-17 14:23:44 +08:00
lvmeng c35572dc41 feat(setting): 添加调料配置功能并优化界面布局
- 在设置页面添加调料配置按钮和设备切换功能
- 将设备配置页面标题从"设备配置"改为"设备切换"
- 新增SeasoningConfigFragment调料配置片段
- 将秤数据监控按钮可见性从gone改为visible
- 优化collectFragment布局加载方式
- 在DeviceConfigActivity中添加调试日志输出
- 重构SettingActivity中的按钮样式管理逻辑
- 调整fragment列表顺序和点击事件处理
- 修改列表项高度以改善界面显示效果
- 注释掉DeviceConfigFragment中未使用的viewModel相关代码
2026-04-17 11:45:08 +08:00
lvmeng 1ca25e6a1d fix(ui): 修复菜品清空图标显示和日志记录问题
- 将菜品清空图标从tools:src改为android:src以确保正常显示
- 在点击清空图标时添加菜品数据的JSON日志输出便于调试
- 移除isOriginalData状态重置避免影响菜品原始数据标记
2026-04-17 09:00:42 +08:00
lvmeng 7373ccacbb feat(activity): 新增食材识别页面,重构识别流程并优化多设备布局适配 2026-04-16 18:05:46 +08:00
lvmeng ad63639f66 refactor(dialog): 重构 CommonDialog 为链式调用 API,内置 title/content,全量替换旧调用方 2026-04-16 15:02:33 +08:00
lvmeng c3f3b1215b refactor(scale): 提取 Scale22/18GridAdapter 到 adapter 包,SlaveActivity 复用网格布局 2026-04-16 14:26:34 +08:00
lvmeng cba5bda757 fix(scale): 子设备断线时从聚合器移除数据,修复列表不消失的问题
- ScaleWebSocketClient 新增 onDeviceDisconnected 回调,在 onFailure/onClosed 时触发
- ScaleServiceManager 绑定回调,断线时调用 aggregator.removeDevice() 清除缓存
- 重连成功后数据重新推送,UI 列表自动恢复
2026-04-16 13:52:11 +08:00
lvmeng 7fd2f02b87 feat(activity): 为 MasterScaleActivity 各秤格子新增清零点击事件,修复高频数据更新导致点击失效的问题 2026-04-16 13:45:39 +08:00
lvmeng b775b20ff1 refactor(activity): 重构 MasterScaleActivity 多类型秤布局,新增 Scale22GridActivity
- MasterScaleActivity 使用 BaseMultiItemAdapter 支持4种 viewType(scale1/2/18/22)
- 内嵌 adapter 改用 BaseQuickAdapter + 自定义 VH,替换原 RecyclerView.Adapter
- 新增 Scale22GridActivity,使用 FlexboxLayoutManager 实现22格混合网格布局
- 新增 list_type_scale1/2/18/22.xml 及 list_item_scale22_row.xml 布局文件
- 删除废弃的 list_item_scale_data.xml
- 新增 flexbox 依赖,注册 Scale22GridActivity
2026-04-15 16:44:33 +08:00
lvmeng 5ac35a9cab refactor(activity): 将 ScaleServiceManager.stop() 迁移至 InitActivity.onDestroy,优化18格子布局间距 2026-04-15 09:52:16 +08:00
lvmeng 94e49eb344 fix(scale): 修复 mDNS 抖动导致子设备永久无法重连的问题 2026-04-14 18:25:20 +08:00
lvmeng 69dc77f06e refactor(activity): 优化 MasterScaleActivity 布局常量与显示逻辑 2026-04-14 16:12:28 +08:00
lvmeng b69b8c10e8 feat(activity): 重构 MasterScaleActivity 秤数据网格布局,按设备号适配不同显示方案 2026-04-14 14:00:13 +08:00
lvmeng 0477fad57b fix(activity): 修复 PrepareCookActivity 相机未就绪时触发拍照导致报错的问题 2026-04-14 10:29:38 +08:00
lvmengandClaude Sonnet 4.6 da7b5b09a0 refactor(activity): 统一使用 onBackPressedDispatcher.addCallback 替代 onBackPressed
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-14 09:45:58 +08:00
lvmeng f1ffc67b9b refactor(dialog): 重构 FoodSearchDialog 和 SeasoningSearchDialog 继承 BottomSheetDialog 2026-04-14 09:17:10 +08:00
lvmeng 910759c99e refactor(PrepareCookActivity): 优化菜品识别逻辑和代码结构
- 移除未使用的 Bitmap 和 PreviewView 导入
- 添加 abs 函数导入用于重量比较计算
- 新增 WEIGHT_CHANGE_VALUE 和 WEIGHT_RECOGNIZE_VALUE 常量定义
- 实现重量变化阈值检测,避免频繁识别拍照
- 添加 lastWeight 变量记录上次重量值
- 将菜品选择逻辑提取为独立回调函数 foodSelectCallback
- 重命名 onItemClick 为 onFoodItemClick 并添加注释
- 为多个方法添加 KDoc 注释说明功能
- 在拍照失败回调中显示错误提示
- 优化菜品识别条件判断逻辑
2026-04-14 09:01:15 +08:00
lvmeng 428852a07e refactor(activity): 优化启动页网络检测逻辑,有网络时直接跳转并隐藏检测区域 2026-04-13 18:17:17 +08:00
lvmeng 96863e2078 feat(activity): 新增菜品识别功能,重构FoodRecognizeDialog并临时跳过调料配置检查
- 新增 FoodRecognizeDialog(继承 BottomSheetDialog),只初始化一次,暴露 loadData() 方法
- 新增 dialog_food_recognize.xml 布局(标题 + 2列 GridLayoutManager RecyclerView)
- PrepareCookActivity 集成相机初始化、拍照识别流程(重量稳定 ≥10g 时触发)
- PrepareCookActivity 新增 flCameraContainer(1dp 隐藏容器)用于相机预览绑定
- SelectDishActivity 临时注释 judgeDeviceConfig 逻辑,直接调用 block()
- 修正 GpioUtils/L/LightManager 包名为 com.shuwei.dish.match.utils
2026-04-13 17:31:31 +08:00
lvmeng 41036cdbf9 feat(layout): 更新主秤监控界面布局并启用PyTorch模型功能
- 将主秤监控界面从LinearLayout改为ConstraintLayout布局
- 添加返回按钮并实现点击关闭页面功能
- 在BaseApp中初始化ObjectBox数据库
- 启用PyTorch模型依赖库并移除注释代码
- 在CollectFragment中激活食物图像向量化功能
- 初始化FoodModule中的PyTorch模型
- 临时忽略assets下的.pt模型文件到.gitignore
2026-04-13 15:11:47 +08:00
lvmengandClaude Sonnet 4.6 0d0fcd24b7 refactor(activity): 优化启动页跳转延迟及子设备页面稳定性,修复导航栏闪烁问题
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-13 14:31:29 +08:00
lvmeng bb32ed84fe refactor(device): 优化设备角色判断和串口配置逻辑
- 移除 Weigher2 的初始化代码从 InitActivity 到 BaseApp
- 将设备角色判断与串口配置逻辑合并到应用启动流程中
- 主设备配置为 /dev/ttyS7,子设备配置为 /dev/ttyS4
- 简化设备角色分配的条件判断逻辑
2026-04-13 09:40:28 +08:00
lvmeng 6a1a1f3c5c feat(activity): 新增启动页网络检测功能,60秒倒计时后显示连接网络入口 2026-04-13 09:36:06 +08:00
lvmeng 9311d13b90 refactor(activity): 清理 InitActivity 中的注释代码,保留有效初始化逻辑 2026-04-13 09:08:05 +08:00
lvmeng 143d24923b chore(global): 更新 .gitignore,忽略 .idea、.claude、app/debug、app/release 目录 2026-04-13 09:06:48 +08:00
lvmeng 9a77733d24 fix(scale): 修复主设备无法发现子设备及IP显示未知的问题
- UdpBroadcastReceiver 补充 socket.broadcast=true,修复广播包被内核丢弃
- MdnsDiscoveryManager 改为串行解析队列,修复多设备并发解析报 FAILURE_ALREADY_ACTIVE
- ScaleWebSocketServer 推送数据时动态填充本机 IP,解决子设备 IP 始终显示未知
2026-04-13 09:00:51 +08:00
lvmeng c72d30e88a feat(scale): 新增 UDP 广播兜底发现机制并恢复开机自启原始方案
- 新增 UdpBroadcastSender/UdpBroadcastReceiver,子设备定时广播,主设备监听,与 mDNS 互为备份
- 恢复 BootReceiver 为直接启动 Activity 的原始方式,删除 BootService
- 移除 InitActivity 开机自启相关 Window flags
- 移除 PyTorch 依赖,缩减安装包体积
- 删除仓库中的 release apk 和 pt 模型文件
2026-04-10 18:04:18 +08:00
lvmeng 904ccdbb06 feat(boot): 新增前台服务中转实现开机自启动
使用 BootService 前台服务绕过 Android 10+ 后台启动 Activity 限制,
通过 setFullScreenIntent 触发 InitActivity,兼容主从设备差异。
同时优化 MasterScaleActivity、SettingActivity 及相关布局。
2026-04-09 18:20:50 +08:00
lvmengandClaude Sonnet 4.6 9ae0d709f2 fix(scale): 修复子设备IP收到数据后仍显示"未知"的问题
setDeviceIp 新增缓存回填逻辑:若设备已有缓存数据且 ip 为空,
立即用新 IP 更新所有相关条目并触发 StateFlow,
解决早期数据包在 IP 到达前入缓存导致 UI 无法更新的时序问题

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-08 18:19:07 +08:00
lvmengandClaude Sonnet 4.6 34adc0fe56 fix(scale): 修复主从设备IP显示异常及RecyclerView滑动崩溃
- 新增 NetworkUtil 统一获取本机IP,兼容 Android 12+(ConnectivityManager)和低版本(WifiManager)
- 主设备IP改为实时读取,修复App启动时网络未就绪导致IP缓存为空的问题
- MasterScaleActivity/SlaveActivity 关闭RecyclerView默认ItemAnimator,消除高频刷新时的闪烁
- BaseActivity.hideSystemBars 加防重入标志,避免重复调用setDecorFitsSystemWindows触发布局重绘导致滑动崩溃
- 新增 CrashHandler,崩溃时记录日志并自动重启应用

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-08 18:09:41 +08:00
lvmengandClaude Sonnet 4.6 29228b069b feat(scale): 新增主从设备秤数据联网同步功能
- 新增 ScaleWebSocketServer/Client、ScaleDataAggregator、ScaleServiceManager 等秤服务模块
- 新增 MasterScaleActivity(主设备秤数据总览,按设备分组展示IP+秤列表)
- 新增 SlaveActivity(子设备专属页面,显示IP、主设备连接状态及本机秤数据)
- SlaveActivity 改为横屏,MasterScaleActivity 保持竖屏
- 子设备连接状态通过 WebSocket onOpen/onClose 回调实时更新
- GlobalData 新增 DeviceRole 枚举,BaseApp 启动时初始化角色并启动秤服务
- SettingActivity 新增设备角色展示和秤数据监控入口
- Weigher2 支持外部设置串口路径,适配不同硬件子设备

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-08 17:15:48 +08:00
lvmeng d6a9c3562d refactor(net): 优化API请求错误处理和基础组件功能
- 添加JsonSyntaxException异常处理,提供更友好的错误提示
- 修复API响应判断逻辑,移除不必要的空值检查
- 优化HttpException转换为ApiException时的数据解析
- 移除BaseActivity中废弃的launch方法和相关变量
- 重构BaseActivity中的权限请求和页面跳转回调机制
- 更新Loading对话框的显示方法,支持自定义消息和内容更新
- 修复CollectFragment中的语法错误和日志记录功能
- 优化DishSamplingActivity中的页面跳转实现方式
- 完善SettingActivity中的相机权限检查逻辑
2026-03-30 15:28:52 +08:00
lvmeng 28c7628321 提交昨天的修改:优化多个模块和UI效果 2026-03-17 13:42:09 +08:00
lvmeng 3cf9818dad 优化SettingActivity底部菜单按钮效果:选中状态显示白色字体和圆角下划线 2026-03-17 13:40:54 +08:00
lvmeng c8eb2b8f24 ttyS4改为ttyS7,删除manifest中sharedUserId配置 2026-03-16 11:07:15 +08:00
lvmeng 795deae228 优化 2026-02-09 16:28:30 +08:00
lvmeng 873ae95c0b 优化 2026-02-06 17:31:52 +08:00
lvmeng a4f3f9527c 优化 2026-02-05 15:06:45 +08:00
lvmeng eaa1b1eb00 新接口调试 2026-01-30 18:01:07 +08:00
lvmeng a4905e7226 新接口调试 2026-01-29 18:51:42 +08:00
341 changed files with 26549 additions and 6736 deletions
+6 -6
View File
@@ -1,15 +1,15 @@
*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
/.idea/
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
local.properties
.claude/
app/debug/
app/release/
# 临时忽略 assets 下的 .pt 模型文件,正式文件就绪后取消此行
app/src/main/assets/*.pt
-3
View File
@@ -1,3 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
-6
View File
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AndroidProjectSystem">
<option name="providerId" value="com.android.tools.idea.GradleProjectSystem" />
</component>
</project>
-6
View File
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="21" />
</component>
</project>
-18
View File
@@ -1,18 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="deploymentTargetSelector">
<selectionStates>
<SelectionState runConfigName="app">
<option name="selectionMode" value="DROPDOWN" />
<DropdownSelection timestamp="2025-09-10T07:28:30.961571900Z">
<Target type="DEFAULT_BOOT">
<handle>
<DeviceId pluginId="Default" identifier="serial=192.168.1.21:5555;connection=bc7af9a5" />
</handle>
</Target>
</DropdownSelection>
<DialogSelection />
</SelectionState>
</selectionStates>
</component>
</project>
-13
View File
@@ -1,13 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DeviceTable">
<option name="columnSorters">
<list>
<ColumnSorterState>
<option name="column" value="Name" />
<option name="order" value="ASCENDING" />
</ColumnSorterState>
</list>
</option>
</component>
</project>
-19
View File
@@ -1,19 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="testRunner" value="CHOOSE_PER_TEST" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleJvm" value="#GRADLE_LOCAL_JAVA_HOME" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>
-10
View File
@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectMigrations">
<option name="MigrateToGradleLocalJavaHome">
<set>
<option value="$PROJECT_DIR$" />
</set>
</option>
</component>
</project>
-9
View File
@@ -1,9 +0,0 @@
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="jbr-21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project>
-17
View File
@@ -1,17 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RunConfigurationProducerService">
<option name="ignoredProducers">
<set>
<option value="com.intellij.execution.junit.AbstractAllInDirectoryConfigurationProducer" />
<option value="com.intellij.execution.junit.AllInPackageConfigurationProducer" />
<option value="com.intellij.execution.junit.PatternConfigurationProducer" />
<option value="com.intellij.execution.junit.TestInClassConfigurationProducer" />
<option value="com.intellij.execution.junit.UniqueIdConfigurationProducer" />
<option value="com.intellij.execution.junit.testDiscovery.JUnitTestDiscoveryConfigurationProducer" />
<option value="org.jetbrains.kotlin.idea.junit.KotlinJUnitRunConfigurationProducer" />
<option value="org.jetbrains.kotlin.idea.junit.KotlinPatternConfigurationProducer" />
</set>
</option>
</component>
</project>
+4
View File
@@ -0,0 +1,4 @@
kotlin version: 2.0.21
error message: The daemon has terminated unexpectedly on startup attempt #1 with error code: 0. The daemon process output:
1. Kotlin compile daemon is ready
+356
View File
@@ -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.
```
+66 -28
View File
@@ -1,8 +1,14 @@
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
id("com.google.devtools.ksp") version "2.0.21-1.0.27"
// alias(libs.plugins.android.application)
// alias(libs.plugins.kotlin.android)
// id("com.google.devtools.ksp") version "2.0.21-1.0.27"
id("com.android.application")
id("org.jetbrains.kotlin.android")
// id("com.google.dagger.hilt.android")
id("com.google.devtools.ksp")
id("kotlin-parcelize")
kotlin("kapt")
}
android {
@@ -10,7 +16,7 @@ android {
compileSdk = 36
defaultConfig {
applicationId = "com.shuwei.dish.match"
applicationId = "com.shuwei.dish.match.new"
minSdk = 29
targetSdk = 36
versionCode = 1
@@ -18,13 +24,12 @@ android {
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
ndk {
//设置支持的SO库架构
abiFilters.addAll(listOf("armeabi-v7a"))
//, 'x86', 'armeabi-v7a', 'x86_64', 'arm64-v8a'
//设置支持的SO库架构x86_64 仅用于在 Windows 模拟器上调试(秤功能不可用)
abiFilters.addAll(listOf("armeabi-v7a", "x86_64"))
}
// 设置输出APK文件名格式
setProperty("archivesBaseName", "菜品配比终端v${versionName}")
setProperty("archivesBaseName", "pbc_v${versionName}")
}
signingConfigs {
create("debug_507") {
@@ -42,10 +47,13 @@ android {
"proguard-rules.pro"
)
signingConfig = signingConfigs.getByName("debug_507")
buildConfigField("Boolean", "IS_TEST_DEVICE", "false")
}
debug {
//507扫码秤主板在android.buildTypes{}内增加
signingConfig = signingConfigs.getByName("debug_507")
// 调试构建视为测试设备,使用固定的 DEVICE_ID_1 代替真实 UDID
buildConfigField("Boolean", "IS_TEST_DEVICE", "false")
}
}
compileOptions {
@@ -57,6 +65,7 @@ android {
}
buildFeatures {
viewBinding = true
buildConfig = true
}
packagingOptions {
pickFirst("lib/armeabi-v7a/libserial_port.so")
@@ -74,7 +83,9 @@ android {
}
// li
}
val isDebug = gradle.startParameter.taskNames.any {
it.contains("debug", ignoreCase = true)
}
dependencies {
implementation(fileTree("libs") { include("*.jar", "*.aar") })
implementation(libs.androidx.core.ktx)
@@ -86,30 +97,57 @@ dependencies {
testImplementation(libs.junit)
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)
implementation("com.squareup.okhttp3:okhttp:4.9.1")
implementation("com.google.code.gson:gson:2.10.1")
// implementation("com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.30")
implementation(libs.gson)
implementation(libs.okhttp)
implementation(libs.logging.interceptor)
implementation(libs.retrofit)
implementation(libs.java.websocket)
implementation(libs.converter.gson)
implementation(libs.flexbox)
implementation("io.github.cymchad:BaseRecyclerViewAdapterHelper4:4.1.2")
implementation(libs.baserecyclerviewadapterhelper4)
implementation("androidx.room:room-runtime:2.5.2")
ksp("androidx.room:room-compiler:2.5.2")
implementation("androidx.room:room-ktx:2.5.2") // Kotlin扩展
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.8.7")
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.7")
implementation("androidx.activity:activity-ktx:1.8.0")
// room
implementation(libs.androidx.room.runtime)
ksp(libs.androidx.room.compiler)
implementation(libs.androidx.room.ktx)
// implementation("biz.laenger.android:vpbs:0.0.6")
//必须 1.0.0 以上
implementation("io.github.scwang90:refresh-layout-kernel:3.0.0-alpha")
//核心必须依赖
implementation("io.github.scwang90:refresh-header-classics:3.0.0-alpha")
//经典刷新头
implementation("io.github.scwang90:refresh-header-radar:3.0.0-alpha")
implementation("io.github.scwang90:refresh-footer-classics:3.0.0-alpha")
//经典加载
// refresh-layout
implementation(libs.refresh.layout.kernel)
implementation(libs.refresh.header.classics)
implementation(libs.refresh.header.radar)
implementation(libs.refresh.footer.classics)
//implementation("com.geyifeng.immersionbar:immersionbar:3.2.2")
}
// glide
implementation(libs.glide)
annotationProcessor(libs.compiler)
// camerax
implementation(libs.androidx.camera.core)
implementation(libs.androidx.camera.camera2)
implementation(libs.androidx.camera.lifecycle)
implementation(libs.androidx.camera.view)
implementation(libs.androidx.camera.extensions)
//pytorch
implementation (libs.pytorch.android)
implementation (libs.pytorch.android.torchvision)
// objectbox
if (isDebug) {
debugImplementation(libs.objectbox.android.objectbrowser)
} else {
releaseImplementation(libs.objectbox.android)
}
}
apply(plugin = "io.objectbox")
Binary file not shown.
+54
View File
@@ -0,0 +1,54 @@
{
"_note1": "KEEP THIS FILE! Check it into a version control system (VCS) like git.",
"_note2": "ObjectBox manages crucial IDs for your object model. See docs for details.",
"_note3": "If you have VCS merge conflicts, you must resolve them according to ObjectBox docs.",
"entities": [
{
"id": "1:6465153867413579585",
"lastPropertyId": "5:7592685238899911344",
"name": "Food",
"properties": [
{
"id": "1:3688350375714699356",
"name": "id",
"type": 6,
"flags": 1
},
{
"id": "2:6503828433160216329",
"name": "name",
"type": 9
},
{
"id": "3:1726525909323356793",
"name": "foodIdx",
"type": 5
},
{
"id": "4:3660727688686055762",
"name": "foodVector",
"indexId": "1:5497952887792054610",
"type": 28,
"flags": 8
},
{
"id": "5:7592685238899911344",
"name": "version",
"type": 9
}
],
"relations": []
}
],
"lastEntityId": "1:6465153867413579585",
"lastIndexId": "1:5497952887792054610",
"lastRelationId": "0:0",
"lastSequenceId": "0:0",
"modelVersion": 5,
"modelVersionParserMinimum": 5,
"retiredEntityUids": [],
"retiredIndexUids": [],
"retiredPropertyUids": [],
"retiredRelationUids": [],
"version": 1
}
Binary file not shown.
+86 -12
View File
@@ -1,11 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:sharedUserId="android.uid.system">
xmlns:tools="http://schemas.android.com/tools">
<!-- android:sharedUserId="android.uid.system" -->
<uses-feature android:name="android.hardware.usb.host" />
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE"
tools:ignore="ProtectedPermissions" />
@@ -41,7 +45,9 @@
<activity
android:name=".ui.InitActivity"
android:exported="true"
android:launchMode="singleTask"
android:screenOrientation="portrait"
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" />
@@ -50,24 +56,59 @@
</intent-filter>
</activity>
<activity android:name=".ui.HomeActivity"
android:theme="@style/Theme.DishMatch.NoSplash"
android:screenOrientation="portrait"
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
<activity android:name=".ui.HomeV2Activity"
android:theme="@style/Theme.DishMatch.NoSplash"
android:screenOrientation="portrait"
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
<activity android:name=".ui.CleanPackActivity"
android:theme="@style/Theme.DishMatch.NoSplash"
android:screenOrientation="portrait"
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
<activity android:name=".ui.MealListActivity"
android:theme="@style/Theme.DishMatch.NoSplash"
android:screenOrientation="portrait"
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
<activity android:name=".ui.PackActivity"
android:theme="@style/Theme.DishMatch.NoSplash"
android:screenOrientation="portrait"
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
<activity android:name=".ui.TaskActivity"
android:theme="@style/Theme.DishMatch.NoSplash"
android:screenOrientation="portrait"
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
<activity android:name=".ui.TaskDetailActivity"
android:theme="@style/Theme.DishMatch.NoSplash"
android:screenOrientation="portrait"
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: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"
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
@@ -82,10 +123,43 @@
<!-- tools:ignore="DiscouragedApi,LockedOrientationActivity" />-->
<activity
android:name=".ui.FoodSearchActivity"
android:theme="@style/Theme.DishMatch.NoSplash"
android:screenOrientation="portrait"
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
<activity android:name="com.shuwei.dish.match.ui.DeviceConfigActivity" />
<activity android:name="com.shuwei.dish.match.ui.SubmitFoodActivity" />
<!-- <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"
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
<activity android:name="com.shuwei.dish.match.ui.SubmitFoodActivity"
android:theme="@style/Theme.DishMatch.NoSplash" />
<activity
android:name="com.shuwei.dish.match.ui.MasterScaleActivity"
android:theme="@style/Theme.DishMatch.NoSplash"
android:screenOrientation="portrait"
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
<activity
android:name="com.shuwei.dish.match.ui.SingleFragmentActivity"
android:theme="@style/Theme.DishMatch.NoSplash"
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
<activity
android:name="com.shuwei.dish.match.ui.FoodRecognizeActivity"
android:theme="@style/Theme.DishMatch.NoSplash"
android:screenOrientation="portrait"
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
<activity
android:name="com.shuwei.dish.match.ui.CollectedFoodActivity"
android:theme="@style/Theme.DishMatch.NoSplash"
android:screenOrientation="portrait"
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
<activity
android:name="com.shuwei.dish.match.ui.SlaveActivity"
android:theme="@style/Theme.DishMatch.NoSplash"
android:launchMode="singleTask"
android:screenOrientation="landscape"
tools:ignore="DiscouragedApi,LockedOrientationActivity" />
<activity android:name="com.shuwei.dish.match.ui.FoodSearchV2Activity" />
<receiver
android:name=".utils.BootReceiver"
+272
View File
@@ -0,0 +1,272 @@
{
"class_names": [
"三黄鸡",
"上海青WP2026020200041",
"冰草WP2026020900054",
"刀豆",
"北豆腐WP2025111900007",
"味精WP2026013000034",
"圆生菜WP2026020900053",
"圆白菜[卷心菜,包菜]WP2025111000063",
"基围虾WP2025110700019",
"多宝鱼WP2025112600011",
"大白菜(代表值)WP2026022800638",
"大葱WP2026013000025",
"姜[黄姜]WP2026022800956",
"娃娃菜WP2026020200005",
"小白菜WP2026022800031",
"小米辣椒WP2026013000027",
"小葱WP2026013000029",
"山药(带皮)WP2026020200008",
"巨人笋",
"广东菜心WP2025120100014",
"木耳(干)[黑木耳,云耳]WP2026022801182",
"杏鲍菇WP2026022700030",
"松花蛋",
"松茸菌WP2025120100016",
"沙葱",
"海带(浸)[江白菜,昆布]WP2026022800035",
"牛腩WP2025110700043",
"猪五花肉WP2026020300048",
"猪腿肉WP2025110700040",
"玉米WP2025120100017",
"玉米糁(黄)WP2026022800038",
"番茄[西红柿]WP2026021000028",
"白吉饼WP2026013000024",
"笋",
"粉丝",
"紫甘蓝",
"红心萝卜[心里美]WP2026022800368",
"红提子WP2025111900006",
"红椒WP2026030300055",
"红洋葱WP2026030600054",
"红美人椒WP2026020300049",
"红薯",
"红薯粉条(袋)",
"羊排WP2025120300021",
"羊血WP2026013000038",
"胡萝卜WP2025110600008",
"芋头",
"花卷",
"芹菜WP2025111000065",
"苦菊",
"茄子(紫皮,长)WP2025110700024",
"茼蒿WP2026020200045",
"莲藕(带皮)",
"莴笋(鲜)[莴苣]WP2026020200009",
"菜花(白色)[花椰菜]",
"菠菜(鲜)[赤根菜]WP2026022800700",
"蒜WP2025111400003",
"蒜苗WP2026013000028",
"蒜薹(圆)",
"蒸鱼豉油WP2026013000032",
"薏米[薏仁米,苡米]WP2026022800037",
"西兰花[绿菜花]WP2025110700029",
"西葫芦",
"豆腐皮WP2025111000059",
"豆角",
"辣椒(红,小)WP2025111000066",
"辣椒(青,尖)WP2026022800504",
"醪糟",
"金针菇[(鲜)[智力菇]WP2026030600051",
"青线椒WP2026013000031",
"韭菜WP2026020200044",
"韭黄",
"馒头(代表值)WP2026030600056",
"香椿[香椿芽]WP2026022801086",
"香菇(鲜)[香蕈,冬菇]WP2026030600050",
"香菜WP2026013000030",
"马铃薯[土豆、洋芋]WP2026012900001",
"鸡全腿(带骨)",
"鸡翅(带骨)",
"鸡腿肉WP2025110700048",
"鸡腿(带骨)",
"鸡蛋WP2026013000039",
"麦芹",
"黄瓜(鲜)[胡瓜]WP2025110700031",
"黄豆芽WP2026020200042",
"黑袋子",
"黑鱼(整条鱼)WP2025110600012"
],
"class_to_idx": {
"三黄鸡": 0,
"上海青WP2026020200041": 1,
"冰草WP2026020900054": 2,
"刀豆": 3,
"北豆腐WP2025111900007": 4,
"味精WP2026013000034": 5,
"圆生菜WP2026020900053": 6,
"圆白菜[卷心菜,包菜]WP2025111000063": 7,
"基围虾WP2025110700019": 8,
"多宝鱼WP2025112600011": 9,
"大白菜(代表值)WP2026022800638": 10,
"大葱WP2026013000025": 11,
"姜[黄姜]WP2026022800956": 12,
"娃娃菜WP2026020200005": 13,
"小白菜WP2026022800031": 14,
"小米辣椒WP2026013000027": 15,
"小葱WP2026013000029": 16,
"山药(带皮)WP2026020200008": 17,
"巨人笋": 18,
"广东菜心WP2025120100014": 19,
"木耳(干)[黑木耳,云耳]WP2026022801182": 20,
"杏鲍菇WP2026022700030": 21,
"松花蛋": 22,
"松茸菌WP2025120100016": 23,
"沙葱": 24,
"海带(浸)[江白菜,昆布]WP2026022800035": 25,
"牛腩WP2025110700043": 26,
"猪五花肉WP2026020300048": 27,
"猪腿肉WP2025110700040": 28,
"玉米WP2025120100017": 29,
"玉米糁(黄)WP2026022800038": 30,
"番茄[西红柿]WP2026021000028": 31,
"白吉饼WP2026013000024": 32,
"笋": 33,
"粉丝": 34,
"紫甘蓝": 35,
"红心萝卜[心里美]WP2026022800368": 36,
"红提子WP2025111900006": 37,
"红椒WP2026030300055": 38,
"红洋葱WP2026030600054": 39,
"红美人椒WP2026020300049": 40,
"红薯": 41,
"红薯粉条(袋)": 42,
"羊排WP2025120300021": 43,
"羊血WP2026013000038": 44,
"胡萝卜WP2025110600008": 45,
"芋头": 46,
"花卷": 47,
"芹菜WP2025111000065": 48,
"苦菊": 49,
"茄子(紫皮,长)WP2025110700024": 50,
"茼蒿WP2026020200045": 51,
"莲藕(带皮)": 52,
"莴笋(鲜)[莴苣]WP2026020200009": 53,
"菜花(白色)[花椰菜]": 54,
"菠菜(鲜)[赤根菜]WP2026022800700": 55,
"蒜WP2025111400003": 56,
"蒜苗WP2026013000028": 57,
"蒜薹(圆)": 58,
"蒸鱼豉油WP2026013000032": 59,
"薏米[薏仁米,苡米]WP2026022800037": 60,
"西兰花[绿菜花]WP2025110700029": 61,
"西葫芦": 62,
"豆腐皮WP2025111000059": 63,
"豆角": 64,
"辣椒(红,小)WP2025111000066": 65,
"辣椒(青,尖)WP2026022800504": 66,
"醪糟": 67,
"金针菇[(鲜)[智力菇]WP2026030600051": 68,
"青线椒WP2026013000031": 69,
"韭菜WP2026020200044": 70,
"韭黄": 71,
"馒头(代表值)WP2026030600056": 72,
"香椿[香椿芽]WP2026022801086": 73,
"香菇(鲜)[香蕈,冬菇]WP2026030600050": 74,
"香菜WP2026013000030": 75,
"马铃薯[土豆、洋芋]WP2026012900001": 76,
"鸡全腿(带骨)": 77,
"鸡翅(带骨)": 78,
"鸡腿肉WP2025110700048": 79,
"鸡腿(带骨)": 80,
"鸡蛋WP2026013000039": 81,
"麦芹": 82,
"黄瓜(鲜)[胡瓜]WP2025110700031": 83,
"黄豆芽WP2026020200042": 84,
"黑袋子": 85,
"黑鱼(整条鱼)WP2025110600012": 86
},
"idx_to_class": {
"0": "三黄鸡",
"1": "上海青WP2026020200041",
"2": "冰草WP2026020900054",
"3": "刀豆",
"4": "北豆腐WP2025111900007",
"5": "味精WP2026013000034",
"6": "圆生菜WP2026020900053",
"7": "圆白菜[卷心菜,包菜]WP2025111000063",
"8": "基围虾WP2025110700019",
"9": "多宝鱼WP2025112600011",
"10": "大白菜(代表值)WP2026022800638",
"11": "大葱WP2026013000025",
"12": "姜[黄姜]WP2026022800956",
"13": "娃娃菜WP2026020200005",
"14": "小白菜WP2026022800031",
"15": "小米辣椒WP2026013000027",
"16": "小葱WP2026013000029",
"17": "山药(带皮)WP2026020200008",
"18": "巨人笋",
"19": "广东菜心WP2025120100014",
"20": "木耳(干)[黑木耳,云耳]WP2026022801182",
"21": "杏鲍菇WP2026022700030",
"22": "松花蛋",
"23": "松茸菌WP2025120100016",
"24": "沙葱",
"25": "海带(浸)[江白菜,昆布]WP2026022800035",
"26": "牛腩WP2025110700043",
"27": "猪五花肉WP2026020300048",
"28": "猪腿肉WP2025110700040",
"29": "玉米WP2025120100017",
"30": "玉米糁(黄)WP2026022800038",
"31": "番茄[西红柿]WP2026021000028",
"32": "白吉饼WP2026013000024",
"33": "笋",
"34": "粉丝",
"35": "紫甘蓝",
"36": "红心萝卜[心里美]WP2026022800368",
"37": "红提子WP2025111900006",
"38": "红椒WP2026030300055",
"39": "红洋葱WP2026030600054",
"40": "红美人椒WP2026020300049",
"41": "红薯",
"42": "红薯粉条(袋)",
"43": "羊排WP2025120300021",
"44": "羊血WP2026013000038",
"45": "胡萝卜WP2025110600008",
"46": "芋头",
"47": "花卷",
"48": "芹菜WP2025111000065",
"49": "苦菊",
"50": "茄子(紫皮,长)WP2025110700024",
"51": "茼蒿WP2026020200045",
"52": "莲藕(带皮)",
"53": "莴笋(鲜)[莴苣]WP2026020200009",
"54": "菜花(白色)[花椰菜]",
"55": "菠菜(鲜)[赤根菜]WP2026022800700",
"56": "蒜WP2025111400003",
"57": "蒜苗WP2026013000028",
"58": "蒜薹(圆)",
"59": "蒸鱼豉油WP2026013000032",
"60": "薏米[薏仁米,苡米]WP2026022800037",
"61": "西兰花[绿菜花]WP2025110700029",
"62": "西葫芦",
"63": "豆腐皮WP2025111000059",
"64": "豆角",
"65": "辣椒(红,小)WP2025111000066",
"66": "辣椒(青,尖)WP2026022800504",
"67": "醪糟",
"68": "金针菇[(鲜)[智力菇]WP2026030600051",
"69": "青线椒WP2026013000031",
"70": "韭菜WP2026020200044",
"71": "韭黄",
"72": "馒头(代表值)WP2026030600056",
"73": "香椿[香椿芽]WP2026022801086",
"74": "香菇(鲜)[香蕈,冬菇]WP2026030600050",
"75": "香菜WP2026013000030",
"76": "马铃薯[土豆、洋芋]WP2026012900001",
"77": "鸡全腿(带骨)",
"78": "鸡翅(带骨)",
"79": "鸡腿肉WP2025110700048",
"80": "鸡腿(带骨)",
"81": "鸡蛋WP2026013000039",
"82": "麦芹",
"83": "黄瓜(鲜)[胡瓜]WP2025110700031",
"84": "黄豆芽WP2026020200042",
"85": "黑袋子",
"86": "黑鱼(整条鱼)WP2025110600012"
},
"embedding_dim": 512,
"total_images": 2093,
"build_time": "2026-03-10T10:33:47.104848"
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -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")
}
@@ -0,0 +1,31 @@
package com.shuwei.dish.match.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.shuwei.dish.match.databinding.ListItemDropdownBinding
import com.shuwei.dish.match.model.DictType
import com.shuwei.dish.match.utils.ext.gone
import com.shuwei.dish.match.utils.ext.visible
class DropdownAdapter(var list: MutableList<DictType>) :
BaseQuickAdapter<DictType, DropdownAdapter.VH>(list) {
inner class VH(var binding: ListItemDropdownBinding) : QuickViewHolder(binding.root)
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
val inflater = LayoutInflater.from(context)
val binding = ListItemDropdownBinding.inflate(inflater, parent, false)
return VH(binding)
}
override fun onBindViewHolder(holder: VH, position: Int, item: DictType?) {
holder.binding.tvDropdown.text = item?.value
holder.binding.divider.run {
if (position == list.size - 1) gone() else visible()
}
}
}
@@ -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,100 @@
package com.shuwei.dish.match.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.shuwei.dish.match.R
import com.shuwei.dish.match.databinding.ListItemFoodListBinding
import com.shuwei.dish.match.model.FoodRecord
import com.shuwei.dish.match.utils.ext.gone
import com.shuwei.dish.match.utils.ext.visible
import java.text.DecimalFormat
/**
* 菜品列表通用 Adapter,合并了 DishShowAdapter 与 SamplingAdapter 的功能。
*
* @param list 数据列表
* @param mode 显示模式:
* - [DisplayMode.COOKING_MODE]:制作模式,支持空状态(虚线边框、隐藏统计行、灰色文字)
* - [DisplayMode.SAMPLING_MODE]:采样模式,始终显示统计行,重量为零时显示 `-`
*/
class FoodListAdapter(
list: MutableList<FoodRecord>,
private val mode: DisplayMode = DisplayMode.COOKING_MODE
) : BaseQuickAdapter<FoodRecord, FoodListAdapter.VH>(list) {
/** 显示模式枚举 */
enum class DisplayMode {
/** 制作模式(原 DishShowAdapter 逻辑) */
COOKING_MODE,
/** 采样模式(原 SamplingAdapter 逻辑) */
SAMPLING_MODE
}
/** item 主体点击回调 */
var onItemClick: ((position: Int) -> Unit)? = null
inner class VH(var binding: ListItemFoodListBinding) : QuickViewHolder(binding.root)
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
val binding = ListItemFoodListBinding.inflate(LayoutInflater.from(context), parent, false)
return VH(binding)
}
/**
* - 烹饪中:黑色文字、实线背景、显示"烹饪中"
* - 有累计重量:绿色文字、实线背景、显示累计统计
* - 空状态:灰色文字、虚线背景、隐藏统计行
*/
override fun onBindViewHolder(holder: VH, position: Int, item: FoodRecord?) {
holder.binding.run {
val isCooking = item!!.isCooking
val totalWeight = item.totalWeight ?: 0.0
val foodWeight = item.foodWeight ?: 0.0
clBlock.setOnClickListener {
onItemClick?.invoke(holder.bindingAdapterPosition)
}
tvDishName.text = item.foodName
// 烹饪中
if (isCooking) {
tvDishName.setTextColor(ContextCompat.getColor(holder.itemView.context, R.color.black))
clBlock.setBackgroundResource(R.drawable.shape_white_fb_15_corners)
tvDishCount.visible()
tvDishCount.text = "制作统计:-kg"
tvShowState.text = "烹饪中"
return@run
}
// 非烹饪中,制作模式
if (mode == DisplayMode.COOKING_MODE) {
if (totalWeight > 0.0) {
tvDishName.setTextColor(ContextCompat.getColor(holder.itemView.context, R.color.dish_green))
clBlock.setBackgroundResource(R.drawable.shape_white_fb_15_corners)
tvDishCount.visible()
tvDishCount.text = "累计统计:${df.format(totalWeight / 1000.0F)}kg(${item.count}次)"
tvShowState.text = "${df.format(foodWeight / 1000.0F)}kg"
} else {
tvDishName.setTextColor(ContextCompat.getColor(holder.itemView.context, R.color.black999))
clBlock.setBackgroundResource(R.drawable.shape_white_dash_15_corners)
tvDishCount.gone()
tvShowState.text = "-"
}
return@run
}
// 非烹饪中,采样模式
tvDishName.setTextColor(ContextCompat.getColor(holder.itemView.context, R.color.dish_green))
clBlock.setBackgroundResource(R.drawable.shape_white_fb_15_corners)
val realTotalWeight = if (totalWeight > 0.0) totalWeight else foodWeight
val showTotalWeight = if (realTotalWeight == 0.0) "-" else df.format(realTotalWeight / 1000.0F)
tvDishCount.text = "累计统计:${showTotalWeight}kg(${item.count ?: "-"}次)"
val showFoodWeight = if (foodWeight == 0.0) "-" else df.format(foodWeight / 1000.0F)
tvShowState.text = "${showFoodWeight}kg"
}
}
private val df = DecimalFormat("0.000")
}
@@ -0,0 +1,86 @@
package com.shuwei.dish.match.adapter
import android.content.Context
import android.content.res.ColorStateList
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.shuwei.dish.match.R
import com.shuwei.dish.match.databinding.ListItemFoodMaterialBinding
import com.shuwei.dish.match.model.GoodsItem
import com.shuwei.dish.match.utils.ext.gone
import com.shuwei.dish.match.utils.ext.roundedOneDecimalPlace
import com.shuwei.dish.match.utils.ext.visible
import androidx.core.graphics.toColorInt
import com.shuwei.dish.match.ui.MaterialTypeTool
class FoodMaterialAdapter(list: MutableList<GoodsItem>) :
BaseQuickAdapter<GoodsItem, FoodMaterialAdapter.VH>(list) {
/** item 主体点击回调 */
var onItemClick: ((position: Int) -> Unit)? = null
inner class VH(var binding: ListItemFoodMaterialBinding) : QuickViewHolder(binding.root)
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
val inflater = LayoutInflater.from(context)
val binding = ListItemFoodMaterialBinding.inflate(inflater, parent, false)
return VH(binding)
}
override fun onBindViewHolder(holder: VH, position: Int, item: GoodsItem?) {
holder.binding.run {
val data = item ?: return
clBlock.setOnClickListener {
onItemClick?.invoke(holder.bindingAdapterPosition)
}
tvDishName.text = data.goodsName
//if (data.isOriginalData) {
// tvDishName.text = data.goodsName
//} else {
// tvDishName.text = data.goodsName + "-${data.rawMaterialsType}"
//}
val showGoodsCode = (data.materCode ?: "").ifBlank { "-" }
tvGoodsCode.text = "溯源码:$showGoodsCode"
val materialText = MaterialTypeTool.getMaterialText(data.materialType)
tvDishType.text = "主辅材:$materialText"
//if (data.materialType == 1) "主辅材:主材" else if (data.materialType == 2) "主辅材:辅材" else ""
tvDishWeight.text =
if (data.useWeight == null || data.useWeight == 0.toDouble()) "" else "${data.useWeight!!.roundedOneDecimalPlace()}"
tvDishWeight.setTextColor(
ContextCompat.getColor(
context,
if (data.isSamplingPage) R.color.black999 else R.color.dish_green
)
)
ivOperateIcon.run {
if (data.isSamplingPage) gone() else visible()
}
// ivClearIcon.visible()
// ivClearIcon.setImageResource(
// if (data.isOriginalData) R.drawable.ic_dish_clear
// else R.drawable.ic_delete
// )
// isOriginalData 时根据是否有重量信息控制图标颜色:无重量染灰色,有重量恢复原色
if (data.isOriginalData) {
val hasWeight = data.useWeight != null && data.useWeight != 0.0
ivClearIcon.imageTintList = if (hasWeight) null
else ColorStateList.valueOf("#BFBFBF".toColorInt())
} else {
ivClearIcon.imageTintList = null
}
ivOperateIcon.setImageResource(
if (data.isSetFinished) R.drawable.ic_dish_selected
else R.drawable.ic_dish_unselected
)
clBlock.setBackgroundResource(
if (data.isClicked) R.drawable.shape_item_cook_dish
else R.drawable.shape_white_fb_15_corners
)
}
}
}
@@ -0,0 +1,245 @@
package com.shuwei.dish.match.adapter
import android.app.DatePickerDialog
import android.content.Context
import android.text.Editable
import android.text.InputType
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.graphics.toColorInt
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.shuwei.dish.match.R
import com.shuwei.dish.match.databinding.ListItemFormFieldBinding
import com.shuwei.dish.match.dialog.DropdownPopup
import com.shuwei.dish.match.model.FieldType
import com.shuwei.dish.match.model.FormField
import com.shuwei.dish.match.utils.ext.dp
import com.shuwei.dish.match.utils.ext.gone
import com.shuwei.dish.match.utils.ext.hideKeyboard
import com.shuwei.dish.match.utils.ext.visible
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import kotlin.math.min
/**
* 动态表单字段 Adapter,配合 FlexboxLayoutManager 实现两列自动换行布局
* 单一 item 布局,通过 visibility 控制 TEXT/INTEGER/DECIMAL/FIXED/DROPDOWN/DATE_PICKER 六种类型渲染
*
* @param fields 表单字段列表(hidden=false 的字段,由外部过滤后传入)
*/
class FormFieldAdapter(
fields: MutableList<FormField>
) : BaseQuickAdapter<FormField, FormFieldAdapter.VH>(fields) {
private val isoFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
private val displayDateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
inner class VH(val binding: ListItemFormFieldBinding) : QuickViewHolder(binding.root)
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
val binding = ListItemFormFieldBinding.inflate(LayoutInflater.from(context), parent, false)
return VH(binding)
}
override fun onBindViewHolder(holder: VH, position: Int, item: FormField?) {
item ?: return
val b = holder.binding
// 设置标签,必填项追加红色星号
b.tvLabel.text = buildLabelSpannable(item.label, item.required)
// 先全部隐藏,再按类型显示对应控件
b.flInputArea.gone()
b.etInput.gone()
b.flDropdown.gone()
b.flDatePicker.gone()
b.llChildren.gone()
// 移除旧的 TextWatcher,防止 RecyclerView 复用时错误触发
(b.etInput.tag as? TextWatcher)?.let { b.etInput.removeTextChangedListener(it) }
b.etInput.tag = null
when (item.type) {
FieldType.TEXT -> bindEditText(b, item, InputType.TYPE_CLASS_TEXT)
FieldType.INTEGER -> bindEditText(b, item, InputType.TYPE_CLASS_NUMBER)
FieldType.DECIMAL -> bindEditText(
b, item,
InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL or InputType.TYPE_NUMBER_FLAG_SIGNED
)
FieldType.FIXED -> bindFixed(b, item)
FieldType.DROPDOWN -> bindDropdown(b, item)
FieldType.DATE_PICKER -> bindDatePicker(b, item)
FieldType.CHILDREN -> bindChildren(b, item)
}
if (item.type == FieldType.CHILDREN) {
b.flInputArea.gone()
b.llChildren.visible()
} else {
b.flInputArea.visible()
b.llChildren.gone()
}
}
/** 绑定可编辑文本框(TEXT / NUMBER */
private fun bindEditText(b: ListItemFormFieldBinding, item: FormField, inputType: Int) {
b.etInput.visible()
b.etInput.isEnabled = true
b.etInput.inputType = inputType
b.etInput.hint = item.hint.ifBlank { item.label }
b.etInput.setBackgroundResource(R.drawable.bg_white_radius10_stroke2)
b.etInput.setText(item.value)
b.etInput.setSelection(b.etInput.text.length)
val watcher = object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable?) {
item.value = s?.toString() ?: ""
}
}
b.etInput.addTextChangedListener(watcher)
b.etInput.tag = watcher
}
/** 绑定固定值(不可编辑,灰色背景区分) */
private fun bindFixed(b: ListItemFormFieldBinding, item: FormField) {
b.etInput.visible()
b.etInput.isEnabled = false
b.etInput.inputType = InputType.TYPE_CLASS_TEXT
b.etInput.hint = ""
b.etInput.setBackgroundResource(R.drawable.bg_gray_radius10)
b.etInput.setText(item.value)
}
/** 绑定下拉选择框,点击时创建 DropdownPopup */
private fun bindDropdown(b: ListItemFormFieldBinding, item: FormField) {
b.flDropdown.visible()
b.tvDropdownValue.hint = item.hint.ifBlank { "请选择${item.label}" }
b.tvDropdownValue.text = item.value.ifBlank { null }
b.flDropdown.setOnClickListener { v ->
v.hideKeyboard()
val popHeight = min(item.options.size.coerceAtLeast(1), 4) * 71.dp
DropdownPopup(
context = context,
list = item.options.toMutableList(),
popWidth = v.width,
popHeight = popHeight
) { dictType ->
item.value = dictType.value ?: ""
b.tvDropdownValue.text = item.value
// 将 extraApiKeys 映射的 DictType 字段值写入 extraValues
item.extraValues.clear()
item.extraApiKeys.forEach { (apiKey, dictField) ->
item.extraValues[apiKey] = dictType[dictField]
}
// 触发选中回调
item.onDropdownSelected?.invoke(dictType)
}.also {
it.bgLayout = b.flDropdown
it.showAsDropDown(v)
}
}
}
/** 绑定日期选择器,点击时弹出 DatePickerDialog */
private fun bindDatePicker(b: ListItemFormFieldBinding, item: FormField) {
b.flDatePicker.visible()
b.tvDateValue.hint = item.hint.ifBlank { "请选择日期" }
b.tvDateValue.text = item.value.ifBlank { null }
b.flDatePicker.setOnClickListener { v ->
v.hideKeyboard()
val cal = Calendar.getInstance()
DatePickerDialog(
context,
{ _, year, month, dayOfMonth ->
val selected = Calendar.getInstance().apply {
set(year, month, dayOfMonth, 0, 0, 0)
set(Calendar.MILLISECOND, 0)
}
// value 存日期显示格式,供提交使用
item.value = displayDateFormat.format(selected.time)
b.tvDateValue.text = item.value
},
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH)
).show()
}
}
/** 构建带红色星号的必填标签 */
private fun buildLabelSpannable(label: String, required: Boolean): SpannableStringBuilder {
return SpannableStringBuilder().apply {
append(label)
if (required) {
val start = length
append(" *")
setSpan(
ForegroundColorSpan("#FFCC0000".toColorInt()),
start, length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
}
/** 绑定 CHILDREN 类型:渲染子列表(表头 + 嵌套 RecyclerView + 添加按钮) */
private fun bindChildren(b: ListItemFormFieldBinding, item: FormField) {
b.llChildren.visible()
b.tvAddChild.text = item.childAddLabel ?: "+ 添加"
// 初始化嵌套 RecyclerView
if (b.rvChildren.adapter == null) {
b.rvChildren.layoutManager = LinearLayoutManager(context)
}
b.rvChildren.adapter = createRowAdapter(b, item)
// 添加按钮点击
b.tvAddChild.setOnClickListener {
item.children?.let { template ->
val newRow = template.map { field ->
FormField(
label = field.label,
type = field.type,
apiKey = field.apiKey,
extraApiKeys = field.extraApiKeys,
required = field.required,
hint = field.hint,
options = field.options
)
}.toMutableList()
item.childrenRows.add(newRow)
b.rvChildren.adapter?.notifyItemInserted(item.childrenRows.size - 1)
}
}
}
/** 创建子列表行 Adapter */
private fun createRowAdapter(b: ListItemFormFieldBinding, item: FormField): IngredientRowAdapter {
return IngredientRowAdapter(
rows = item.childrenRows,
onDelete = onDelete@{ position ->
val adapter = b.rvChildren.adapter as? IngredientRowAdapter ?: return@onDelete
item.childrenRows.removeAt(position)
adapter.notifyItemRemoved(position)
if (position < item.childrenRows.size) {
adapter.notifyItemRangeChanged(position, item.childrenRows.size - position)
}
},
onChildClick = { _, _, _ ->
// 子字段值已直接更新到 row 的 FormField 中,无需额外操作
}
)
}
}
@@ -1,49 +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()
// materialType1主料 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
@@ -0,0 +1,40 @@
package com.shuwei.dish.match.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.shuwei.dish.match.R
import com.shuwei.dish.match.databinding.ListItemInboundIngredientBinding
import com.shuwei.dish.match.model.NutCleanInboundIngredientVO
import com.shuwei.dish.match.utils.ext.formatDecimal
/**
* 已入库净菜食材列表适配器
*/
class InboundIngredientAdapter(list: MutableList<NutCleanInboundIngredientVO>) :
BaseQuickAdapter<NutCleanInboundIngredientVO, InboundIngredientAdapter.VH>(list) {
inner class VH(var binding: ListItemInboundIngredientBinding) : QuickViewHolder(binding.root)
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
val binding = ListItemInboundIngredientBinding.inflate(
LayoutInflater.from(context), parent, false
)
return VH(binding)
}
override fun onBindViewHolder(holder: VH, position: Int, item: NutCleanInboundIngredientVO?) {
item ?: return
holder.binding.run {
tvIngredientName.text = item.ingredientName ?: "-"
val traceCode = item.traceCode.takeUnless { it.isNullOrBlank() } ?: "-"
tvTraceCode.text = "溯源码:$traceCode"
val stock = item.currentStock.takeUnless { it.isNullOrBlank() } ?: "0"
tvStock.text = "库存:${stock.formatDecimal()}kg"
}
}
}
@@ -0,0 +1,40 @@
package com.shuwei.dish.match.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.shuwei.dish.match.databinding.ListItemInboundIngredient2Binding
import com.shuwei.dish.match.model.NutCleanInboundIngredientVO
import com.shuwei.dish.match.utils.ext.formatDecimal
/**
* 已入库净菜食材列表适配器 V2
*/
class InboundIngredientV2Adapter(list: MutableList<NutCleanInboundIngredientVO>) :
BaseQuickAdapter<NutCleanInboundIngredientVO, InboundIngredientV2Adapter.VH>(list) {
inner class VH(var binding: ListItemInboundIngredient2Binding) :
QuickViewHolder(binding.root)
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
val binding = ListItemInboundIngredient2Binding.inflate(
LayoutInflater.from(context), parent, false
)
return VH(binding)
}
override fun onBindViewHolder(holder: VH, position: Int, item: NutCleanInboundIngredientVO?) {
item ?: return
holder.binding.run {
tvIngredientName.text = item.ingredientName ?: "-"
val traceCode = item.traceCode.takeUnless { it.isNullOrBlank() } ?: "-"
tvTraceCode.text = "溯源码:$traceCode"
val stock = item.currentStock.takeUnless { it.isNullOrBlank() } ?: "0"
tvStock.text = "库存:${stock.formatDecimal()}kg"
}
}
}
@@ -0,0 +1,149 @@
package com.shuwei.dish.match.adapter
import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.shuwei.dish.match.R
import com.shuwei.dish.match.databinding.ListItemIngredientRowBinding
import com.shuwei.dish.match.dialog.DropdownPopup
import com.shuwei.dish.match.model.FormField
import com.shuwei.dish.match.utils.ext.dp
import com.shuwei.dish.match.utils.ext.hideKeyboard
/**
* 食材行 Adapter,用于「包含食材」子列表的嵌套渲染
* @param context Activity 上下文
* @param rows 每行包含多个 FormField,对应溯源码、食材名称、分类、用量
* @param onDelete 删除行回调
* @param onChildClick 子字段点击回调(如下拉框点击)
*/
class IngredientRowAdapter(
rows: MutableList<MutableList<FormField>>,
private val onDelete: (Int) -> Unit,
private val onChildClick: (Int, Int, FormField) -> Unit
) : BaseQuickAdapter<MutableList<FormField>, IngredientRowAdapter.VH>(rows) {
inner class VH(val binding: ListItemIngredientRowBinding) : QuickViewHolder(binding.root)
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
val binding = ListItemIngredientRowBinding.inflate(LayoutInflater.from(context), parent, false)
return VH(binding)
}
override fun onBindViewHolder(holder: VH, position: Int, item: MutableList<FormField>?) {
item ?: return
val b = holder.binding
// 假设 children 模板顺序:[溯源码(TEXT), 食材名称(DROPDOWN), 分类(DROPDOWN), 用量(TEXT)]
val traceCodeField = item.getOrNull(0)
val materNameField = item.getOrNull(1)
val classifyField = item.getOrNull(2)
val amountField = item.getOrNull(3)
// 溯源码 - TEXT
traceCodeField?.let { field ->
b.etTraceCode.setText(field.value)
b.etTraceCode.hint = field.hint.ifBlank { field.label }
(b.etTraceCode.tag as? TextWatcher)?.let { b.etTraceCode.removeTextChangedListener(it) }
val watcher = object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable?) {
field.value = s?.toString() ?: ""
}
}
b.etTraceCode.addTextChangedListener(watcher)
b.etTraceCode.tag = watcher
}
// 食材名称
materNameField?.let { field ->
when (field.type) {
com.shuwei.dish.match.model.FieldType.FIXED -> {
b.flMaterName.setOnClickListener { v -> v.hideKeyboard() }
b.flMaterName.isClickable = false
b.tvMaterName.text = field.value
}
else -> {
b.tvMaterName.hint = field.hint.ifBlank { "请选择${field.label}" }
b.tvMaterName.text = field.value.ifBlank { null }
b.flMaterName.setOnClickListener { v ->
v.hideKeyboard()
showDropdown(b.flMaterName, field, b.tvMaterName, holder.getAdapterPosition(), 1)
}
}
}
}
// 分类 - DROPDOWN
classifyField?.let { field ->
b.tvClassify.hint = field.hint.ifBlank { "请选择${field.label}" }
b.tvClassify.text = field.value.ifBlank { null }
b.flClassify.setOnClickListener { v ->
v.hideKeyboard()
showDropdown(b.flClassify, field, b.tvClassify, holder.getAdapterPosition(), 2)
}
}
// 用量 - TEXT
amountField?.let { field ->
b.etAmount.setText(field.value)
b.etAmount.hint = field.hint.ifBlank { field.label }
(b.etAmount.tag as? TextWatcher)?.let { b.etAmount.removeTextChangedListener(it) }
val watcher = object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable?) {
field.value = s?.toString() ?: ""
}
}
b.etAmount.addTextChangedListener(watcher)
b.etAmount.tag = watcher
}
// 删除按钮
b.tvRemove.setOnClickListener {
val pos = holder.layoutPosition
if (pos != RecyclerView.NO_POSITION) {
onDelete(pos)
}
}
}
/** 显示下拉弹出框 */
private fun showDropdown(
anchorView: ViewGroup,
field: FormField,
valueView: TextView,
rowPosition: Int,
childIndex: Int
) {
DropdownPopup(
context = context,
list = field.options.toMutableList(),
popWidth = anchorView.width,
popHeight = kotlin.math.min(field.options.size.coerceAtLeast(1), 4) * 50.dp
) { dictType ->
field.value = dictType.value ?: ""
valueView.text = field.value
// 将 extraApiKeys 映射值写入 extraValues
field.extraValues.clear()
field.extraApiKeys.forEach { (apiKey, dictField) ->
field.extraValues[apiKey] = dictType[dictField]
}
field.onDropdownSelected?.invoke(dictType)
// 回调通知外部更新
onChildClick(rowPosition, childIndex, field)
}.also {
it.bgLayout = anchorView
it.showAsDropDown(anchorView)
}
}
}
@@ -0,0 +1,36 @@
package com.shuwei.dish.match.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.shuwei.dish.match.databinding.ListItemFood2Binding
import com.shuwei.dish.match.model.NutFoodOptionVO
/**
* 餐品列表适配器
*/
class MealListAdapter(list: MutableList<NutFoodOptionVO>) :
BaseQuickAdapter<NutFoodOptionVO, MealListAdapter.VH>(list) {
inner class VH(var binding: ListItemFood2Binding) : QuickViewHolder(binding.root)
override fun onBindViewHolder(
holder: VH,
position: Int,
item: NutFoodOptionVO?
) {
holder.binding.tvDishInfo.text = item?.foodName
}
override fun onCreateViewHolder(
context: Context,
parent: ViewGroup,
viewType: Int
): VH {
val inflater = LayoutInflater.from(context)
val binding = ListItemFood2Binding.inflate(inflater, parent, false)
return VH(binding)
}
}
@@ -1,54 +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 SamplingAdapter(list: MutableList<FoodRecord>) :
BaseQuickAdapter<FoodRecord, SamplingAdapter.VH>(list) {
inner class VH(var binding: ListItemDishBinding) : QuickViewHolder(binding.root)
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
val inflater = LayoutInflater.from(context)
val binding = ListItemDishBinding.inflate(inflater, parent, false)
return VH(binding)
}
override fun onBindViewHolder(holder: VH, position: Int, item: FoodRecord?) {
holder.binding.run {
val isCooking = item!!.isCooking
clBlock.setBackgroundResource(R.drawable.shape_white_fb_15_corners)
val totalWeight = item!!.totalWeight ?: 0.toDouble()
tvDishName.run {
text = item!!.foodName
setTextColor(
ContextCompat.getColor(
holder.itemView.context,
if (isCooking) R.color.black else R.color.dish_green
)
)
}
tvDishCount.visible()
if (isCooking) {
tvDishCount.text = "制作统计:-kg"
tvShowState.text = "烹饪中"
} else {
val useWeight = if (totalWeight > 0.toDouble()) totalWeight else (item.foodWeight ?: 0.toDouble())
tvDishCount.text = "累计统计:${df.format(useWeight / 1000.0F)}kg(${item.count}次)"
tvShowState.text = "${df.format((item.foodWeight ?: 0.toDouble()) / 1000.0F)}kg"
}
}
}
val df = DecimalFormat("0.000")
}
@@ -0,0 +1,104 @@
package com.shuwei.dish.match.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.shuwei.dish.match.R
import com.shuwei.dish.match.databinding.ListItemScaleRowBinding
import com.shuwei.dish.match.utils.WeightUtil
/**
* 线性列表秤数据 Adapter
* 用于 SlaveActivity 非22/18格子设备的秤列表展示
* 通过 updateItem / updateName / removeByAddress 同步更新,避免 submitList 的
* AsyncListDiffer 异步窗口期导致点击事件丢失
*/
class ScaleRowAdapter : BaseQuickAdapter<ScaleRowAdapter.ScaleItem, ScaleRowAdapter.VH>() {
/**
* 秤数据条目
* @param address 秤地址
* @param weight 重量(克)
* @param state 状态码
* @param name 调料名称,未配置时为空
*/
data class ScaleItem(val address: Int, val weight: Double, val state: Int, val name: String = "")
/** item 点击回调 */
var onItemClick: ((ScaleItem) -> Unit)? = null
inner class VH(val b: ListItemScaleRowBinding) : QuickViewHolder(b.root)
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
return VH(ListItemScaleRowBinding.inflate(LayoutInflater.from(context), parent, false))
}
override fun onBindViewHolder(holder: VH, position: Int, item: ScaleItem?) {
item ?: return
holder.b.tvScaleLabel.text = "${item.address}"
holder.b.tvName.text = item.name.ifEmpty { "-" }
holder.b.tvWeight.text = "${item.weight} g"
holder.b.tvState.text = WeightUtil.getStateStr(item.state)
if (item.state == WeightUtil.STATE_OVER_WEIGHT) {
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell_over_weight)
val white = ContextCompat.getColor(holder.b.root.context, R.color.white)
holder.b.tvScaleLabel.setTextColor(white)
holder.b.tvName.setTextColor(white)
holder.b.tvWeight.setTextColor(white)
holder.b.tvState.setTextColor(white)
} else {
holder.b.root.setBackgroundResource(R.drawable.shape_scale_cell)
holder.b.tvScaleLabel.setTextColor(ContextCompat.getColor(holder.b.root.context, R.color.black))
holder.b.tvName.setTextColor(ContextCompat.getColor(holder.b.root.context, R.color.black))
holder.b.tvWeight.setTextColor(ContextCompat.getColor(holder.b.root.context, R.color.home_title))
holder.b.tvState.setTextColor(ContextCompat.getColor(holder.b.root.context, R.color.home_sub_title))
}
// 点击时通过 bindingAdapterPosition 取最新数据,避免闭包捕获过期 item
holder.b.root.setOnClickListener {
val pos = holder.bindingAdapterPosition
if (pos != RecyclerView.NO_POSITION) {
items.getOrNull(pos)?.let { onItemClick?.invoke(it) }
}
}
}
/**
* 同步更新单条秤数据:存在则定点刷新,不存在则按 address 升序插入
* 使用 set/add 替代 submitList,消除 AsyncListDiffer 异步窗口期
* @param item 最新秤数据
*/
fun updateItem(item: ScaleItem) {
val idx = items.indexOfFirst { it.address == item.address }
if (idx >= 0) {
set(idx, item)
} else {
// 找到按 address 升序的插入位置
val insertPos = items.indexOfFirst { it.address > item.address }
.let { if (it < 0) items.size else it }
add(insertPos, item)
}
}
/**
* 同步更新指定地址的调料名称
* @param address 秤地址
* @param name 新名称
*/
fun updateName(address: Int, name: String) {
val idx = items.indexOfFirst { it.address == address }
if (idx >= 0) set(idx, items[idx].copy(name = name))
}
/**
* 同步移除指定地址的条目
* @param address 秤地址
*/
fun removeByAddress(address: Int) {
val idx = items.indexOfFirst { it.address == address }
if (idx >= 0) removeAt(idx)
}
}
@@ -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=0margin大),其余为第2-3行(viewType=1margin小) */
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)
}
}
@@ -1,134 +0,0 @@
//package com.shuwei.dish.match.adapter
//
//import android.annotation.SuppressLint
//import android.widget.TextView
//import androidx.recyclerview.widget.GridLayoutManager
//import androidx.recyclerview.widget.RecyclerView
//import com.shuwei.dish.match.base.BaseActivity
//import com.shuwei.dish.match.dialog.BottomDialog2
//import com.shuwei.dish.match.entity.SeasoningEntity
//import com.shuwei.dish.match.ui.DeviceSettingActivity
//import com.shuwei.dish.match.ui.SubmitDishActivity
//import com.shuwei.dish.match.utils.DataUtil
//
//object SeasoningCellTool {
// private val TAG = "SeasoningCellTool"
//
// private val list = mutableListOf<SeasoningEntity>()
// private lateinit var activity: BaseActivity
// private var pageType: Int = 0
//
// @SuppressLint("StaticFieldLeak")
// private lateinit var cellAdapter: TextCellAdapter
//
// @SuppressLint("NotifyDataSetChanged")
// fun loadData(
// activity: BaseActivity,
// initList: MutableList<SeasoningEntity>? = null,
// recyclerView: RecyclerView,
// tvCell: TextView,
// pageType: Int = 0
// ) {
// this.activity = activity
// this.pageType = pageType
// list.clear()
// val tempList = buildData(initList, pageType)
// list.addAll(tempList)
// recyclerView.run {
// if (adapter == null) {
// layoutManager = GridLayoutManager(
// activity,
// 3,
// GridLayoutManager.VERTICAL,
// false
// )
// cellAdapter = TextCellAdapter(list).apply {
// onCellClick = { position ->
// val currentAddress = DataUtil.getWeighAddressArray().get(position)
// BottomDialog2(
// weighIndex = position,
// weighAddress = currentAddress,
// clickName = list[position].goodsName
// ).show(activity) { item ->
// list[position].let { current ->
// syncItem(current, item)
// //3-调料
// current.materialType = 3
// current.sort = position
// }
// notifyItemChanged(position)
// if (position == 14) {
// syncItem(list[10], list[14])
// syncItem(list[11], list[14])
// syncItem(list[13], list[14])
// TextCellAdapter.loadCell(tvCell, list[14])
// notifyItemChanged(10)
// notifyItemChanged(11)
// notifyItemChanged(13)
// notifyItemChanged(14)
// }
// if (activity is DeviceSettingActivity) {
// //activity.list = list
// activity.saveSeasoning(list[position])
// }
// }
// }
// }
// adapter = cellAdapter
// } else {
// cellAdapter.notifyDataSetChanged()
// }
// if (activity is SubmitDishActivity) {
// activity.updateSeasoningList(list)
// }
// }
// if (pageType == 1) {
// tvCell.setOnClickListener {
// cellAdapter.onCellClick?.invoke(14)
// }
// }
// TextCellAdapter.loadCell(tvCell, list[list.size - 1])
// }
//
// private fun buildData(
// initList: MutableList<SeasoningEntity>?,
// pageType: Int = 0
// ): MutableList<SeasoningEntity> {
// val list = mutableListOf<SeasoningEntity>()
// repeat(15) {
// list.add(SeasoningEntity().apply { this.pageType = pageType })
// }
// if (initList.isNullOrEmpty().not()) {
// initList.forEach {
// if (it.sort < list.size) {
// list[it.sort] = it.apply { this.pageType = pageType }
// }
// }
// var lastItem = initList.firstOrNull { it.sort == 14 }
// lastItem = lastItem ?: list[list.size - 1]
// list[10] = lastItem
// list[11] = lastItem
// list[13] = lastItem
// }
// return list
// }
//
// private fun syncItem(item: SeasoningEntity, newItem: SeasoningEntity) {
// item.run {
// goodsId = newItem.goodsId
// goodsName = newItem.goodsName
// goodsOrRelationCode = newItem.goodsOrRelationCode
// relateionType = newItem.relateionType
// materialType = newItem.materialType
// allEdible = newItem.allEdible
// useWeight = newItem.useWeight
// popularName = newItem.popularName
// canteenId = newItem.canteenId
// relateionType_dictText = newItem.relateionType_dictText
//
// foodId = newItem.foodId
// sort = newItem.sort
// }
// }
//
//}
@@ -7,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)
}
@@ -0,0 +1,53 @@
package com.shuwei.dish.match.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.shuwei.dish.match.R
import com.shuwei.dish.match.databinding.ListItemTaskBinding
import com.shuwei.dish.match.model.NutComboTaskVO
/**
* 组配任务列表适配器
*/
class TaskAdapter(list: MutableList<NutComboTaskVO>) :
BaseQuickAdapter<NutComboTaskVO, TaskAdapter.VH>(list) {
inner class VH(var binding: ListItemTaskBinding) : QuickViewHolder(binding.root)
override fun onBindViewHolder(
holder: VH,
position: Int,
item: NutComboTaskVO?
) {
holder.binding.apply {
tvTaskNo.text = "任务编号:${item?.taskNo}"
tvTargetDish.text = item?.targetDish
tvSpec.text = item?.spec
tvPlanDate.text = "计划日期:${item?.planDate}"
tvPortions.text = "总份数:${item?.portions}"
tvOwnerName.text = "负责人:${item?.ownerName}"
// 状态文本映射
val statusText = when (item?.comboStatus) {
0 -> "待组配"
1 -> "组配中"
2 -> "已完成"
else -> "未知"
}
tvStatus.text = statusText
}
}
override fun onCreateViewHolder(
context: Context,
parent: ViewGroup,
viewType: Int
): VH {
val inflater = LayoutInflater.from(context)
val binding = ListItemTaskBinding.inflate(inflater, parent, false)
return VH(binding)
}
}
@@ -0,0 +1,96 @@
package com.shuwei.dish.match.adapter
import android.content.Context
import android.content.res.ColorStateList
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.graphics.toColorInt
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.shuwei.dish.match.R
import com.shuwei.dish.match.databinding.ListItemTaskDetailBinding
import com.shuwei.dish.match.model.NutComboTaskItemDetail
import com.shuwei.dish.match.ui.MaterialTypeTool
import com.shuwei.dish.match.utils.ext.formatDecimal
import com.shuwei.dish.match.utils.ext.gone
import com.shuwei.dish.match.utils.ext.visible
import java.math.BigDecimal
/**
* 组配任务详情食材列表适配器
* Adapter for displaying ingredient list in task details
*/
class TaskDetailAdapter(list: MutableList<NutComboTaskItemDetail>) :
BaseQuickAdapter<NutComboTaskItemDetail, TaskDetailAdapter.VH>(list) {
// ViewHolder class for holding the view bindings
inner class VH(var binding: ListItemTaskDetailBinding) : QuickViewHolder(binding.root)
/**
* Called by RecyclerView to display the item at the specified position.
* This method updates the ViewHolder's contents with the item's data.
*
* @param holder The ViewHolder to be updated
* @param position The position of the item in the adapter
* @param item The NutComboTaskItemDetail to be displayed
*/
override fun onBindViewHolder(
holder: VH,
position: Int,
item: NutComboTaskItemDetail?
) {
item ?: return
holder.binding.apply {
// Set ingredient name
tvIngredientName.text = item.ingredientName
// 食材类别
// val classText = when (item.ingredientClass) {
// 1 -> "主材"
// 2 -> "辅材"
// 3 -> "调料"
// else -> "-"
// }
tvIngredientClass.text = MaterialTypeTool.getMaterialText(item.ingredientClass ?: 0)
val unit = item.unit ?: "g"
tvPerPortionQty.text = "每份用量:${item.perPortionQty.formatDecimal()}${unit}"
tvActualQty.run {
if (item.actualQty.isNullOrBlank()) {
setTextColor("#999999".toColorInt())
text = "-"
} else {
setTextColor("#00BC71".toColorInt())
text = item.actualQty.formatDecimal() + unit
}
}
// tvTotalQty.text = "合计用量:${item?.totalQty.formatDecimal()}${unit}"
tvTraceCode.visible()
tvTraceCode.text = "溯源码:${(item.traceCode ?: "").ifBlank { "-" }}"
// val hasWeight = item.actualQty.isNullOrBlank().not()
// ivClearIcon.imageTintList = if (hasWeight) null else ColorStateList.valueOf("#BFBFBF".toColorInt())
ivOperateIcon.setImageResource(
if (item.isSetFinished == true) R.drawable.ic_dish_selected
else R.drawable.ic_dish_unselected
)
root.setBackgroundResource(
if (item.isClicked == true) R.drawable.shape_item_cook_dish
else R.drawable.shape_white_fb_15_corners
)
}
}
override fun onCreateViewHolder(
context: Context,
parent: ViewGroup,
viewType: Int
): VH {
val inflater = LayoutInflater.from(context)
val binding = ListItemTaskDetailBinding.inflate(inflater, parent, false)
return VH(binding)
}
}
@@ -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)
// )
// }
// }
// }
//
//}
@@ -0,0 +1,58 @@
package com.shuwei.dish.match.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.shuwei.dish.match.R
import com.shuwei.dish.match.databinding.ListItemVectorCollectionBinding
import com.shuwei.dish.match.model.FoodCollectionBean
import com.shuwei.dish.match.utils.ext.load
class VectorCollectionAdapter (var list: MutableList<FoodCollectionBean>) :
BaseQuickAdapter<FoodCollectionBean, VectorCollectionAdapter.VH>(list) {
inner class VH(var binding: ListItemVectorCollectionBinding) : QuickViewHolder(binding.root)
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
val inflater = LayoutInflater.from(context)
val binding = ListItemVectorCollectionBinding.inflate(inflater, parent, false)
return VH(binding)
}
override fun onBindViewHolder(holder: VH, position: Int, item: FoodCollectionBean?) {
val binding = holder.binding
item?.let {
binding.ivFinish.visibility = if (it.isFinish) View.VISIBLE else View.GONE
binding.ivDelete.visibility = if (it.isShowCamera) View.GONE else View.VISIBLE
binding.imageView.run {
if (it.isShowCamera) {
scaleType = ImageView.ScaleType.CENTER
setImageResource(R.drawable.ic_camera_default)
} else {
//scaleType = ImageView.ScaleType.FIT_CENTER
scaleType = ImageView.ScaleType.CENTER_CROP
//setImageURI(it.imageUri)
//setImageBitmap(it.bitmap)
if (it.imageUri!=null) {
setImageURI(it.imageUri)
} else {
load(it.imageFile)
}
// it.bitmap?.let { bitmap ->
// GlideUtils.loadRoundCornerWitBitmap(
// context,
// url = bitmap,
// imageView = this,
// radius = 8.dp
// )
// }
}
}
}
}
}
@@ -1,6 +1,7 @@
package com.shuwei.dish.match.base
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.os.Handler
import android.os.Looper
@@ -9,94 +10,82 @@ 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
import androidx.core.content.ContextCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import com.shuwei.dish.match.R
import com.shuwei.dish.match.databinding.ActivityBaseBinding
import com.shuwei.dish.match.dialog.Loading
import com.shuwei.dish.match.http.HttpUtil
import com.shuwei.dish.match.http.UrlConfig
import com.shuwei.dish.match.ui.HomeActivity.Companion.TAG
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
import com.shuwei.dish.match.utils.ext.put
import com.shuwei.dish.match.utils.ext.toast
import com.shuwei.dish.match.utils.ext.visible
import java.time.LocalDateTime
import java.time.ZoneId
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
private var launcher: ActivityResultLauncher<Intent>? = null
private var launchCallback: ((Intent?) -> Unit)? = null
public fun launch(cls: Class<*>, launchCallback: (Intent?) -> Unit) {
this.launchCallback = launchCallback
launcher?.launch(Intent(this, cls))
}
public fun launch(intent: Intent, launchCallback: (Intent?) -> Unit) {
this.launchCallback = launchCallback
launcher?.launch(intent)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// 提前隐藏系统栏,避免窗口创建时导航栏闪烁
hideSystemBars()
// 主设备竖屏,子设备横屏
// requestedOrientation = if (GlobalData.deviceRole == DeviceRole.MASTER)
// ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
// else
// ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
ActivityManager.addActivity(this)
binding = ActivityBaseBinding.inflate(layoutInflater)
if (this !is InitActivity) {
if (this !is InitActivity || GlobalData.deviceRole == DeviceRole.SLAVE) {
binding.root.setBackgroundColor(ContextCompat.getColor(this, R.color.bg_color))
}
setContentView(binding.root)
statusBarDarkFont(enable = false)
launcher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == RESULT_OK) {
launchCallback?.invoke(result.data)
}
}
// window.setDecorFitsSystemWindows(false) // 启用 Edge-to-Edge
// window.insetsController?.apply {
// hide(WindowInsets.Type.statusBars()) // 隐藏状态栏
// systemBarsBehavior =
// WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE // 滑动时临时显示
// }
// 主设备垂直 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
val color = ContextCompat.getColor(
this, if (enable) R.color.black else R.color.white
)
binding.tvLeftTime.setTextColor(color)
binding.tvRightTime.setTextColor(color)
@@ -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,8 +128,7 @@ 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]
@@ -161,20 +153,127 @@ open class BaseActivity : AppCompatActivity() {
handler.removeCallbacks(updateTask)
}
fun showLoading() {
Loading.show(this)
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)
}, 500)
}
/**
* 在主线程延迟执行任务,供子类使用
* @param delayMs 延迟毫秒数
* @param block 待执行的任务
*/
protected fun postDelayed(delayMs: Long, block: () -> Unit) {
handler.postDelayed(block, delayMs)
}
val netViewModel: NetViewModel by viewModels()
val dbViewModel: DbViewModel by viewModels()
private var singlePermissionCallback: ((isGranted: Boolean) -> Unit)? = null
private var multiplePermissionsCallback: ((isGranted: Boolean) -> Unit)? = null
private var activityCallback: ((intent: Intent?) -> Unit)? = null
fun requestMultiplePermissions(
permissions: Array<String>,
callback: (isGranted: Boolean) -> Unit
) {
this.multiplePermissionsCallback = callback
requestMultiplePermissionsLauncher.launch(permissions)
}
fun requestPermission(permission: String, callback: (isGranted: Boolean) -> Unit) {
this.singlePermissionCallback = callback
requestPermissionLauncher.launch(permission)
}
private val requestMultiplePermissionsLauncher = registerForActivityResult(
ActivityResultContracts.RequestMultiplePermissions()
) { permissions ->
var isGranted = true
permissions.entries.forEach {
if (!it.value) {
isGranted = false
}
}
multiplePermissionsCallback?.invoke(isGranted)
}
// 权限请求回调
private val requestPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted ->
singlePermissionCallback?.invoke(isGranted)
}
fun startActivity(intent: Intent, callback: (Intent?) -> Unit) {
this.activityCallback = callback
startActivityLauncher.launch(intent)
}
// activity页面返回的回调
private val startActivityLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
activityCallback?.invoke(it.data)
}
/**
* 窗口焦点变化时回调
* 场景:弹出 Dialog 后焦点丢失,Dialog 消失后焦点恢复,此时需重新隐藏系统栏,
* 避免系统栏在 Dialog 关闭后意外"复活"
*/
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) {
hideSystemBars()
}
}
/**
* 隐藏状态栏和导航栏
* 使用 WindowInsetsControllerCompatAndroidx 推荐方式,向下兼容性好)
* - setDecorFitsSystemWindows 只在首次调用时设置,避免反复触发布局重绘
* (重绘会导致 RecyclerView 滑动时抛出 "view is not a child, cannot hide" 异常)
* - 每次调用仍重新执行 hide(),保证系统栏在滑出后能被重新隐藏
*/
private var systemBarsConfigured = false
private fun hideSystemBars() {
if (!systemBarsConfigured) {
// 只执行一次:允许布局延伸到系统栏区域
WindowCompat.setDecorFitsSystemWindows(window, false)
systemBarsConfigured = true
}
WindowInsetsControllerCompat(window, window.decorView).apply {
hide(WindowInsetsCompat.Type.systemBars())
systemBarsBehavior =
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}
}
fun hideKeyboard() {
KeyboardUtil.hideKeyboard(binding.root)
}
}
@@ -1,14 +1,22 @@
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.scale.ScaleDeviceConfig
import com.shuwei.dish.match.utils.AppUtil
import com.shuwei.dish.match.utils.BootReceiver
import com.shuwei.dish.match.utils.CrashHandler
import com.shuwei.dish.match.utils.SpTool
import com.shuwei.dish.match.utils.WeightUtil
class BaseApp : Application() {
@@ -17,31 +25,76 @@ class BaseApp : Application() {
override fun onCreate() {
super.onCreate()
instance = this
// 读取本地保存的环境地址,覆盖默认值
val savedBaseUrl = SpTool.baseUrl
if (savedBaseUrl.isNotEmpty()) {
GlobalData.appBaseUrl = savedBaseUrl
}
CrashHandler.init(this)
GlobalData.deviceId = AppUtil.getUDID(this)
// val deviceId = if (BuildConfig.IS_TEST_DEVICE) ScaleDeviceConfig.DEVICE_ID_2 else AppUtil.getUDID(this)
// Log.d(TAG, "onCreate: deviceId=$deviceId, isTestDevice=${BuildConfig.IS_TEST_DEVICE}")
// GlobalData.deviceId = deviceId
//
// // 根据设备 ID 判断角色:指定 ID 为主设备,其余为子设备
// // 主设备是/dev/ttyS7,子设备是/dev/ttyS4
// if (deviceId == ScaleDeviceConfig.DEVICE_ID_2) {
// GlobalData.deviceRole = DeviceRole.MASTER
// Weigher2.setDevicePort("/dev/ttyS7")
// } else {
// GlobalData.deviceRole = DeviceRole.SLAVE
// Weigher2.setDevicePort("/dev/ttyS4")
// }
// Log.d(TAG, "设备角色: ${GlobalData.deviceRole}")
//
// // 启动秤服务(主设备多启动发现+聚合,子设备只启动服务端+注册)
// ScaleServiceManager.start(this)
//
// // 初始化秤,进程级生命周期管理:最后一个 Activity 销毁时才停止读取
WeightUtil.init()
WeightUtil.getWeight()
WeightUtil.startContinuousRead()
registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
private var activityCount = 0
override fun onActivityCreated(a: Activity, b: Bundle?) { activityCount++ }
override fun onActivityDestroyed(a: Activity) {
if (--activityCount <= 0) {
WeightUtil.stopContinuousRead()
}
}
override fun onActivityStarted(a: Activity) {}
override fun onActivityResumed(a: Activity) {}
override fun onActivityPaused(a: Activity) {}
override fun onActivityStopped(a: Activity) {}
override fun onActivitySaveInstanceState(a: Activity, b: Bundle) {}
})
// GlobalData.deviceId = "39a7abdd06b3c7ab"
val filter = IntentFilter(Intent.ACTION_BOOT_COMPLETED)
registerReceiver(BootReceiver(), filter)
// ObjectBox.init(this)
}
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
}
}
@@ -18,8 +18,16 @@ abstract class BaseFragment<VB : ViewBinding> : Fragment() {
abstract fun inflateBinding(inflater: LayoutInflater, container: ViewGroup?): VB
abstract fun initialize()
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initialize()
}
}
@@ -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
}
@@ -0,0 +1,44 @@
package com.shuwei.dish.match.base
/**
* 设备角色枚举
* MASTER:主设备,负责汇聚所有设备的秤数据并展示大屏界面
* SLAVE:子设备,负责推送本机秤数据给主设备
*/
enum class DeviceRole { MASTER, SLAVE }
object GlobalData {
var appBaseUrl: String = LOCAL_BASE_URL
/**
* 具体业务 BaseUrl
*/
// const val LOCAL_BASE_URL = "http://192.168.1.201:14801"
const val LOCAL_BASE_URL = "http://192.168.10.101:24801"
const val TEST_BASE_URL = "https://dev.yixiong-tech.com:8081"
// const val TEST_BASE_URL = "https://dev.yixiong-tech.com:8083"
const val PROD_BASE_URL = "https://api.dm.yixiong-tech.com:8443"
/**
* 设备id
*/
var deviceId: String = ""
/**
* 当前设备角色,启动时从 SpTool 读取,默认为 SLAVE
*/
var deviceRole: DeviceRole = DeviceRole.SLAVE
var userName = "张三"
}
/**
*
*/
object GlobalKey {
const val KEY_EQUIPMENT_INFO = "equipmentInfo"
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
}
@@ -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,17 @@ 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
var matchingConstituteInfoList: MutableList<CookFoodGoodsEntity>? = null
@Ignore
var foodConstituteList: MutableList<CookFoodGoodsEntity>? = null
constructor() : this(foodId = "") // 必需的空构造
}
}
@@ -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
@@ -43,10 +43,14 @@ class CookFoodGoodsEntity(
*/
var materialType: Int = 0,
// /**
// * 物品 是否全部可食:1-全部可食,0-部分可食,默认全部
// */
// var allEdible: Int = 1,
/**
* 物品 是否全部可食1-全部可食0-部分可食默认全部
* 物品 是否全部可食true-全部可食false-部分可食默认全部
*/
var allEdible: Int = 1,
var allEdible: Boolean = true,
/**
* 物品 用料重量
@@ -59,23 +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
}
/**
* 转换为 GoodsItem用于 UI DishPartAdapterPrepareFoodActivity
*/
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
)
}
@@ -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
@@ -36,11 +35,14 @@ data class SeasoningEntity(
*/
var materialType: Int = 3,
// /**
// * 物品 是否全部可食:1-全部可食,0-部分可食,默认全部
// */
// var allEdible: Int = 1,
/**
* 物品 是否全部可食1-全部可食0-部分可食默认全部
* 物品 是否全部可食true-全部可食false-部分可食默认全部
*/
var allEdible: Int = 1,
var allEdible: Boolean = true,
/**
* 物品 用料重量
*/
@@ -52,18 +54,22 @@ 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-正常使用有效数据
*/
var isDel: Int = 0,
* isDel表示数据是否已删除1-已删除为无效数据0-正常使用有效数据
*/
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,201 +0,0 @@
package com.shuwei.dish.match.dialog
import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import androidx.core.view.isEmpty
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.shuwei.dish.match.R
import com.shuwei.dish.match.adapter.GoodsInfoSearchAdapter
import com.shuwei.dish.match.base.BaseActivity
import com.shuwei.dish.match.base.BaseApp
import com.shuwei.dish.match.databinding.DialogBottomSheetBinding
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
import com.shuwei.dish.match.entity.GoodsRecordBean
import com.shuwei.dish.match.http.HttpUtil
import com.shuwei.dish.match.http.UrlConfig
import com.shuwei.dish.match.utils.KeyboardUtil
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
import com.shuwei.dish.match.utils.ext.toJsonString
import com.shuwei.dish.match.utils.ext.toObject
import com.shuwei.dish.match.utils.ext.toast
/**
* @param goodsType 1-调料,0-食材
*/
class BottomDialog(
private var goodsType: Int = 1,
private var defGoodsName:String? = null
) {
companion object {
const val TAG = "BottomDialog"
}
private var list = mutableListOf<CookFoodGoodsEntity>()
private lateinit var binding: DialogBottomSheetBinding
private lateinit var goodsInfoSearchAdapter: GoodsInfoSearchAdapter
private var goodsName: String? = null
private var activity: BaseActivity? = null
fun show(activity: BaseActivity, callback: (item: CookFoodGoodsEntity) -> Unit) {
this.activity = activity
//直接使用BottomSheetDialog
var dialog: BottomSheetDialog? = null
val inflater = LayoutInflater.from(activity)
binding = DialogBottomSheetBinding.inflate(inflater)
binding.tvSheetName.text = if (goodsType == 1) "调料检索" else "食材检索"
binding.etSheetInput.hint = if (goodsType == 1) "输入调料名称" else "输入食材名称或速记码"
goodsInfoSearchAdapter = GoodsInfoSearchAdapter(list).apply {
setOnItemClickListener { _, _, position ->
list[position].isClicked = true
notifyItemChanged(position)
Handler(Looper.getMainLooper()).postDelayed({
callback(list[position])
dialog?.dismiss()
}, 300)
}
}
binding.recyclerView.run {
layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
adapter = goodsInfoSearchAdapter
addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(rv: RecyclerView, newState: Int) {
super.onScrollStateChanged(rv, newState);
}
override fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) {
//解决RecyclerView和smartRefreshLayout滑动冲突问题
super.onScrolled(rv, dx, dy)
val topRowVerticalPosition = if (rv.isEmpty()) 0 else rv.getChildAt(0).top
binding.refreshLayout.setNestedScrollingEnabled(topRowVerticalPosition >= 0)
}
})
}
dialog = BottomSheetDialog(activity, R.style.BottomSheet).apply {
setContentView(binding.root)
setCancelable(true)
behavior.skipCollapsed = false // 跳过折叠状态
// behavior.peekHeight = 880.dp
// window?.setLayout(-1, 880.dp)
show()
setOnDismissListener {
activity.hideStatusBar()
}
}
binding.refreshLayout.setOnRefreshListener {
pageNo = 1
getGoodsList()
}
binding.refreshLayout.setOnLoadMoreListener {
getGoodsList()
}
binding.etSheetInput.addTextChangedListener(
onTextChanged = { text, start, before, count ->
goodsName = text.toString()
})
binding.ivSearch.setOnClickListener { v ->
searchGoods(v)
}
binding.root.setOnClickListener { v ->
KeyboardUtil.hideKeyboard(v.context, v)
}
binding.etSheetInput.let { v ->
v.addOnActionSearchListener {
searchGoods(v)
}
}
binding.refreshLayout.setEnableRefresh(false)
binding.refreshLayout.setEnableLoadMore(false)
if (defGoodsName.isNullOrBlank().not()) {
binding.etSheetInput.let {
it.setText(defGoodsName)
searchGoods(it)
}
}
}
private fun searchGoods(v: View) {
if (goodsName.isNullOrBlank()) {
activity?.toast("${binding.etSheetInput.hint}")
return
}
pageNo = 1
getGoodsList()
KeyboardUtil.hideKeyboard(v.context, v)
}
private var pageNo = 1
private val pageSize = 120
/**
*/
@SuppressLint("NotifyDataSetChanged")
private fun getGoodsList() {
// val pathSegmentList = UrlConfig.QUERY_GOODS_LIST.split(delimiters = arrayOf("/"), limit = 1)
val queryParams = mutableMapOf(
"goodsType" to "$goodsType",
"canteenId" to BaseApp.canteenId,
"pageNo" to "$pageNo",
"pageSize" to "$pageSize"
)
if (goodsName.isNullOrBlank().not()) {
queryParams.put("name", goodsName!!)
}
val sb = StringBuilder().apply {
append(UrlConfig.QUERY_GOODS_LIST)
append("?")
queryParams.forEach { (key, value) ->
append("$key=$value&")
}
}
sb.deleteCharAt(sb.length - 1)
Log.d(TAG, "getGoodsList: url = $sb")
HttpUtil.get(
url = sb.toString(),
doSuccess = {
val json = it.toJsonString()
Log.d(TAG, "getGoodsList: json=$json")
val recordBean: GoodsRecordBean? = json.toObject<GoodsRecordBean>()
if (recordBean == null || recordBean.records.isNullOrEmpty()) {
activity?.toast(if (goodsType == 1) "暂未搜索到调料信息" else "暂未搜索到食材信息")
return@get
}
val records = recordBean.records
if (pageNo == 1) {
list.clear()
}
list.addAll(records!!)
goodsInfoSearchAdapter.notifyDataSetChanged()
if (pageNo == 1) {
binding.refreshLayout.finishRefresh(1200)
} else {
binding.refreshLayout.finishLoadMore(1200)
}
val isLoadMoreEnable = records.size >= pageSize
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
if (isLoadMoreEnable) {
pageNo++
}
}, doFailure = { code, msg ->
activity?.toast(msg)
if (pageNo == 1) {
binding.refreshLayout.finishRefresh(1200)
} else {
binding.refreshLayout.finishLoadMore(1200)
}
})
}
}
@@ -1,258 +0,0 @@
package com.shuwei.dish.match.dialog
import android.annotation.SuppressLint
import android.graphics.Typeface
import android.os.Handler
import android.os.Looper
import android.text.SpannableStringBuilder
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.text.style.LineHeightSpan
import android.text.style.StyleSpan
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import androidx.core.graphics.toColorInt
import androidx.core.view.isEmpty
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.shuwei.dish.match.R
import com.shuwei.dish.match.adapter.SeasoningSearchAdapter
import com.shuwei.dish.match.base.BaseActivity
import com.shuwei.dish.match.base.BaseApp
import com.shuwei.dish.match.databinding.DialogBottomSheet2Binding
import com.shuwei.dish.match.entity.SeasoningEntity
import com.shuwei.dish.match.entity.SeasoningRecordBean
import com.shuwei.dish.match.http.HttpUtil
import com.shuwei.dish.match.http.UrlConfig
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.roundedOneDecimalPlace
import com.shuwei.dish.match.utils.ext.toJsonString
import com.shuwei.dish.match.utils.ext.toObject
import com.shuwei.dish.match.utils.ext.toast
/**
* @param goodsType 1-调料,0-食材
*/
class BottomDialog2(
private var weighIndex: Int,
private var weighAddress: Int,
private var clickName: String? = null
) {
companion object {
const val TAG = "BottomDialog2"
}
private val goodsType: Int = 1
private var list = mutableListOf<SeasoningEntity>()
private lateinit var binding: DialogBottomSheet2Binding
private lateinit var searchAdapter: SeasoningSearchAdapter
private var goodsName: String? = null
private var activity: BaseActivity? = null
fun show(activity: BaseActivity, callback: (item: SeasoningEntity) -> Unit) {
this.activity = activity
//直接使用BottomSheetDialog
var dialog: BottomSheetDialog? = null
val inflater = LayoutInflater.from(activity)
binding = DialogBottomSheet2Binding.inflate(inflater)
//binding.tvSheetName.text = if (goodsType == 1) "调料检索" else "食材检索"
binding.etSheetInput.hint = if (goodsType == 1) "输入调料名称" else "输入食材名称或速记码"
searchAdapter = SeasoningSearchAdapter(list).apply {
setOnItemClickListener { _, _, position ->
list[position].isClicked = true
notifyItemChanged(position)
Handler(Looper.getMainLooper()).postDelayed({
callback(list[position].also { it.useWeight = currentWeight })
dialog?.dismiss()
}, 300)
}
}
binding.recyclerView.run {
layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
adapter = searchAdapter
addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(rv: RecyclerView, newState: Int) {
super.onScrollStateChanged(rv, newState);
}
override fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) {
//解决RecyclerView和smartRefreshLayout滑动冲突问题
super.onScrolled(rv, dx, dy)
val topRowVerticalPosition = if (rv.isEmpty()) 0 else rv.getChildAt(0).top
binding.refreshLayout.setNestedScrollingEnabled(topRowVerticalPosition >= 0)
}
})
}
dialog = BottomSheetDialog(activity, R.style.BottomSheet).apply {
setContentView(binding.root)
setCancelable(true)
behavior.skipCollapsed = false // 跳过折叠状态
// behavior.peekHeight = 880.dp
// window?.setLayout(-1, 880.dp)
show()
setOnDismissListener {
activity.hideStatusBar()
}
}
binding.refreshLayout.setOnRefreshListener {
pageNo = 1
getGoodsList()
}
binding.refreshLayout.setOnLoadMoreListener {
getGoodsList()
}
binding.etSheetInput.addTextChangedListener(
onTextChanged = { text, start, before, count ->
goodsName = text.toString()
})
binding.ivSearch.setOnClickListener { v ->
searchGoods(v)
}
binding.root.setOnClickListener { v ->
KeyboardUtil.hideKeyboard(v.context, v)
}
binding.etSheetInput.let { v ->
v.addOnActionSearchListener {
searchGoods(v)
}
}
binding.refreshLayout.setEnableRefresh(false)
binding.tvClear.setOnClickListener {
Log.d(TAG, "show: weighAddress=$weighAddress")
WeightUtil.tareTwo(weighAddress)
// repeat(14) { num->
// Log.d(TAG, "show: num=$num")
// WeightUtil.tareTwo(num+1)
// }
}
WeightUtil.addWeightListener (
weightKey = TAG,
getWeight = { address, state, weight ->
if (weighAddress == address) {
this.currentWeight = weight.toDouble()
binding.tvWeight.text = getTextSpan(weight)
}
})
binding.tvWeight.text = getTextSpan(0.0)
if (clickName.isNullOrBlank().not()) {
binding.etSheetInput.setText(clickName!!.trim())
pageNo = 1
getGoodsList()
}
}
private fun searchGoods(v: View) {
if (goodsName.isNullOrBlank()) {
activity?.toast("${binding.etSheetInput.hint}")
return
}
pageNo = 1
getGoodsList()
KeyboardUtil.hideKeyboard(v.context, v)
}
private var currentWeight = 0.toDouble()
private var pageNo = 1
private val pageSize = 120
/**
*/
@SuppressLint("NotifyDataSetChanged")
private fun getGoodsList() {
val queryParams = mutableMapOf(
"goodsType" to "$goodsType",
"canteenId" to BaseApp.canteenId,
"pageNo" to "$pageNo",
"pageSize" to "$pageSize"
)
if (goodsName.isNullOrBlank().not()) {
queryParams.put("name", goodsName!!)
}
val sb = StringBuilder().apply {
append(UrlConfig.QUERY_GOODS_LIST)
append("?")
queryParams.forEach { (key, value) ->
append("$key=$value&")
}
}
sb.deleteCharAt(sb.length - 1)
Log.d(TAG, "getGoodsList: url = $sb")
HttpUtil.get(
url = sb.toString(),
doSuccess = {
val json = it.toJsonString()
Log.d(TAG, "getGoodsList: json=$json")
val recordBean: SeasoningRecordBean? = json.toObject<SeasoningRecordBean>()
if (recordBean == null || recordBean.records.isNullOrEmpty()) {
activity?.toast(if (goodsType == 1) "暂未搜索到调料信息" else "暂未搜索到食材信息")
return@get
}
val records = recordBean.records
if (pageNo == 1) {
list.clear()
}
list.addAll(records!!)
searchAdapter.notifyDataSetChanged()
if (pageNo == 1) {
binding.refreshLayout.finishRefresh(1200)
} else {
binding.refreshLayout.finishLoadMore(1200)
}
val isLoadMoreEnable = records.size >= pageSize
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
if (isLoadMoreEnable) {
pageNo++
}
}, doFailure = { code, msg ->
activity?.toast(msg)
if (pageNo == 1) {
binding.refreshLayout.finishRefresh(1200)
} else {
binding.refreshLayout.finishLoadMore(1200)
}
})
}
fun getTextSpan(weight: Double): SpannableStringBuilder {
var topWeight = "$weight"
var bottomUnit = ""
if (weight >= 1000) {
topWeight = "${(weight/1000).roundedDecimalPlace(3)}"
bottomUnit = "千克"
}
return buildSpannableString {
appendText(
topWeight,
ForegroundColorSpan("#000000".toColorInt()),
StyleSpan(Typeface.BOLD),
AbsoluteSizeSpan(72, true),
LineHeightSpan { text, start, end, spanstartv, v, fm ->
fm.descent += 10.dp // 增加行间距
}
)
append("\n")
appendText(
bottomUnit,
ForegroundColorSpan("#999999".toColorInt()),
AbsoluteSizeSpan(30, true)
)
}
}
}
@@ -1,18 +1,19 @@
package com.shuwei.dish.match.dialog
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.View
import android.view.Window
import android.view.WindowManager
import androidx.annotation.StyleRes
import androidx.fragment.app.FragmentActivity
import android.widget.LinearLayout
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
@@ -20,62 +21,165 @@ open class CommonDialog(
private lateinit var binding: DialogCommonBinding
private var titleText: String? = null
private var contentText: CharSequence? = null
private var negativeText = "取消"
private var positiveText = "确认"
private var neutralText: String? = null
private var singleText: String? = null
private var negativeClick: (() -> Unit)? = null
// 返回 true 时关闭弹窗,返回 false 时保持弹窗显示(用于校验不通过的场景)
private var positiveClick: (() -> Boolean)? = null
private var neutralClick: (() -> Unit)? = null
private var singleClick: (() -> Unit)? = null
private var dismissCallback: (() -> Unit)? = null
// 待添加到 llContent 的自定义 View,在 onCreate 后挂载
private var pendingContentView: View? = null
// pendingContentView 非空时对 tvContent 的灵活控制回调(可调整可见性、间距等)
private var tvContentConfigurator: ((TextView) -> Unit)? = null
/** 设置标题,为空时隐藏 */
fun setTitle(text: String): CommonDialog = apply { titleText = text }
/** 设置内容,为空时隐藏 */
fun setContent(text: CharSequence): CommonDialog = apply { contentText = text }
/** 设置左侧取消按钮文字及点击回调(3按钮模式下对应顶部按钮) */
fun setNegativeButton(text: String, onClick: (() -> Unit)? = null): CommonDialog = apply {
negativeText = text
negativeClick = onClick
}
/** 设置右侧确认按钮文字及点击回调(3按钮模式下对应底部按钮),点击后自动关闭弹窗 */
fun setPositiveButton(text: String, onClick: (() -> Unit)? = null): CommonDialog = apply {
positiveText = text
positiveClick = onClick?.let { cb -> { cb(); true } }
}
/**
* 设置右侧确认按钮文字及可拦截的点击回调
* 回调返回 true 时关闭弹窗,返回 false 时保持弹窗显示(用于校验不通过的场景)
*/
fun setPositiveButtonInterceptable(text: String, onClick: () -> Boolean): CommonDialog = apply {
positiveText = text
positiveClick = onClick
}
/** 设置中间第三个按钮文字及点击回调,调用后自动切换为垂直3按钮布局 */
fun setNeutralButton(text: String, onClick: (() -> Unit)? = null): CommonDialog = apply {
neutralText = text
neutralClick = onClick
}
/** 设置单按钮文字及点击回调,调用后自动切换为单按钮布局(优先级最高) */
fun setSingleButton(text: String, onClick: (() -> Unit)? = null): CommonDialog = apply {
singleText = text
singleClick = onClick
}
/** 设置弹窗消失回调 */
fun setOnDismissCallback(callback: () -> Unit): CommonDialog = apply {
dismissCallback = callback
}
/**
* 向弹窗自定义内容区域添加 View,调用后 llContent 自动显示
* @param view 要嵌入的自定义布局(如单选列表)
* @param tvContentConfig 可选回调,用于在 pendingContentView 非空时灵活控制 tvContent 的可见性及间距等属性
*/
fun addContentView(view: View, tvContentConfig: ((TextView) -> Unit)? = null): CommonDialog = apply {
pendingContentView = view
tvContentConfigurator = tvContentConfig
}
override fun onCreate(savedInstanceState: Bundle?) {
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 {
// decorView.setPadding(0.dp, 0, 0.dp, 0)
val screenWidth = context.resources.displayMetrics.widthPixels
attributes = attributes.apply {
width = 708.dp
width = if (isMaster) (screenWidth * 0.72f).toInt() else (screenWidth * 0.60f).toInt()
}
// 透明背景,让 shape_dialog_bg 的阴影层正常显示
setBackgroundDrawable(ColorDrawable())
setCancelable(false)
// setFlags(
// WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
// WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
// )
// 应用缩放+淡入淡出动画
setWindowAnimations(R.style.CommonDialogAnimation)
}
// 主/从设备边距微调:主设备内容区域更大,适当增加上下留白
val verticalMargin = if (isMaster) 48.dp else 36.dp
binding.tvTitle.updateLayoutParams<LinearLayout.LayoutParams> { topMargin = verticalMargin }
binding.tvContent.updateLayoutParams<LinearLayout.LayoutParams> { bottomMargin = verticalMargin }
// 2按钮点击事件
binding.btnLeft.setOnClickListener {
negativeClick?.invoke()
dismiss()
}
binding.btnRight.setOnClickListener {
// 回调返回 false 时阻止关闭,null 或 true 时正常关闭
if (positiveClick?.invoke() != false) dismiss()
}
binding.llContent.run {
removeAllViews()
addView(messageView)
// 3按钮点击事件(negativeClick/positiveClick 与2按钮模式共用)
binding.btnTop.setOnClickListener {
negativeClick?.invoke()
dismiss()
}
binding.btnMiddle.setOnClickListener {
neutralClick?.invoke()
dismiss()
}
binding.btnBottom.setOnClickListener {
if (positiveClick?.invoke() != false) dismiss()
}
addListener()
}
private fun addListener() {
binding.btnLeft.setOnClickListener { onLeftClick?.invoke() }
binding.btnRight.setOnClickListener { onRightClick?.invoke() }
setOnDismissListener { onDismiss?.invoke() }
}
// 单按钮点击事件
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() {
super.show()
binding.btnLeft.text = leftText
binding.btnRight.text = rightText
}
binding.tvTitle.text = titleText
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
var messageView: View? = null
var onLeftClick: (() -> Unit)? = null
var onRightClick: (() -> Unit)? = null
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
var leftText = ""
var rightText = ""
var onDismiss: (() -> Unit)? = null
}
open class SafeDialog(activity: Activity, @StyleRes themeResId: Int) :
Dialog(activity, themeResId) {
private val weakContext = WeakReference(activity)
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
}
}
}
@@ -1,38 +0,0 @@
package com.shuwei.dish.match.dialog
import android.content.Context
import android.view.LayoutInflater
import com.shuwei.dish.match.databinding.LayoutFoodRemindBinding
object DialogTool {
fun load(
context: Context,
title:String,
content:String,
leftBtnText: String,
rightBtnText: String,
leftBtnClick: () -> Unit = {},
rightBtnClick: () -> Unit = {}
) {
val layoutInflater = LayoutInflater.from(context)
val remindBinding = LayoutFoodRemindBinding.inflate(layoutInflater)
remindBinding.tvDialogTitle.text = title
remindBinding.tvDialogContent.text = content
CommonDialog(context).apply {
messageView = remindBinding.root
leftText = leftBtnText
rightText = rightBtnText
onLeftClick = {
leftBtnClick()
dismiss()
}
onRightClick = {
rightBtnClick()
dismiss()
}
onDismiss = { }
}.show()
}
}
@@ -0,0 +1,78 @@
package com.shuwei.dish.match.dialog
import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.PopupWindow
import androidx.core.graphics.drawable.toDrawable
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.shuwei.dish.match.R
import com.shuwei.dish.match.adapter.DropdownAdapter
import com.shuwei.dish.match.databinding.LayoutPopupDropdownBinding
import com.shuwei.dish.match.model.DictType
import com.shuwei.dish.match.utils.ext.dp
class DropdownPopup(
var context: Context,
var list: MutableList<DictType>,
var popWidth: Int = 280.dp,
var popHeight: Int = 284.dp,
var onPopupItemClick: (DictType) -> Unit
) : PopupWindow() {
init {
// 初始化PopupWindow
// val popupView = LayoutInflater.from(context).inflate(R.layout.layout_popup_dropdown, null)
val binding = LayoutPopupDropdownBinding.inflate(LayoutInflater.from(context))
contentView = binding.root
width = ViewGroup.LayoutParams.WRAP_CONTENT
height = ViewGroup.LayoutParams.WRAP_CONTENT
// 设置透明背景,避免覆盖圆角
setBackgroundDrawable(Color.TRANSPARENT.toDrawable())
isOutsideTouchable = true
isFocusable = true
// 设置动画样式
// animationStyle = R.style.PopupAnimation
// 初始化视图和事件
initViews(binding.rvWarehouse)
}
private fun initViews(rv: RecyclerView) {
// 获取关闭按钮并设置点击事件
rv.updateLayoutParams {
width = popWidth
height = popHeight
}
rv.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
rv.adapter = DropdownAdapter(list).setOnItemClickListener { adapter, view, position ->
onPopupItemClick(list[position])
dismiss()
}
}
var arrowImage: ImageView? = null
var bgLayout: ViewGroup? = null
var defLayoutBgResId = R.drawable.bg_white_radius10_stroke2
override fun showAsDropDown(anchor: View?) {
super.showAsDropDown(anchor)
bgLayout?.setBackgroundResource(R.drawable.shape_green_stroke)
arrowImage?.setImageResource(R.mipmap.ic_triangle_up)
}
override fun dismiss() {
super.dismiss()
bgLayout?.setBackgroundResource(defLayoutBgResId)
arrowImage?.setImageResource(R.mipmap.ic_triangle_down)
}
}
@@ -0,0 +1,68 @@
package com.shuwei.dish.match.dialog
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import com.shuwei.dish.match.base.GlobalData
import com.shuwei.dish.match.databinding.DialogEnvSwitchContentBinding
import com.shuwei.dish.match.utils.SpTool
import com.shuwei.dish.match.utils.ext.toast
/**
* 环境切换弹窗
*
* 基于 [CommonDialog] 实现,通过 addContentView 注入 RadioGroup 内容区。
* 提供 TEST / UAT / PROD 三套环境的切换功能,初始化时自动根据
* [GlobalData.appBaseUrl] 选中当前环境,确认后更新 [GlobalData.appBaseUrl]
* 并通过 [onEnvChanged] 回调通知外部。
*
* @param context 上下文
* @param onEnvChanged 确认切换后的回调,参数为新的 baseUrl
*/
class EnvSwitchDialog(
context: Context,
private val onEnvChanged: (newBaseUrl: String) -> Unit = {}
) {
private val contentBinding = DialogEnvSwitchContentBinding.inflate(LayoutInflater.from(context))
private val dialog = CommonDialog(context)
.setTitle("切换环境")
.addContentView(contentBinding.root) { tvContent ->
// 内容区已由 RadioGroup 承载,隐藏默认文本
tvContent.visibility = View.GONE
}
.setNegativeButton("取消")
.setPositiveButtonInterceptable("确认") {
// 未选中任何选项时提示并阻止关闭
if (contentBinding.rgEnv.checkedRadioButtonId == -1) {
context.toast("请选择环境")
return@setPositiveButtonInterceptable false
}
val newUrl = when (contentBinding.rgEnv.checkedRadioButtonId) {
contentBinding.rbTest.id -> GlobalData.LOCAL_BASE_URL
contentBinding.rbUat.id -> GlobalData.TEST_BASE_URL
contentBinding.rbProd.id -> GlobalData.PROD_BASE_URL
else -> return@setPositiveButtonInterceptable false
}
GlobalData.appBaseUrl = newUrl
SpTool.baseUrl = newUrl
onEnvChanged(newUrl)
true
}
init {
// 根据当前 appBaseUrl 预选对应 RadioButton
when (GlobalData.appBaseUrl) {
GlobalData.LOCAL_BASE_URL -> contentBinding.rbTest.isChecked = true
GlobalData.TEST_BASE_URL -> contentBinding.rbUat.isChecked = true
GlobalData.PROD_BASE_URL -> contentBinding.rbProd.isChecked = true
}
}
/** 显示弹窗 */
fun show() = dialog.show()
/** 关闭弹窗 */
fun dismiss() = dialog.dismiss()
}
@@ -0,0 +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.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()
// }
//}
@@ -0,0 +1,291 @@
package com.shuwei.dish.match.dialog
import android.annotation.SuppressLint
import android.graphics.Rect
import android.text.Editable
import android.view.KeyboardShortcutGroup
import android.view.LayoutInflater
import android.view.Menu
import android.view.MotionEvent
import android.view.View
import android.view.Window
import android.widget.FrameLayout
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter4.util.setOnDebouncedItemClick
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.shuwei.dish.match.R
import com.shuwei.dish.match.adapter.FoodAdapter
import com.shuwei.dish.match.base.BaseActivity
import com.shuwei.dish.match.databinding.DialogFoodSearchBinding
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
import com.shuwei.dish.match.model.GoodsItem
import com.shuwei.dish.match.net.UiState
import com.shuwei.dish.match.utils.KeyboardUtil
import com.shuwei.dish.match.utils.showRawMaterialsDialog
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
import com.shuwei.dish.match.utils.ext.toast
import kotlinx.coroutines.launch
/**
* 食材搜索弹窗,继承 BottomSheetDialog 确保只初始化一次
* @param activity 宿主 Activity
* @param defGoodsName 默认填充的食材名称(可选)
* @param onItemSelected 用户点击某一食材时的回调
*/
class FoodSearchDialog(
private val activity: BaseActivity,
private val defGoodsName: String? = null,
private val onItemSelected: (item: GoodsItem) -> Unit
) : BottomSheetDialog(activity, R.style.BottomSheet) {
companion object {
const val PAGE_SIZE = 50
}
private val binding = DialogFoodSearchBinding.inflate(LayoutInflater.from(activity))
private val list = mutableListOf<GoodsItem>()
private val adapter = FoodAdapter(list).apply {
isStateViewEnable = true
setOnDebouncedItemClick { _, _, position ->
val item = list.getOrNull(position) ?: return@setOnDebouncedItemClick
// 弹出净材种类单选弹窗,确认后再回调并关闭弹窗
showRawMaterialsDialog(
context = activity,
types = item.rawMaterialsTypes,
checkedType = item.rawMaterialsType
) { selectedType ->
item.rawMaterialsType = selectedType
item.isClicked = true
notifyItemChanged(position)
binding.root.postDelayed({
onItemSelected(item)
dismiss()
}, 300)
}
}
}
private var goodsName: String? = null
private var pageNo = 1
init {
setContentView(binding.root)
setCancelable(true)
behavior.skipCollapsed = false
setOnDismissListener { activity.hideStatusBar() }
binding.tvSheetName.text = "食材检索"
// 输入框:清空时重置列表
binding.etSheetInput.run {
hint = "输入食材名称或速记码"
addTextChangedListener(
onTextChanged = { text, _, _, _ -> goodsName = text.toString() },
afterTextChanged = { it: Editable? ->
if (it.isNullOrBlank()) {
list.clear()
adapter.notifyDataSetChanged()
}
}
)
addOnActionSearchListener { searchGoods(this) }
}
// RecyclerView 初始化
binding.recyclerView.run {
layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
adapter = this@FoodSearchDialog.adapter
// addOnScrollListener(object : RecyclerView.OnScrollListener() {
// override fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) {
// super.onScrolled(rv, dx, dy)
// // 解决 RecyclerView 与 SmartRefreshLayout 滑动冲突
// val topRowVerticalPosition = if (rv.isEmpty()) 0 else rv.getChildAt(0).top
// binding.refreshLayout.setNestedScrollingEnabled(topRowVerticalPosition >= 0)
// }
// })
}
binding.refreshLayout.run {
setEnableRefresh(true)
setEnableLoadMore(false)
setOnRefreshListener { pageNo = 1; getGoodsList() }
setOnLoadMoreListener { getGoodsList() }
}
binding.ivSearch.setOnClickListener { searchGoods(it) }
binding.root.setOnClickListener { KeyboardUtil.hideKeyboard(it) }
initObserver()
// 若有默认食材名称,自动填充并触发搜索
//if (!defGoodsName.isNullOrBlank()) {
//binding.etSheetInput.setText(defGoodsName)
pageNo = 1
getGoodsList()
KeyboardUtil.hideKeyboard(binding.root)
//}
}
/** 弹窗显示时在 Window.Callback 层提前拦截触摸,解决 BottomSheet 拖拽与列表滑动的手势冲突 */
override fun show() {
super.show()
// Window.Callback.dispatchTouchEvent 在整个 View 树的 onInterceptTouchEvent 之前执行,
// 是最早能感知触摸的时机。在此处判断触摸点位置来控制 behavior.isDraggable
// 从而确保 BottomSheetBehavior 在 CoordinatorLayout.onInterceptTouchEvent 时
// 已经是禁用状态,不会拦截列表区域的滑动手势。
val originalCallback = window?.callback ?: return
window?.callback = object : Window.Callback by originalCallback {
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
val rect = Rect()
binding.refreshLayout.getGlobalVisibleRect(rect)
// 触摸点落在列表区域内则禁止 BottomSheet 拖拽
behavior.isDraggable = !rect.contains(event.rawX.toInt(), event.rawY.toInt())
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
behavior.isDraggable = true
}
}
return originalCallback.dispatchTouchEvent(event)
}
override fun onPointerCaptureChanged(hasCapture: Boolean) {
originalCallback.onPointerCaptureChanged(hasCapture)
}
override fun onProvideKeyboardShortcuts(
data: List<KeyboardShortcutGroup?>?,
menu: Menu?,
deviceId: Int
) {
originalCallback.onProvideKeyboardShortcuts(data, menu, deviceId)
}
}
}
/**
* 收集 foodSearchGoodsListState,统一处理 Loading / Success / Error 状态
* 使用独立的 State,避免与 FoodRecognizeActivity 等页面共用 goodsListState 产生干扰
*/
private fun initObserver() {
activity.lifecycleScope.launch {
activity.repeatOnLifecycle(Lifecycle.State.STARTED) {
activity.netViewModel.foodSearchGoodsListState.collect { state ->
when (state) {
is UiState.Success -> loadGoodsList(state.data)
is UiState.Error -> {
activity.toast(state.msg)
finishRefresh()
}
else -> {}
}
}
}
}
}
/**
* 触发搜索:校验输入、隐藏键盘、发起请求
*/
private fun searchGoods(v: View) {
if (goodsName.isNullOrBlank()) {
activity.toast("${binding.etSheetInput.hint}")
return
}
pageNo = 1
getGoodsList()
KeyboardUtil.hideKeyboard(v)
}
/**
* 请求食材列表,使用弹窗专用接口,结果写入 foodSearchGoodsListState
*/
private fun getGoodsList() {
activity.netViewModel.queryFoodSearchGoodsList(
goodsType = "0",
pageNum = pageNo,
pageSize = PAGE_SIZE,
goodsName = goodsName.takeUnless { it.isNullOrBlank() }
)
}
/**
* 将返回数据填充到列表
*/
@SuppressLint("NotifyDataSetChanged")
private fun loadGoodsList(records: MutableList<GoodsItem>?) {
finishRefresh()
if (records.isNullOrEmpty()) {
if (pageNo == 1) {
loadEmptyView()
}
return
}
// 仅当当前不是 GridLayoutManager 时才重新赋值(空态切回网格时)
binding.recyclerView.run {
if (layoutManager !is GridLayoutManager) {
layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
}
}
if (pageNo == 1) list.clear()
// 将接口返回的 rawMaterialsType(全部种类)移存到 rawMaterialsTypes,供弹窗使用
records.forEach {
it.rawMaterialsTypes = it.rawMaterialsType
it.rawMaterialsType = null
it.oldGoodsId = it.goodsId
it.goodsId = it.materId ?: ""
}
list.addAll(records)
adapter.notifyDataSetChanged()
val isLoadMoreEnable = records.size >= PAGE_SIZE
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
if (isLoadMoreEnable) pageNo++
}
private fun finishRefresh() {
if (pageNo == 1) binding.refreshLayout.finishRefresh()
else binding.refreshLayout.finishLoadMore()
}
private var emptyViewBinding: LayoutEmptyViewBinding? = null
@SuppressLint("NotifyDataSetChanged")
private fun loadEmptyView() {
try {
binding.refreshLayout.setEnableRefresh(true)
binding.refreshLayout.setEnableLoadMore(false)
list.clear()
adapter.notifyDataSetChanged()
if (emptyViewBinding == null) {
emptyViewBinding = LayoutEmptyViewBinding.inflate(
LayoutInflater.from(activity),
binding.recyclerView,
false
)
}
emptyViewBinding?.let {
it.tvContent.text = "暂无数据"
it.tvSubContent.text = "未查询到食材信息,请联系管理员添加"
// it.root.setOnClickListener { loadGoodsList(buildMockGoodsList().toMutableList()) }
it.root.layoutParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT
)
binding.recyclerView.layoutManager = LinearLayoutManager(activity)
binding.recyclerView.post {
it.root.minimumHeight = binding.recyclerView.height
adapter.stateView = it.root
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
@@ -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 宿主 ContextActivity
* @param goodsList 需要展示的物品列表
*/
class GoodsPreviewDialog(
context: android.content.Context,
private val goodsList: List<CookFoodGoodsEntity>
) : BottomSheetDialog(context, R.style.BottomSheet) {
private val binding = DialogGoodsPreviewBinding.inflate(LayoutInflater.from(context))
init {
setContentView(binding.root)
setCancelable(true)
window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
binding.rvGoodsList.run {
layoutManager = LinearLayoutManager(context)
adapter = GoodsPreviewAdapter(goodsList)
}
// foodId 对同一菜品所有条目相同,统一显示在列表上方
val foodId = goodsList.firstOrNull()?.foodId.orEmpty()
binding.tvFoodId.text = "菜品ID${foodId.ifEmpty { "-" }}"
if (goodsList.isEmpty()) {
binding.rvGoodsList.gone()
binding.tvEmpty.visible()
}
}
/** 弹出时注入 Window.Callback,解决 RecyclerView 与 BottomSheet 拖拽的滑动冲突 */
override fun show() {
super.show()
val originalCallback = window?.callback ?: return
window?.callback = object : android.view.Window.Callback by originalCallback {
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
val rect = Rect()
binding.rvGoodsList.getGlobalVisibleRect(rect)
behavior.isDraggable = !rect.contains(event.rawX.toInt(), event.rawY.toInt())
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
behavior.isDraggable = true
}
}
return originalCallback.dispatchTouchEvent(event)
}
override fun onPointerCaptureChanged(hasCapture: Boolean) {
originalCallback.onPointerCaptureChanged(hasCapture)
}
override fun onProvideKeyboardShortcuts(
data: List<KeyboardShortcutGroup?>?,
menu: Menu?,
deviceId: Int
) {
originalCallback.onProvideKeyboardShortcuts(data, menu, deviceId)
}
}
}
}
@@ -0,0 +1,214 @@
package com.shuwei.dish.match.dialog
import android.annotation.SuppressLint
import android.graphics.Rect
import android.text.Editable
import android.view.KeyboardShortcutGroup
import android.view.LayoutInflater
import android.view.Menu
import android.view.MotionEvent
import android.view.View
import android.view.Window
import android.widget.FrameLayout
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter4.util.setOnDebouncedItemClick
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.shuwei.dish.match.R
import com.shuwei.dish.match.adapter.InboundIngredientAdapter
import com.shuwei.dish.match.base.BaseActivity
import com.shuwei.dish.match.databinding.DialogInboundIngredientSearchBinding
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
import com.shuwei.dish.match.model.NutCleanInboundIngredientVO
import com.shuwei.dish.match.net.NetViewModelV2
import com.shuwei.dish.match.net.UiState
import com.shuwei.dish.match.utils.KeyboardUtil
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
import com.shuwei.dish.match.utils.ext.toast
/**
* 已入库净菜食材搜索弹窗
* @param activity 宿主 Activity
* @param defIngredientName 默认填充的食材名称(可选)
* @param onItemSelected 用户点击某项食材时的回调
*/
class InboundIngredientSearchDialog(
private val activity: BaseActivity,
private val viewModelV2: NetViewModelV2,
private val defIngredientName: String? = null,
private val onItemSelected: (item: NutCleanInboundIngredientVO) -> Unit
) : BottomSheetDialog(activity, R.style.BottomSheet) {
private val binding = DialogInboundIngredientSearchBinding.inflate(LayoutInflater.from(activity))
private val list = mutableListOf<NutCleanInboundIngredientVO>()
private val adapter = InboundIngredientAdapter(list).apply {
isStateViewEnable = true
setOnDebouncedItemClick { _, _, position ->
val item = list.getOrNull(position) ?: return@setOnDebouncedItemClick
onItemSelected(item)
dismiss()
}
}
private var keyword: String? = null
init {
setContentView(binding.root)
setCancelable(true)
behavior.skipCollapsed = false
setOnDismissListener { activity.hideStatusBar() }
binding.tvSheetName.text = "已入库净菜检索"
// 输入框:清空时重置列表
binding.etSheetInput.run {
hint = "输入食材名称"
addTextChangedListener(
onTextChanged = { text, _, _, _ -> keyword = text.toString() },
afterTextChanged = { it: Editable? ->
if (it.isNullOrBlank()) {
list.clear()
adapter.notifyDataSetChanged()
}
}
)
addOnActionSearchListener { searchIngredient(this) }
}
// RecyclerView 初始化
binding.recyclerView.run {
layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
adapter = this@InboundIngredientSearchDialog.adapter
}
binding.refreshLayout.run {
setEnableRefresh(true)
setEnableLoadMore(false)
setOnRefreshListener { getIngredientList() }
}
binding.ivSearch.setOnClickListener { searchIngredient(it) }
binding.root.setOnClickListener { KeyboardUtil.hideKeyboard(it) }
// 若有默认食材名称,自动填充并触发搜索
if (!defIngredientName.isNullOrBlank()) {
binding.etSheetInput.setText(defIngredientName)
getIngredientList()
KeyboardUtil.hideKeyboard(binding.root)
}
}
/** 弹窗显示时在 Window.Callback 层提前拦截触摸,解决 BottomSheet 拖拽与列表滑动的手势冲突 */
override fun show() {
super.show()
val originalCallback = window?.callback ?: return
window?.callback = object : Window.Callback by originalCallback {
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
val rect = Rect()
binding.refreshLayout.getGlobalVisibleRect(rect)
behavior.isDraggable = !rect.contains(event.rawX.toInt(), event.rawY.toInt())
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
behavior.isDraggable = true
}
}
return originalCallback.dispatchTouchEvent(event)
}
override fun onPointerCaptureChanged(hasCapture: Boolean) {
originalCallback.onPointerCaptureChanged(hasCapture)
}
override fun onProvideKeyboardShortcuts(
data: List<KeyboardShortcutGroup?>?,
menu: Menu?,
deviceId: Int
) {
originalCallback.onProvideKeyboardShortcuts(data, menu, deviceId)
}
}
}
/**
* 触发搜索:校验输入、隐藏键盘、发起请求
*/
private fun searchIngredient(v: View) {
if (keyword.isNullOrBlank()) {
activity.toast("请输入食材名称")
return
}
getIngredientList()
KeyboardUtil.hideKeyboard(v)
}
/**
* 请求食材列表,使用回调方式发起
*/
private fun getIngredientList() {
viewModelV2.getInboundIngredientOptionsWithCallback(
keyword = keyword.takeUnless { it.isNullOrBlank() },
onLoading = {},
onResult = { state ->
when (state) {
is UiState.Success -> loadIngredientList(state.data)
is UiState.Error -> {
activity.toast(state.msg)
binding.refreshLayout.finishRefresh()
}
else -> {}
}
}
)
}
/**
* 将返回数据填充到列表
*/
@SuppressLint("NotifyDataSetChanged")
private fun loadIngredientList(records: List<NutCleanInboundIngredientVO>?) {
binding.refreshLayout.finishRefresh()
if (records.isNullOrEmpty()) {
loadEmptyView()
return
}
binding.recyclerView.layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
list.clear()
list.addAll(records)
adapter.notifyDataSetChanged()
}
private var emptyViewBinding: LayoutEmptyViewBinding? = null
@SuppressLint("NotifyDataSetChanged")
private fun loadEmptyView() {
try {
list.clear()
adapter.notifyDataSetChanged()
if (emptyViewBinding == null) {
emptyViewBinding = LayoutEmptyViewBinding.inflate(
LayoutInflater.from(activity),
binding.recyclerView,
false
)
}
emptyViewBinding?.let {
it.tvContent.text = "暂无数据"
it.tvSubContent.text = "未查询到已入库净菜信息"
it.root.layoutParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT
)
binding.recyclerView.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
binding.recyclerView.post {
it.root.minimumHeight = binding.recyclerView.height
adapter.stateView = it.root
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
@@ -1,43 +1,103 @@
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 show(context: Context) {
fun isShowing(): Boolean {
return dialog != null && dialog!!.isShowing
}
fun updateContent(content: String) {
if (isShowing().not()) return
dialog!!.updateContent(content)
}
/**
* 显示 Loading 弹窗
*
* @param context 上下文
* @param message 提示文案
* @param timeoutMs 超时兜底时长(毫秒):到期自动 dismiss;传 0 关闭兜底,由业务方自己负责
* @param onDismiss 关闭回调
*/
fun show(
context: Context,
message: String = "加载中……",
timeoutMs: Long = DEFAULT_TIMEOUT_MS,
onDismiss: () -> Unit = {}
) {
try {
// 节流:已显示中只更新文案 + 重置超时,不重新 attach 窗口
// 避免反复触发 FocusEvent 在主线程繁忙时引发 ANR
if (dialog?.isShowing == true) {
dialog?.dismiss()
}
if (dialog == null) {
dialog = LoadingDialog(context)
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)
}
}
@@ -45,25 +105,32 @@ object Loading {
class LoadingDialog(
context: Context,
message: String = "加载中……",
private var onDismiss: () -> Unit = {}
message: String,
private var onDismiss: () -> Unit
) : Dialog(context, R.style.LoadingDialog) {
private val binding: DialogLoadingBinding by lazy {
DialogLoadingBinding.inflate(LayoutInflater.from(context))
}
init {
val binding = DialogLoadingBinding.inflate(LayoutInflater.from(context))
binding.tvMessage.text = message
setContentView(binding.root)
setCancelable(true)
window?.run {
setBackgroundDrawable(Color.TRANSPARENT.toDrawable())
setFlags(
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
);
// setFlags(
// WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
// WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
// );
}
setOnDismissListener {
onDismiss()
}
}
fun updateContent(content: String) {
binding.tvMessage.text = content
}
}
//class LoadingDialog3(
@@ -0,0 +1,259 @@
//package com.shuwei.dish.match.dialog
//
//import android.annotation.SuppressLint
//import android.graphics.Typeface
//import android.os.Handler
//import android.os.Looper
//import android.text.SpannableStringBuilder
//import android.text.style.AbsoluteSizeSpan
//import android.text.style.ForegroundColorSpan
//import android.text.style.LineHeightSpan
//import android.text.style.StyleSpan
//import android.util.Log
//import android.view.Gravity
//import android.view.LayoutInflater
//import android.view.View
//import android.view.ViewGroup
//import android.view.WindowManager
//import androidx.core.graphics.toColorInt
//import androidx.core.view.isEmpty
//import androidx.core.widget.addTextChangedListener
//import androidx.lifecycle.Lifecycle
//import androidx.lifecycle.lifecycleScope
//import androidx.lifecycle.repeatOnLifecycle
//import androidx.recyclerview.widget.GridLayoutManager
//import androidx.recyclerview.widget.RecyclerView
//import com.google.android.material.bottomsheet.BottomSheetDialog
//import com.shuwei.dish.match.R
//import com.shuwei.dish.match.adapter.SeasoningSearchAdapter
//import com.shuwei.dish.match.base.BaseActivity
//import com.shuwei.dish.match.base.BaseApp
//import com.shuwei.dish.match.databinding.DialogSeasoningSearchBinding
//import com.shuwei.dish.match.entity.SeasoningEntity
//import com.shuwei.dish.match.net.UiState
//import com.shuwei.dish.match.utils.KeyboardUtil
//import com.shuwei.dish.match.utils.WeightUtil
//import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
//import com.shuwei.dish.match.utils.ext.appendText
//import com.shuwei.dish.match.utils.ext.buildSpannableString
//import com.shuwei.dish.match.utils.ext.dp
//import com.shuwei.dish.match.utils.ext.roundedDecimalPlace
//import com.shuwei.dish.match.utils.ext.toast
//import kotlinx.coroutines.launch
//
///**
// * 调料搜索弹窗,继承 BottomSheetDialog 确保只初始化一次
// * @param activity 宿主 Activity
// * @param weighIndex 秤的索引
// * @param weighAddress 秤的地址,用于监听重量和去皮
// * @param clickName 默认填充的调料名称(可选)
// * @param onItemSelected 用户点击某一调料时的回调,携带当前重量
// */
//class SeasoningSearchDialog(
// private val activity: BaseActivity,
// private val weighIndex: Int,
// private val weighAddress: Int,
// private val clickName: String? = null,
// private val onItemSelected: (item: SeasoningEntity) -> Unit
//) : BottomSheetDialog(activity, R.style.BottomSheet) {
//
// companion object {
// const val TAG = "BottomDialog2"
// }
//
// private val binding = DialogSeasoningSearchBinding.inflate(LayoutInflater.from(activity))
// private val list = mutableListOf<SeasoningEntity>()
// private val adapter = SeasoningSearchAdapter(list).apply {
// setOnItemClickListener { _, _, position ->
// list[position].isClicked = true
// notifyItemChanged(position)
// Handler(Looper.getMainLooper()).postDelayed({
// onItemSelected(list[position].also { it.useWeight = currentWeight })
// dismiss()
// }, 300)
// }
// }
//
// private var goodsName: String? = null
// private var currentWeight = 0.0
// private var pageNo = 1
// private val pageSize = 50
//
// init {
// setContentView(binding.root)
// setCancelable(true)
// behavior.skipCollapsed = false
// window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
// window?.setGravity(Gravity.BOTTOM)
// window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
// window?.setWindowAnimations(R.style.DialogSoftInputAnimation)
// window?.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
//
// setOnDismissListener {
// // 弹窗关闭时移除重量监听,避免内存泄漏
// WeightUtil.removeWeightListener(TAG)
// activity.hideStatusBar()
// }
//
// // 输入框:清空时重置列表
// binding.etSheetInput.run {
// hint = "输入调料名称"
// addTextChangedListener(
// onTextChanged = { text, _, _, _ -> goodsName = text.toString() },
// afterTextChanged = {
// if (it.isNullOrBlank()) {
// list.clear()
// adapter.notifyDataSetChanged()
// }
// }
// )
// addOnActionSearchListener { searchGoods(this) }
// }
//
// // RecyclerView 初始化及滑动冲突处理
// binding.recyclerView.let {
// it.layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
// it.adapter = adapter
// it.addOnScrollListener(object : RecyclerView.OnScrollListener() {
// override fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) {
// super.onScrolled(rv, dx, dy)
// // 解决 RecyclerView 与 SmartRefreshLayout 滑动冲突
// val topRowVerticalPosition = if (rv.isEmpty()) 0 else rv.getChildAt(0).top
// binding.refreshLayout.setNestedScrollingEnabled(topRowVerticalPosition >= 0)
// }
// })
// }
//
// binding.refreshLayout.run {
// setEnableRefresh(false)
// setEnableLoadMore(false)
// setOnRefreshListener { pageNo = 1; getGoodsList() }
// setOnLoadMoreListener { getGoodsList() }
// }
//
// binding.ivSearch.setOnClickListener { searchGoods(it) }
// binding.root.setOnClickListener { KeyboardUtil.hideKeyboard(it) }
//
// // 去皮按钮
// binding.tvClear.setOnClickListener {
// Log.d(TAG, "tareTwo: weighAddress=$weighAddress")
// WeightUtil.tareTwo(weighAddress)
// }
//
// // 监听对应秤的重量变化
// WeightUtil.addWeightListener(
// weightKey = TAG,
// getWeight = { address, _, weight ->
// if (weighAddress == address) {
// currentWeight = weight.toDouble()
// binding.tvWeight.text = getTextSpan(weight)
// }
// }
// )
// binding.tvWeight.text = getTextSpan(0.0)
//
// initObserver()
//
// // 若有默认调料名称,自动填充并触发搜索
// if (!clickName.isNullOrBlank()) {
// binding.etSheetInput.setText(clickName.trim())
// pageNo = 1
// getGoodsList()
// }
// }
//
// /**
// * 收集 seasoningListState,统一处理 Loading / Success / Error 状态
// */
// private fun initObserver() {
// activity.lifecycleScope.launch {
// activity.repeatOnLifecycle(Lifecycle.State.STARTED) {
// activity.netViewModel.seasoningListState.collect { state ->
// when (state) {
// is UiState.Success -> loadGoodsList(state.data)
// is UiState.Error -> {
// activity.toast(state.msg)
// finishRefresh()
// }
// else -> {}
// }
// }
// }
// }
// }
//
// /**
// * 触发搜索:校验输入、隐藏键盘、发起请求
// */
// private fun searchGoods(v: View) {
// if (goodsName.isNullOrBlank()) {
// activity.toast("请${binding.etSheetInput.hint}")
// return
// }
// pageNo = 1
// getGoodsList()
// KeyboardUtil.hideKeyboard(v)
// }
//
// /**
// * 请求调料列表
// */
// private fun getGoodsList() {
// val param = mutableMapOf<String, Any>(
// "goodsType" to "1",
// "placeId" to BaseApp.canteenId,
// "pageNum" to pageNo,
// "pageSize" to pageSize
// )
// if (!goodsName.isNullOrBlank()) {
// param["goodsName"] = goodsName!!
// }
// activity.netViewModel.querySeasoningList(param)
// }
//
// /**
// * 将返回数据填充到列表
// */
// @SuppressLint("NotifyDataSetChanged")
// private fun loadGoodsList(records: MutableList<SeasoningEntity>?) {
// finishRefresh()
// if (records.isNullOrEmpty()) {
// activity.toast("暂未搜索到调料信息")
// return
// }
// if (pageNo == 1) list.clear()
// list.addAll(records)
// adapter.notifyDataSetChanged()
// val isLoadMoreEnable = records.size >= pageSize
// binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
// if (isLoadMoreEnable) pageNo++
// }
//
// private fun finishRefresh() {
// if (pageNo == 1) binding.refreshLayout.finishRefresh()
// else binding.refreshLayout.finishLoadMore()
// }
//
// /**
// * 生成重量显示的富文本:数值大字加粗,单位小字灰色
// */
// fun getTextSpan(weight: Double): SpannableStringBuilder {
// val topWeight = if (weight >= 1000) "${(weight / 1000).roundedDecimalPlace(3)}" else "$weight"
// val bottomUnit = if (weight >= 1000) "千克" else "克"
// return buildSpannableString {
// appendText(
// topWeight,
// ForegroundColorSpan("#000000".toColorInt()),
// StyleSpan(Typeface.BOLD),
// AbsoluteSizeSpan(72, true),
// LineHeightSpan { _, _, _, _, _, fm -> fm.descent += 10.dp }
// )
// append("\n")
// appendText(
// bottomUnit,
// ForegroundColorSpan("#999999".toColorInt()),
// AbsoluteSizeSpan(30, true)
// )
// }
// }
//}
@@ -0,0 +1,283 @@
package com.shuwei.dish.match.dialog
import android.annotation.SuppressLint
import android.graphics.Rect
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.KeyboardShortcutGroup
import android.view.LayoutInflater
import android.view.Menu
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import android.widget.FrameLayout
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.shuwei.dish.match.R
import com.shuwei.dish.match.adapter.SeasoningSearchAdapter
import com.shuwei.dish.match.base.BaseActivity
import com.shuwei.dish.match.databinding.DialogSeasoningSelectBinding
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
import com.shuwei.dish.match.model.GoodsItem
import com.shuwei.dish.match.net.UiState
import com.shuwei.dish.match.utils.KeyboardUtil
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
import com.shuwei.dish.match.utils.ext.toast
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
/**
* 调料选择弹窗,不含重量显示,继承 BottomSheetDialog 确保只初始化一次
* @param activity 宿主 Activity
* @param onItemSelected 用户点击某一调料时的回调
*/
class SeasoningSelectDialog(
private val activity: BaseActivity,
private val onItemSelected: (item: GoodsItem) -> Unit
) : BottomSheetDialog(activity, R.style.BottomSheet) {
companion object {
const val TAG = "SeasoningSelectDialog"
const val PAGE_SIZE = 50
}
private val binding = DialogSeasoningSelectBinding.inflate(LayoutInflater.from(activity))
private val list = mutableListOf<GoodsItem>()
private val adapter = SeasoningSearchAdapter(list).apply {
isStateViewEnable = true
setOnItemClickListener { _, v, position ->
val item = list.getOrNull(position) ?: return@setOnItemClickListener
item.isClicked = true
notifyItemChanged(position)
v.postDelayed({
onItemSelected(item)
dismiss()
}, 300)
}
}
private var goodsName: String? = null
private var pageNo = 1
private var collectJob: Job? = null
init {
setContentView(binding.root)
setCancelable(true)
behavior.skipCollapsed = false
window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
window?.setGravity(Gravity.BOTTOM)
window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
window?.setWindowAnimations(R.style.DialogSoftInputAnimation)
window?.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
setOnDismissListener {
collectJob?.cancel()
activity.hideStatusBar()
}
// 输入框:清空时重置列表
binding.etSheetInput.run {
hint = "输入调料名称"
addTextChangedListener(
onTextChanged = { text, _, _, _ -> goodsName = text.toString() },
afterTextChanged = {
if (it.isNullOrBlank()) {
list.clear()
adapter.notifyDataSetChanged()
}
}
)
addOnActionSearchListener { searchGoods(this) }
}
// RecyclerView 初始化
binding.recyclerView.run {
layoutManager = GridLayoutManager(activity, 3, GridLayoutManager.VERTICAL, false)
adapter = this@SeasoningSelectDialog.adapter
}
binding.refreshLayout.run {
setEnableRefresh(true)
setEnableLoadMore(false)
setOnRefreshListener { pageNo = 1; getGoodsList() }
setOnLoadMoreListener { getGoodsList() }
}
binding.ivSearch.setOnClickListener { searchGoods(it) }
binding.root.setOnClickListener { KeyboardUtil.hideKeyboard(it) }
}
/** 弹窗显示时自动加载默认调料列表,并在 Window.Callback 层提前拦截触摸以解决滑动冲突 */
override fun show() {
super.show()
// 启动 StateFlow 收集,弹窗关闭时由 setOnDismissListener 取消
collectJob = activity.lifecycleScope.launch {
activity.netViewModel.foodSearchGoodsListState.collect { state ->
when (state) {
is UiState.Loading -> {}
is UiState.Success -> loadGoodsList(state.data)
is UiState.Error -> {
activity.toast(state.msg)
finishRefresh()
if (pageNo == 1) {
loadEmptyView()
}
}
is UiState.Idle -> {}
}
}
}
pageNo = 1
getGoodsList()
// Window.Callback.dispatchTouchEvent 在整个 View 树的 onInterceptTouchEvent 之前执行,
// 是最早能感知触摸的时机。在此处判断触摸点位置来控制 behavior.isDraggable
// 从而确保 BottomSheetBehavior 在 CoordinatorLayout.onInterceptTouchEvent 时
// 已经是禁用状态,不会拦截列表区域的滑动手势。
val originalCallback = window?.callback ?: return
window?.callback = object : Window.Callback by originalCallback {
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
val rect = Rect()
binding.refreshLayout.getGlobalVisibleRect(rect)
// 触摸点落在列表区域内则禁止 BottomSheet 拖拽
behavior.isDraggable = !rect.contains(event.rawX.toInt(), event.rawY.toInt())
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
behavior.isDraggable = true
}
}
return originalCallback.dispatchTouchEvent(event)
}
override fun onPointerCaptureChanged(hasCapture: Boolean) {
originalCallback.onPointerCaptureChanged(hasCapture)
}
override fun onProvideKeyboardShortcuts(
data: List<KeyboardShortcutGroup?>?,
menu: Menu?,
deviceId: Int
) {
originalCallback.onProvideKeyboardShortcuts(data, menu, deviceId)
}
}
}
/**
* 触发搜索:校验输入、隐藏键盘、发起请求
*/
private fun searchGoods(v: View) {
if (goodsName.isNullOrBlank()) {
activity.toast("${binding.etSheetInput.hint}")
return
}
pageNo = 1
getGoodsList()
KeyboardUtil.hideKeyboard( v)
}
/**
* 请求调料列表
*/
private fun getGoodsList() {
activity.netViewModel.queryFoodSearchGoodsList(
goodsType = "1",
pageNum = pageNo,
pageSize = PAGE_SIZE,
goodsName = goodsName.takeUnless { it.isNullOrBlank() }
)
}
/**
* 加载本地模拟数据,仅用于联调时点击空布局快速验证 UI
*/
private fun loadMockData() {
val nameList = listOf(
"", "白砂糖", "冰糖", "鸡精", "味精", "陈醋", "老抽", "生抽", "番茄酱", "胡椒粉", "孜然", "十三香",
"料酒", "白醋", "蚝油", "辣椒面", "辣椒酱", "豆瓣酱", "淀粉", "", "", "", "香菜", ""
)
val mockData = mutableListOf<GoodsItem>()
nameList.forEachIndexed { index, name ->
val padString = "${index + 1}".padStart(2, '0')
mockData.add(GoodsItem(goodsId = "1000$padString", goodsName = name))
}
pageNo = 1
loadGoodsList(mockData)
}
/**
* 将返回数据转换并填充到列表
*/
@SuppressLint("NotifyDataSetChanged")
private fun loadGoodsList(records: MutableList<GoodsItem>?) {
finishRefresh()
if (records.isNullOrEmpty()) {
//activity.toast("暂未搜索到调料信息")
if (pageNo == 1) {
loadEmptyView()
}
return
}
binding.recyclerView.layoutManager = GridLayoutManager(activity, 3, GridLayoutManager.VERTICAL, false)
if (pageNo == 1) list.clear()
list.addAll(records)
list.forEach {
it.oldGoodsId = it.goodsId
//materId才是提交数据需要的goodsId数据
it.goodsId = it.materId ?:""
}
adapter.notifyDataSetChanged()
val isLoadMoreEnable = records.size >= PAGE_SIZE
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
if (isLoadMoreEnable) pageNo++
}
private fun finishRefresh() {
if (pageNo == 1) binding.refreshLayout.finishRefresh()
else binding.refreshLayout.finishLoadMore()
}
private var emptyViewBinding: LayoutEmptyViewBinding? = null
@SuppressLint("NotifyDataSetChanged")
private fun loadEmptyView() {
try {
binding.refreshLayout.setEnableRefresh(true)
binding.refreshLayout.setEnableLoadMore(false)
list.clear()
adapter.notifyDataSetChanged()
if (emptyViewBinding == null) {
emptyViewBinding = LayoutEmptyViewBinding.inflate(
LayoutInflater.from(activity),
binding.recyclerView,
false
)
}
emptyViewBinding?.let {
it.tvContent.text = "暂无数据"
it.tvSubContent.text = "未查询到调料信息,请联系管理员添加"
// 点击空布局加载本地模拟数据,方便联调时验证 UI
//it.root.setOnClickListener { loadMockData() }
it.root.layoutParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT
)
binding.recyclerView.layoutManager = LinearLayoutManager(activity)
binding.recyclerView.post {
it.root.minimumHeight = binding.recyclerView.height
adapter.stateView = it.root
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
@@ -1,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,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 JSONHTTPS
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,36 +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 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,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
}
}
@@ -0,0 +1,25 @@
package com.shuwei.dish.match.model
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
/**
* 字典类型 如仓库列表 物品类型 存储方式等
*/
@Parcelize
data class DictType(
val id: String? = null,
val value: String? = null,
val type: String = "",
var position: Int = 0
) : Parcelable {
/**
* 按字段名取值,供 extraApiKeys 映射直接使用
*/
operator fun get(fieldName: String): String = when (fieldName) {
"id" -> id ?: ""
"value" -> value ?: ""
else -> type
}
}
@@ -1,4 +1,4 @@
package com.shuwei.dish.match.entity
package com.shuwei.dish.match.model
import java.io.Serializable
@@ -13,7 +13,7 @@ data class FoodRecord(
var cookMode: Int = 0,
//1-早餐,2-午餐,3-晚餐
var dinnerType: String = "0",
//true-原始数据,false-非原始数据
var isOriginalData: Boolean = true,
var sort: Int = 0
) : Serializable
@@ -0,0 +1,52 @@
package com.shuwei.dish.match.model
/** 表单字段类型枚举 */
enum class FieldType {
/** 普通文本输入 */
TEXT,
/** 整数输入 */
INTEGER,
/** 小数输入 */
DECIMAL,
/** 下拉选择 */
DROPDOWN,
/** 日期选择弹窗 */
DATE_PICKER,
/** 固定值,不可编辑 */
FIXED,
/** 子列表容器,用于动态增减行(如"包含食材" */
CHILDREN
}
/**
* 动态表单字段数据模型
* @param label 字段标签名称
* @param type 字段类型,决定渲染哪种输入控件
* @param apiKey 非下拉字段对应的接口参数名,空字符串表示不提交
* @param extraApiKeys 下拉字段的多接口参数映射,key=接口参数名,value=DictType 字段名(id/value/type
* @param required 是否必填,提交时校验
* @param hidden 是否隐藏,hidden=true 时不渲染该字段
* @param hint 校验失败提示文案,同时作为输入框 hint
* @param options 下拉框选项列表(DROPDOWN 类型使用)
* @param value 当前显示值/输入值;DATE_PICKER 存 yyyy-MM-dd 显示格式
* @param extraValues 下拉选中后按 extraApiKeys 映射存储的提交值,key=接口参数名
* @param children 子字段模板(CHILDREN 类型使用),每行按此模板创建一组字段
* @param childAddLabel 添加按钮文案(CHILDREN 类型使用),如 "+ 添加食材"
* @param childrenRows 子列表实际数据(CHILDREN 类型使用),每行是一个 List<FormField>
*/
data class FormField(
val label: String,
val type: FieldType,
val apiKey: String = "",
val extraApiKeys: Map<String, String> = emptyMap(),
val required: Boolean = false,
val hidden: Boolean = false,
val hint: String = "",
var options: MutableList<DictType> = mutableListOf(),
var value: String = "",
val extraValues: MutableMap<String, String> = mutableMapOf(),
val children: List<FormField>? = null,
val childAddLabel: String? = null,
val childrenRows: MutableList<MutableList<FormField>> = mutableListOf(),
var onDropdownSelected: ((DictType) -> Unit)? = null
)
@@ -0,0 +1,83 @@
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 = "",
var goodsName: String? = null,
val popularName: String? = null,
val zjmCode: String? = null,
var materId: String? = null,
var 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,
// 识图匹配分数,-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,264 @@
package com.shuwei.dish.match.model
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
/**
* 食堂VO - 食堂下拉列表响应
*/
@Parcelize
data class NutCanteenVO(
val id: Long?,
val canteenCode: String?,
val canteenName: String?,
val orgCode: String?,
val orgName: String?,
val leader: String?,
val leaderPhone: String?,
val useTerminal: Short?,
val address: String?,
val longitude: String?,
val latitude: String?,
val status: Short?
) : Parcelable
/**
* 字典项VO - 字典项下拉响应
*/
@Parcelize
data class NutDictItemVO(
val id: Long?,
val dictType: String?,
val dictCode: String?,
val dictLabel: String?,
val sortOrder: Int?,
val isBuiltin: Short?,
val status: Short?,
val remark: String?
) : Parcelable
/**
* 食材选项VO - 食材下拉响应
*/
@Parcelize
data class NutMaterOptionVO(
val id: Long?,
val materClassName: String?
) : Parcelable
/**
* 包装设备VO - 包装设备下拉响应
*/
@Parcelize
data class NutSupPkgDeviceVO(
val id: Long?,
val deviceNo: String?,
val deviceName: String?
) : Parcelable
/**
* 餐品选项VO - 餐品下拉搜索响应
*/
@Parcelize
data class NutFoodOptionVO(
val foodId: Long?,
val foodCode: String?,
val foodName: String?,
val compositions: List<NutFoodComposition>?
) : Parcelable
/**
* 餐品食材构成
*/
@Parcelize
data class NutFoodComposition(
var materId: Long?,
var ingredientName: String?,
var traceCode: String?,
var amount: Double?,
var isMain: Int?,
//1-主材、2-辅材、3-调料
var mainText: String?=null
) : Parcelable
/**
* 溯源码查食材信息VO
*/
@Parcelize
data class NutSupHygieneIngredientOptionVO(
val traceCode: String?,
val materId: Long?,
val materName: String?,
val vegTypes: String?,
val materClassId: Long?,
val materClassName: String?,
val testNo: String?
) : Parcelable
/**
* 组配任务视频监控VO
*/
@Parcelize
data class NutProdComboVideoVO(
val cameraCode: String?,
val streamUrl: String?,
val snapshotUrl: String?,
val onlineStatus: Int?,
val recordType: Int?,
val startTime: String?,
val endTime: String?
) : Parcelable
/**
* 组配任务DTO - 上报组配任务请求体
*/
data class NutProdComboTaskDTO(
val planDate: String,
val canteenId: Long,
val mealType: Short?,
val foodId: Long?,
val targetDish: String,
val spec: String,
val portions: Int,
val taskDeadline: String?,
val taskSource: Short?,
val ownerName: String?,
val items: List<NutProdComboTaskItem>?
)
/**
* 组配任务食材明细
*/
data class NutProdComboTaskItem(
val ingredientCode: String?,
val ingredientName: String,
val perPortionQty: String,
val unit: String? = "g",
val sortOrder: Int?
)
/**
* 单品净菜包装DTO - 上报单品净菜包装记录请求体
*/
data class NutSupCleanPackageDTO(
val traceCode: String,
val cleanInboundId: Long?,
val cleanName: String,
val packageMethod: String,
val spec: String,
val quantity: Int,
val packageDate: String,
val expiryDate: String,
val storageTemp: String?,
val relatedOrderNo: String?,
val operator: String?,
val deviceId: Long?,
val cameraCode: String?,
val videoUrl: String?
)
/**
* 餐品净菜包装DTO - 上报餐品净菜包装记录请求体
*/
data class NutSupMealPackageDTO(
val foodId: Long,
val mealName: String,
val spec: String,
val packageMethod: String,
val quantity: Int,
val packageDate: String,
val expiryDate: String,
val storageTemp: String?,
val relatedOrderNo: String?,
val operator: String?,
val deviceId: Long?,
val cameraCode: String?,
val videoUrl: String?,
val ingredients: List<NutSupMealPackageIngredient>
)
/**
* 餐品净菜包装食材明细
*/
data class NutSupMealPackageIngredient(
val materId: Long,
val ingredientName: String,
val amount: String?,
val traceCode: String
)
/**
* 组配任务VO - 未完成组配任务列表响应
*/
@Parcelize
data class NutComboTaskVO(
val id: Long?,
val taskNo: String?,
val planDate: String?,
val canteenId: Long?,
val mealType: Int?,
val foodId: Long?,
val targetDish: String?,
val spec: String?,
val portions: Int?,
var comboStatus: Int?,
val ownerName: String?,
val createTime: String?
) : Parcelable
/**
* 组配任务详情VO - 组配任务详情响应
*/
@Parcelize
data class NutComboTaskDetailVO(
var id: Long? = null,
var taskNo: String? = null,
var planDate: String? = null,
var canteenId: Long? = null,
var mealType: Int? = null,
var foodId: Long? = null,
var targetDish: String? = null,
var spec: String? = null,
var portions: Int? = null,
var comboStatus: Int? = null,
var ownerName: String? = null,
var deviceCode: String? = null,
var items: List<NutComboTaskItemDetail>? = null,
) : Parcelable
/**
* 组配任务食材明细
*/
@Parcelize
data class NutComboTaskItemDetail(
val id: Long?,
val ingredientCode: String?,
val ingredientName: String?,
val ingredientClass: Int?,
var traceCode: String?,
val perPortionQty: String?,
var actualQty: String?,
val totalQty: String?,
val unit: String?,
var isClicked: Boolean? = false,
var isSetFinished: Boolean? = false,
) : Parcelable
/**
* 已入库净菜食材VO - 按食材名称查询已入库有库存的净菜记录
*/
@Parcelize
data class NutCleanInboundIngredientVO(
val id: Long?,
val materId: Long?,
val ingredientName: String?,
val traceCode: String?,
val currentStock: String?
) : Parcelable
/**
* ID通用DTO - 用于开始/完成组配等需要id参数的接口
*/
data class IdDTO(
val id: Long
)
@@ -0,0 +1,35 @@
package com.shuwei.dish.match.model
/**
* 设置页面的列表项实体类
*
* @param type 菜单项类型,用于唯一标识每一项
* @param title 主标题文字
* @param subtitle 副标题文字,仅部分项目(如菜品模式)有值
* @param isHidden 是否为隐藏项,隐藏项需触发开发者模式后才显示
* @param onClick 点击回调,初始化时直接注入对应的业务逻辑
*/
data class SettingItem(
val type: Type,
val title: String = type.label,
val subtitle: String? = null,
val isHidden: Boolean = false,
val onClick: () -> Unit
) {
/** 设置菜单项类型枚举 */
enum class Type(val label: String) {
COOK_MODE("菜品模式"),
SEASONING_CONFIG("调料区设置"),
FOOD_COLLECT("食材采集"),
WEIGHT_CONFIG("减重配置"),
CLEAN_PACKAGE("净菜包"),
MEAL_PACKAGE("餐品净菜包"),
GROUP_TASK("组配任务"),
// MEAL_PACKAGE_TEST("餐品净菜包-测试"),
DB_INSPECT("数据库查看"),
SCALE_OBSERVE("秤数据监控"),
ENV_SWITCH("切换环境"),
CLEAR_DATA("数据清除"),
TEST_SEASONING("测试调料拿取"),
}
}
@@ -0,0 +1,131 @@
package com.shuwei.dish.match.net
import com.google.gson.JsonSyntaxException
import com.shuwei.dish.match.utils.ext.toJsonString
import com.shuwei.dish.match.utils.ext.toObject
import com.shuwei.dish.match.utils.ext.toType
import org.apache.http.conn.ConnectTimeoutException
import retrofit2.HttpException
import java.io.IOException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
///**
// * 通用网络请求封装,统一处理异常
// * @param onRequest 实际的 Retrofit 接口请求
// * @param onSuccess 成功回调
// * @param onFailure 自定义错误回调(可选,不传则用默认提示)
// */
//suspend fun <T> apiRequest(
// onRequest: suspend () -> T,
// onSuccess: (T) -> Unit,
// onFailure: ((ApiException) -> Unit)? = null
//) {
// try {
// // 执行实际的网络请求
// val result = onRequest()
// onSuccess(result)
// } catch (e: Exception) {
// val apiException = getApiException(e)
// // 优先执行自定义错误回调,没有则用默认提示
// if (onFailure != null) {
// onFailure(apiException)
// } else {
// // 默认的错误提示(可根据 ErrorType 定制)
// val tip = apiException.errorMsg
// // 切换到UI线程弹提示(用 MainScope 确保在主线程)
// MainScope().launch {
// BaseApp.instance?.toast(tip)
// }
// }
// }
//}
/**
* 通用网络请求封装,统一处理异常
* @param onRequest 实际的 Retrofit 接口请求
* @param onSuccess 成功回调
* @param onFailure 自定义错误回调(可选,不传则用默认提示)
*/
@Suppress("UNCHECKED_CAST")
suspend fun <T> request(
onRequest: suspend () -> ApiResponse<T>,
onSuccess: (T) -> Unit,
onFailure: (String, String) -> Unit
) {
var response: ApiResponse<T>?
try {
// 执行实际的网络请求
response = onRequest()
} catch (e: Exception) {
val apiException = getApiException(e)
onFailure("-1", apiException.errorMsg)
return
}
if (response.isSuccess()) {
onSuccess(response.data as T)
} else {
onFailure(response.code, response.msg ?: "")
}
}
data class CodeMsg(
var code: String? = null,
var msg: String? = null
)
@Suppress("DEPRECATION")
fun getApiException(e: Exception): ApiException {
// 捕获各类网络异常并转换为自定义异常
return when (e) {
is HttpException -> httpException2ApiException(e)
is JsonSyntaxException -> ApiException(
ErrorType.NETWORK_ERROR,
errorMsg = "服务器响应异常,请稍后重试"
)
is UnknownHostException -> ApiException(
ErrorType.NETWORK_ERROR,
errorMsg = "网络未连接,请检查网络"
)
is SocketTimeoutException -> ApiException(
ErrorType.TIMEOUT_ERROR,
errorMsg = "请求超时,请稍后重试"
)
is ConnectTimeoutException -> ApiException(
ErrorType.TIMEOUT_ERROR,
errorMsg = "连接超时,请检查网络"
)
is IOException -> ApiException(
ErrorType.NETWORK_ERROR,
errorMsg = "网络异常:${e.message ?: "未知IO错误"}"
)
is ApiException -> e
else -> ApiException(
ErrorType.UNKNOWN_ERROR,
errorMsg = "未知错误:${e.message ?: "未知"}",
throwable = e
)
}
}
fun httpException2ApiException(e: HttpException): ApiException {
val body = e.response()?.errorBody()?.string()
val codeMsg: CodeMsg? = try {
body?.toObject<CodeMsg>()
} catch (_: Exception) {
null
}
return ApiException(
ErrorType.NETWORK_ERROR,
errorMsg = if (codeMsg == null) "数据解析异常(${e.code()})"
else codeMsg.msg ?: "服务器错误(${e.code()})"
)
}
@@ -0,0 +1,76 @@
package com.shuwei.dish.match.net
import com.shuwei.dish.match.base.GlobalData
import com.shuwei.dish.match.model.CookFoodDTO
import com.shuwei.dish.match.model.FoodRecord
import com.shuwei.dish.match.model.GoodsItem
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.Query
import retrofit2.http.Url
interface ApiService {
/**
* 查询菜品详情
*/
@GET
suspend fun getFoodDetail(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/getConstituteByFoodId",
@Query("foodId") foodId: String
): ApiResponse<CookFoodDTO?>
/**
* 提交制作菜品
*/
@POST
suspend fun submitCookFood(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/saveConstitute",
@Body param: CookFoodDTO
): ApiResponse<Any?>
/**
* 搜索菜品
*/
@POST
suspend fun searchFoodList(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/queryPageList",
@Body param: MutableMap<String, Any>
): ApiResponse<MutableList<FoodRecord>?>
/**
* 采样数据
*/
@POST
suspend fun getSamplingList(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/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",
@Body param: MutableMap<String, Any>
): ApiResponse<MutableList<GoodsItem>?>
/**
* 提交采集图片数据
*/
@Multipart
@POST
suspend fun uploadFoodVectorData(
@Url url: String = "${GlobalData.appBaseUrl}/terminal/neglect/matching/app/addWeighingCollectionData",
@PartMap params: MutableMap<String, RequestBody>,
@Part foodPics: List<MultipartBody.Part>
): ApiResponse<List<String>?>
}

Some files were not shown because too many files have changed in this diff Show More