package com.develop.step.details

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import androidx.fragment.app.activityViewModels
import com.develop.food.base.ui.BaseFragment
import com.develop.food.base.utils.ResDimension
import com.develop.food.base.utils.isNightTheme
import com.develop.food.base.utils.setGone
import com.develop.step.R
import com.develop.step.databinding.FragmentDetailCookSourceBinding
import java.math.BigDecimal

class CookDetailSourceFragment: BaseFragment() {

    private lateinit var binding: FragmentDetailCookSourceBinding
    private val adapter = CookDetailSourceAdapter()
    private val viewModel by activityViewModels<CookDetailViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentDetailCookSourceBinding.inflate(
            inflater, container, false
        )
        binding.rvList.adapter = adapter
        val params = binding.ivCollapse.layoutParams as RelativeLayout.LayoutParams
        if (isNightTheme()){
            params.width = ResDimension(R.dimen.convert_83px).toInt()
            params.height = ResDimension(R.dimen.convert_83px).toInt()
            binding.ivCollapse.layoutParams = params
        }
        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 ?: "",
                        "${BigDecimal.valueOf(recipeFood.amount ?: 0f.toDouble()).stripTrailingZeros().toPlainString()} ${recipeFood.unit}"
                    )
                    if (recipeFood.recipePortionSizeNumber == size.portionSize) {
                        sourceItems.add(sourceItem)
                    }
                    originalList.add(sourceItem)
                }
                if (sourceItems.isEmpty()) {
                    // 防止没有任何数据显示
                    sourceItems.addAll(originalList)
                }
                adapter.setNewInstance(sourceItems)
                val jarCount = size?.portionSize?.toIntOrNull() ?: 1
                val string = if (jarCount > 1) {
                    getString(R.string.make_n_jars, jarCount.toString())
                } else {
                    getString(R.string.make_1_jar)
                }
                binding.tvStepTitle.text = string
            }
        }
        if (isNightTheme()){
            binding.ivCollapse.setGone()
        }
        binding.ivCollapse.setOnClickListener {

        }
        return binding.root
    }

}