package com.base.browserwhite.ui.fragment

import android.content.Intent
import android.text.TextUtils
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo.IME_ACTION_DONE
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.base.browserwhite.R
import com.base.browserwhite.bean.ConstObject
import com.base.browserwhite.bean.ConstObject.APP_PROCESS
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.JUNK_CLEANER
import com.base.browserwhite.bean.ConstObject.NEWS
import com.base.browserwhite.bean.ConstObject.YAHOO
import com.base.browserwhite.bean.ConstObject.YANDEX
import com.base.browserwhite.bean.ConstObject.searchEngineSp
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.fcm.NotificationUtil
import com.base.browserwhite.help.NewsUtils.requestNews
import com.base.browserwhite.service.StayNotificationService.Companion.restartStartStayNotification
import com.base.browserwhite.ui.activity.appprocess.AppProcessActivity
import com.base.browserwhite.ui.activity.cleanjunk.ScanJunkActivity
import com.base.browserwhite.ui.activity.news.NewsActivity
import com.base.browserwhite.ui.activity.news.NewsDetailActivity
import com.base.browserwhite.ui.activity.scanqrc.ScanQRCActivity
import com.base.browserwhite.ui.activity.weather.WeatherInterface
import com.base.browserwhite.ui.activity.webbrowser.WebBrowserActivity
import com.base.browserwhite.ui.adapter.HeadWebsiteAdapter
import com.base.browserwhite.ui.adapter.HeaderAdapter
import com.base.browserwhite.ui.adapter.NewsAdapter
import com.base.browserwhite.ui.views.DialogViews.showSearchEngineDialog
import com.base.browserwhite.utils.AppPreferences
import com.base.browserwhite.utils.ClipboardUtils.copyText
import com.base.browserwhite.utils.LinkSearchUtils
import com.base.browserwhite.utils.LinkSearchUtils.getBaiduSearch
import com.base.browserwhite.utils.LinkSearchUtils.getBingSearch
import com.base.browserwhite.utils.LinkSearchUtils.getDuckDuckGoSearch
import com.base.browserwhite.utils.LinkSearchUtils.getGoogleSearch
import com.base.browserwhite.utils.LinkSearchUtils.getYahooSearch
import com.base.browserwhite.utils.LinkSearchUtils.getYandexSearch
import com.base.browserwhite.utils.LogEx
import com.chad.library.adapter4.QuickAdapterHelper
import com.chad.library.adapter4.loadState.LoadState
import com.chad.library.adapter4.loadState.trailing.TrailingLoadStateAdapter


class HomeFragment : BaseFragment<FragmentHomeBinding>() {

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


    private lateinit var newsAdapter: NewsAdapter
    private lateinit var helper: QuickAdapterHelper
    private var isLoading = false
    private var headWebsiteAdapter: HeadWebsiteAdapter? = null
    private var searchAction: (context: String) -> String = ::getBaiduSearch
    private var searchEngine: String = GOOGLE

    override fun setView() {


        newsAdapter = NewsAdapter(
            clickAction = { url ->
                requireContext().startActivity(Intent(requireContext(), NewsDetailActivity::class.java).apply {
                    putExtra("url", url)
                })
            },
            moreAction = {
                startActivity(Intent(requireContext(), NewsActivity::class.java).apply {

                })
            })
        helper =
            QuickAdapterHelper.Builder(newsAdapter).setTrailingLoadStateAdapter(object : TrailingLoadStateAdapter.OnTrailingListener {
                override fun onLoad() {
                    LogEx.logDebug(TAG, "onLoad")
                    requestMore()
                }

                override fun onFailRetry() {
                    LogEx.logDebug(TAG, "onFailRetry")
                    requestMore()
                }

                override fun isAllowLoading(): Boolean {
                    LogEx.logDebug(TAG, "isLoading=$isLoading")
                    return !isLoading
                }
            }).build()
        // 设置预加载，请调用以下方法
//        helper.trailingLoadStateAdapter?.preloadSize = 1
        helper.addBeforeAdapter(0, HeaderAdapter { key ->
            when (key) {
                JUNK_CLEANER -> {
                    requireContext().startActivity(Intent(requireContext(), ScanJunkActivity::class.java))
                }

                NEWS -> {
                    requireContext().startActivity(Intent(requireContext(), NewsActivity::class.java))
                }

                APP_PROCESS -> {
                    requireContext().startActivity(Intent(requireContext(), AppProcessActivity::class.java))
                }

            }

        })

        binding.rv.adapter = helper.adapter
        binding.rv.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
//            LogEx.logDebug(TAG, "scrollY=$scrollY oldScrollY=$oldScrollY")

            // 检查当前滚动位置
            val firstVisibleItem: Int = (binding.rv.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()

            if (firstVisibleItem > 3) {
                binding.ivUp.isVisible = true
            }

            if (firstVisibleItem == 0) {
                binding.ivUp.isVisible = false
            }

        }
        requestMore()
    }

    fun requestMore() {
        isLoading = true
        helper.trailingLoadState = LoadState.None
        val lastNewsId = newsAdapter.getLastPageNumber()
        LogEx.logDebug(TAG, "requestMore lastNewsId=$lastNewsId")
        requestNews(pageNumber = lastNewsId, errorCallBack = {
            isLoading = false
            LogEx.logDebug(TAG, "errorCallBack")
        }, beanCallBack = {
            isLoading = false
            binding.root.post {
                LogEx.logDebug(TAG, "beanCallBack")
                if (lastNewsId == null) {
                    newsAdapter.submitList(it)
                } else {
                    newsAdapter.addAll(it)
                }
                helper.trailingLoadState = LoadState.NotLoading(false)
            }

        })
    }


    override fun onResume() {
        super.onResume()
        setWebSiteData()
        binding.editWeb.setText("")
    }

    private fun setWebSiteData() {

        if (headWebsiteAdapter != null) {
            headWebsiteAdapter?.let { helper.removeAdapter(it) }
        }

        val recommendWebSite = webSiteGroupBeanList.flatMap { it.items }.filter { bean ->
            AppPreferences.getInstance().getBoolean("${bean.id}_${bean.name}", defaultValue(bean.name))
        }
        val list = arrayListOf<WebSiteBean>()
        list.addAll(recommendWebSite)
        list.add(WebSiteBean(name = "Increase").apply {
            localIcon = R.mipmap.increase
            increase = true
        })
        headWebsiteAdapter = HeadWebsiteAdapter()
        headWebsiteAdapter?.setItem(list, null)
        headWebsiteAdapter?.let {
            helper.addBeforeAdapter(1, it)
        }
    }


    var i = 0
    var lastClickTime = 0L
    override fun setListener() {
        super.setListener()
        binding.llWeather.setOnClickListener {
            startActivity(Intent(requireContext(), WeatherInterface::class.java))
        }

        binding.flSearchEngine.setOnClickListener {
            requireContext().showSearchEngineDialog { website ->
                searchEngine = website
                searchEngineSp = website
                when (website) {
                    GOOGLE -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_google)
                        searchAction = ::getGoogleSearch
                    }

                    BING -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_bing)
                        searchAction = ::getBingSearch
                    }

                    YAHOO -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_yahoo)
                        searchAction = ::getYahooSearch
                    }

                    DUCKDUCKGO -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_xuckd)
                        searchAction = ::getDuckDuckGoSearch
                    }

                    YANDEX -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_yandex)
                        searchAction = ::getYandexSearch
                    }

                    BAIDU -> {
                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_baidu)
                        searchAction = ::getBaiduSearch
                    }

                }
            }
        }

        binding.editWeb.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                if (actionId == IME_ACTION_DONE) {
                    val content = v?.text.toString()
                    if (TextUtils.isEmpty(content)) {
                        Toast.makeText(context, "input something please", Toast.LENGTH_SHORT).show()
                        return true
                    }
                    LinkSearchUtils.handleInput(
                        content,
                        loadUrl = { url ->
                            requireActivity().startActivity(Intent(requireContext(), WebBrowserActivity::class.java).apply {
                                putExtra("searchEngine", searchEngine)
                                putExtra("url", url)
                            })
                        },
                        performSearch = { url ->
                            val searchUrl = searchAction.invoke(url)
                            requireActivity().startActivity(Intent(requireContext(), WebBrowserActivity::class.java).apply {
                                putExtra("searchEngine", searchEngine)
                                putExtra("url", searchUrl)
                            })
                        })

                    return true // 返回true表示事件已处理
                }
                return false

            }
        })


        binding.flScan.setOnClickListener {
            requireContext().startActivity(Intent(requireContext(), ScanQRCActivity::class.java))
        }
        binding.tvName.setOnClickListener {
//            if (System.currentTimeMillis() - lastClickTime > 5 * 1000 && i != 0) {
//                lastClickTime = 0
//                i = 0
//            }
//            if (i == 20) {
//                copyUuidGid()
//                i = 0
//            }
//            i++
//            lastClickTime = System.currentTimeMillis()

            NotificationUtil.sendNotification(requireContext(), ConstObject.ID_NEWS)
        }
        binding.ivUp.setOnClickListener {
            binding.rv.scrollToPosition(0)
            binding.ivUp.isVisible = false
        }

    }

    private fun copyUuidGid() {
        val uuid = AppPreferences.getInstance().getString("uuid", "")
        val gid = AppPreferences.getInstance().getString("gid", "")
        requireContext().copyText("uuid", "uuid=$uuid gid=$gid")
        Toast.makeText(requireContext(), "copy", Toast.LENGTH_SHORT).show()
    }


}