package com.ccwangluo.accelerator.ui.news

import android.content.Intent
import android.graphics.Color
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.HtmlUtil
import com.ccwangluo.accelerator.utils.datareport.DataRePortUtils
import com.github.shadowsocks.http.HttpConfig
import com.hjq.toast.ToastUtils
import com.xuexiang.xpage.core.PageOption


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() {
        gameId = arguments?.getInt(NewsCollectionAdapter.GAME_ID)!!
        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(HtmlUtil.delHTMLTag(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 imgs1 = itemView.findViewById<ImageView>(R.id.imgs1)
                    val imgs2 = itemView.findViewById<ImageView>(R.id.imgs2)
                    val vedio = itemView.findViewById<JCVideoPlayerStandard>(R.id.video_view)
                    vedio.backButton.visibility = View.GONE
                    vedio.tinyBackImageView.visibility = View.GONE
                    itemData.imgs?.let {
                        val split = itemData.imgs.split(",")
                        if (split.size > 0) {
                            imgs.visibility = View.VISIBLE
                            Glide.with(this@NewsObjectFragment).load(split.get(0))
                                .into(imgs)
                        } else {
                            imgs.visibility = View.GONE
                        }
                        if (split.size > 1) {
                            imgs1.visibility = View.VISIBLE
                            Glide.with(this@NewsObjectFragment).load(split.get(1))
                                .into(imgs1)
                        } else {
                            imgs1.visibility = View.GONE
                        }

                        if (split.size > 2) {
                            imgs2.visibility = View.VISIBLE
                            Glide.with(this@NewsObjectFragment).load(split.get(2))
                                .into(imgs2)
                        } else {
                            imgs2.visibility = View.GONE
                        }
                    } ?: let {
                        imgs.visibility = View.GONE
                        imgs1.visibility = View.GONE
                        imgs2.visibility = View.GONE
                    }
                    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)
                        }
                    } ?: let {
                        vedio.visibility = View.GONE
                    }
                    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 {
                        openWebviewForResult(itemData)
                    }
                }
                .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)
        })
        newsViewModel?.clearList?.observe(this, {
            if (it) {
                dataList.clear()
            }
        })
    }

    var CLICK_GREAT_REQUEST_CODE = 200
    var itemData: News? = null
    private fun openWebviewForResult(itemData: News) {
        this.itemData = itemData
        PageOption.to(CommonWebViewFragment::class.java)
            .putString(
                CommonWebViewFragment.WEBVIEW_URL_KEY, HttpConfig.UI_MAIN_URL +
                        "/gameDetail?id=${itemData.id}"
            )
            .putInt(CommonWebViewFragment.GAME_ID,gameId)
            .setRequestCode(CLICK_GREAT_REQUEST_CODE)
            .open(this)
    }

    override fun onFragmentResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onFragmentResult(requestCode, resultCode, data)
        if (requestCode == CLICK_GREAT_REQUEST_CODE) {
            itemData?.let {
                if (resultCode == 200) {
                    it.isGreat = true
                    it.greatNum++
                } else {
                    it.isGreat = false
                    it.greatNum--
                }
                recycle_view?.adapter?.notifyDataSetChanged()
            }
        }
    }

    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() {
            page = 1
            newsViewModel?.freshData(position, gameId, page)

    }
}