package com.apps.sketchmaster.view

import com.apps.sketchmaster.data.MainViewModel
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.apps.sketchmaster.adapter.ThreeTypeAdapter
import com.apps.sketchmaster.event.DeleteClickListener
import com.apps.sketchmaster.databinding.FragmentPageLikeBinding

class PageLikeFragment : Fragment(), DeleteClickListener {
    private lateinit var binding: FragmentPageLikeBinding
    private lateinit var mainViewModel: MainViewModel
    private var adapter = ThreeTypeAdapter()
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentPageLikeBinding.inflate(inflater,container,false)
        mainViewModel = ViewModelProvider(requireActivity())[MainViewModel::class.java]
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init()
    }

    private fun init() {
        adapter.setListener(this)
        setupRecyclerView()
        binding.recyclerView.adapter = adapter
        mainViewModel.locals.observe(viewLifecycleOwner) { list ->
            if (list.isNotEmpty()) {
                binding.recyclerView.visibility = View.VISIBLE
                binding.llEmpty.visibility = View.GONE
                Log.d("YYYYY", "Collect is change,list is$list")
                adapter.setLocalList(list, 2)
                adapter.notifyDataSetChanged()
            } else {
                binding.recyclerView.visibility = View.GONE
                binding.llEmpty.visibility = View.VISIBLE
            }
        }
        val gridLayoutManager = GridLayoutManager(requireActivity(), 3)
        binding.recyclerView.layoutManager = gridLayoutManager
    }

    private fun setupRecyclerView() {
        // 先设置空适配器，让UI快速显示
        binding.recyclerView.adapter = adapter
        val gridLayoutManager = GridLayoutManager(requireActivity(), 3)
        binding.recyclerView.layoutManager = gridLayoutManager
        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.setItemViewCacheSize(20)
        binding.recyclerView.isDrawingCacheEnabled = true
        binding.recyclerView.drawingCacheQuality = View.DRAWING_CACHE_QUALITY_HIGH
    }

    override fun onClick(name: String) {
        val tag = "ImageDialog"
        if (requireActivity().supportFragmentManager.findFragmentByTag(tag) == null) {
            val dialog = IntentDialog.newInstance(name)
            dialog.show(requireActivity().supportFragmentManager, tag)
        }
    }
}