package com.keyboard.craft.fragment

import android.annotation.SuppressLint
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.keyboard.craft.CraftApp
import com.keyboard.craft.adapter.HomeBannerImgAdapter
import com.keyboard.craft.adapter.HomeDataAdapter
import com.keyboard.craft.bean.CategoryDataBean
import com.keyboard.craft.bean.ItemDataBean
import com.keyboard.craft.bean.MainDataBean
import com.keyboard.craft.databinding.FragmentHomeBinding
import com.keyboard.craft.util.LogUtil
import com.keyboard.craft.util.NetworkCallback
import com.keyboard.craft.util.NetworkUtil
import com.keyboard.craft.util.getRandomInt
import com.youth.banner.indicator.CircleIndicator
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 kotlin.coroutines.resume


class HomeFragment : Fragment() {
    private lateinit var binding: FragmentHomeBinding
    var dataList: MutableList<MainDataBean> = mutableListOf()
    private var mainAdapter: HomeDataAdapter? = null

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initData()
    }

    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(CraftApp.TAG, "--------------dataList=${dataList.size}")
                        mainAdapter?.notifyDataSetChanged()
                        loadingClose()
                        if (dataList.size > 0) {
                            binding.noDataLayout.visibility = View.GONE
                        } else {
                            binding.noDataLayout.visibility = View.VISIBLE
                        }

                        val randomList = getRandomItemsFromMainDataBeans(dataList, 5)
                        if (randomList != null) {
                            binding.banner.addBannerLifecycleObserver(requireActivity())//添加生命周期观察者
                                .setAdapter(HomeBannerImgAdapter(requireActivity(), randomList))
                                .setIndicator(CircleIndicator(requireActivity()))
                        }
                    }
                }

            }

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

            }
        })
    }

    // numberOfItems需要的数量
    fun getRandomItemsFromMainDataBeans(
        mainDataBeans: List<MainDataBean>,
        numberOfItems: Int
    ): List<ItemDataBean>? {
        val randomMainDataBeans = mainDataBeans.shuffled().take(2)
        val items = randomMainDataBeans.flatMap { it.items ?: emptyList() }
        return if (items.size >= numberOfItems) {
            items.shuffled().take(numberOfItems)
        } else {
            null // 如果总数不足，返回 null
        }
    }

    private fun initClick() {
        binding.tryAgain.setOnClickListener {
            initData()
        }
    }

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


        initClick()
    }


    private fun loadingPlay() {
        binding.loadingLayout.visibility = View.VISIBLE
    }

    private fun loadingClose() {
        binding.loadingLayout.visibility = View.GONE
    }
}