package com.base.browserwhite.ui.fragment

import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Intent
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
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.ads.AdDialog.showAdPreparingDialog
import com.base.browserwhite.bean.BookmarkBean
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.BOOKMARK
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.NewsBean
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.Constants
import com.base.browserwhite.help.NewsUtils.requestNews
import com.base.browserwhite.help.RxBus
import com.base.browserwhite.help.SearchTipUtils
import com.base.browserwhite.ui.activity.search.SearchActivity
import com.base.browserwhite.ui.activity.appprocess.AppProcessActivity
import com.base.browserwhite.ui.activity.bookmark.BookmarkActivity
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.getSpSearchAction
import com.base.browserwhite.utils.LinkSearchUtils.getYahooSearch
import com.base.browserwhite.utils.LinkSearchUtils.getYandexSearch
import com.base.browserwhite.utils.LogEx
import com.base.browserwhite.utils.SpBeanUtils
import com.base.browserwhite.utils.SpBeanUtils.BOOKMARK_NAV_SP_KEY
import com.chad.library.adapter4.QuickAdapterHelper
import com.chad.library.adapter4.loadState.LoadState
import com.chad.library.adapter4.loadState.trailing.TrailingLoadStateAdapter
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import com.google.gson.Gson
import io.reactivex.rxjava3.core.Observable


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 = ::getSpSearchAction
    private var searchEngine: String = GOOGLE
    private var mChangeSearchType: Observable<String>? = null
    private var mResetSearchView: Observable<Int>? = null

    @SuppressLint("CheckResult")
    override fun setView() {

        switchSearch(searchEngineSp)

        mChangeSearchType = RxBus.get().register(Constants.CHANGE_SEARCH_TYPE, String::class.java)
        mChangeSearchType?.observeOn(AndroidSchedulers.mainThread())?.subscribe { t ->
            LogEx.logDebug("glc", "i:$t")
            switchSearch(t)
        }
        mResetSearchView = RxBus.get().register(Constants.RESET_SEARCH_VIEW, Int::class.java)
        mResetSearchView?.observeOn(AndroidSchedulers.mainThread())?.subscribe { t ->
            binding.searchLayout.translationY = y
        }
        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
                        )
                    )
                }

                BOOKMARK -> {
                    requireContext().startActivity(
                        Intent(
                            requireContext(),
                            BookmarkActivity::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
            }

        }
        binding.appbarLayout.addOnOffsetChangedListener { appBarLayout, i ->
            verticalOffset = i
        }
        y = binding.searchLayout.translationY
        binding.editWeb.setOnClickListener {
            binding.tvCancel.visibility = View.VISIBLE
            binding.flScan.visibility = View.GONE
            SearchActivity.startActivityWithButtonAnimation(
                requireActivity(),
                binding.searchLayout,
                verticalOffset
            )
        }
        requestMore()
    }

    private var verticalOffset = 0
    private var y = 0f
    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)
            }

        })
    }

    fun addNativeAdNewsBean(it: List<NewsBean>) {
        val list = arrayListOf<NewsBean>()

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val animator: ObjectAnimator = ObjectAnimator.ofFloat(
            binding.searchLayout,
            "translationY",
            binding.searchLayout.translationY,
            y
        )
        animator.setDuration(500)
        animator.start()
        binding.tvCancel.visibility = View.GONE
        binding.flScan.visibility = View.VISIBLE
    }

    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)

        //书签导航
        SpBeanUtils.getSpBeanList(BOOKMARK_NAV_SP_KEY).forEach { json ->
            val bean = Gson().fromJson(json, BookmarkBean::class.java)
            list.add(WebSiteBean(name = bean.name, url = bean.url).apply {
                isBookmarkNav = true
                color = bean.color
            })
        }

        //添加按钮
        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 ->
                switchSearch(website)
            }
        }

        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.ivName.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 switchSearch(website: String) {
        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
            }

        }

    }

    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()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mChangeSearchType != null) {
            RxBus.get().unregister(Constants.CHANGE_SEARCH_TYPE, mChangeSearchType!!);
        }
        if (mResetSearchView != null) {
            RxBus.get().unregister(Constants.RESET_SEARCH_VIEW, mResetSearchView!!);
        }
    }

}