package com.rdiot.yx485.ui.family

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.drake.net.utils.scopeDialog
import com.rdiot.yx485.BuildConfig
import com.rdiot.yx485.R
import com.rdiot.yx485.adapter.FamilyAdapter
import com.rdiot.yx485.base.BaseFragment
import com.rdiot.yx485.base.FamilyDataModelFactory
import com.rdiot.yx485.bean.FamilyData
import com.rdiot.yx485.databinding.FraFamilyListBinding
import com.rdiot.yx485.net.getAllFamilyData
import com.rdiot.yx485.ui.family.model.FamilyDataViewModel
import kotlinx.coroutines.delay

/**
 * 家庭列表
 * @author mR2hao
 * @date 2022/12/3
 */
class FamilyListFragment : BaseFragment<FraFamilyListBinding>() {
    private val familyDataViewModel: FamilyDataViewModel by activityViewModels { FamilyDataModelFactory() }

    override fun getLayoutId() = R.layout.fra_family_list

    private lateinit var familyAdapter: FamilyAdapter

    override fun initView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) {
        binding.nb.setLeftClickListener { act.finish() }
        binding.nb.setRightClickListener { findNavController().navigate(R.id.action_familyListFragment_to_addFamilyFragment) }

        familyAdapter = FamilyAdapter(object : FamilyAdapter.OnItemClickListener {
            override fun onItemClicked(position: Int, familyData: FamilyData) {
                familyDataViewModel.selFamilyData = familyData
                findNavController().navigate(R.id.action_familyListFragment_to_familyInfoFragment)
            }
        })

        binding.rv.apply {
            adapter = familyAdapter
            layoutManager = LinearLayoutManager(act)
        }
    }

    override fun onResume() {
        super.onResume()
        scopeDialog(cancelable = BuildConfig.DEBUG) {
            delay(100)
            getAllFamilyData(true).await().apply {
                familyAdapter.update(this)
            }
        }
    }


}