package com.lukouguoji.gjj.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.lukouguoji.gjj.R
import com.lukouguoji.gjj.databinding.FragmentIntImpQueryStorageBinding
import com.lukouguoji.gjj.holder.IntImpQueryStorageViewHolder
import com.lukouguoji.gjj.viewModel.IntImpQueryDetailsViewModel
import com.lukouguoji.module_base.base.CommonAdapter
import com.lukouguoji.module_base.bean.GjjStorageUse
import com.lukouguoji.module_base.http.net.NetApply

/**
 * 国际进港查询详情 - 库位信息Fragment
 */
class IntImpQueryStorageFragment : Fragment() {

    private lateinit var binding: FragmentIntImpQueryStorageBinding
    private lateinit var viewModel: IntImpQueryDetailsViewModel
    private lateinit var adapter: CommonAdapter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = DataBindingUtil.inflate(
            inflater,
            R.layout.fragment_int_imp_query_storage,
            container,
            false
        )
        binding.lifecycleOwner = viewLifecycleOwner

        initRecyclerView()
        observeData()

        return binding.root
    }

    private fun initRecyclerView() {
        adapter = CommonAdapter(
            requireContext(),
            R.layout.item_int_imp_query_storage,
            IntImpQueryStorageViewHolder::class.java
        )

        binding.rvStorageList.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = this@IntImpQueryStorageFragment.adapter
        }
    }

    private fun observeData() {
        viewModel.storageUseList.observe(viewLifecycleOwner) { mapList ->
            if (mapList.isEmpty()) {
                binding.rvStorageList.visibility = View.GONE
                binding.llEmpty.visibility = View.VISIBLE
            } else {
                val beanList = mapList.map { map ->
                    try {
                        val json = NetApply.gson.toJson(map)
                        NetApply.gson.fromJson(json, GjjStorageUse::class.java)
                    } catch (e: Exception) {
                        e.printStackTrace()
                        GjjStorageUse()
                    }
                }

                binding.rvStorageList.visibility = View.VISIBLE
                binding.llEmpty.visibility = View.GONE
                adapter.refresh(beanList)
            }
        }
    }

    companion object {
        @JvmStatic
        fun newInstance(vm: IntImpQueryDetailsViewModel) =
            IntImpQueryStorageFragment().apply {
                viewModel = vm
            }
    }
}
