package com.ccwangluo.accelerator.ui.home

import android.graphics.Color
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.manager.DownloadUtils
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.annotation.Page
import com.xuexiang.xpage.base.XPageFragment
import com.xuexiang.xpage.utils.TitleBar
import com.xuexiang.xutil.app.AppUtils

@Page(name = "news")
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
    }

    private var gameId: Int = 0

    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() {
        gameId = arguments?.getInt(GAME_ID)!!
        val gameName = arguments?.getString(GAME_NAME)!!
        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", mapOf("gameid" to GAME_ID.toString()))
                openToWebviewNative("/notice?noticeId=${it1.id}")
            }
        }
        binding.newsTitle.setText(gameName)
        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)
                if (itemData.type == 3) {
                    AcceleratorUtils.game?.let {
                        val version =
                            AppUtils.getAppVersionCode(it.packageName)
                        itemData.url?.let {
                            if (!it.isNullOrBlank()) {
                                val split = it.split("/")
                                if (split.size > 1 && split.get(split.lastIndex - 1).isNotEmpty()) {
                                    var newversion = split.get(split.lastIndex - 1).toInt()
                                    if (newversion > version && version != -1) {
                                        itemView.findViewById<TextView>(R.id.plugin_name)
                                            .setText("游戏更新")
                                        itemView.findViewById<TextView>(R.id.plugin_name)
                                            .setTextColor(Color.parseColor("#329CF3"))
                                    }
                                }
                            }
                        }
                    }

                }
                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 {
                            activity?.let { it1 ->
                                DownloadUtils.downloadFile(it1, it)
                            }
                        }
                    }
                }

            }.create()
        newsViewModel.pluginList.observe(this, {
            dataList.clear()
            dataList.addAll(it)
            binding.gameNewsList.adapter?.notifyDataSetChanged()
        })
        adapter = NewsCollectionAdapter(this, titles, gameId)
        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?) {

            }

        })

        newsViewModel.getNotice(gameId)
        newsViewModel.getPlugin(gameId)

    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser) {
            binding.gameNewsList.adapter?.notifyDataSetChanged()
        }
    }

    fun openToWebviewNative(url: String) {
        val params = Bundle()
        params.putString(CommonWebViewFragment.WEBVIEW_URL_KEY, HttpConfig.UI_MAIN_URL + url)
        params.putInt(CommonWebViewFragment.GAME_ID, gameId)
        openPage(CommonWebViewFragment::class.java, params)

    }

    fun openToWebview(url: String) {
        val params = Bundle()
        params.putString(CommonWebViewFragment.WEBVIEW_URL_KEY, url)
        params.putInt(CommonWebViewFragment.GAME_ID, gameId)
        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
        }

        val GAME_NAME = "GAME_NAME"
        val GAME_ID = "GAME_ID"
    }

}