package com.ccwangluo.accelerator.ui.home

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import com.ccwangluo.accelerator.R
import com.ccwangluo.accelerator.databinding.FragmentNewsBinding
import com.ccwangluo.accelerator.ui.news.DemoCollectionAdapter
import com.google.android.material.tabs.TabLayoutMediator
import com.xuexiang.xpage.base.XPageFragment
import com.xuexiang.xpage.utils.TitleBar

class NewsFragment : XPageFragment() {
    private var _binding: FragmentNewsBinding? = null
    private val binding get() = _binding!!
    private lateinit var newsViewModel: NewsViewModel
    override fun initTitleBar(): TitleBar? {
        //不使用@Page标注的一定要注意覆盖这个方法
        return null
    }

    override fun inflateView(inflater: LayoutInflater?, container: ViewGroup?): View {
        _binding = FragmentNewsBinding.inflate(inflater!!, container, false)
        newsViewModel = ViewModelProvider(requireActivity()).get(NewsViewModel::class.java)
        return binding.root
    }

    val titles = arrayOf("动态", "攻略", "视频", "评价", "问答")
    var adapter: DemoCollectionAdapter? = null
    override fun initViews() {
        newsViewModel.refreshState.observe(this, {
            if (!it) {
                binding.refreshLayout.isRefreshing = false
            }
        })

        binding.tvMarquee.addDisplayString("【公告】韩服 DNF已经开启预约啦，小伙伴…")
        binding.tvMarquee.startRoll()

        adapter = DemoCollectionAdapter(this, titles)
        binding.viewPager.adapter = adapter
        TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position ->
            tab.setCustomView(R.layout.item_tab)
            tab.text = titles[position]
        }.attach()

    }

    override fun initListeners() {
        binding.refreshLayout.setOnRefreshListener {
            adapter?.refresh(binding.viewPager.currentItem)
            binding.refreshLayout.postDelayed({
                binding.refreshLayout.isRefreshing = false
            }, 2000)
        }
    }

    companion object {
        fun newInstance(): NewsFragment {
            val fragment = NewsFragment()
            return fragment
        }
    }

}