package com.base.browserwhite.ui.activity.result

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import androidx.activity.addCallback
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.recyclerview.widget.LinearLayoutManager
import com.base.browserwhite.ads.admob.AdmobNativeUtils
import com.base.browserwhite.bean.ConstObject.APP_PROCESS
import com.base.browserwhite.bean.ConstObject.JUNK_CLEANER
import com.base.browserwhite.bean.ConstObject.optimizationShow
import com.base.browserwhite.databinding.ActivityResultBinding
import com.base.browserwhite.help.BatteryOptimizationIntentHelper
import com.base.browserwhite.ui.activity.BaseActivity
import com.base.browserwhite.ui.activity.news.NewsDetailActivity
import com.base.browserwhite.ui.activity.news.NewsAdapter
import com.base.browserwhite.utils.BarUtils
import com.base.browserwhite.utils.LogEx
import com.base.browserwhite.help.NewsUtils
import com.base.browserwhite.ui.activity.appprocess.AppProcessActivity
import com.base.browserwhite.ui.views.DialogViews.showImproveStabilityDialog
import com.base.browserwhite.utils.KotlinExt.toFormatSize
import com.chad.library.adapter4.QuickAdapterHelper
import com.chad.library.adapter4.loadState.LoadState
import com.chad.library.adapter4.loadState.trailing.TrailingLoadStateAdapter

class ResultActivity : BaseActivity<ActivityResultBinding>() {

    private lateinit var newsAdapter: NewsAdapter
    private lateinit var helper: QuickAdapterHelper
    private val TAG = "ResultActivity"
    private var isLoading = false

    override val binding: ActivityResultBinding by lazy {
        ActivityResultBinding.inflate(layoutInflater)
    }

    @SuppressLint("SetTextI18n")
    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.parseColor("#4C9E80"))
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())

        val from = intent.getStringExtra("from")

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

            }
        )
        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.addBeforeAdapter(0, ResultHeadAdapter { headBinding ->

            when (from) {
                JUNK_CLEANER -> {
                    val cleanSize = intent.getLongExtra("clean_size", 0L)
                    if (cleanSize > 0) {
                        headBinding.tvTip.text = "Cleaned up ${cleanSize.toFormatSize(1)}"
                    } else {
                        headBinding.tvTip.text = "No junk files found."
                    }
                }

                APP_PROCESS -> {
                    headBinding.tvTip.text = "Complete!"
                }
            }
            headBinding.tvFunctionBtn.setOnClickListener {
                startActivity(Intent(this, AppProcessActivity::class.java))
                finish()
            }
        })
        binding.rvNews.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
//            LogEx.logDebug(TAG, "scrollY=$scrollY oldScrollY=$oldScrollY")

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

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

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

        }
        binding.ivUp.setOnClickListener {
            binding.rvNews.scrollToPosition(0)
            binding.ivUp.isVisible = false
        }
        binding.rvNews.adapter = helper.adapter

        if (!optimizationShow) {
            optimizationShow = true
            showImproveStabilityDialog {
                val ignoreBatteryOptimizationIntent = BatteryOptimizationIntentHelper.getIgnoreBatteryOptimizationIntent(this)
                startActivity(ignoreBatteryOptimizationIntent)
            }
        }
        requestMore()
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            finishToMain()
        }
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }

    }

    fun requestMore() {
        isLoading = true
        helper.trailingLoadState = LoadState.None
        val lastNewsId = newsAdapter.getLastPageNumber()
        LogEx.logDebug(TAG, "requestMore lastNewsId=$lastNewsId")
        NewsUtils.requestNews(pageNumber = lastNewsId, errorCallBack = {
            isLoading = false
            LogEx.logDebug(TAG, "errorCallBack")
        }, beanCallBack = {
            isLoading = false
            binding.root.post {
                LogEx.logDebug(TAG, "beanCallBack")
//                val newsAdList = AdmobNativeUtils.addNativeAdNewsBean(it)
                if (lastNewsId == null) {
                    runCatching { newsAdapter.add(AdmobNativeUtils.readyNative[0]) }
                    newsAdapter.addAll(it)
                } else {
                    newsAdapter.addAll(it)
                }
                helper.trailingLoadState = LoadState.NotLoading(false)
            }

        })
    }


}