package com.base.browserwhite.ui.fragment

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Intent
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo.IME_ACTION_DONE
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
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.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.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.LinkMatchUtils
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
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(
            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)
        }

//        val file = File(Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS), "localImage")
//        if (!file.exists()) {
//            file.mkdirs()
//        }
//        webSiteGroupBeanList.flatMap { it.items }.forEach { bean: WebSiteBean ->
//            val url = bean.icon_url
//            val name = bean.name.lowercase(Locale.getDefault()).replace(" ", "_")
//            val imageFile = File(file, "${name}_${bean.id}_local.png")
//            download(url, imageFile)
//        }
    }

//    fun download(imageUrl: String, file: File) {
//        val client = OkHttpClient()
//        val request: Request = Request.Builder().url(imageUrl).build()
//
//        client.newCall(request).enqueue(object : Callback {
//
//
//            override fun onFailure(call: Call, e: IOException) {
//            }
//
//            override fun onResponse(call: Call, response: Response) {
//                if (response.isSuccessful) {
//
//                    // 将图片数据写入文件
//                    val fos: FileOutputStream = FileOutputStream(file)
//                    fos.write(response.body?.bytes())
//                    fos.flush()
//                    fos.close()
//
//                }
//            }
//        })
//    }

    var i = 0
    var lastClickTime = 0L
    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) {
                    val content = v?.text.toString()

                    LinkMatchUtils.handleInput(requireContext(),
                        content,
                        loadUrl = { url ->
                            requireActivity().startActivity(Intent(requireContext(), WebBrowserActivity::class.java).apply {
                                putExtra("searchEngine", searchEngine)
                                putExtra("url", url)
                            })
                        },
                        performSearch = { url ->
                            searchAction.invoke(url)
                        })

                    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", "")
        // 获取系统服务ClipboardManager
        val clipboard: ClipboardManager =
            requireContext().getSystemService(AppCompatActivity.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建一个ClipData对象，其中包含要复制的文本
        val clip = ClipData.newPlainText("uuid", "uuid=$uuid gid=$gid")
        // 将ClipData对象设置到剪贴板中
        clipboard.setPrimaryClip(clip)
        Toast.makeText(requireContext(), "copy", Toast.LENGTH_SHORT).show()
    }


    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"
        }

    }


}