package com.ccwangluo.accelerator.ui.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.ccwangluo.accelerator.R
import com.ccwangluo.accelerator.adapter.KotlinDataAdapter
import com.ccwangluo.accelerator.databinding.FragmentNewsBinding
import com.ccwangluo.accelerator.model.Plugin

import com.ccwangluo.accelerator.ui.news.NewsCollectionAdapter
import com.ccwangluo.accelerator.ui.web.CommonWebViewFragment
import com.ccwangluo.accelerator.utils.AcceleratorUtils
import com.ccwangluo.accelerator.utils.LoginUtils
import com.ccwangluo.accelerator.utils.SysUtils
import com.ccwangluo.accelerator.utils.datareport.DataRePortUtils
import com.github.shadowsocks.http.HttpConfig
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.hjq.toast.ToastUtils
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
    }

    var dataList = arrayListOf<Plugin>()

    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: NewsCollectionAdapter? = null
    override fun initViews() {
        newsViewModel.notice.observe(this) { it1 ->
            binding.newsNotice.visibility = View.VISIBLE
            binding.tvMarquee.addDisplayString(it1.title)
            binding.tvMarquee.startRoll()
            binding.newsNotice.setOnClickListener {
                DataRePortUtils.report("st_msg_annoucement_clk")
                val params = Bundle()
                params.putString(
                    CommonWebViewFragment.WEBVIEW_URL_KEY,
                    it1.url
                )
                openPage(CommonWebViewFragment::class.java, params)
            }
        }

        newsViewModel.isRefresh.observe(this, Observer {
            binding.refreshNews.isRefreshing = false
        })
        binding.appbar.addOnOffsetChangedListener(object : AppBarLayout.OnOffsetChangedListener {
            override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) {
                if (verticalOffset >= 0) {
                    binding.refreshNews.isEnabled = true
                } else {
                    binding.refreshNews.isEnabled = false
                }
            }
        })
        binding.refreshNews.setOnRefreshListener {
            adapter?.refresh(binding.viewPager.currentItem)
            binding.refreshNews.postDelayed({
                binding.refreshNews.isRefreshing = false
            }, 2000)
        }

        val layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
        binding.gameNewsList?.setLayoutManager(layoutManager)
        binding.gameNewsList.adapter = KotlinDataAdapter.Builder<Plugin>()
            .setData(dataList)
            .setLayoutId(R.layout.item_news_game)
            .addBindView { itemView, itemData ->
                context?.let {
                    Glide.with(it).load(itemData.icon)
                        .into(itemView.findViewById<ImageView>(R.id.plugin_img))
                }
                itemView.findViewById<TextView>(R.id.plugin_name).setText(itemData.name)
                itemView.setOnClickListener {
                    if (itemData.type == 3) {
                        DataRePortUtils.report("st_game_down_clk", mapOf("scene" to "3"))
                    }
                    if (!itemData.isOpen) {
                        ToastUtils.show("暂不支持${itemData.name}")
                        return@setOnClickListener
                    }

                    if (itemData.type == 1) {
                        itemData.url?.let {
                            DataRePortUtils.report("st_qq_clk", mapOf("scene" to "3"))
                            context?.let { it1 -> SysUtils.joinQQGroup(it1) }
                        }
                    }

                    if (itemData.type == 2) {
                        itemData.url?.let {
                            DataRePortUtils.report("st_google_clk", mapOf("scene" to "3"))
                            openToWebview(it)
                        }
                    }

                    if (itemData.type == 3) {
                        itemData.url?.let {
                            DataRePortUtils.report("st_game_down_clk", mapOf("scene" to "3"))
                            context?.let { it1 ->
                                SysUtils.downloadFile(it1, it)
                                ToastUtils.show("开始下载")
                            }
                        }
                    }
                }

            }.create()
        newsViewModel.pluginList.observe(this, {
            dataList.clear()
            dataList.addAll(it)
            binding.gameNewsList.adapter?.notifyDataSetChanged()
        })
        adapter = NewsCollectionAdapter(this, titles)
        binding.viewPager.adapter = adapter
        TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position ->
            tab.setCustomView(R.layout.item_tab)
            tab.text = titles[position]
        }.attach()
        binding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab?.let {
                    DataRePortUtils.report("st_msg_channel_clk", mapOf("headlin" to it.position))
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

        })

        AcceleratorUtils.getGameList(this) {
            if (it) {
                AcceleratorUtils.game?.let {
                    newsViewModel.getNotice(it.id)
                    newsViewModel.getPlugin(it.id)
                }
            }
        }

    }

    fun openToWebview(url: String) {
        val params = Bundle()
        params.putString(CommonWebViewFragment.WEBVIEW_URL_KEY, url)
        openPage(CommonWebViewFragment::class.java, params)
    }

    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
        }
    }

}