代码提交

This commit is contained in:
2025-08-11 18:32:04 +08:00
parent 317ac05278
commit 3b4ba599bf
188 changed files with 9770 additions and 34 deletions
@@ -0,0 +1,265 @@
package com.shuwei.dish.match.ui
import android.graphics.Typeface
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.text.style.LineHeightSpan
import android.text.style.StyleSpan
import android.util.Log
import androidx.core.graphics.toColorInt
import androidx.lifecycle.ViewModelProvider
import com.shuwei.dish.match.R
import com.shuwei.dish.match.adapter.SeasoningCellTool
import com.shuwei.dish.match.adapter.TextCellAdapter
import com.shuwei.dish.match.base.BaseActivity
import com.shuwei.dish.match.base.BaseApp
import com.shuwei.dish.match.databinding.ActivityDeviceSettingBinding
import com.shuwei.dish.match.db.AppRepository
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.dp
import com.shuwei.dish.match.utils.ext.startActivity
import com.shuwei.dish.match.utils.ext.toJsonString
import com.shuwei.dish.match.utils.ext.toast
import com.shuwei.dish.match.utils.ext.visible
import com.shuwei.dish.match.viewmodel.AppViewModel
import com.shuwei.dish.match.viewmodel.factory.AppFactory
class DeviceSettingActivity : BaseActivity() {
companion object {
const val TAG = "DeviceSettingActivity"
const val COOK_MODE = "cookMode"
val modeList = listOf<ModeBean>(
ModeBean("制作模式", "菜品快速制作,记录熟重"),
ModeBean("采样模式", "菜品快速制作,记录熟重"),
ModeBean("品控模式", "菜品快速制作,记录熟重")
)
}
data class ModeBean(
var modeName: String,
var modeDesc: String
)
private lateinit var binding: ActivityDeviceSettingBinding
private lateinit var appViewModel: AppViewModel
// public lateinit var list: MutableList<SeasoningEntity>
private var cookMode: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDeviceSettingBinding.inflate(layoutInflater)
setContentView(binding.root)
cookMode = intent.getIntExtra(COOK_MODE, 0)
initViewModel()
setHeaderBackground()
setTitleBar(titleBarAction = {
it.visible()
}, titleAction = {
it.text = "设备配置"
})
addListener()
loadQualitySpan(isEnable = false)
when (cookMode) {
1 -> {
binding.rbModeCook.isChecked = true
binding.rbModeSampling.isChecked = false
loadCookSpan(isClicked = true)
loadSamplingSpan()
}
2 -> {
binding.rbModeCook.isChecked = false
binding.rbModeSampling.isChecked = true
loadCookSpan()
loadSamplingSpan(isClicked = true)
}
else -> 0
}
binding.rbModeCook.setOnClickListener {
binding.rbModeCook.isChecked = true
binding.rbModeSampling.isChecked = false
loadCookSpan(isClicked = true)
loadSamplingSpan()
startActivity<SelectDishActivity> { }
finish()
}
binding.rbModeSampling.setOnClickListener {
binding.rbModeCook.isChecked = false
binding.rbModeSampling.isChecked = true
loadCookSpan()
loadSamplingSpan(isClicked = true)
startActivity<SamplingListActivity> { }
finish()
}
}
private fun initViewModel() {
val db = BaseApp.instance!!.database
val factory =
AppFactory(AppRepository(db.appDao()))
appViewModel =
ViewModelProvider(this, factory)[AppViewModel::class.java]
}
override fun onResume() {
super.onResume()
appViewModel.loadSeasoning { it ->
SeasoningCellTool.loadData(
activity = this,
initList = it,
recyclerView = binding.rvSeasoning,
tvCell = binding.tvRightBottomCell,
pageType = 1
)
// (binding.rvSeasoning.adapter as TextCellAdapter).let { adapter ->
// list = adapter.list
// }
}
}
// private var isCookMode: Boolean = true
private fun addListener() {
// binding.modeRadioGroup.setOnCheckedChangeListener { _, checkedId ->
// when (checkedId) {
// R.id.rbModeCook -> {
// isCookMode = true
// loadCookSpan(isClicked = true)
// loadSamplingSpan()
// loadQualitySpan(isEnable = false)
// }
//
// R.id.rbModeSampling -> {
// isCookMode = false
// loadCookSpan()
// loadSamplingSpan(isClicked = true)
// loadQualitySpan(isEnable = false)
// }
//
// R.id.rbModeQuality -> {
// loadCookSpan()
// loadSamplingSpan()
// loadQualitySpan(isEnable = false)
// }
// }
// }
// binding.btnCancel.setOnClickListener { finish() }
// binding.btnConfirm.setOnClickListener { confirmSetting() }
}
private fun confirmSetting() {
// runCatching {
// showLoading()
//// list.forEachIndexed { index, entity ->
//// entity.sort = index
//// }
//// val list2 = mutableListOf<SeasoningEntity>()
//// list2.addAll(list)
//// val array = arrayOf(10, 11, 13)
//// list.forEachIndexed { index, entity ->
//// if (entity.sort == 14 && array.contains(index)) {
//// list2.remove(entity)
//// }
//// }
// Log.d(TAG, "addListener->Click: ${list.toJsonString()}")
//
// appViewModel.addSeasoning(list) {
// dismissLoading()
// if (isCookMode) {
// startActivity<SelectDishActivity> { }
// } else {
// startActivity<SamplingListActivity> { }
// }
//// val activityStack = ActivityManager.getActivityStack()
//// activityStack.forEach {
//// if (it !is SelectDishActivity && it !is SamplingListActivity) {
//// it.finish()
//// }
//// }
// }
// }.onFailure {
// it.printStackTrace()
// toast("数据提交失败")
// }
}
private fun loadQualitySpan(isClicked: Boolean = false, isEnable: Boolean = true) {
binding.rbModeQuality.text =
getModeTextSpan(
topText = modeList[2].modeName,
bottomText = modeList[2].modeDesc,
topColor = if (isEnable) if (isClicked) "#00BC71" else "#000000" else "#B4B4B4",
bottomColor = if (isEnable) "#8B8B8B" else "#B4B4B4"
)
}
private fun loadSamplingSpan(isClicked: Boolean = false, isEnable: Boolean = true) {
binding.rbModeSampling.text =
getModeTextSpan(
topText = modeList[1].modeName,
bottomText = modeList[1].modeDesc,
topColor = if (isEnable) if (isClicked) "#00BC71" else "#000000" else "#B4B4B4",
bottomColor = if (isEnable) "#8B8B8B" else "#B4B4B4"
)
}
private fun loadCookSpan(isClicked: Boolean = false, isEnable: Boolean = true) {
binding.rbModeCook.text =
getModeTextSpan(
topText = modeList[0].modeName,
bottomText = modeList[0].modeDesc,
topColor = if (isEnable) if (isClicked) "#00BC71" else "#000000" else "#B4B4B4",
bottomColor = if (isEnable) "#8B8B8B" else "#B4B4B4"
)
}
private fun getModeTextSpan(
topText: String,
topColor: String,
bottomText: String,
bottomColor: String
): SpannableStringBuilder {
return buildSpannableString {
appendText(
topText,
ForegroundColorSpan(topColor.toColorInt()),
StyleSpan(Typeface.BOLD),
AbsoluteSizeSpan(36, true),
LineHeightSpan { text, start, end, spanstartv, v, fm ->
fm.descent += 10.dp // 增加行间距
}
)
append("\n")
appendText(
bottomText,
ForegroundColorSpan(bottomColor.toColorInt()),
AbsoluteSizeSpan(26, true)
)
}
}
fun saveSeasoning(entity: SeasoningEntity) {
appViewModel.saveSeasoning(entity){
toast("保存成功")
}
}
}
@@ -0,0 +1,131 @@
package com.shuwei.dish.match.ui
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.shuwei.dish.match.R
import com.shuwei.dish.match.base.BaseActivity
import com.shuwei.dish.match.base.BaseApp
import com.shuwei.dish.match.databinding.ActivitySamplingBinding
import com.shuwei.dish.match.databinding.LayoutFoodRemindBinding
import com.shuwei.dish.match.db.AppRepository
import com.shuwei.dish.match.dialog.CommonDialog
import com.shuwei.dish.match.entity.CookFoodEntity
import com.shuwei.dish.match.ui.fragment.DishSamplingFragment
import com.shuwei.dish.match.utils.ext.gone
import com.shuwei.dish.match.utils.ext.startActivity
import com.shuwei.dish.match.utils.ext.visible
import com.shuwei.dish.match.viewmodel.AppViewModel
import com.shuwei.dish.match.viewmodel.factory.AppFactory
class DishSamplingActivity : BaseActivity() {
private lateinit var binding: ActivitySamplingBinding
var foodName: String? = null
companion object {
public const val FOOD_NAME = "foodName"
public const val PAGE_FROM = "pageFrom"
public const val HOME = "home"
}
private var pageFrom: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySamplingBinding.inflate(layoutInflater)
setContentView(binding.root)
pageFrom = intent.getStringExtra(PAGE_FROM)
setTitleBar()
setHeaderBackground()
initViewModel()
loadDishSamplingPage()
foodName = intent.getStringExtra(FOOD_NAME)
}
private fun setTitleBar() {
setTitleBar(titleBarAction = {
it.visible()
}, titleAction = {
it.text = "菜品采集"
}, rightIconActon = {
it.gone()
it.setImageResource(R.drawable.ic_setting)
it.setOnClickListener {
//startActivity<DeviceSettingActivity>()
}
}, backAction = {
it.visible()
it.setOnClickListener {
onBackPressed()
}
})
}
private var dishSamplingFragment: DishSamplingFragment? = null
private fun loadDishSamplingPage() {
if (dishSamplingFragment == null) {
dishSamplingFragment = DishSamplingFragment()
}
dishSamplingFragment?.let {
loadFragment(it)
}
}
private fun loadFragment(fragment: Fragment) {
supportFragmentManager.beginTransaction().apply {
replace(R.id.flContainer, fragment)
commit()
}
}
private lateinit var appViewModel: AppViewModel
private fun initViewModel() {
val db = BaseApp.instance!!.database
val factory =
AppFactory(AppRepository(db.appDao()))
appViewModel =
ViewModelProvider(this, factory)[AppViewModel::class.java]
}
fun getCookFoodList(action: (MutableList<CookFoodEntity>?) -> Unit) {
appViewModel.getCookFoodList(cookMode = 1) { action(it) }
}
@Suppress("DEPRECATION")
@SuppressLint("GestureBackNavigation")
@Deprecated("Deprecated in Java")
override fun onBackPressed() {
val list = dishSamplingFragment?.list
if (list.isNullOrEmpty().not()) {
//说明有新增的食材
saveDataRemindDialog()
return
}
if (pageFrom == HOME) {
startActivity<SamplingListActivity>()
}
super.onBackPressed()
}
private fun saveDataRemindDialog() {
val remindBinding = LayoutFoodRemindBinding.inflate(layoutInflater)
remindBinding.tvDialogTitle.text = "温馨提示"
remindBinding.tvDialogContent.text = "您好,当前页面存在未保存的数据,确认返回吗?"
CommonDialog(this).apply {
messageView = remindBinding.root
leftText = "取消"
rightText = "确认"
onLeftClick = { dismiss() }
onRightClick = {
dismiss()
finish()
}
onDismiss = { hideStatusBar() }
}.show()
}
}
@@ -0,0 +1,215 @@
package com.shuwei.dish.match.ui
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import androidx.recyclerview.widget.LinearLayoutManager
import com.shuwei.dish.match.R
import com.shuwei.dish.match.adapter.FoodRecordAdapter
import com.shuwei.dish.match.base.BaseActivity
import com.shuwei.dish.match.databinding.ActivityFoodSearchBinding
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
import com.shuwei.dish.match.entity.FoodRecord
import com.shuwei.dish.match.entity.FoodRecordBean
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.gone
import com.shuwei.dish.match.utils.ext.startActivity
import com.shuwei.dish.match.utils.ext.toJsonString
import com.shuwei.dish.match.utils.ext.toObject
import com.shuwei.dish.match.utils.ext.toast
import com.shuwei.dish.match.utils.ext.visible
import java.io.Serializable
class FoodSearchActivity : BaseActivity() {
companion object {
private const val TAG = "FoodSearchActivity"
const val PAGE_TYPE = "pageType"
const val FOOD_ID = "foodId"
const val FOOD_NAME = "foodName"
}
private lateinit var binding: ActivityFoodSearchBinding
private var list: MutableList<FoodRecord> = mutableListOf()
private var pageType = 0
private val recordAdapter by lazy {
FoodRecordAdapter(list).apply {
isStateViewEnable = true
setOnItemClickListener { adapter, view, position ->
if (pageType == 1) {
startActivity<PrepareCookActivity> {
putExtra(PrepareCookActivity.FOOD_ITEM, list[position] as Serializable)
}
return@setOnItemClickListener
}
setResult(RESULT_OK, Intent().apply {
putExtra(FOOD_ID, list[position].foodId)
putExtra(FOOD_NAME, list[position].foodName)
})
finish()
}
}
}
private var foodName: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityFoodSearchBinding.inflate(layoutInflater)
setContentView(binding.root)
pageType = intent.getIntExtra(PAGE_TYPE, 0)
setHeaderBackground()
foodName = intent.getStringExtra(FOOD_NAME)
binding.etInputDish.setText(foodName)
setTitleBar(titleBarAction = {
it.visible()
}, titleAction = {
it.text = "菜品搜索"
}, rightIconActon = {
it.gone()
it.setImageResource(R.drawable.ic_setting)
it.setOnClickListener {
//startActivity<DeviceSettingActivity>()
}
})
binding.rvDishSearchList.run {
layoutManager =
LinearLayoutManager(this@FoodSearchActivity, LinearLayoutManager.VERTICAL, false)
adapter = recordAdapter
}
addViewListener()
}
private fun addViewListener() {
binding.ivDishSearch.setOnClickListener { v ->
pageNo = 1
getInputAndSearch()
KeyboardUtil.hideKeyboard(v.context, v)
}
binding.refreshLayout.setEnableRefresh(true)
binding.refreshLayout.setEnableLoadMore(false)
binding.refreshLayout.setOnRefreshListener {
pageNo = 1
getInputAndSearch()
}
binding.refreshLayout.setOnLoadMoreListener {
getInputAndSearch()
}
if (foodName.isNullOrBlank().not()) {
pageNo = 1
queryListInfo(foodName!!)
}
binding.root.setOnClickListener { v ->
KeyboardUtil.hideKeyboard(v.context, v)
}
binding.etInputDish.let { v ->
v.addOnActionSearchListener {
pageNo = 1
getInputAndSearch()
KeyboardUtil.hideKeyboard(v.context, v)
}
}
}
private fun getInputAndSearch() {
val input = binding.etInputDish.text.toString().trim()
if (input.isBlank()) {
toast("请输入菜品名称")
binding.refreshLayout.finishRefresh()
return
}
queryListInfo(input)
}
private var pageNo = 1
private var pageSize = 100
@SuppressLint("NotifyDataSetChanged")
private fun queryListInfo(input: String) {
showLoading()
val map = mapOf(
"foodName" to input.trim(),
"pageNo" to "$pageNo",
"pageSize" to "$pageSize",
"canteenId" to "0"
)
val sb = StringBuilder(UrlConfig.QUERY_FOOD_LIST).apply {
append("?")
map.forEach { (key, value) -> append("$key=$value&") }
}
sb.deleteCharAt(sb.length - 1)
HttpUtil.get(
url = sb.toString(),
doSuccess = {
delayDismissLoading()
finishRefresh()
binding.refreshLayout.run {
setEnableRefresh(true)
}
val json = it.toJsonString()
val recordBean: FoodRecordBean? = json.toObject<FoodRecordBean>()
if (recordBean == null || recordBean.records.isNullOrEmpty()) {
// toast("暂未搜索到相关菜品信息")
if (pageNo == 1) {
loadEmptyView()
}
return@get
}
val records = recordBean.records
if (pageNo == 1) {
list.clear()
}
list.addAll(records!!)
recordAdapter.notifyDataSetChanged()
val isLoadMoreEnable = records.size >= pageSize
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
if (isLoadMoreEnable) {
pageNo++
}
},
doFailure = { code, msg ->
binding.refreshLayout.run {
setEnableRefresh(true)
}
toast(msg)
delayDismissLoading()
finishRefresh()
if (pageNo == 1) {
loadEmptyView()
}
}
)
}
private fun finishRefresh() {
if (pageNo == 1) {
binding.refreshLayout.finishRefresh(1200)
} else {
binding.refreshLayout.finishLoadMore(1200)
}
}
private var emptyViewBinding: LayoutEmptyViewBinding? = null
@SuppressLint("NotifyDataSetChanged")
private fun loadEmptyView() {
list.clear()
recordAdapter.notifyDataSetChanged()
if (emptyViewBinding == null) {
emptyViewBinding = LayoutEmptyViewBinding.inflate(LayoutInflater.from(this), binding.rvDishSearchList, false)
}
emptyViewBinding!!.tvContent.text = "暂无数据"
emptyViewBinding!!.tvSubContent.text = "可以尝试换个名称重新搜索"
recordAdapter.stateView = emptyViewBinding!!.root
binding.refreshLayout.run {
setEnableRefresh(false)
setEnableLoadMore(false)
}
}
}
@@ -0,0 +1,156 @@
package com.shuwei.dish.match.ui
import android.annotation.SuppressLint
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.aithings.Weigher
import com.shuwei.dish.match.R
import com.shuwei.dish.match.adapter.HomeModeAdapter
import com.shuwei.dish.match.base.BaseActivity
import com.shuwei.dish.match.base.BaseApp
import com.shuwei.dish.match.databinding.ActivityHomeBinding
import com.shuwei.dish.match.db.AppRepository
import com.shuwei.dish.match.entity.HomeModeBean
import com.shuwei.dish.match.http.HttpUtil
import com.shuwei.dish.match.http.UrlConfig
import com.shuwei.dish.match.utils.WeightUtil
import com.shuwei.dish.match.utils.ext.put
import com.shuwei.dish.match.utils.ext.startActivity
import com.shuwei.dish.match.utils.ext.toast
import com.shuwei.dish.match.viewmodel.AppViewModel
import com.shuwei.dish.match.viewmodel.factory.AppFactory
class HomeActivity : BaseActivity() {
companion object {
const val TAG = "HomeActivity"
}
private lateinit var binding: ActivityHomeBinding
private var connect: Boolean = false
@SuppressLint("HardwareIds")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
statusBarDarkFont(enable = true)
initViewModel()
// 获取 ANDROID_ID
BaseApp.instance?.androidId =
Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
binding = ActivityHomeBinding.inflate(layoutInflater)
setContentView(binding.root)
setHeaderBackground(isHomePage = true)
initRecyclerView()
getAppToken()
WeightUtil.connect { connect ->
this.connect = connect
}
Weigher.init()
Weigher.getWeight()
Weigher.startContinuousRead()
// binding.tvTopText.setOnClickListener {
// startActivity<SamplingListActivity>()
// }
// appViewModel.deleteEmptySeasoning()
// appViewModel.deleteCookFoodAndGoods(0,"") {}
// appViewModel.getCookFoodGoodsList("") {goodsList->
// goodsList.forEach {
// it.foodId = "1594990392084779010"
// appViewModel.updateGoods(it)
// }
// }
// appViewModel.deleteAll()
}
private fun initRecyclerView() {
initModeList()
binding.rvModeList.run {
layoutManager =
LinearLayoutManager(this@HomeActivity, LinearLayoutManager.VERTICAL, false)
adapter = modeAdapter
}
}
private val modeList = mutableListOf<HomeModeBean>()
private val modeAdapter by lazy {
HomeModeAdapter(modeList).apply {
addOnItemChildClickListener(R.id.layoutCard) { adapter, view, position ->
modeList[position].onClick?.invoke()
}
}
}
private fun initModeList() {
modeList.add(
HomeModeBean(
modeName = "制作模式",
modeDesc = "菜品快速制作,记录熟重",
modeIconId = R.drawable.ic_mode_cook,
onClick = {
startActivity<SelectDishActivity>()
finish()
})
)
modeList.add(
HomeModeBean(
modeName = "采样模式",
modeDesc = "菜品快速制作,记录熟重",
modeIconId = R.drawable.ic_mode_sampling,
onClick = {
goSampling()
})
)
modeList.add(
HomeModeBean(
modeName = "品控模式",
modeDesc = "菜品快速制作,记录熟重",
modeIconId = R.drawable.ic_mode_quality,
isLocked = true,
onClick = {
toast("即将解锁")
})
)
}
private lateinit var appViewModel: AppViewModel
private fun initViewModel() {
val db = BaseApp.instance!!.database
val factory = AppFactory(AppRepository(db.appDao()))
appViewModel = ViewModelProvider(this, factory)[AppViewModel::class.java]
}
private fun goSampling() {
appViewModel.countCookFood(cookMode = 1) {
if (it > 0) {
startActivity<SamplingListActivity>()
finish()
return@countCookFood
}
startActivity<DishSamplingActivity> {
putExtra(DishSamplingActivity.PAGE_FROM, DishSamplingActivity.HOME)
}
finish()
}
}
private fun getAppToken() {
val url = "${UrlConfig.GET_TOKEN}?qrcodeId=${BaseApp.instance?.androidId}"
// Log.d(TAG, "getToken: url = $url")
HttpUtil.get(url = url, doSuccess = {
BaseApp.getSharedPref()?.put("token" to it)
BaseApp.instance?.token = it.toString()
}) { code, msg ->
toast(msg)
}
}
}
@@ -0,0 +1,316 @@
package com.shuwei.dish.match.ui
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Typeface
import android.os.Bundle
import android.util.Log
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import com.aithings.Weigher
import com.shuwei.dish.match.R
import com.shuwei.dish.match.adapter.DishPartAdapter
import com.shuwei.dish.match.base.BaseActivity
import com.shuwei.dish.match.databinding.ActivityPrepareCookBinding
import com.shuwei.dish.match.databinding.LayoutFoodRemindBinding
import com.shuwei.dish.match.dialog.BottomDialog
import com.shuwei.dish.match.dialog.CommonDialog
import com.shuwei.dish.match.entity.CookFoodEntity
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
import com.shuwei.dish.match.entity.FoodRecord
import com.shuwei.dish.match.http.HttpUtil
import com.shuwei.dish.match.http.UrlConfig
import com.shuwei.dish.match.utils.SwipeCallback
import com.shuwei.dish.match.utils.WeightUtil
import com.shuwei.dish.match.utils.ext.clickWithDebounce
import com.shuwei.dish.match.utils.ext.gone
import com.shuwei.dish.match.utils.ext.toJsonString
import com.shuwei.dish.match.utils.ext.toObject
import com.shuwei.dish.match.utils.ext.toast
import com.shuwei.dish.match.utils.ext.visible
import java.io.Serializable
@SuppressLint("NotifyDataSetChanged")
class PrepareCookActivity : BaseActivity() {
companion object {
const val TAG = "CookActivity"
const val FOOD_ITEM = "foodItem"
}
private lateinit var binding: ActivityPrepareCookBinding
private var food: FoodRecord? = null
private var goodsList: MutableList<CookFoodGoodsEntity>? = null
@Suppress("DEPRECATION")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityPrepareCookBinding.inflate(layoutInflater)
setContentView(binding.root)
setHeaderBackground()
setTitleBar(titleBarAction = {
it.visible()
}, titleAction = {
it.text = "菜品制作"
}, rightIconActon = {
it.gone()
it.setImageResource(R.drawable.ic_setting)
it.setOnClickListener {
//startActivity<DeviceSettingActivity>()
}
}, backAction = {
it.setOnClickListener {
onBackPressed()
}
})
food = intent.extras?.getSerializable(FOOD_ITEM) as FoodRecord?
binding.tvDishName.text = food?.foodName ?: ""
addViewClickListener()
getDishDetail()
}
private fun addViewClickListener() {
binding.ivWeightClear.setOnClickListener {
Weigher.tareTwo(2)
}
WeightUtil.addWeightListener(getWeight = { address, state, weight ->
Log.d(TAG, "addViewClickListener: address=$address,state=$state,weight=$weight")
if (address == 2) {
binding.tvDishPartWeight.text = "${weight}"
}
})
binding.ivWeightAdd.setOnClickListener {
if (clickIndex == -1) {
toast("请选择菜品构成")
return@setOnClickListener
}
val clickItem = list[clickIndex]
clickItem.run {
if (isNewDishType && materialType != 1 && materialType != 2) {
toast("请选择主辅材类型")
return@setOnClickListener
}
}
val weight = binding.tvDishPartWeight.text.toString().toInt()
if (weight <= 0) {
toast("食材用量需要大于0")
return@setOnClickListener
}
Log.d(TAG, "addViewClickListener->useRealWeight=$weight")
clickItem.run {
useWeight = weight
isSetFinished = true
dishPartAdapter.notifyItemChanged(clickIndex)
}
}
binding.tvAddFood.clickWithDebounce {
BottomDialog(goodsType = 0).show(this) { item ->
val filterResult = list.firstOrNull { it.goodsId == item.goodsId }
if (filterResult != null) {
toast("不允许重复添加同一食材")
return@show
}
list.add(CookFoodGoodsEntity().apply {
goodsId = item.goodsId
goodsName = item.goodsName
// materialType =
isNewDishType = true
})
onItemClick(list.size - 1)
}
}
binding.btnCook.clickWithDebounce {
val count = list.count { it.isSetFinished.not() }
if (count > 0) {
showRemindDialog()
return@clickWithDebounce
}
goToSubmit()
}
binding.rgCook.setOnCheckedChangeListener { group, checkedId ->
val tempType =
if (checkedId == R.id.rbDishTypeFirst) 1 else if (checkedId == R.id.rbDishTypeSecond) 2 else -1
list[clickIndex].materialType = tempType
dishPartAdapter.notifyItemChanged(clickIndex)
binding.tvDishType.text =
if (tempType == 1) "主材" else if (tempType == 2) "辅材" else ""
}
}
private fun goToSubmit() {
getGoodsList()
if (goodsList.isNullOrEmpty()) {
toast("菜品构成信息未设置")
return
}
Log.d(TAG, "goToSubmit: goodsList:${goodsList?.toJsonString()}")
startActivity(
Intent(this, SubmitDishActivity::class.java)
.putExtra(SubmitDishActivity.GOODS_LIST, goodsList as Serializable)
.putExtra(SubmitDishActivity.FOOD_ITEM, food as Serializable)
)
}
private fun getGoodsList() {
if (goodsList == null) {
goodsList = mutableListOf()
}
list.forEach {
if (it.isSetFinished) {
goodsList?.add(CookFoodGoodsEntity().apply {
foodId = food!!.foodId
goodsId = it.goodsId
relateionType = it.relateionType
allEdible = it.allEdible
goodsName = it.goodsName
materialType = it.materialType
useWeight = it.useWeight ?: 0
goodsOrRelationCode = it.goodsOrRelationCode
})
}
}
}
private fun showRemindDialog() {
val remindBinding = LayoutFoodRemindBinding.inflate(layoutInflater)
CommonDialog(this).apply {
messageView = remindBinding.root
leftText = "返回调整"
rightText = "确认无误"
onLeftClick = { dismiss() }
onRightClick = {
goToSubmit()
dismiss()
}
onDismiss = { hideStatusBar() }
}.show()
}
private fun getDishDetail() {
//649
val url = "${UrlConfig.DISH_DETAIL}?foodId=${food?.foodId}"
HttpUtil.get(
url = url,
doSuccess = {
val json = it.toJsonString()
Log.d(TAG, "getDishDetail: json:$json")
val detail: CookFoodEntity? = json.toObject<CookFoodEntity>()
if (detail == null) {
toast("查询菜品信息为空")
return@get
}
loadDishDetail(detail)
}) { code, msg ->
toast(msg)
}
}
private fun loadDishDetail(detail: CookFoodEntity) {
val voList = detail.stFoodInfoConstituteList
if (voList.isNullOrEmpty()) {
return
}
//筛选出主材和辅材
val tempDate = voList.filter { it.materialType == 1 || it.materialType == 2 }
.apply {
forEach { it.useWeight = 0 }
}
list.clear()
list.addAll(tempDate)
firstReqSize = list.size
initRecyclerView()
}
private var firstReqSize = 0
private val list = mutableListOf<CookFoodGoodsEntity>()
private val dishPartAdapter by lazy {
DishPartAdapter(list).apply {
setOnItemClickListener { _, _, positon ->
onItemClick(positon)
}
}
}
private fun onItemClick(positon: Int) {
this@PrepareCookActivity.clickIndex = positon
list[clickIndex].let { it ->
binding.tvDishShowName.run {
text = it.goodsName
setTypeface(typeface, Typeface.BOLD)
}
binding.tvDishType.text =
if (it.materialType == 1) "主材" else if (it.materialType == 2) "辅材" else ""
list.forEach { bean -> bean.isItemClicked = false }
it.isItemClicked = true
dishPartAdapter.notifyDataSetChanged()
if (it.isNewDishType) {
binding.dividerDishType.visible()
binding.llDishType.visible()
} else {
binding.dividerDishType.gone()
binding.llDishType.gone()
}
}
}
private var clickIndex = -1
private fun initRecyclerView() {
binding.rvDishPartList.run {
layoutManager =
LinearLayoutManager(this@PrepareCookActivity, LinearLayoutManager.VERTICAL, false)
adapter = dishPartAdapter
val itemTouchHelper = ItemTouchHelper(SwipeCallback(dishPartAdapter) { position ->
if (list[position].isNewDishType.not()) {
toast("只能删除刚添加的食材")
dishPartAdapter.notifyItemChanged(position)
return@SwipeCallback
}
dishPartAdapter.removeAt(position)
toast("已删除")
})
itemTouchHelper.attachToRecyclerView(this)
}
}
@Suppress("DEPRECATION")
@SuppressLint("GestureBackNavigation")
@Deprecated("Deprecated in Java")
override fun onBackPressed() {
if (list.size > firstReqSize) {
//说明有新增的食材
saveDataRemindDialog()
return
}
val filterResult = list.firstOrNull { (it.useWeight ?: 0) > 0 }
if (filterResult != null) {
//说明有称重的数据
saveDataRemindDialog()
return
}
super.onBackPressed()
}
private fun saveDataRemindDialog() {
val remindBinding = LayoutFoodRemindBinding.inflate(layoutInflater)
remindBinding.tvDialogTitle.text = "温馨提示"
remindBinding.tvDialogContent.text = "您好,当前页面存在尚未保存的数据,确认返回上页吗?"
CommonDialog(this).apply {
messageView = remindBinding.root
leftText = "取消"
rightText = "确认"
onLeftClick = { dismiss() }
onRightClick = {
dismiss()
finish()
}
onDismiss = { hideStatusBar() }
}.show()
}
}
@@ -0,0 +1,111 @@
package com.shuwei.dish.match.ui
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.shuwei.dish.match.R
import com.shuwei.dish.match.base.BaseActivity
import com.shuwei.dish.match.base.BaseApp
import com.shuwei.dish.match.databinding.ActivitySamplingBinding
import com.shuwei.dish.match.db.AppRepository
import com.shuwei.dish.match.entity.CookFoodEntity
import com.shuwei.dish.match.ui.fragment.SamplingListFragment
import com.shuwei.dish.match.utils.ext.gone
import com.shuwei.dish.match.utils.ext.startActivity
import com.shuwei.dish.match.utils.ext.toast
import com.shuwei.dish.match.utils.ext.visible
import com.shuwei.dish.match.viewmodel.AppViewModel
import com.shuwei.dish.match.viewmodel.factory.AppFactory
class SamplingListActivity : BaseActivity() {
private lateinit var binding: ActivitySamplingBinding
companion object {
const val IS_COOKING = "isCooking"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySamplingBinding.inflate(layoutInflater)
setContentView(binding.root)
setTitleBar()
setHeaderBackground()
initViewModel()
loadSamplingListPage()
}
private fun setTitleBar() {
setTitleBar(titleBarAction = {
it.visible()
}, titleAction = {
it.text = "采样历史"
}, rightIconActon = {
it.visible()
it.setImageResource(R.drawable.ic_setting)
it.setOnClickListener {
startActivity<DeviceSettingActivity> {
putExtra(DeviceSettingActivity.COOK_MODE, 2)
}
}
}, backAction = {
it.gone()
})
}
private var samplingListFragment: SamplingListFragment? = null
private fun loadSamplingListPage() {
if (samplingListFragment == null) {
samplingListFragment = SamplingListFragment()
}
samplingListFragment?.let {
loadFragment(it)
}
}
private fun loadFragment(fragment: Fragment) {
supportFragmentManager.beginTransaction().apply {
replace(R.id.flContainer, fragment)
commit()
}
}
private lateinit var appViewModel: AppViewModel
private fun initViewModel() {
val db = BaseApp.instance!!.database
val factory =
AppFactory(AppRepository(db.appDao()))
appViewModel =
ViewModelProvider(this, factory)[AppViewModel::class.java]
}
fun getCookFoodList(action: (MutableList<CookFoodEntity>?) -> Unit) {
appViewModel.getCookFoodList(cookMode = 1) { action(it) }
}
fun deleteCookFoodAndGoods(foodId: String, action: () -> Unit) {
appViewModel.deleteCookFoodAndGoods(cookMode = 1, foodId = foodId, onFinish = action)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
val isCooking = intent?.getBooleanExtra(IS_COOKING, false) ?: false
samplingListFragment?.refreshPage(isCooking)
}
@Deprecated("Deprecated in Java")
@SuppressLint("GestureBackNavigation", "MissingSuperCall")
override fun onBackPressed() {
//super.onBackPressed()
//当前页面不允许返回
//dialog = toast("不允许返回操作")
}
}
@@ -0,0 +1,138 @@
package com.shuwei.dish.match.ui
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import com.shuwei.dish.match.R
import com.shuwei.dish.match.base.BaseActivity
import com.shuwei.dish.match.base.BaseApp
import com.shuwei.dish.match.databinding.ActivitySelectDishBinding
import com.shuwei.dish.match.db.AppRepository
import com.shuwei.dish.match.entity.CookFoodEntity
import com.shuwei.dish.match.ui.fragment.DishListFragment
import com.shuwei.dish.match.utils.KeyboardUtil
import com.shuwei.dish.match.utils.ext.addOnActionSearchListener
import com.shuwei.dish.match.utils.ext.gone
import com.shuwei.dish.match.utils.ext.startActivity
import com.shuwei.dish.match.utils.ext.toast
import com.shuwei.dish.match.utils.ext.visible
import com.shuwei.dish.match.viewmodel.AppViewModel
import com.shuwei.dish.match.viewmodel.factory.AppFactory
class SelectDishActivity : BaseActivity() {
companion object {
const val IS_COOKING = "isCooking"
}
private lateinit var binding: ActivitySelectDishBinding
private var dishListFragment: DishListFragment? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySelectDishBinding.inflate(layoutInflater)
setContentView(binding.root)
setHeaderBackground()
setTitleBar(titleBarAction = {
it.visible()
}, titleAction = {
it.text = "选择菜品"
}, rightIconActon = {
it.visible()
it.setImageResource(R.drawable.ic_setting)
it.setOnClickListener {
startActivity<DeviceSettingActivity> {
putExtra(DeviceSettingActivity.COOK_MODE, 1)
}
}
}, backAction = {
it.gone()
})
initViewModel()
addViewListener()
loadFragment()
}
private lateinit var appViewModel: AppViewModel
var dinnerType: String = "早餐"
private fun initViewModel() {
val db = BaseApp.instance!!.database
val factory =
AppFactory(AppRepository(db.appDao()))
appViewModel =
ViewModelProvider(this, factory)[AppViewModel::class.java]
}
fun getCookFoodList(action: (MutableList<CookFoodEntity>?) -> Unit) {
appViewModel.getCookFoodList(cookMode = 0) { action(it) }
}
fun addViewListener() {
binding.dishRadioGroup.setOnCheckedChangeListener { _, checkedId ->
dinnerType = when (checkedId) {
R.id.rbBreakfast -> "早餐"
R.id.rbLunch -> "午餐"
R.id.rbDinner -> "晚餐"
else -> ""
}
dishListFragment?.getDishList(1, false)
}
// binding.llSearchBar.setOnClickListener {
// startActivity<FoodSearchActivity> {
// putExtra(FoodSearchActivity.PAGE_TYPE, 1)
// }
// }
binding.etInputDish.addOnActionSearchListener {
jumpSearch()
}
binding.ivDishSearch.setOnClickListener {
jumpSearch()
}
}
private fun jumpSearch() {
val searchText = binding.etInputDish.text.toString().trim()
if (searchText.isBlank()) {
toast(binding.etInputDish.hint.toString())
return
}
startActivity<FoodSearchActivity> {
putExtra(FoodSearchActivity.PAGE_TYPE, 1)
putExtra(FoodSearchActivity.FOOD_NAME, searchText)
}
KeyboardUtil.hideKeyboard(this, binding.etInputDish)
}
private fun loadFragment() {
DishListFragment.instance().let {
dishListFragment = it
supportFragmentManager.beginTransaction().apply {
replace(R.id.flSubPage, it)
commit()
}
}
}
fun deleteCookFoodAndGoods(foodId: String, action: () -> Unit) {
appViewModel.deleteCookFoodAndGoods(cookMode = 0, foodId = foodId, onFinish = action)
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
val isCooking = intent?.getBooleanExtra(IS_COOKING, false) ?: false
dishListFragment?.getDishList(1, isCooking)
}
@Deprecated("Deprecated in Java")
@SuppressLint("GestureBackNavigation", "MissingSuperCall")
override fun onBackPressed() {
//super.onBackPressed()
//当前页面不允许返回
// dialog = toast("不允许返回操作")
}
}
@@ -0,0 +1,393 @@
package com.shuwei.dish.match.ui
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.util.SparseArray
import android.util.SparseIntArray
import androidx.core.util.forEach
import androidx.lifecycle.ViewModelProvider
import com.aithings.Weigher
import com.google.gson.reflect.TypeToken
import com.shuwei.dish.match.R
import com.shuwei.dish.match.adapter.SeasoningCellTool
import com.shuwei.dish.match.adapter.TextCellAdapter
import com.shuwei.dish.match.base.BaseActivity
import com.shuwei.dish.match.base.BaseApp
import com.shuwei.dish.match.databinding.ActivitySubmitDishBinding
import com.shuwei.dish.match.db.AppRepository
import com.shuwei.dish.match.entity.CookFoodEntity
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
import com.shuwei.dish.match.entity.FoodRecord
import com.shuwei.dish.match.entity.SeasoningEntity
import com.shuwei.dish.match.http.HttpUtil
import com.shuwei.dish.match.http.UrlConfig
import com.shuwei.dish.match.utils.DataUtil
import com.shuwei.dish.match.utils.WeightUtil
import com.shuwei.dish.match.utils.ext.clickWithDebounce
import com.shuwei.dish.match.utils.ext.gone
import com.shuwei.dish.match.utils.ext.startActivity
import com.shuwei.dish.match.utils.ext.toJsonString
import com.shuwei.dish.match.utils.ext.toType
import com.shuwei.dish.match.utils.ext.toast
import com.shuwei.dish.match.utils.ext.visible
import com.shuwei.dish.match.viewmodel.AppViewModel
import com.shuwei.dish.match.viewmodel.factory.AppFactory
@SuppressLint("UseSparseArrays")
class SubmitDishActivity : BaseActivity() {
companion object {
const val TAG = "SubmitDishActivity"
const val FOOD_ITEM = "foodItem"
const val GOODS_LIST = "goodsList"
}
private lateinit var binding: ActivitySubmitDishBinding
private var food: FoodRecord? = null
private var goodsList: MutableList<CookFoodGoodsEntity>? = null
private var isCooking = false
private val cookFoodEntity by lazy {
CookFoodEntity().apply {
food?.let {
foodId = it.foodId ?: ""
foodName = it.foodName
cookMode = it.cookMode
}
canteenId = 0
}
}
@Suppress("unchecked_cast", "DEPRECATION")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySubmitDishBinding.inflate(layoutInflater)
setContentView(binding.root)
initViewModel()
setHeaderBackground()
intent.extras?.apply {
food = getSerializable(FOOD_ITEM) as FoodRecord?
Log.d(TAG, "onCreate: cookMode=${food?.cookMode}")
isCooking = food?.isCooking ?: false
if (isCooking) {
//烹饪中,从本地查询数据
loadSeasoningFromLocal()
} else {
//非烹饪中,从菜品主辅材配置页面带入数据
goodsList = getSerializable(GOODS_LIST) as MutableList<CookFoodGoodsEntity>?
}
}
setTitleBar(titleBarAction = {
it.visible()
}, titleAction = {
it.text = food?.foodName
}, rightIconActon = {
it.gone()
it.setImageResource(R.drawable.ic_setting)
it.setOnClickListener {
//startActivity<DeviceSettingActivity>()
}
})
addViewListener()
}
private fun loadSeasoningFromLocal() {
appViewModel.getCookFoodGoodsList(food?.foodId!!) { it ->
goodsList = mutableListOf()
//设置主辅材数据
goodsList?.addAll(it.filter { goods -> goods.materialType != 3 })
//获取调料数据并展示
val filterList: List<SeasoningEntity>? = it.filter { goods -> goods.materialType == 3 }
.map { entity ->
SeasoningEntity().also { se ->
se.goodsId = entity.goodsId
se.goodsName = entity.goodsName
se.goodsOrRelationCode = entity.goodsOrRelationCode
se.relateionType = entity.relateionType
se.materialType = entity.materialType
se.allEdible = entity.allEdible
se.useWeight = entity.useWeight
se.popularName = entity.popularName
se.canteenId = entity.canteenId
se.relateionType_dictText = entity.relateionType_dictText
se.foodId = entity.foodId
se.sort = entity.sort
se.pageType = 0
}
}
filterList?.toMutableList()?.let { cellData ->
loadTextCell(cellData)
}
}
}
private lateinit var seasoningList: List<SeasoningEntity>
private var isFirstSave = true
fun updateSeasoningList(list: MutableList<SeasoningEntity>) {
if (isFirstSave) {
val json = list.toJsonString()
val typeToken = object : TypeToken<List<SeasoningEntity>>() {}
seasoningList = json.toType(typeToken = typeToken)
isFirstSave = false
}
}
private val seasoningArray by lazy {
SparseArray<Int>()
}
private val firstGoodsArray by lazy {
SparseArray<Int>()
}
private fun addViewListener() {
addWeightListener()
binding.btnWeightClear.setOnClickListener { Weigher.tareTwo(1) }
binding.btnCook.clickWithDebounce {
cook()
}
binding.btnSubmit.clickWithDebounce {
if (cookFoodEntity.foodWeight <= 0) {
toast("未识别到菜品熟重")
return@clickWithDebounce
}
submit()
}
}
private fun addWeightListener() {
WeightUtil.addWeightListener(getWeight = { address, state, weight ->
if (address == 1) {
cookFoodEntity.foodWeight = weight
binding.tvTotalWeight.text = "${weight / 1000f}"
}
// if (state != SensorScale.STATE_STABLE) {
// return@addWeightListener
// }
val firstWeight = firstGoodsArray.get(address, null)
if (firstWeight != weight) {
Log.d(
TAG,
"addViewListener: state=$state,address=$address,weight=$weight,firstWeight=$firstWeight"
)
}
if (firstWeight == null) {
//未设置数据
firstGoodsArray.put(address, weight)
return@addWeightListener
}
// val cookingWeight =
// if (isCooking && seasoningList.isNullOrEmpty().not())
// seasoningList?.get(weightRelateArray2.get(address))?.weight ?: 0
// else 0
// var realUseWeight = firstWeight - weight + cookingWeight
var realUseWeight = firstWeight - weight
realUseWeight = if (realUseWeight > 0) realUseWeight else 0
// Log.d(
// TAG,
// "addViewListener: state=$state,address=$address,总共使用重量:$realUseWeight"
// )
seasoningArray.put(address, realUseWeight)
refreshSeasoningWeight()
})
}
@SuppressLint("NotifyDataSetChanged")
private fun refreshSeasoningWeight() {
binding.rvSeasoning.adapter?.let { adapter ->
if (adapter is TextCellAdapter) {
adapter.list.let { items ->
weightRelateArray.forEach { key, value ->
items[key].useWeight =
(seasoningArray.get(value) ?: 0) + getCookingSeasoning(value)
}
}
adapter.notifyDataSetChanged()
TextCellAdapter.loadCell(binding.tvRightBottomCell, adapter.list[14])
}
}
}
private fun getCookingSeasoning(address: Int): Int {
if (isCooking.not()) return 0
if (seasoningList.isEmpty()) return 0
val weight = seasoningList[weightRelateArray2.get(address)].useWeight ?: 0
//Log.i(TAG, "getCookingSeasoning: weight[${address}]=$weight,seasoningList=${seasoningList.toJsonString()}")
return weight
}
private val weightRelateArray2 by lazy {
SparseIntArray().apply {
weightRelateArray.forEach { key, value ->
if (value == 3) {
put(3, 14)
} else {
put(value, key)
}
}
}
}
private val weightRelateArray by lazy {
DataUtil.getWeighAddressArray()
}
// private fun prepareData(acton: () -> Unit) {
//
// //只有制作和采样列表页面才能进入设置页面,提交页面无法进行设置,不存在调料数据被修改的问题
// val seasoningJson = realSeasoningData.toJsonString()
// val typeToken = object : TypeToken<List<CookFoodGoodsEntity>>() {}
// val tempSeasoningList = seasoningJson.toType(typeToken = typeToken)
// goodsList?.addAll(tempSeasoningList)
// acton()
//
// }
private fun cook() {
if (food == null || goodsList.isNullOrEmpty()) {
toast("未获取到菜品或构成信息")
return
}
val realSeasoningData = (binding.rvSeasoning.adapter as TextCellAdapter).list
if (realSeasoningData.isEmpty() && !isCooking) {
toast("未获取到调料信息")
return
}
showLoading()
//只有制作和采样列表页面才能进入设置页面,提交页面无法进行设置,不存在调料数据被修改的问题
val seasoningJson = realSeasoningData.toJsonString()
val typeToken = object : TypeToken<List<CookFoodGoodsEntity>>() {}
val tempSeasoningList = seasoningJson.toType(typeToken = typeToken)
goodsList?.addAll(tempSeasoningList)
val isSamplingData = food!!.cookMode == 1
if (isSamplingData) {
//生成临时foodId,解决采样模式没有foodId,无法关联数据的问题
val tempFoodId = cookFoodEntity.foodId.ifBlank { "${System.currentTimeMillis()}" }
cookFoodEntity.foodId = tempFoodId
}
//全部设置同一foodId
goodsList?.forEach {
it.foodId = cookFoodEntity.foodId
}
//保存菜品-保存主辅料调料
appViewModel.saveCookFoodAndGoods(
cookMode = food!!.cookMode,
entity = cookFoodEntity,
list = goodsList,
onFinish = {
runOnUiThread {
dismissLoading()
jumpPage(isSamplingData, true)
}
})
}
private fun submit() {
if (food == null || goodsList.isNullOrEmpty()) {
toast("未获取到菜品或构成信息")
return
}
val realSeasoningData = (binding.rvSeasoning.adapter as TextCellAdapter).list
if (realSeasoningData.isEmpty() && !isCooking) {
toast("未获取到调料信息")
return
}
showLoading()
//只有制作和采样列表页面才能进入设置页面,提交页面无法进行设置,不存在调料数据被修改的问题
val seasoningJson = realSeasoningData.toJsonString()
val typeToken = object : TypeToken<List<CookFoodGoodsEntity>>() {}
val tempSeasoningList = seasoningJson.toType(typeToken = typeToken)
tempSeasoningList.forEach { entity ->
val realWeight = entity.useWeight ?: 0
val filterData = goodsList?.firstOrNull { it.goodsId == entity.goodsId }
//确保重量大于0,且无重复数据
if (realWeight > 0 && filterData == null) {
goodsList?.add(entity)
}
}
cookFoodEntity.stFoodInfoConstituteList = this@SubmitDishActivity.goodsList
val isSamplingData = food!!.cookMode == 1
if (isSamplingData) {
//采样模式没有foodId
cookFoodEntity.foodId = ""
goodsList?.forEach { it.foodId = "" }
}
val json = cookFoodEntity.toJsonString()
Log.d(TAG, "submit: json=$json")
HttpUtil.postJson(
url = UrlConfig.SUBMIT_DISH,
json = json,
doSuccess = {
Log.d(TAG, "submit: postJson=$it")
//删除本地数据
appViewModel.deleteCookFoodAndGoods(
cookMode = food!!.cookMode,
foodId = food!!.foodId!!
) {
dismissLoading()
jumpPage(isSamplingData, false)
}
}, doFailure = { code, msg ->
Log.d(TAG, "submit: postJson:code=$code,msg=$msg")
toast(msg)
dismissLoading()
})
}
private fun jumpPage(isSampling: Boolean, isCooking: Boolean) {
if (isSampling) {
startActivity<SamplingListActivity> {
putExtra(SelectDishActivity.IS_COOKING, isCooking)
}
return
}
startActivity<SelectDishActivity> {
putExtra(SelectDishActivity.IS_COOKING, isCooking)
}
}
private lateinit var appViewModel: AppViewModel
private fun initViewModel() {
val db = BaseApp.instance!!.database
val factory =
AppFactory(AppRepository(db.appDao()))
appViewModel =
ViewModelProvider(this, factory)[AppViewModel::class.java]
}
override fun onResume() {
super.onResume()
binding.tvRightBottomCell.visible()
if (isCooking.not()) {
//烹饪中使用本地数据,未烹饪则使用默认的调料配置数据
appViewModel.loadSeasoning {
Log.d(TAG, "onResume: loadSeasoning:${it.toJsonString()}")
loadTextCell(it)
}
}
}
private fun loadTextCell(list: MutableList<SeasoningEntity>) {
SeasoningCellTool.loadData(
activity = this,
initList = list,
recyclerView = binding.rvSeasoning,
tvCell = binding.tvRightBottomCell
)
}
}
@@ -0,0 +1,243 @@
package com.shuwei.dish.match.ui.fragment
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import com.shuwei.dish.match.adapter.DishShowAdapter
import com.shuwei.dish.match.databinding.FragmentDishListBinding
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
import com.shuwei.dish.match.entity.FoodRecord
import com.shuwei.dish.match.entity.FoodRecordBean
import com.shuwei.dish.match.http.HttpUtil
import com.shuwei.dish.match.http.UrlConfig
import com.shuwei.dish.match.ui.PrepareCookActivity
import com.shuwei.dish.match.ui.SelectDishActivity
import com.shuwei.dish.match.ui.SubmitDishActivity
import com.shuwei.dish.match.utils.SwipeCallback
import com.shuwei.dish.match.utils.ext.startActivity
import com.shuwei.dish.match.utils.ext.toJsonString
import com.shuwei.dish.match.utils.ext.toObject
import com.shuwei.dish.match.utils.ext.toast
import java.io.Serializable
class DishListFragment : Fragment() {
companion object {
private const val TAG = "DishListFragment"
// const val DINNER_TYPE = "dinnerType"
public fun instance(): DishListFragment {
return DishListFragment().apply {
// arguments = Bundle().apply {
// putInt(DINNER_TYPE, type)
// }
}
}
}
// private var dinnerType = ""
private var pageNo = 1
private val pageSize = 30
private lateinit var activity: SelectDishActivity
private var list: MutableList<FoodRecord> = mutableListOf()
private val dishAdapter by lazy {
DishShowAdapter(list = list).apply {
isStateViewEnable = true
setOnItemClickListener { adapter, view, position ->
val item = list[position]
if (item.isCooking) {
//烹饪中,跳到称熟重页面
context.startActivity<SubmitDishActivity> {
putExtra(
SubmitDishActivity.FOOD_ITEM,
item as Serializable
)
}
return@setOnItemClickListener
}
context.startActivity<PrepareCookActivity> {
putExtra(
SubmitDishActivity.FOOD_ITEM,
item as Serializable
)
}
}
}
}
private lateinit var binding: FragmentDishListBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentDishListBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
activity = requireActivity() as SelectDishActivity
//toast("type=$type")
binding.rvDishList.run {
layoutManager =
LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
adapter = dishAdapter
val itemTouchHelper = ItemTouchHelper(SwipeCallback(dishAdapter) { position ->
if (list[position].isCooking.not()) {
activity.toast("只能删除烹饪中的菜品")
dishAdapter.notifyItemChanged(position)
return@SwipeCallback
}
activity.deleteCookFoodAndGoods(foodId = list[position].foodId ?: "") {
dishAdapter.removeAt(position)
activity.toast("已删除")
}
})
itemTouchHelper.attachToRecyclerView(this)
}
addViewListener()
pageNo = 1
activity.showLoading()
getDishList()
}
private fun addViewListener() {
binding.refreshLayout.run {
setEnableRefresh(true)
setEnableLoadMore(false)
setOnRefreshListener {
pageNo = 1
getDishList()
}
setOnLoadMoreListener {
getDishList()
}
}
}
fun getDishList(pageNo: Int, isCooking: Boolean) {
this.pageNo = pageNo
getDishList()
}
@SuppressLint("NotifyDataSetChanged")
@Suppress("unchecked_cast")
fun getDishList() {
activity.showLoading()
val map = mapOf(
// "foodName" to input,
"dinnerType" to activity.dinnerType,
"pageNo" to "$pageNo",
"pageSize" to "$pageSize",
"canteenId" to "0"
)
val sb = StringBuilder(UrlConfig.QUERY_FOOD_LIST).apply {
append("?")
map.forEach { (key, value) -> append("$key=$value&") }
}
sb.deleteCharAt(sb.length - 1)
HttpUtil.get(
url = sb.toString(),
doSuccess = {
binding.refreshLayout.run {
setEnableRefresh(true)
}
activity.delayDismissLoading()
finishRefresh()
val json = it.toJsonString()
val recordBean: FoodRecordBean? = json.toObject<FoodRecordBean>()
if (recordBean == null || recordBean.records.isNullOrEmpty()) {
//toast("暂未搜索到相关菜品信息")
if (pageNo == 1) {
loadEmptyView()
}
return@get
}
val records = recordBean.records
if (pageNo == 1) {
list.clear()
}
list.addAll(records!!)
dishAdapter.notifyDataSetChanged()
val isLoadMoreEnable = records.size >= pageSize
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
if (isLoadMoreEnable) {
pageNo++
}
refreshLocalData(list)
}, doFailure = { code, msg ->
binding.refreshLayout.run {
setEnableRefresh(true)
}
toast(msg)
finishRefresh()
if (pageNo == 1) {
loadEmptyView()
}
activity.delayDismissLoading()
})
}
private var emptyViewBinding: LayoutEmptyViewBinding? = null
@SuppressLint("NotifyDataSetChanged")
private fun loadEmptyView() {
list.clear()
dishAdapter.notifyDataSetChanged()
if (emptyViewBinding == null) {
emptyViewBinding = LayoutEmptyViewBinding.inflate(
LayoutInflater.from(requireContext()),
binding.rvDishList,
false
)
}
emptyViewBinding!!.tvContent.text = "暂无数据"
emptyViewBinding!!.tvSubContent.text = "获取菜品数据失败,请检查网络设置或稍后重试"
dishAdapter.stateView = emptyViewBinding!!.root
//dishAdapter.setStateViewLayout(requireContext(), R.layout.layout_empty_view)
}
private fun finishRefresh() {
if (pageNo == 1) {
binding.refreshLayout.finishRefresh(1200)
} else {
binding.refreshLayout.finishLoadMore(1200)
}
}
@SuppressLint("NotifyDataSetChanged")
private fun refreshLocalData(list: MutableList<FoodRecord>) {
activity.getCookFoodList { cookFoodEntities ->
if (cookFoodEntities.isNullOrEmpty()) {
return@getCookFoodList
}
val tempList = mutableListOf<FoodRecord>()
cookFoodEntities.forEachIndexed { index, entity ->
val food = list.firstOrNull { it.foodId == entity.foodId }
if (food != null) {
food.isCooking = true
food.sort = index
tempList.add(food)
}
}
list.removeAll(tempList)
list.addAll(0, tempList)
dishAdapter.notifyDataSetChanged()
}
}
}
@@ -0,0 +1,187 @@
package com.shuwei.dish.match.ui.fragment
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.aithings.Weigher
import com.shuwei.dish.match.R
import com.shuwei.dish.match.adapter.DishPartAdapter
import com.shuwei.dish.match.databinding.FragmentDishSamplingBinding
import com.shuwei.dish.match.dialog.BottomDialog
import com.shuwei.dish.match.entity.CookFoodGoodsEntity
import com.shuwei.dish.match.entity.FoodRecord
import com.shuwei.dish.match.ui.FoodSearchActivity
import com.shuwei.dish.match.ui.DishSamplingActivity
import com.shuwei.dish.match.ui.SubmitDishActivity
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.clickWithDebounce
import com.shuwei.dish.match.utils.ext.startActivity
import com.shuwei.dish.match.utils.ext.toJsonString
import com.shuwei.dish.match.utils.ext.toast
import java.io.Serializable
class DishSamplingFragment : Fragment() {
private val TAG = "DishSamplingFragment"
private lateinit var activity: DishSamplingActivity
private lateinit var binding: FragmentDishSamplingBinding
val list: MutableList<CookFoodGoodsEntity> = mutableListOf()
private var tempDishEntity: CookFoodGoodsEntity? = null
private var dishMaterialType = 1
private val dishAdapter by lazy {
DishPartAdapter(list).apply {
addOnItemChildClickListener(R.id.ivOperateIcon) { _, _, positon ->
//删除操作
removeAt(positon)
}
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
binding = FragmentDishSamplingBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
activity = requireActivity() as DishSamplingActivity
addViewClickListener()
foodName = activity.foodName
binding.etInputDish.setText(foodName)
}
@SuppressLint("NotifyDataSetChanged")
private fun addViewClickListener() {
binding.rvDishPartList.run {
layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
adapter = dishAdapter
}
binding.tvInputDishType.run {
clickWithDebounce {
BottomDialog(goodsType = 0).show(activity) { item ->
val filterResult = list.firstOrNull { it.goodsName == item.goodsName }
if (filterResult != null) {
toast("不允许重复添加同一食材")
return@show
}
text = item.goodsName
tempDishEntity = CookFoodGoodsEntity().apply {
goodsId = item.goodsId
goodsName = item.goodsName
relateionType = item.relateionType?:0
goodsOrRelationCode = item.goodsOrRelationCode
// TODO: 待定
//allEdible = item.allEdible
}
}
}
}
binding.ivWeightClear.setOnClickListener {
Weigher.tareTwo(2)
}
WeightUtil.addWeightListener(getWeight = { address, state, weight ->
Log.d(TAG, "addViewClickListener: address=$address,state=$state,weight=$weight")
if (address == 2) {
tempDishEntity?.useWeight = weight
binding.tvDishPartWeight.text = "${weight}"
}
})
binding.ivWeightAdd.setOnClickListener {
if (tempDishEntity == null) {
activity.toast("请输入食材名称")
return@setOnClickListener
}
if (binding.rgSampling.checkedRadioButtonId == -1) {
activity.toast("请选择主辅材类型")
return@setOnClickListener
}
if (tempDishEntity!!.useWeight == null) {
activity.toast("请将食材放在称上称重")
return@setOnClickListener
}
tempDishEntity!!.apply {
isSamplingPage = true
materialType = dishMaterialType
}
val result = list.firstOrNull { it.goodsId == tempDishEntity!!.goodsId }
if (result != null) {
activity.toast("${result.goodsName}食材已添加,请勿重复操作")
return@setOnClickListener
}
list.add(tempDishEntity!!)
dishAdapter.notifyDataSetChanged()
tempDishEntity = null
binding.tvInputDishType.text = ""
binding.rgSampling.clearCheck()
}
binding.rgSampling.setOnCheckedChangeListener { group, checkedId ->
dishMaterialType = if (checkedId == R.id.rbDishTypeFirst) 1 else 2
}
binding.ivDishSearch.setOnClickListener { v ->
jumpSearch(v)
}
binding.btnCook.clickWithDebounce {
val showFoodName = binding.etInputDish.text.toString().trim()
if (showFoodName.isBlank()) {
toast("菜品名称为空")
return@clickWithDebounce
}
if (list.isEmpty()) {
toast("菜品构成信息未设置")
return@clickWithDebounce
}
val food = FoodRecord()
food.foodId = foodId
food.foodName = showFoodName
food.cookMode = 1
Log.d(TAG, "goToSubmit: goodsList:${list.toJsonString()}")
activity.startActivity<SubmitDishActivity> {
putExtra(SubmitDishActivity.GOODS_LIST, list as Serializable)
putExtra(SubmitDishActivity.FOOD_ITEM, food as Serializable)
}
}
binding.etInputDish.let { v ->
v.addOnActionSearchListener {
jumpSearch(v)
}
}
}
private fun jumpSearch(v: View) {
activity.launch(Intent(activity, FoodSearchActivity::class.java).apply {
putExtra(FoodSearchActivity.FOOD_NAME, binding.etInputDish.text.toString().trim() )
}) { intent ->
intent?.let {
foodId = it.getStringExtra(FoodSearchActivity.FOOD_ID)
foodName = it.getStringExtra(FoodSearchActivity.FOOD_NAME)
binding.etInputDish.run {
setText(foodName)
setSelection(text.length)
}
}
}
KeyboardUtil.hideKeyboard(v.context, v)
}
private var foodId: String? = null
private var foodName: String? = null
}
@@ -0,0 +1,254 @@
package com.shuwei.dish.match.ui.fragment
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import com.shuwei.dish.match.R
import com.shuwei.dish.match.adapter.SamplingAdapter
import com.shuwei.dish.match.databinding.FragmentSamplingListBinding
import com.shuwei.dish.match.databinding.LayoutEmptyViewBinding
import com.shuwei.dish.match.entity.FoodRecord
import com.shuwei.dish.match.entity.FoodRecordBean
import com.shuwei.dish.match.http.HttpUtil
import com.shuwei.dish.match.http.UrlConfig
import com.shuwei.dish.match.ui.DishSamplingActivity
import com.shuwei.dish.match.ui.SamplingListActivity
import com.shuwei.dish.match.ui.SubmitDishActivity
import com.shuwei.dish.match.utils.DateTimeUtil
import com.shuwei.dish.match.utils.SwipeCallback
import com.shuwei.dish.match.utils.ext.startActivity
import com.shuwei.dish.match.utils.ext.toJsonString
import com.shuwei.dish.match.utils.ext.toObject
import com.shuwei.dish.match.utils.ext.toast
import java.io.Serializable
class SamplingListFragment : Fragment() {
companion object {
private const val TAG = "SamplingListFragment"
}
private lateinit var activity: SamplingListActivity
private lateinit var binding: FragmentSamplingListBinding
private var list: MutableList<FoodRecord> = mutableListOf()
private val dishAdapter by lazy {
SamplingAdapter(list = list).apply {
isStateViewEnable = true
setOnItemClickListener { adapter, view, position ->
val item = list[position]
if (item.isCooking) {
//烹饪中,跳到称熟重页面
context.startActivity<SubmitDishActivity> {
putExtra(
SubmitDishActivity.FOOD_ITEM,
item as Serializable
)
}
return@setOnItemClickListener
}
context.startActivity<DishSamplingActivity> {
putExtra(DishSamplingActivity.FOOD_NAME, item.foodName)
}
}
}
}
@SuppressLint("NotifyDataSetChanged")
private fun initRecyclerView() {
binding.rvSamplingList.run {
layoutManager =
LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
adapter = dishAdapter
val itemTouchHelper = ItemTouchHelper(SwipeCallback(dishAdapter) { position ->
if (list[position].isCooking.not()) {
activity.toast("只能删除烹饪中的菜品")
dishAdapter.notifyItemChanged(position)
return@SwipeCallback
}
activity.deleteCookFoodAndGoods(foodId = list[position].foodId?:"") {
if (list.size > 1) {
dishAdapter.removeAt(position)
} else {
loadEmptyView()
}
activity.toast("已删除")
}
})
itemTouchHelper.attachToRecyclerView(this)
}
}
private fun addViewListener() {
binding.btnAddSampling.setOnClickListener {
activity.startActivity<DishSamplingActivity>()
}
binding.refreshLayout.setOnRefreshListener {
pageNo = 1
getSamplingList()
}
binding.refreshLayout.setOnLoadMoreListener {
getSamplingList()
}
binding.dishRadioGroup.setOnCheckedChangeListener { group, checkedId ->
if (checkedId == R.id.rbCooking) {
refreshLocalData()
} else {
pageNo = 1
getSamplingList()
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentSamplingListBinding.inflate(inflater, container, false)
return binding.root
}
@SuppressLint("NotifyDataSetChanged")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
activity = requireActivity() as SamplingListActivity
initRecyclerView()
addViewListener()
refreshLocalData()
}
var pageNo = 1
private val pageSize = 30
@SuppressLint("NotifyDataSetChanged")
fun getSamplingList() {
activity.showLoading()
val map = mapOf(
// "foodName" to input,
"pageNo" to "$pageNo",
"pageSize" to "$pageSize",
"canteenId" to "0"
)
val sb = StringBuilder(UrlConfig.SAMPLING_LIST).apply {
append("?")
map.forEach { (key, value) -> append("$key=$value&") }
}
sb.deleteCharAt(sb.length - 1)
HttpUtil.get(
url = sb.toString(),
doSuccess = {
binding.refreshLayout.run {
setEnableRefresh(true)
}
activity.delayDismissLoading()
finishRefresh()
val json = it.toJsonString()
val recordBean: FoodRecordBean? = json.toObject<FoodRecordBean>()
if (recordBean == null || recordBean.records.isNullOrEmpty()) {
//toast("暂未搜索到相关菜品信息")
if (pageNo == 1) {
loadEmptyView()
}
return@get
}
val records = recordBean.records
if (pageNo == 1) {
list.clear()
}
list.addAll(records!!)
dishAdapter.notifyDataSetChanged()
val isLoadMoreEnable = records.size >= pageSize
binding.refreshLayout.setEnableLoadMore(isLoadMoreEnable)
binding.refreshLayout.setEnableRefresh(true)
if (isLoadMoreEnable) {
pageNo++
}
}, doFailure = { code, msg ->
binding.refreshLayout.run {
setEnableRefresh(true)
}
toast(msg)
finishRefresh()
binding.refreshLayout.setEnableRefresh(true)
activity.delayDismissLoading()
if (pageNo == 1) {
loadEmptyView()
}
})
}
private fun finishRefresh() {
if (pageNo == 1) {
binding.refreshLayout.finishRefresh(1200)
} else {
binding.refreshLayout.finishLoadMore(1200)
}
}
private var emptyViewBinding:LayoutEmptyViewBinding?=null
@SuppressLint("NotifyDataSetChanged")
private fun loadEmptyView() {
list.clear()
dishAdapter.notifyDataSetChanged()
if (emptyViewBinding == null) {
emptyViewBinding = LayoutEmptyViewBinding.inflate(LayoutInflater.from(requireContext()), binding.rvSamplingList, false)
}
emptyViewBinding!!.tvContent.text = "暂无数据"
emptyViewBinding!!.tvSubContent.text = "今日暂无采样数据,点击下方按钮新增采样"
dishAdapter.stateView = emptyViewBinding!!.root
//dishAdapter.setStateViewLayout(requireContext(), R.layout.layout_empty_view)
binding.refreshLayout.run {
setEnableRefresh(false)
setEnableLoadMore(false)
}
}
fun refreshPage(isCooking: Boolean) {
binding.dishRadioGroup.check(
if (isCooking) R.id.rbCooking else R.id.rbFinished
)
}
@SuppressLint("NotifyDataSetChanged")
fun refreshLocalData() {
activity.showLoading()
//查询本地数据
activity.getCookFoodList { cookFoodEntities ->
activity.delayDismissLoading()
if (cookFoodEntities.isNullOrEmpty()) {
loadEmptyView()
return@getCookFoodList
}
val tempList = mutableListOf<FoodRecord>()
cookFoodEntities
.sortedByDescending { DateTimeUtil.convert(dateStr = it.createTime) }
.forEach { entity ->
tempList.add(FoodRecord().apply {
foodId = entity.foodId
foodName = entity.foodName
cookMode = 1
isCooking = true
})
}
list.clear()
list.addAll(tempList)
dishAdapter.notifyDataSetChanged()
binding.refreshLayout.run {
setEnableRefresh(false)
setEnableLoadMore(false)
}
}
}
}