package com.gh.gamecenter.mypost

import android.app.Activity
import android.content.Context
import android.text.SpannableStringBuilder
import android.util.SparseBooleanArray
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.R
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.core.utils.SpanBuilder
import com.gh.gamecenter.databinding.CommunityAnswerItemBinding
import com.gh.gamecenter.entity.ForumVideoEntity
import com.gh.gamecenter.entity.PersonalHistoryEntity
import com.gh.gamecenter.forum.home.ArticleItemVideoView
import com.gh.gamecenter.personalhome.PersonalItemViewHolder
import com.gh.gamecenter.personalhome.home.UserHistoryViewModel
import com.gh.gamecenter.qa.entity.AnswerEntity
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.utils.OrientationUtils

class MyPostAdapter(
    context: Context,
    private val mListViewModel: UserHistoryViewModel,
    private val mEntrance: String,
    private val itemClickCallback: (historyEntity: PersonalHistoryEntity, position: Int) -> Unit
) : ListAdapter<PersonalHistoryEntity>(context) {

    private var mExpandSparseBooleanArray = SparseBooleanArray()

    override fun getItemViewType(position: Int): Int {
        return when (position) {
            itemCount - 1 -> ItemViewType.ITEM_FOOTER
            else -> ItemViewType.ITEM_BODY
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view: View
        return when (viewType) {
            ItemViewType.ITEM_FOOTER -> {
                view = mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false)
                FooterViewHolder(view)
            }
            else -> {
                view = mLayoutInflater.inflate(R.layout.community_answer_item, parent, false)
                PersonalItemViewHolder(CommunityAnswerItemBinding.bind(view))
            }
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is PersonalItemViewHolder -> bindNormalItem(holder, position)
            is FooterViewHolder -> {
                holder.initItemPadding()
                holder.initFooterViewHolder(mListViewModel, mIsLoading, mIsNetworkError, mIsOver)
            }
        }
    }

    private fun bindNormalItem(holder: PersonalItemViewHolder, position: Int) {
        val historyEntity = mEntityList[position]

        holder.bindPersonalItem(historyEntity, mEntrance)

        val answer = AnswerEntity()
        answer.images = historyEntity.images
        answer.imagesInfo = historyEntity.imagesInfo
        answer.videos = historyEntity.videos
        answer.type = historyEntity.type
        answer.id = historyEntity.id
        answer.communityId = historyEntity.community.id
        answer.communityName = historyEntity.community.name
        answer.status = historyEntity.status ?: "pending"
        answer.user.id = historyEntity.user?.id ?: ""

        holder.binding.imageContainer.bindData(answer, mEntrance)
        bindVideoData(holder.binding, historyEntity.transformForumVideoEntity())

        holder.binding.run {
            topLine.goneIf(position == 0)
            forumNameLl.visibleIf(historyEntity.community.id.isNotEmpty())
            ImageUtils.display(userBadgeIcon, historyEntity.user?.badge?.icon)

            statusTv.goneIf(!(historyEntity.status == "pending" || historyEntity.status == "fail") && !historyEntity.me.isFollower)
            statusTv.setText(
                when {
                    historyEntity.me.isFollower -> R.string.follow_status
                    historyEntity.status == "pending" -> R.string.content_pending_status
                    else -> R.string.fail_status
                }
            )
            statusTv.setTextColor(
                when {
                    historyEntity.me.isFollower -> R.color.theme_alpha_80
                    historyEntity.status == "pending" -> R.color.text_subtitleDesc
                    else -> R.color.text_CCFF5269
                }.toColor(mContext)
            )
            statusTv.setDrawableStart(
                when {
                    historyEntity.me.isFollower -> R.drawable.ic_forum_follow
                    historyEntity.status == "pending" -> R.drawable.ic_forum_pending
                    else -> R.drawable.icon_forum_fail
                }
            )
            title.goneIf(historyEntity.type.contains("answer"))
            title.text =
                if ((historyEntity.type.contains("question") || historyEntity.type.contains("article") || historyEntity.type.contains(
                        "video"
                    ))
                ) historyEntity.title else historyEntity.question.title
            questionTitle.goneIf(!historyEntity.type.contains("answer"))
            questionTitle.text = historyEntity.question.title
            content.goneIf(historyEntity.brief.isEmpty() && historyEntity.des.isEmpty() && historyEntity.description.isEmpty())
            content.text = when {
                historyEntity.type.contains("video") -> historyEntity.des
                historyEntity.type.contains("question") -> historyEntity.description
                else -> historyEntity.brief
            }
            forumNameTv.text = historyEntity.community.name

            when (historyEntity.type) {
                "question" -> {
                    val titleStr = "  ${historyEntity.title}"
                    val drawable = R.drawable.ic_ask_label.toDrawable()
                    drawable?.run {
                        setBounds(0, 0, 16F.dip2px(), 16F.dip2px())
                        title.text = SpanBuilder(titleStr).image(0, 1, this).build()
                    }
                }

                "answer" -> {
                    val briefStr = "  ${historyEntity.brief}"
                    val drawable = R.drawable.ic_answer_label.toDrawable()
                    drawable?.run {
                        setBounds(0, 0, 16F.dip2px(), 16F.dip2px())
                        content.text = SpanBuilder(briefStr).image(0, 1, this).build()
                    }
                }

                "community_article" -> {
                    if (historyEntity.getPassVideos().isNotEmpty() && historyEntity.images.isNotEmpty()) {
                        val titleStr = title.text
                        val videoSpan =
                            SpanBuilder("  ").image(1, "  ".length, R.drawable.ic_article_video_label).build()
                        title.text = SpannableStringBuilder()
                            .append(titleStr)
                            .append(videoSpan)
                    }
                }
            }

            userIcon.visibility = View.GONE
            userName.visibility = View.GONE
            userBadgeIcon.visibility = View.GONE
            userBadgeName.visibility = View.GONE
            concernBtn.visibility = View.GONE
            timeContainer.visibility = View.GONE
            title.layoutParams = (title.layoutParams as ViewGroup.MarginLayoutParams).apply {
                topMargin = 20F.dip2px()
            }

            title.setOnClickListener {
                holder.itemView.performClick()
            }
        }
        holder.itemView.setOnClickListener {
            itemClickCallback.invoke(historyEntity, position)
        }
    }

    private fun bindVideoData(binding: CommunityAnswerItemBinding, entity: ForumVideoEntity) {
        binding.run {
            if (entity.url.isEmpty()) {
                horizontalVideoView.visibility = View.GONE
                verticalVideoView.visibility = View.GONE
            } else {
                val videoInfo = entity.videoInfo
                val visibleView = if (videoInfo.height > videoInfo.width) {
                    horizontalVideoView.visibility = View.GONE
                    verticalVideoView.visibility = View.VISIBLE
                    verticalVideoView
                } else {
                    horizontalVideoView.visibility = View.VISIBLE
                    verticalVideoView.visibility = View.GONE
                    horizontalVideoView
                }

                val orientationUtils = OrientationUtils(mContext as Activity, visibleView)
                orientationUtils.isEnable = false
                GSYVideoOptionBuilder()
                    .setIsTouchWiget(false)
                    .setUrl(entity.url)
                    .setRotateViewAuto(false)
                    .setCacheWithPlay(true)
                    .setRotateWithSystem(false)
                    .setReleaseWhenLossAudio(true)
                    .setLooping(false)
                    .setShowFullAnimation(false)
                    .setEnlargeImageRes(R.drawable.ic_game_detail_enter_full_screen)
                    .setShrinkImageRes(R.drawable.ic_game_detail_exit_full_screen)
                    .setVideoAllCallBack(object : GSYSampleCallBack() {
                        override fun onQuitFullscreen(url: String?, vararg objects: Any) {
                            orientationUtils.backToProtVideo()
                            visibleView.uploadVideoStreamingPlaying("退出全屏")
                        }
                    })
                    .build(visibleView)
                visibleView.run {
                    updateVideoData(entity)
                    updateThumb(entity.poster)
                    updateDurationTv(entity.duration)

                    setVideoStatus(entity.status)

                    fullscreenButton.setOnClickListener {
                        val horizontalVideoView = startWindowFullscreen(mContext, true, true) as? ArticleItemVideoView
                        if (horizontalVideoView == null) {
                            toastInInternalRelease("全屏失败，请向技术人员提供具体的操作步骤")
                            return@setOnClickListener
                        }
                        orientationUtils.resolveByClick()
                        horizontalVideoView.uuid = uuid
                        horizontalVideoView.updateVideoData(entity)
                        horizontalVideoView.updateThumb(entity.poster)
                        horizontalVideoView.violenceUpdateMuteStatus()
                        horizontalVideoView.setFullViewStatus()
                        uploadVideoStreamingPlaying("开始播放")
                        uploadVideoStreamingPlaying("点击全屏")
                    }
                }
            }
        }
    }

    override fun getItemCount(): Int {
        return if (mEntityList == null || mEntityList.isEmpty()) 0 else mEntityList.size + 1
    }
}