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.FragmentIntImpQueryWarehouseBinding
import com.lukouguoji.gjj.holder.IntImpQueryWarehouseViewHolder
import com.lukouguoji.gjj.viewModel.IntImpQueryDetailsViewModel
import com.lukouguoji.module_base.base.CommonAdapter
import com.lukouguoji.module_base.bean.GjjWarehouse
import com.lukouguoji.module_base.http.net.NetApply

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

    private lateinit var binding: FragmentIntImpQueryWarehouseBinding
    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_warehouse,
            container,
            false
        )
        binding.lifecycleOwner = viewLifecycleOwner

        initRecyclerView()
        observeData()

        return binding.root
    }

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

        binding.rvWarehouseList.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = this@IntImpQueryWarehouseFragment.adapter
        }
    }

    private fun observeData() {
        viewModel.warehouseList.observe(viewLifecycleOwner) { mapList ->
            if (mapList.isEmpty()) {
                binding.rvWarehouseList.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, GjjWarehouse::class.java)
                    } catch (e: Exception) {
                        e.printStackTrace()
                        GjjWarehouse()
                    }
                }

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

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