package com.gh.gamecenter.collection

import android.content.Context
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.gamecenter.common.syncpage.ISyncAdapterHandler
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.databinding.CommunityAnswerItemBinding
import com.gh.gamecenter.databinding.PopupHistoryOptionBinding
import com.gh.gamecenter.common.entity.CommunityEntity
import com.gh.gamecenter.common.view.DrawableView
import com.gh.gamecenter.history.ManageOption
import com.gh.gamecenter.qa.answer.CommunityAnswerItemViewHolder
import com.gh.gamecenter.qa.article.detail.ArticleDetailActivity
import com.gh.gamecenter.feature.entity.ArticleEntity
import com.gh.gamecenter.qa.questions.newdetail.NewQuestionDetailActivity

class CommunityArticleAdapter(
    context: Context,
    private val mViewModel: CommunityArticleViewModel,
    private val mEntrance: String
) : ListAdapter<ArticleEntity>(context), ISyncAdapterHandler {

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

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

    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.community_answer_item, parent, false)
                CommunityAnswerItemViewHolder(CommunityAnswerItemBinding.bind(view))
            }
        }
    }

    override fun getItemCount(): Int = if (mEntityList.size == 0) 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: RecyclerView.ViewHolder, position: Int) {
        if (holder is CommunityAnswerItemViewHolder) {
            var path = ""
            val entity = mEntityList[position]

            if (mViewModel.type == CommunityArticleFragment.Type.COLLECTION.value) {
                path = "我的收藏-文章列表"
            } else {
                path = "浏览记录-文章列表"
                holder.itemView.setOnLongClickListener {
                    consume {
                        DialogHelper.showDialog(holder.binding.root.context,
                            "删除记录",
                            "删除浏览记录将不可恢复，确定删除吗？",
                            "确定",
                            "取消", {
                                mViewModel.removeHistory(entity)
                            })
                    }
                }
            }

            if (entity.bbs == CommunityEntity()) {
                entity.bbs = entity.community
            }
            holder.binding.selectIv.goneIf(mCurrentOption == ManageOption.OPTION_MANAGER)
            holder.binding.selectIv.isChecked = selectItems.contains(entity.id)
            holder.binding.imageContainer.setOffset(if (mCurrentOption == ManageOption.OPTION_MANAGER) 40f else 76f)
            holder.bindArticleItem(entity, mEntrance, path)
            holder.itemView.setOnClickListener {
                if (mCurrentOption == ManageOption.OPTION_MANAGER) {
                    if (entity.type == "question") {
                        mContext.startActivity(
                            NewQuestionDetailActivity.getIntent(
                                mContext,
                                entity.id,
                                mEntrance,
                                path
                            )
                        )
                    } else {
                        if (entity.active) {
                            mContext.startActivity(
                                ArticleDetailActivity.getIntent(
                                    mContext,
                                    entity.community,
                                    entity.id,
                                    mEntrance,
                                    path
                                )
                            )
                        } else {
                            DialogHelper.showDialog(mContext, "提示", "内容已被删除，是否取消收藏？", "取消收藏", "暂不", {
                                mViewModel.deleteCollection(entity.community.id, entity.id)
                            }, extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true))
                        }
                    }

                    if (!entity.read) {
                        entity.read = true
                        holder.binding.unreadHint.visibility = View.GONE
                        mViewModel.postCollectionArticleRead(entity.community.id, entity.id)
                    }
                } else {
                    if (selectItems.contains(entity.id)) {
                        selectItems.remove(entity.id)
                    } else {
                        selectItems.add(entity.id)
                    }
                    checkSelectItems()
                    notifyItemChanged(position)
                }
            }
        } else if (holder is FooterViewHolder) {
            holder.initItemPadding()
            holder.initFooterViewHolder(mViewModel, mIsLoading, isNetworkError, 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
        }
    }

    override fun getSyncData(position: Int): Pair<String, ArticleEntity>? {
        if (position >= mEntityList.size) return null
        val entity = mEntityList[position]
        return Pair(entity.id, entity)
    }
}