package com.gh.gamecenter.message.view.message

import android.content.Context
import android.graphics.Typeface
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.therouter.TheRouter
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.feature.game.GameItemViewHolder
import com.gh.gamecenter.feature.provider.ICommentUtilsProvider
import com.gh.gamecenter.message.R
import com.gh.gamecenter.message.databinding.ItemSortedMessageBinding
import com.gh.gamecenter.message.entity.SortedMessageEntity
import com.gh.gamecenter.message.utils.NewFlatLogUtils

class SortedMessageListAdapter(
    context: Context,
    private val mViewModel: SortedMessageListViewModel,
    private val mEntrance: String
) : ListAdapter<SortedMessageEntity>(context) {
    private val mMessageTypeMap = mapOf(
        TYPE_SYSTEM to R.drawable.ic_system_message,
        TYPE_USER to R.drawable.ic_user_message,
        TYPE_ANNOUNCEMENT to R.drawable.ic_announcement_message,
        TYPE_SERVICE to R.drawable.ic_service_message,
    )

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

    override fun areContentsTheSame(oldItem: SortedMessageEntity?, newItem: SortedMessageEntity?): Boolean {
        return (oldItem?.id == newItem?.id) &&
                (oldItem?.unreadCount == newItem?.unreadCount) &&
                (oldItem?.setting == newItem?.setting) &&
                (oldItem?.latestContent == newItem?.latestContent)
    }

    override fun getItemViewType(position: Int): Int {
        return if (position == mEntityList.size) ItemViewType.ITEM_FOOTER else ItemViewType.ITEM_BODY
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return if (viewType == ItemViewType.ITEM_FOOTER) {
            FooterViewHolder(mLayoutInflater.inflate(com.gh.gamecenter.common.R.layout.refresh_footerview, parent, false))
        } else {
            SortedMessageItemViewHolder(parent.toBinding())
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is SortedMessageItemViewHolder) {
            mEntityList.safelyGetInRelease(position)?.let { entity ->
                holder.binding.run {
                    root.background =
                        if (entity.setting.top) R.drawable.sorted_message_top_item_style.toDrawable(mContext) else com.gh.gamecenter.common.R.drawable.reuse_listview_item_style.toDrawable(
                            mContext
                        )
                    divider.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_divider.toColor(mContext))
                    titleTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(mContext))
                    contentTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(mContext))
                    timeTv.setTextColor(com.gh.gamecenter.common.R.color.text_neutral.toColor(mContext))
                    hintTv.background = com.gh.gamecenter.common.R.drawable.message_unread_hint.toDrawable(mContext)
                    ovalHint.background = com.gh.gamecenter.common.R.drawable.oval_message_hint_bg.toDrawable(mContext)

                    titleTv.text = entity.title
                    if (mMessageTypeMap[entity.type] != null && entity.icon.isEmpty()) {
                        ImageUtils.display(iconIv, mMessageTypeMap[entity.type])
                    } else {
                        ImageUtils.display(iconIv, entity.icon)
                    }
                    if (entity.type == TYPE_GAME && entity.game != null) {
                        GameItemViewHolder.initGameSubtitleAndAdLabel(entity.game!!.toGameEntity(), gameSubtitleTv)
                    } else {
                        gameSubtitleTv.visibility = View.GONE
                    }

                    val commentUtils = TheRouter.get(ICommentUtilsProvider::class.java)
                    entity.latestContent?.let {
                        if (it.time <= 0) {
                            timeTv.text = ""
                        } else {
                            timeTv.text = commentUtils?.getCommentTime(it.time)
                        }
                    }
                    contentTv.text = entity.latestContent?.text
                    hintTv.isVisible = !entity.setting.doNotDisturb && entity.unreadCount > 0
                    hintTv.text = if (entity.unreadCount < 100) entity.unreadCount.toString() else "99+"
                    hintTv.typeface = Typeface.createFromAsset(mContext.assets, Constants.DIN_FONT_PATH)
                    ovalHint.isVisible = entity.setting.doNotDisturb && entity.unreadCount > 0
                    doNotDisturbIv.isVisible = entity.setting.doNotDisturb && entity.unreadCount == 0
                    ConstraintSet().apply {
                        clone(root)
                        clear(contentTv.id, ConstraintSet.END)
                        connect(
                            contentTv.id,
                            ConstraintSet.END,
                            if (ovalHint.isVisible) ovalHint.id else if (hintTv.isVisible) hintTv.id else doNotDisturbIv.id,
                            ConstraintSet.START,
                            16F.dip2px()
                        )
                    }.applyTo(root)

                    val gameId = if (entity.type == TYPE_GAME) entity.game?.id ?: "" else ""
                    val gameName = if (entity.type == TYPE_GAME) entity.game?.name ?: "" else ""
                    val categoryChinese = if (entity.type == TYPE_GAME) entity.game?.categoryChinese ?: "" else ""

                    root.setOnClickListener {
                        NewFlatLogUtils.logMessageInformClick(
                            mEntrance,
                            entity.typeChinese,
                            gameId,
                            gameName,
                            position + 1,
                            entity.setting.top,
                            entity.unreadCount,
                            "点击进入消息列表"
                        )
                        SensorsBridge.trackMessageSessionClick(
                            gameId = gameId,
                            gameName = gameName,
                            gameType = categoryChinese,
                            sessionMessageType = entity.typeChinese
                        )
                        if (entity.unreadCount > 0) {
                            mViewModel.markSortedMessageRead(position, entity.id)
                        }
                        mContext.startActivity(
                            MessageListActivity.getIntent(
                                mContext,
                                entity.type,
                                entity.title,
                                gameId,
                                gameName,
                                categoryChinese,
                                BaseActivity.mergeEntranceAndPath(mEntrance, "二级列表")
                            )
                        )
                    }

                    root.setOnLongClickListener {
                        if (mContext is AppCompatActivity) {
                            NewFlatLogUtils.logMessageInformClick(
                                mEntrance,
                                entity.typeChinese,
                                gameId,
                                gameName,
                                position + 1,
                                entity.setting.top,
                                entity.unreadCount,
                                "长按更多"
                            )
                            SortedMessageActionDialog.show(
                                mContext as AppCompatActivity,
                                position,
                                entity,
                                mEntrance,
                                SortedMessageListFragment::class.java.name
                            )
                        }
                        true
                    }
                }
            }
        }

        if (holder is FooterViewHolder) {
            holder.initItemPadding()
            holder.initFooterViewHolder(mViewModel, mIsLoading, mIsNetworkError, mIsOver)
            holder.hint.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_B3B3B3))
            val lp = holder.itemView.layoutParams as RecyclerView.LayoutParams
            lp.height = DisplayUtils.dip2px(48F)
            lp.width = ViewGroup.LayoutParams.MATCH_PARENT
            holder.itemView.layoutParams = lp
        }
    }

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


    class SortedMessageItemViewHolder(val binding: ItemSortedMessageBinding) : BaseRecyclerViewHolder<Any>(binding.root)

    companion object {
        const val TYPE_SYSTEM = "system" // 系统通知
        const val TYPE_USER = "user" // 互动消息
        const val TYPE_ANNOUNCEMENT = "announcement" // 运营公告
        const val TYPE_SERVICE = "service" // 光环客服
        const val TYPE_GAME = "game" // 游戏会话
        const val TYPE_BBS = "bbs" // 论坛会话
    }
}