package com.gh.gamecenter.collection

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.drawable.StateListDrawable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.PopupWindow
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.common.util.*
import com.gh.gamecenter.R
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.DrawableView
import com.gh.gamecenter.databinding.PopupHistoryOptionBinding
import com.gh.gamecenter.databinding.VideoNewItemBinding
import com.gh.gamecenter.entity.MyVideoEntity
import com.gh.gamecenter.history.ManageOption
import com.gh.gamecenter.video.VideoItemViewHolder
import com.gh.gamecenter.video.detail.VideoDetailContainerViewModel

class VideoAdapter(
    context: Context,
    val mViewModel: VideoViewModel,
    val mVideoStyle: String,
    val mIsInsertBbsVideo: Boolean,
    val mEntrance: String
) : ListAdapter<MyVideoEntity>(context) {

    private var mCurrentOption = ManageOption.OPTION_MANAGER
    private var mPopWindow: PopupWindow? = null
    private var mPopupBinding: PopupHistoryOptionBinding? = null
    var selectItems = arrayListOf<String>()

    override fun getItemViewType(position: Int): Int {
        if (position == itemCount - 1) return ItemViewType.ITEM_FOOTER
        return 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.video_new_item, parent, false)
                return VideoItemViewHolder(VideoNewItemBinding.bind(view))
            }
        }
    }

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

    }

    fun changeOption(option: ManageOption) {
        mCurrentOption = option
        when (mCurrentOption) {
            ManageOption.OPTION_MANAGER -> {
                selectItems.clear()
                mPopWindow?.dismiss()
                mPopWindow = null
            }
            else -> {
                if (mPopWindow == null || mPopWindow?.isShowing == false) {
                    showOptionWindow()
                }
            }
        }
        notifyItemRangeChanged(0, mEntityList.size)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is VideoItemViewHolder) {
            val entity = mEntityList[position]
            holder.bindVideoItem(entity)

            holder.binding.selectIv.goneIf(mCurrentOption == ManageOption.OPTION_MANAGER)
            holder.binding.selectIv.isChecked = selectItems.contains(entity.id)

            holder.itemView.setOnClickListener {
                if (!mIsInsertBbsVideo) {
                    if (mCurrentOption == ManageOption.OPTION_MANAGER) {
                        if (mVideoStyle == VideoFragment.VideoStyle.COLLECT.value) {
                            DirectUtils.directToVideoDetail(
                                mContext,
                                entity.id,
                                VideoDetailContainerViewModel.Location.USER_FAVORITE_VIDEO.value,
                                false,
                                path = getPath()
                            )
                        } else {
                            DirectUtils.directToVideoDetail(
                                mContext,
                                entity.id,
                                VideoDetailContainerViewModel.Location.VIDEO_HOT.value,
                                false,
                                path = getPath()
                            )
                        }
                    } else {
                        if (selectItems.contains(entity.id)) {
                            selectItems.remove(entity.id)
                        } else {
                            selectItems.add(entity.id)
                        }
                        checkSelectItems()
                        notifyItemChanged(position)
                    }
                } else {
                    val intent = Intent()
                    intent.putExtra(MyVideoEntity::class.java.simpleName, entity)
                    (mContext as AppCompatActivity).setResult(Activity.RESULT_OK, intent)
                    (mContext as AppCompatActivity).finish()
                }
            }

            if (!mIsInsertBbsVideo && mVideoStyle == VideoFragment.VideoStyle.BROWSING_HISTORY.value) {
                holder.itemView.setOnLongClickListener {
                    consume {
                        DialogHelper.showDialog(holder.binding.root.context,
                            "删除记录",
                            "删除浏览记录将不可恢复，确定删除吗？",
                            "确定",
                            "取消", {
                                mViewModel.removeHistory(entity)
                            })
                    }
                }
            }
            if (!mIsInsertBbsVideo) {
                holder.binding.userInfo.setOnClickListener {
                    DirectUtils.directToHomeActivity(mContext, entity.user.id, mEntrance, getPath())
                }
            }
        } else if (holder is FooterViewHolder) {
            holder.initFooterViewHolder(mViewModel, mIsLoading, mIsNetworkError, mIsOver)
        }
    }

    private fun getPath(): String {
        return if (mVideoStyle == VideoFragment.VideoStyle.COLLECT.value) "我的收藏-视频" else "浏览记录-视频"
    }

    private fun showOptionWindow() {
        mPopupBinding = PopupHistoryOptionBinding.inflate(LayoutInflater.from(mContext))
        mPopupBinding?.root?.isFocusable = true
        mPopupBinding?.root?.isFocusableInTouchMode = true

        mPopWindow = PopupWindow(mPopupBinding?.root, LinearLayout.LayoutParams.MATCH_PARENT, 56f.dip2px())
        mPopWindow?.showAtLocation((mContext as AppCompatActivity).window.decorView, Gravity.BOTTOM, 0, 0)

        mPopupBinding?.itemDelete?.setOnClickListener {
            DialogHelper.showDialog(mContext, "是否删除${selectItems.size}条记录？", "提示：删除记录将不可恢复", "删除", "取消", {
                mViewModel.removeHistories(selectItems)
                selectItems.clear()
                checkSelectItems()
            }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true))

        }
        mPopupBinding?.checkAllCb?.setCompoundDrawablesWithIntrinsicBounds(
            DrawableView.getCheckSelectorDrawable(
                mContext
            ), null, null, null
        )
        mPopupBinding?.checkAllCb?.setOnClickListener {
            if (mPopupBinding?.checkAllCb?.isChecked == true) {
                selectItems.clear()
                selectItems.addAll(mEntityList.map { it.id }.toList())
            } else {
                selectItems.clear()
            }
            checkSelectItems()
            notifyItemRangeChanged(0, mEntityList.size)
        }
        checkSelectItems()
    }

    private fun checkSelectItems() {
        mPopupBinding?.run {
            selectNumTv.text = if (selectItems.isEmpty()) "" else "(${selectItems.size})"
            itemDelete.background =
                if (selectItems.isEmpty()) R.drawable.bg_shape_f5_radius_999.toDrawable(mContext) else R.drawable.download_button_normal_style.toDrawable(
                    mContext
                )
            itemDelete.setTextColor(
                if (selectItems.isEmpty()) R.color.text_body.toColor(mContext) else R.color.white.toColor(
                    mContext
                )
            )
            itemDelete.isEnabled = selectItems.isNotEmpty()
            checkAllCb.isChecked = selectItems.size == mEntityList.size
        }
    }

}