package com.base.browserwhite.ui.activity.bookmark

import android.annotation.SuppressLint
import android.content.Intent
import android.view.View
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import com.base.browserwhite.R
import com.base.browserwhite.bean.BookmarkBean
import com.base.browserwhite.databinding.FragmentBookmarkBinding
import com.base.browserwhite.ui.activity.webbrowser.WebBrowserActivity
import com.base.browserwhite.ui.fragment.BaseFragment
import com.base.browserwhite.ui.views.BookmarkDialog.showBookmarkMoreDialog
import com.base.browserwhite.ui.views.DialogViews.showDeleteTipDialog
import com.base.browserwhite.utils.ShortcutUtils
import com.base.browserwhite.utils.SpBeanUtils
import com.google.gson.Gson


class BookmarkFragment : BaseFragment<FragmentBookmarkBinding>() {

    private val TAG = "BookmarkFragment"

    override val binding: FragmentBookmarkBinding by lazy {
        FragmentBookmarkBinding.inflate(layoutInflater)
    }

    lateinit var bookmarkAdapter: BookmarkAdapter

    private val bookmarkList = arrayListOf<BookmarkBean>()
    private var viewInit: Boolean = false

    @SuppressLint("NotifyDataSetChanged")
    override fun setView() {

        bookmarkAdapter = BookmarkAdapter()
        binding.rv.adapter = bookmarkAdapter

        bookmarkAdapter.changeFolderAction = { folderId ->
            val list = bookmarkList.filter { it.folderId == folderId }
            binding.llEmpty.isVisible = list.isEmpty()
            bookmarkAdapter.submitList(list)
        }
        bookmarkAdapter.moreAction = { view, bean ->
            requireContext().showBookmarkMoreDialog(
                view, if (bean.isFolder) 0 else -1,
                //新开
                openNewTab = {
                    startActivity(Intent(requireContext(), WebBrowserActivity::class.java).apply {
                        putExtra("url", bean.url)
                    })
                },
                //删除
                deleteAction = {
                    if (bean.isFolder) {//书签目录
                        val desc = "Delete folder [${bean.name}] and the bookmarks in the folder?"
                        requireContext().showDeleteTipDialog(desc) {
                            //删除书签目录
                            SpBeanUtils.deleteSpBeanCondition(SpBeanUtils.BOOKMARK_SP_KEY, bean.id)
                            bookmarkList.remove(bean)
                            bookmarkAdapter.remove(bean)

                            //删除目录下书签
                            val subBeanList = bookmarkList.filter { it.folder == bean.name }
                            subBeanList.forEach { subBean ->
                                SpBeanUtils.deleteSpBeanCondition(SpBeanUtils.BOOKMARK_SP_KEY, subBean.id)
                                bookmarkList.remove(subBean)
                                //删除书签导航
                                SpBeanUtils.deleteSpBeanCondition(SpBeanUtils.BOOKMARK_NAV_SP_KEY, bean.id)
                            }
                        }
                    } else {//书签直接删除
                        SpBeanUtils.deleteSpBeanCondition(SpBeanUtils.BOOKMARK_SP_KEY, bean.id)
                        bookmarkList.remove(bean)
                        bookmarkAdapter.remove(bean)
                        //删除书签导航
                        SpBeanUtils.deleteSpBeanCondition(SpBeanUtils.BOOKMARK_NAV_SP_KEY, bean.id)
                    }
                },
                //编辑
                editAction = {
                    BookmarkFolderEditActivity.editFolder = bean
                    val launcher = (requireActivity() as BookmarkActivity).launcher
                    launcher.launch(Intent(Intent(requireContext(), BookmarkFolderEditActivity::class.java)))
                },
                //添加导航
                addNavAction = {
                    SpBeanUtils.addSpBean(SpBeanUtils.BOOKMARK_NAV_SP_KEY, bean)
                },
                //选择
                selectAction = {
                    (requireActivity() as BookmarkActivity).selectUI()
                },
                //添加桌面快捷方式
                addDeskAction = {
                    val appName = this.resources.getString(R.string.app_name)
                    ShortcutUtils.requestCreateShortcut(
                        requireContext(), "my_shortcut_id", appName, appName,
                        WebBrowserActivity::class.java, R.mipmap.logo, intentAction = { jIntent ->
                            jIntent.putExtra("url", bean.url)
                        }
                    )
                }
            )
        }
        viewInit = true
        initData()
    }


    override fun setListener() {
        super.setListener()
        binding.editSearch.addTextChangedListener {
            if (it.isNullOrEmpty()) {
                showAllList()
                binding.tvCancel.visibility = View.GONE
                return@addTextChangedListener
            } else {
                binding.tvCancel.visibility = View.VISIBLE
                filterList(it.toString())
            }
        }
        binding.tvCancel.setOnClickListener {
            binding.editSearch.setText("")
            binding.tvCancel.visibility = View.GONE
        }
    }

    private fun filterList(content: String) {
        val filterList = bookmarkList.filter { it.folderId == bookmarkAdapter.currentFolderId }.filter { it.name.contains(content) }
        binding.llEmpty.isVisible = filterList.isEmpty()
        bookmarkAdapter.submitList(filterList)
    }

    private fun showAllList() {
        val list = bookmarkList.filter { it.folderId == bookmarkAdapter.currentFolderId }
        binding.llEmpty.isVisible = list.isEmpty()
        bookmarkAdapter.submitList(list)
    }

    fun initData() {
        if (!viewInit) return

        bookmarkList.clear()
        val list = SpBeanUtils.getSpBeanList(SpBeanUtils.BOOKMARK_SP_KEY)
        val gson = Gson()
        val items = list.map { gson.fromJson(it, BookmarkBean::class.java) }

        bookmarkList.addAll(items)
        bookmarkAdapter.currentFolderId = 0
        bookmarkAdapter.submitList(bookmarkList.filter { it.folderId == bookmarkAdapter.currentFolderId })
        binding.llEmpty.isVisible = items.isEmpty()
    }


}