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.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.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.cleanjunk.ScanJunkActivity
import com.base.browserwhite.ui.activity.news.NewsDetailActivity
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.ui.views.DialogViews.showSearchEngineDialog
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
import java.net.MalformedURLException
import java.net.URL
import java.net.URLEncoder
import java.nio.charset.StandardCharsets


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 { url ->
            requireContext().startActivity(Intent(requireContext(), NewsDetailActivity::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 { key ->
            when (key) {
                JUNK_CLEANER -> {
                    requireContext().startActivity(Intent(requireContext(), ScanJunkActivity::class.java))
                }
            }

        })

        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 ->
                searchEngine = 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) {
                    requireActivity().startActivity(Intent(requireContext(), WebBrowserActivity::class.java).apply {
                        putExtra("searchEngine", searchEngine)
                        val content = v?.text.toString()
                        putExtra("url", getWWWSearch(content) ?: searchAction(content))
                    })
                    return true; // 返回true表示事件已处理
                }
                return false

            }
        })


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


    companion object {

        fun isValidUrl(urlString: String?): Boolean {
            return try {
                // 尝试将字符串转换为URL对象
                URL(urlString)
                true
            } catch (e: MalformedURLException) {
                // 如果转换失败，说明不是有效的URL
                false
            }
        }

        fun isMatchesUrl(urlString: String): Boolean {
            val pattern = "^(https?://)?(www\\.)?[a-z0-9]+\\.[a-z0-9.-]+\\.[a-z]{2,6}(:[0-9]{1,5})?(/.*)?$"
            return urlString.matches(pattern.toRegex())
        }

        fun getWWWSearch(content: String): String? {
            if (isValidUrl(content) || isMatchesUrl(content)) {
                return if (content.contains("http") or content.contains("https")) {
                    content
                } else {
                    "https://$content"
                }
            }
            return null
        }

        fun getGoogleSearch(content: String): String {
            val base = "https://www.google.com/"
            val encodedQuery = URLEncoder.encode(content, StandardCharsets.UTF_8.toString())
            val search = "search?q=${encodedQuery}&oq=${encodedQuery}"
            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"
        }


        fun getYahooSearch(content: String): String {
            val encodedQuery = URLEncoder.encode(content, StandardCharsets.UTF_8.toString())

            return "https://search.yahoo.com/search?p=$encodedQuery"
        }

        fun getDuckDuckGoSearch(content: String): String {
            val encodedQuery = URLEncoder.encode(content, StandardCharsets.UTF_8.toString())
            return "https://www.duckduckgo.com/?q=encodedQuery"
        }

        fun getYandexSearch(content: String): String {
            val encodedQuery = URLEncoder.encode(content, StandardCharsets.UTF_8.toString())
            return "https://yandex.com/search/?text=$encodedQuery"
        }

        fun getBaiduSearch(content: String): String {
            val encodedQuery = URLEncoder.encode(content, StandardCharsets.UTF_8.toString())
            return "https://www.baidu.com/s?wd=$encodedQuery"
        }

    }


}