package com.base.browserwhite.ui.fragment

import android.content.Intent
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo.IME_ACTION_DONE
import android.widget.TextView
import com.base.browserwhite.R
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.adapter.HeadWebsiteAdapter
import com.base.browserwhite.ui.adapter.HeaderAdapter
import com.base.browserwhite.ui.adapter.NewsAdapter
import com.base.browserwhite.utils.AppPreferences
import com.base.browserwhite.utils.LogEx
import com.base.browserwhite.utils.NewsUtils.requestNews
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

    override fun setView() {


        newsAdapter = NewsAdapter { url ->
            requireContext().startActivity(Intent(requireContext(), WebBrowserActivity::class.java).apply {
                putExtra("url", url)
            })
        }
        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())

        binding.rv.adapter = helper.adapter
        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)
        }
    }

    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.editWeb.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                if (actionId == IME_ACTION_DONE) {
                    requireActivity().startActivity(Intent(requireContext(), WebBrowserActivity::class.java).apply {
                        putExtra("url", getGoogleSearch(v?.text.toString()))
                    })
                    return true; // 返回true表示事件已处理
                }
                return false

            }
        })


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


    companion object {
        fun getGoogleSearch(content: String): String {
            val base = "https://www.google.com/"
            val search = "search?q=${content}&oq=${content}"
            return "$base$search"
        }

        fun getBingSearch(content: String): String {
            //https://cn.bing.com/search?q=aaa&form=QBLHCN&sp=-1&lq=0&pq=aaa&sc=10-3&qs=n&sk=&cvid=CBA1E2A2A9124EBB9C9970DC69330095&ghsh=0&ghacc=0&ghpl=
            val base = "https://cn.bing.com/"
            val search = "search?q=${content}&form=QBLHCN&sp=-1&lq=0&pq=${content}"
            return "$base$search"
        }


    }


}