package com.develop.step.ui.recipes_detail

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.develop.base.ext.updateText
import com.develop.common.ui.CommonBVMFragment
import com.develop.step.R
import com.develop.step.databinding.FragmentDetailCookSourceBinding
import com.develop.step.ui.recipes_detail.model.CookSourceItem
import com.develop.step.viewmodel.CookDetailViewModel
import com.drake.brv.utils.linear
import com.drake.brv.utils.models
import com.drake.brv.utils.setup

class CookDetailSourceFragment :
    CommonBVMFragment<FragmentDetailCookSourceBinding, CookDetailViewModel>() {
    override fun createViewModel(): CookDetailViewModel {
        return getViewModelOfActivity(CookDetailViewModel::class.java)
    }

    override fun createViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentDetailCookSourceBinding {
        return FragmentDetailCookSourceBinding.inflate(inflater, container, false)
    }

    override fun onPostCreateView() {
        super.onPostCreateView()
        binding.rvList.apply {
            linear()
            setup {
                addType<CookSourceItem>(R.layout.item_cook_source)
                onBind {
                    val model = getModel<CookSourceItem>()
                    findView<TextView>(R.id.tv_source_name).updateText(model.name)
                    findView<TextView>(R.id.tv_source_amount).updateText(model.amount)
                }
            }
        }
        viewModel.getRecipeLiveData().observe(viewLifecycleOwner) {
            viewModel.portionSizeLiveData.observe(viewLifecycleOwner) { size ->
                val sourceItems = mutableListOf<CookSourceItem>()
                val originalList = mutableListOf<CookSourceItem>()
                for (recipeFood in it.material) {
                    val sourceItem = CookSourceItem(
                        recipeFood.foodName ?: "",
                        "${recipeFood.amount} ${recipeFood.unit}"
                    )
                    if (recipeFood.recipePortionSizeNumber == size.portionSize) {
                        sourceItems.add(sourceItem)
                    }
                    originalList.add(sourceItem)
                }
                if (sourceItems.isEmpty()) {
                    // 防止没有任何数据显示
                    sourceItems.addAll(originalList)
                }
                val jarCount = size?.portionSize?.toIntOrNull() ?: 1
                val string = if (jarCount > 1) {
                    getString(com.develop.common.R.string.make_n_jars, jarCount.toString())
                } else {
                    getString(com.develop.common.R.string.make_1_jar)
                }
                binding.tvStepTitle.text = string
                binding.rvList.models = sourceItems
            }
        }
    }
}