package com.gh.gamecenter.history

import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.PopupWindow
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.common.util.*
import com.gh.gamecenter.GameDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.adapter.viewholder.GameViewHolder
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.DrawableView
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.databinding.GameItemBinding
import com.gh.gamecenter.databinding.PopupHistoryOptionBinding
import com.gh.gamecenter.entity.GameEntity
import com.gh.gamecenter.game.GameItemViewHolder

class HistoryGameListAdapter(context: Context, private val mViewModel: HistoryGameListViewModel) :
    ListAdapter<GameEntity>(context) {

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

    override fun areItemsTheSame(oldItem: GameEntity?, newItem: GameEntity?): Boolean {
        return oldItem?.id == newItem?.id
    }

    override fun getItemViewType(position: Int): Int {
        if (position == itemCount - 1) {
            return ItemViewType.ITEM_FOOTER
        }
        return ItemViewType.GAME_NORMAL
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): androidx.recyclerview.widget.RecyclerView.ViewHolder {
        return when (viewType) {
            ItemViewType.GAME_NORMAL -> {
                GameItemViewHolder(GameItemBinding.bind(mLayoutInflater.inflate(R.layout.game_item, parent, false)))
            }
            else -> {
                FooterViewHolder(mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false))
            }
        }
    }

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

    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: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is GameItemViewHolder -> {
                val gameEntity = mEntityList[position]

                holder.bindGameItem(gameEntity)
                holder.initServerType(gameEntity)

                (holder.binding.selectIv.layoutParams as ConstraintLayout.LayoutParams).apply {
                    width = 20f.dip2px()
                    height = 20f.dip2px()
                    holder.binding.selectIv.layoutParams = this
                }
                holder.binding.selectIv.setImageDrawable(R.drawable.selector_ic_history.toDrawable())
                holder.binding.selectIv.goneIf(mCurrentOption == ManageOption.OPTION_MANAGER)
                holder.binding.selectIv.isChecked = selectItems.contains(gameEntity.id)

                holder.itemView.setOnClickListener {
                    if (mCurrentOption == ManageOption.OPTION_MANAGER) {
                        GameDetailActivity.startGameDetailActivity(mContext, gameEntity.id, "(浏览记录:游戏)")
                    } else {
                        if (selectItems.contains(gameEntity.id)) {
                            selectItems.remove(gameEntity.id)
                        } else {
                            selectItems.add(gameEntity.id)
                        }
                        checkSelectItems()
                        notifyItemChanged(position)
                    }
                }
                DownloadItemUtils.setOnClickListener(
                    mContext, holder.binding.downloadBtn,
                    gameEntity, position, this,
                    "(浏览记录:游戏)",
                    StringUtils.buildString("浏览记录", ":", gameEntity.name)
                )
                DownloadItemUtils.updateItemWithViewOnlyStyle(GameViewHolder(holder.binding))

                holder.itemView.setOnLongClickListener {
                    consume {
                        DialogHelper.showDialog(holder.binding.root.context,
                            "删除记录",
                            "删除浏览记录将不可恢复，确定删除吗？",
                            "确定",
                            "取消", {
                                mViewModel.removeHistory(gameEntity)
                            })
                    }
                }
            }
            is FooterViewHolder -> {
                holder.initItemPadding()
                holder.initFooterViewHolder(mViewModel, mIsLoading, mIsNetworkError, mIsOver)
            }
        }
    }

    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
        }
    }
}