package com.keyboard.journey

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.gyf.immersionbar.ktx.immersionBar
import com.keyboard.journey.adapter.BannerImgAdapter
import com.keyboard.journey.adapter.MainDataAdapter
import com.keyboard.journey.bean.CategoryDataBean
import com.keyboard.journey.bean.MainDataBean
import com.keyboard.journey.databinding.JourneyActivityMainBinding
import com.keyboard.journey.util.NetworkCallback
import com.keyboard.journey.util.NetworkUtil
import com.keyboard.journey.util.getRandomInt
import com.youth.banner.listener.OnPageChangeListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import org.libpag.PAGFile
import kotlin.coroutines.resume


class HomeFragment : Fragment() {
    private lateinit var binding: JourneyActivityMainBinding
    private var imgList: MutableList<Int> = mutableListOf()
    private var dataList: MutableList<MainDataBean> = mutableListOf()
    private var mainAdapter: MainDataAdapter? = null
    private var currentBannerType = 0

    private lateinit var bannerStr0: String
    private lateinit var bannerStr1: String

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        binding = JourneyActivityMainBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        bannerStr0 = getString(R.string.recommend)
        bannerStr1 = getString(R.string.cool)
        initBar()
        initView()
        initData()
    }

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

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            initImmersionBar()
        }
    }

    private fun initImmersionBar() {
        immersionBar {
            statusBarDarkFont(true)
            statusBarView(binding.view)
        }
    }

    private suspend fun getFetchCategory(
        key: String,
        offset: Int,
        pageSize: Int,
    ): CategoryDataBean? {
        return try {
            suspendCancellableCoroutine<CategoryDataBean> { continuation ->
                NetworkUtil().fetchCategory(key,
                    offset,
                    pageSize,
                    object : NetworkCallback<List<CategoryDataBean>> {
                        override fun onSuccess(data: List<CategoryDataBean>) {
                            continuation.resume(data[0])
                        }

                        override fun onFailure(errorMessage: String) {
                        }
                    })
            }
        } catch (e: Exception) {
            return null
        }
    }

    @OptIn(DelicateCoroutinesApi::class)
    private fun initData() {
        loadingPlay()
        binding.noDataLayout.visibility = View.GONE
        NetworkUtil().fetchData(object : NetworkCallback<List<MainDataBean>> {
            @SuppressLint("NotifyDataSetChanged")
            override fun onSuccess(data: List<MainDataBean>) {
                GlobalScope.launch(Dispatchers.IO) {
                    val jobs = data.map { bean ->
                        GlobalScope.async(Dispatchers.IO) {
                            val resultCategory = getFetchCategory(
                                bean.key, getRandomInt(1, 15),
                                getRandomInt(5, 16),
                            )
                            bean.items = resultCategory?.items!!
                            bean
                        }
                    }
                    val list = awaitAll(*jobs.toTypedArray())
                    withContext(Dispatchers.Main) {
                        dataList.clear()
                        dataList.addAll(list)
                        Log.d(JourneyApp.TAG, "--------------dataList=${dataList.size}")
                        mainAdapter?.notifyDataSetChanged()
                        loadingClose()
                        if (dataList.size > 0) {
                            binding.noDataLayout.visibility = View.GONE
                        } else {
                            binding.noDataLayout.visibility = View.VISIBLE
                        }
                    }
                }

            }

            override fun onFailure(errorMessage: String) {
                CoroutineScope(Dispatchers.Main).launch {
                    LogUtil.logMsgD(errorMessage)
                    binding.noDataLayout.visibility = View.VISIBLE
                    loadingClose()
                }

            }
        })
    }

    private fun initBar() {
        immersionBar {
            statusBarDarkFont(true)
            statusBarView(binding.view)
        }
    }

    private fun initClick() {
        binding.tryAgain.setOnClickListener {
            initData()
        }
        binding.bannerBtn.setOnClickListener {
            for (data in dataList) {
                Log.d(JourneyApp.TAG, "----------  data=${data.title}")
            }
            val recommend = dataList.filter { it.title.contains("For You") }
            val cool = dataList.filter { it.title.contains(bannerStr1) }
            if (currentBannerType == 0) {
                Log.d(JourneyApp.TAG, "----------0  recommend.size=${recommend.size}")
                if (recommend.isNotEmpty()) {
                    val intent =
                        Intent(requireActivity(), JourneyCategoryDetailsActivity::class.java)
                    intent.putExtra(
                        JourneyCategoryDetailsActivity.CATEGORY_DETAILS_BEAN_KEY, recommend[0]
                    )
                    startActivity(intent)
                }
            } else if (currentBannerType == 1) {
                Log.d(JourneyApp.TAG, "----------1  cool.size=${cool.size}")
                if (cool.isNotEmpty()) {
                    val intent =
                        Intent(requireActivity(), JourneyCategoryDetailsActivity::class.java)
                    intent.putExtra(
                        JourneyCategoryDetailsActivity.CATEGORY_DETAILS_BEAN_KEY, cool[0]
                    )
                    startActivity(intent)
                }
            }
        }
    }

    private fun initView() {
        binding.rv.layoutManager = LinearLayoutManager(requireActivity())
        mainAdapter = MainDataAdapter(requireActivity(), dataList)
        binding.rv.adapter = mainAdapter

        imgList.add(R.mipmap.recommend_top_banner_img)
        imgList.add(R.mipmap.cool_top_banner_img)
        val adapter = BannerImgAdapter(imgList)
        binding.banner.setAdapter(adapter).addBannerLifecycleObserver(this) //添加生命周期观察者
        binding.banner.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(
                position: Int, positionOffset: Float, positionOffsetPixels: Int
            ) {

            }

            override fun onPageSelected(position: Int) {
                when (position) {
                    0 -> {
                        currentBannerType = 0
                        binding.indicatorLayout.setBackgroundColor(requireActivity().getColor(R.color.banner_indicator_one_bg))
                        binding.indicatorImg.setImageResource(R.mipmap.top_banner_one_img)
                        binding.indicatorTxt.text = bannerStr0
                        binding.indicatorGoBg.background = requireActivity().getDrawable(R.drawable.draw_go_bg)
                        binding.indicatorLineOneBg.setBackgroundColor(requireActivity().getColor(R.color.banner_indicator_one_go_bg_color))
                        binding.indicatorLineTowBg.setBackgroundColor(requireActivity().getColor(R.color.black_10))
                    }

                    1 -> {
                        currentBannerType = 1
                        binding.indicatorLayout.setBackgroundColor(requireActivity().getColor(R.color.banner_indicator_tow_bg))
                        binding.indicatorImg.setImageResource(R.mipmap.top_banner_tow_img)
                        binding.indicatorTxt.text = bannerStr1
                        binding.indicatorGoBg.background = requireActivity().getDrawable(R.drawable.draw_go_2_bg)
                        binding.indicatorLineOneBg.setBackgroundColor(requireActivity().getColor(R.color.black_10))
                        binding.indicatorLineTowBg.setBackgroundColor(requireActivity().getColor(R.color.banner_indicator_tow_go_bg_color))
                    }
                }
            }

            override fun onPageScrollStateChanged(state: Int) {

            }
        })
        initClick()
    }

    private fun loadingPlay() {
        binding.loadingLayout.visibility = View.VISIBLE
        binding.indicatorGoBg.visibility = View.GONE
        val pagFile = PAGFile.Load(requireActivity().assets, "loading.pag")
        binding.pagView.composition = pagFile
        binding.pagView.setRepeatCount(0)
        binding.pagView.play()
    }

    private fun loadingClose() {
        binding.loadingLayout.visibility = View.GONE
        binding.indicatorGoBg.visibility = View.VISIBLE
        if (binding.pagView.isPlaying) {
            binding.pagView.stop()
        }
    }
}