package com.app.intelligent.board.uifragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager  // 改用LinearLayoutManager
import com.app.intelligent.board.AppContextHelper
import com.app.intelligent.board.uimodel.KeyboardItemInfo
import com.app.intelligent.board.databinding.FragmentFavoritesKeyboardBinding
import com.app.intelligent.board.uidb.MyAppDatabase
import com.app.intelligent.board.uidb.MyAppDatabaseManager
import com.app.intelligent.board.uilistener.FavoriteItemDeleteListener
import com.app.intelligent.board.uiadapter.FavoriteItemAdapter
import com.app.intelligent.board.utils.KeyboardRvItemDecoration
import kotlinx.coroutines.launch

class FavoritesKeyboardFragment : Fragment() {
    private lateinit var vb: FragmentFavoritesKeyboardBinding
    companion object {
        @JvmStatic
        fun newInstance() = FavoritesKeyboardFragment()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        vb = FragmentFavoritesKeyboardBinding.inflate(layoutInflater)
        init()
        return vb.root
    }

    private fun init() {
        val mainAdapter = FavoriteItemAdapter(
            requireContext()
        ).apply {
            setRemoveLike(object : FavoriteItemDeleteListener {
                override fun OnRemoveLike(data: KeyboardItemInfo) {
                    lifecycleScope.launch {
                        MyAppDatabaseManager.removeLike(data)
                    }
                }
            })
        }

        // 配置RecyclerView：改用LinearLayoutManager（一行一列更适配）
        vb.likeRecycler.run {
            adapter = mainAdapter
            layoutManager = LinearLayoutManager(requireContext())  // 核心：替换为线性布局
            // 原15改为5，缩小RecyclerView的条目间距
            addItemDecoration(KeyboardRvItemDecoration(5, 5, 0))
            setHasFixedSize(true)  // 提升性能
        }

        // 监听数据变化
        MyAppDatabase.Companion.baseDataBase.ThemesDao().queryAllLike().observe(requireActivity()) {
            Log.d(AppContextHelper.Companion.TAG, "---------it=${it?.size}")
            if(it.isNullOrEmpty()){
                vb.likeRecycler.isVisible = false
                vb.emptyTitle.isVisible = true
            }else{
                vb.likeRecycler.isVisible = true
                vb.emptyTitle.isVisible = false
                mainAdapter.setForYouList(it)
            }
        }
    }
}