package com.base.browserwhite.ui.fragment

import android.content.Intent
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import com.base.browserwhite.R
import com.base.browserwhite.bean.ConstObject.BAIDU
import com.base.browserwhite.bean.ConstObject.BING
import com.base.browserwhite.bean.ConstObject.DUCKDUCKGO
import com.base.browserwhite.bean.ConstObject.GOOGLE
import com.base.browserwhite.bean.ConstObject.YAHOO
import com.base.browserwhite.bean.ConstObject.YANDEX
import com.base.browserwhite.bean.WebSiteBean
import com.base.browserwhite.bean.defaultValue
import com.base.browserwhite.bean.webSiteGroupBeanList
import com.base.browserwhite.databinding.FragmentHomeBinding
import com.base.browserwhite.service.StayNotificationService.Companion.restartStartStayNotification
import com.base.browserwhite.ui.activity.scanqrc.ScanQRCActivity
import com.base.browserwhite.ui.activity.webbrowser.WebBrowserActivity
import com.base.browserwhite.ui.activity.webstore.WevStoreActivity
import com.base.browserwhite.ui.adapter.NewsAdapter
import com.base.browserwhite.ui.adapter.WebsiteAdapter
import com.base.browserwhite.ui.views.DialogViews.showSearchEngineDialog
import com.base.browserwhite.ui.views.itemtouch.MyItemTouchHelperCallBack
import com.base.browserwhite.utils.AppPreferences
import com.base.browserwhite.utils.LogEx


class HomeFragment : BaseFragment<FragmentHomeBinding>() {

    private val TAG = "HomeFragment"
    override val binding: FragmentHomeBinding by lazy {
        FragmentHomeBinding.inflate(layoutInflater)
    }

    private lateinit var websiteAdapter: WebsiteAdapter
    private lateinit var itemTouchHelper: ItemTouchHelper
    private lateinit var newsAdapter: NewsAdapter
    private var isLoadingMore = false

    override fun setView() {

        binding.rvWeb.layoutManager = GridLayoutManager(requireContext(), 4, LinearLayoutManager.VERTICAL, false)
        websiteAdapter = WebsiteAdapter(0) { bean ->
            if (bean.name == "Increase") {
                requireContext().startActivity(Intent(requireContext(), WevStoreActivity::class.java))
            } else {
                requireContext().startActivity(Intent(requireContext(), WebBrowserActivity::class.java).apply {
                    putExtra("uri", bean.url)
                })
            }

        }
        binding.rvWeb.adapter = websiteAdapter
        itemTouchHelper = ItemTouchHelper(MyItemTouchHelperCallBack())
        itemTouchHelper.attachToRecyclerView(binding.rvWeb)

        newsAdapter = NewsAdapter(lifecycleScope)
        binding.rvNews.adapter = newsAdapter
        binding.rvNews.addOnScrollListener(object : OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val lastVisibleItemPosition = (recyclerView.layoutManager as LinearLayoutManager).findLastVisibleItemPosition()
                if (!isLoadingMore && lastVisibleItemPosition == newsAdapter.itemCount - 5) {
                    isLoadingMore = true
                    // 触发加载更多数据
                    newsAdapter.loadMore {
                        LogEx.logDebug(TAG, "loadMore BACK")
                        isLoadingMore = false
                    }
                }

            }
        })
        isLoadingMore = true
        newsAdapter.loadMore {
            LogEx.logDebug(TAG, "loadMore BACK")
            isLoadingMore = false
        }
    }

    override fun onResume() {
        super.onResume()
        setWebSiteData()
    }

    private fun setWebSiteData() {
        val recommendWebSite = webSiteGroupBeanList.flatMap { it.items }.filter { bean ->
            AppPreferences.getInstance().getBoolean("${bean.id}_${bean.name}", defaultValue(bean.name))
        }
        websiteAdapter.setData(recommendWebSite, WebSiteBean(name = "Increase").apply {
            localIcon = R.mipmap.increase
            increase = true
        })
    }

    override fun setListener() {
        super.setListener()
        binding.llWeather.setOnClickListener {
            requireContext().restartStartStayNotification()
        }

        binding.flSearchEngine.setOnClickListener {
            requireContext().showSearchEngineDialog { website ->
                when (website) {
                    GOOGLE -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_google)
                    }

                    BING -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_bing)
                    }

                    YAHOO -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_yahoo)
                    }

                    DUCKDUCKGO -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_xuckd)
                    }

                    YANDEX -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_yandex)
                    }

                    BAIDU -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_baidu)
                    }

                }
            }
        }

        binding.flScan.setOnClickListener {
            requireContext().startActivity(Intent(requireContext(), ScanQRCActivity::class.java))
        }
    }


}