package com.base.appzxhy.ui.main

import android.content.Intent
import androidx.core.view.updatePadding
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ConcatAdapter
import androidx.recyclerview.widget.RecyclerView
import com.base.appzxhy.BuildConfig
import com.base.appzxhy.R
import com.base.appzxhy.base.BaseFragment
import com.base.appzxhy.databinding.FragmentHomeBinding
import com.base.appzxhy.ui.category.CategoryActivity
import com.base.appzxhy.ui.concatAdapter.BannerAdapter
import com.base.appzxhy.ui.concatAdapter.ShortPlayCategoryAdapter
import com.base.appzxhy.ui.concatAdapter.ShortPlayColumnsAdapter
import com.base.appzxhy.ui.play.PlayFullActivity
import com.base.appzxhy.utils.BarUtils
import com.base.appzxhy.utils.LogEx
import com.base.appzxhy.utils.ToastUtils.toast
import com.bytedance.sdk.shortplay.api.ShortPlay
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch


class HomeFragment : BaseFragment<FragmentHomeBinding>(FragmentHomeBinding::inflate) {

    private var contactAdapter: ConcatAdapter? = null
    private var bannerAdapter: BannerAdapter? = null
    private var columnsAdapter: ShortPlayColumnsAdapter? = null


    override fun initView() {
        super.initView()
        val top = BarUtils.getStatusBarHeight()+requireContext().resources.getDimensionPixelSize(R.dimen.dp_6)
        binding.flSearch.updatePadding(top = top)
        contactAdapter = ConcatAdapter()
        binding.rv.adapter = contactAdapter

        initBannerAdapter()
        initNewShortAdapter()
        initCategoryAdapter()

        binding.rv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                if (recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset() >= recyclerView.computeVerticalScrollRange()) {
                    LogEx.logDebug(TAG, "loadMore")
                    val activity = requireActivity() as MainActivity?
                    activity?.viewModel?.getCategoryListFlow()
                }
            }
        })
    }

    private val categories = arrayListOf<Long>()
    private fun initCategoryAdapter() {
        val activity = requireActivity() as MainActivity?
        lifecycleScope.launch {
            activity?.viewModel?.categoryList?.collectLatest { list ->
                if (list.size > 4) {
                    var ids = 1L
                    kotlin.runCatching {
                        ids = list[0].categories[0].id
                    }
                    if (!categories.contains(ids)) {
                        categories.add(ids)
                        val categoryTitle = activity.viewModel.categoryTitle(requireContext(), ids)
                        val categoryAdapter = ShortPlayCategoryAdapter(categoryTitle, list)
                        categoryAdapter.itemClick = ::shortPlayClick
                        categoryAdapter.categoryClick = {
                            jumpCategory(ids)
                        }
                        contactAdapter?.addAdapter(categoryAdapter)
                    }
                }
            }
        }
    }

    private fun initBannerAdapter() {
        val activity = requireActivity() as MainActivity?
        bannerAdapter = BannerAdapter()
        bannerAdapter?.let {
            it.playAction = { shortPlay ->
                startActivity(Intent(activity, PlayFullActivity::class.java).apply {
                    putExtra("data", Gson().toJson(shortPlay))
                })
            }
            contactAdapter?.addAdapter(0, it)
        }

        lifecycleScope.launch(Dispatchers.Main) {
            activity?.viewModel?.bannerList?.collectLatest { bannerList ->
                LogEx.logDebug(TAG, "bannerList=${bannerList.size}")
                bannerAdapter?.submitList(listOf(bannerList))
            }
        }

    }


    override fun onResumeOneShoot() {
        super.onResumeOneShoot()

        val activity = requireActivity() as MainActivity?
        activity?.viewModel?.getPopularDrama()
        activity?.viewModel?.getNewDrama()
        activity?.viewModel?.getCategoryListFlow(true)
    }

    override fun onResume() {
        super.onResume()
    }

    override fun onPause() {
        super.onPause()
        bannerAdapter?.setBannerAutoLoop(false)
    }

    private fun initNewShortAdapter() {
        val activity = requireActivity() as MainActivity?
        columnsAdapter = ShortPlayColumnsAdapter("New Short")
        columnsAdapter?.let { contactAdapter?.addAdapter(it) }

        lifecycleScope.launch(Dispatchers.Main) {
            activity?.viewModel?.newList?.collectLatest { list ->
                if (list.size > 4) {
                    columnsAdapter?.submitList(listOf(list))
                }
            }
        }
    }

    override fun initListener() {
        columnsAdapter?.itemClick = ::shortPlayClick
    }

    private fun shortPlayClick(item: ShortPlay) {
        if (BuildConfig.DEBUG) {
            requireContext().toast("${item.title}")
        }
        val activity = requireActivity() as MainActivity?
        activity ?: return
        activity.startActivity(Intent(activity, PlayFullActivity::class.java).apply {
            putExtra("data", Gson().toJson(item))
        })
    }

    private fun jumpCategory(ids: Long) {
        val activity = requireActivity() as MainActivity?
        activity ?: return
        activity.startActivity(Intent(activity, CategoryActivity::class.java).apply {
            putExtra("data", ids)
        })
    }
}