package com.base.appzxhy.ui.main.mylist

import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.base.appzxhy.R
import com.base.appzxhy.base.BaseFragment
import com.base.appzxhy.bean.ShortPlayHistory
import com.base.appzxhy.databinding.FragmentHistoryPageBinding
import com.base.appzxhy.ui.adapter.ShortPlayHistoryAdapter
import com.base.appzxhy.utils.SpJsonUtils
import com.base.appzxhy.utils.SpJsonUtils.KEY_SHORTPLAY_FAVORITE
import com.base.appzxhy.utils.SpJsonUtils.KEY_SHORTPLAY_HISTORY
import com.bytedance.sdk.shortplay.api.ShortPlay
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


class HistoryPageFragment : BaseFragment<FragmentHistoryPageBinding>(FragmentHistoryPageBinding::inflate) {

    private val shortPlayAdapter = ShortPlayHistoryAdapter(R.layout.item_shortplay_style_5)

    override fun initView() {
        super.initView()
        binding.rv.adapter = shortPlayAdapter
    }

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

    private fun refreshRv() {
        lifecycleScope.launch(Dispatchers.IO) {

            val favoriteList = SpJsonUtils.getSpJsonList<ShortPlay>(KEY_SHORTPLAY_FAVORITE).map { it.id }

            val list = SpJsonUtils.getSpJsonList<ShortPlayHistory>(KEY_SHORTPLAY_HISTORY)

            list.forEach {
                if (favoriteList.contains(it.shortPlay.id)) {
                    it.isFavorite = true
                }
            }

            launch(Dispatchers.Main) {
                binding.llEmpty.isVisible = list.isEmpty()
                shortPlayAdapter.submitList(list)
                val pfg = parentFragment as MyListFragment
                pfg.changeEditEnable(list.isNotEmpty())
            }
        }
    }

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

}