package com.ccwangluo.accelerator.ui.news

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.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.model.News
import com.ccwangluo.accelerator.ui.home.NewsViewModel
import com.ccwangluo.accelerator.ui.news.NewsCollectionAdapter.Companion.ARG_OBJECT
import com.ccwangluo.accelerator.utils.AcceleratorUtils
import com.xuexiang.xpage.base.XPageFragment
import com.xuexiang.xpage.utils.TitleBar
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard
import com.ccwangluo.accelerator.model.NewsModel
import com.ccwangluo.accelerator.ui.view.RatingBar
import com.ccwangluo.accelerator.ui.web.CommonWebViewFragment
import com.ccwangluo.accelerator.utils.datareport.DataRePortUtils
import com.github.shadowsocks.http.HttpConfig
import com.hjq.toast.ToastUtils


class NewsObjectFragment : XPageFragment() {
    var recycle_view: RecyclerView? = null
    override fun initTitleBar(): TitleBar? {
        //不使用@Page标注的一定要注意覆盖这个方法
        return null
    }

    private var newsViewModel: NewsObjectModel? = null
    private lateinit var viewModel: NewsViewModel

    private val dataList = arrayListOf<News>()
    private var page = 1
    private lateinit var position: String
    private var newsModel: NewsModel? = null
    override fun inflateView(inflater: LayoutInflater?, container: ViewGroup?): View {
        viewModel = ViewModelProvider(requireActivity()).get(NewsViewModel::class.java)
        newsViewModel = ViewModelProvider(this).get(NewsObjectModel::class.java)
        return inflater!!.inflate(R.layout.fragment_collection_object, container, false)
    }

    private var gameId = 0

    override fun initViews() {
        arguments?.takeIf { it.containsKey(ARG_OBJECT) }?.apply {
            position = getInt(ARG_OBJECT).toString()
            recycle_view = findViewById(R.id.recycle_view)
            val layoutManager = LinearLayoutManager(context)
            recycle_view?.setLayoutManager(layoutManager)
            val adapter = KotlinDataAdapter.Builder<News>()
                    .setData(dataList)
                    .setLayoutId(R.layout.item_dynamic)
                    .addBindView { itemView, itemData ->
                        val avatar = itemView.findViewById<ImageView>(R.id.avatar)
                        Glide.with(this@NewsObjectFragment)
                                .load(if (itemData.type == 4) itemData.qAvatar else itemData.avatar)
                                .into(avatar)

                        itemView.findViewById<TextView>(R.id.nickname)
                                .setText(if (itemData.type == 4) itemData.qNickname else itemData.nickname)
                        itemView.findViewById<TextView>(R.id.createdDate)
                                .setText(
                                        (if (itemData.type == 4) itemData.qCreatedDate else itemData.createdDate)?.substring(
                                                0,
                                                10
                                        )
                                )
                        itemData.title?.let {
                            itemView.findViewById<TextView>(R.id.title).visibility = View.VISIBLE
                            itemView.findViewById<TextView>(R.id.title).setText(it)
                        }
                                ?: let { itemView.findViewById<TextView>(R.id.title).visibility = View.GONE }


                        if (itemData.type == 5) {
                            itemData.content?.let {
                                itemView.findViewById<TextView>(R.id.abbrContent).visibility = View.VISIBLE
                                itemView.findViewById<TextView>(R.id.abbrContent).setText(it)
                            } ?: let {
                                itemView.findViewById<TextView>(R.id.abbrContent).visibility = View.GONE
                            }
                        } else {
                            itemData.abbrContent?.let {
                                itemView.findViewById<TextView>(R.id.abbrContent).visibility = View.VISIBLE
                                itemView.findViewById<TextView>(R.id.abbrContent).setText(it)
                            } ?: let {
                                itemView.findViewById<TextView>(R.id.abbrContent).visibility = View.GONE
                            }
                        }


                        //	资讯类型：0攻略 1视频
                        val imgs = itemView.findViewById<ImageView>(R.id.imgs)
                        val vedio = itemView.findViewById<JCVideoPlayerStandard>(R.id.video_view)
                        vedio.backButton.visibility = View.GONE
                        vedio.tinyBackImageView.visibility = View.GONE
                        itemData.imgs?.let {
                            imgs.visibility = View.VISIBLE
                            Glide.with(this@NewsObjectFragment).load(itemData.imgs.split(",").get(0))
                                    .into(imgs)
                        }
                        itemData.videoUrl?.let {
                            vedio.visibility = View.VISIBLE
                            vedio.setUp(
                                    it, JCVideoPlayer.SCREEN_LAYOUT_LIST
                            )
                            itemData.videoImg?.let {
                                Glide.with(this@NewsObjectFragment).load(it)
                                        .into(vedio.thumbImageView)
                            }

                        }
                        val star = itemView.findViewById<RatingBar>(R.id.star)
                        itemData.star?.let {
                            star.visibility = View.VISIBLE
                            star.setStar(it.toFloat())
                        } ?: let {
                            star.visibility = View.GONE
                        }

                        itemData.pageViews?.let {
                            itemView.findViewById<TextView>(R.id.pageViews).setText("${it}浏览")
                        }
                        itemData.greatNum?.let {
                            itemView.findViewById<TextView>(R.id.great_num).setText("${it}")
                        }
                        itemData.isGreat?.let {
                            if (it) {
                                itemView.findViewById<TextView>(R.id.great_num).setTextColor(Color.parseColor("#3CA4FD"))
                                itemView.findViewById<ImageView>(R.id.great_img)
                                        .setBackgroundResource(R.mipmap.icon_praise_bu)
                            } else {
                                itemView.findViewById<TextView>(R.id.great_num).setTextColor(Color.parseColor("#FFBBBBBB"))
                                itemView.findViewById<ImageView>(R.id.great_img)
                                        .setBackgroundResource(R.mipmap.icon_praise_ga)
                            }
                        }
                        itemView.findViewById<ImageView>(R.id.great_img).setOnClickListener {
                            itemData.isGreat?.let {
                                if (!it) {
                                    DataRePortUtils.report("st_like_clk")
                                }
                                newsViewModel?.greate(this@NewsObjectFragment, itemData.type, gameId, itemData.id, it) {
                                    if (!it) {
                                        ToastUtils.show("点赞成功")
                                        itemData.isGreat = true
                                        itemData.greatNum++
                                    } else {
                                        itemData.isGreat = false
                                        itemData.greatNum--
                                    }
                                    recycle_view?.adapter?.notifyDataSetChanged()
                                }
                            }
                        }

                        itemView.findViewById<View>(R.id.item_click_view).setOnClickListener {
                            val params = Bundle()
                            params.putString(
                                    CommonWebViewFragment.WEBVIEW_URL_KEY, HttpConfig.UI_MAIN_URL +
                                    "/gameDetail?gameId=${gameId}&id=${itemData.id}"
                            )
                            openPage(CommonWebViewFragment::class.java, params)
                        }
                    }
                    .create()
            recycle_view?.adapter = adapter
            refresh()
            recycle_view?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                }

                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    if (isSlideToBottom(recyclerView)) {
                        newsModel?.let {
                            if (dataList.size < it.total) {
                                page++
                                newsViewModel?.freshData(position, gameId, page)
                            }
                        }

                    }
                }
            })
        }
        newsViewModel?.newsModel?.observe(this, {
            newsModel = it
            dataList.addAll(it.list)
            recycle_view?.adapter?.notifyDataSetChanged()
            viewModel.isRefresh.postValue(true)
        })
    }

    protected fun isSlideToBottom(recyclerView: RecyclerView?): Boolean {
        if (recyclerView == null) return false
        return if (recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset() >= recyclerView.computeVerticalScrollRange()) true else false
    }


    override fun initListeners() {

    }

    fun refresh() {
        AcceleratorUtils.game?.let {
            dataList.clear()
            gameId = it.id
            page = 1
            newsViewModel?.freshData(position, it.id, page)
        }

    }
}