package com.gh.gamecenter.vote

import android.app.Dialog
import android.content.Context
import android.util.SparseArray
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.ProgressBar
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.exposure.IExposable
import com.gh.common.util.DirectUtils.directToLinkPage
import com.gh.gamecenter.CleanApkActivity
import com.gh.gamecenter.GameDetailActivity.Companion.startGameDetailActivity
import com.gh.gamecenter.NewsDetailActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.adapter.viewholder.VoteViewHolder
import com.gh.gamecenter.common.baselist.ListAdapter
import com.gh.gamecenter.common.baselist.LoadStatus
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.common.view.CustomLinkMovementMethod
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.SpanBuilder
import com.gh.gamecenter.databinding.VoteItemBinding
import com.gh.gamecenter.entity.VersionVoteEntity
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.feature.entity.MeEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.feature.exposure.ExposureSource
import com.gh.gamecenter.feature.game.SelectGameAdapter
import com.gh.gamecenter.game.upload.GameUploadFragment
import com.lightgame.utils.Utils

class VoteAdapter(
    context: Context,
    private val fragment: VoteFragment,
    private val addVoteCallback: () -> Unit,
    private val voteCallback: (id: String?) -> Unit
) : ListAdapter<VersionVoteEntity>(context), IExposable {

    var mSelectGameDialog: Dialog? = null
    var mUploadPosition = -1
    private val mExposureEventSparseArray: SparseArray<ExposureEvent> = SparseArray()

    //进度条原始最大宽度
    private var mPbWidth = (DisplayUtils.getScreenWidth() - 144F.dip2px()).toFloat()

    override fun areItemsTheSame(oldItem: VersionVoteEntity, newItem: VersionVoteEntity) =
        !oldItem.id.isNullOrEmpty() && oldItem.id == newItem.id

    override fun getItemViewType(position: Int) = if (position == itemCount - 1) 0 else 1

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        when (viewType) {
            0 -> FooterViewHolder(mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false))
            else -> VoteViewHolder(VoteItemBinding.inflate(mLayoutInflater, parent, false))
        }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is VoteViewHolder) {
            val versionVoteEntity = mEntityList[position]
            holder.binding.root.setBackgroundColor(
                if (versionVoteEntity.isHighLight) R.color.comment_highlight.toColor(
                    mContext
                ) else R.color.background_white.toColor(mContext)
            )
            if (versionVoteEntity.open) {
                val userData = versionVoteEntity.me
                if (userData != null && userData.isVersionRequested) {
                    holder.binding.voteItemBtn.background = R.drawable.button_round_border_eeeeee.toDrawable(mContext)
                    holder.binding.voteItemBtn.setTextColor(R.color.text_subtitleDesc.toColor(mContext))
                    holder.binding.voteItemBtn.setText(R.string.voted)
                    holder.binding.voteItemBtn.isEnabled = false
                } else {
                    holder.binding.voteItemBtn.background = R.drawable.button_round_primary_light.toDrawable(mContext)
                    holder.binding.voteItemBtn.setTextColor(R.color.theme_font.toColor(mContext))
                    holder.binding.voteItemBtn.setText(R.string.vote)
                    holder.binding.voteItemBtn.isEnabled = true
                }
            } else {
                val link = versionVoteEntity.link
                if (EntranceConsts.HOST_GAME == link.type) {
                    holder.binding.voteItemBtn.setText(R.string.download)
                } else {
                    holder.binding.voteItemBtn.setText(R.string.libao_check)
                }
                holder.binding.voteItemBtn.background = R.drawable.button_blue_oval.toDrawable(mContext)
                holder.binding.voteItemBtn.setTextColor(R.color.white.toColor(mContext))
                holder.binding.voteItemBtn.isEnabled = true
            }

            val layoutParams = holder.binding.progressbar.layoutParams
            if (position > 0) {
                val maxSize = mEntityList[0].num.toFloat()
                val curSize = versionVoteEntity.num.toFloat()
                var width = curSize / maxSize * mPbWidth
                if (width < 4F.dip2px()) width = 4F.dip2px().toFloat()
                layoutParams.width = if (width > mPbWidth) mPbWidth.toInt() else width.toInt()
            } else {
                layoutParams.width = mPbWidth.toInt()
            }

            if (!versionVoteEntity.reply.isNullOrEmpty()) {
                var replyText: CharSequence = "小编回复:" + versionVoteEntity.reply
                if (versionVoteEntity.permitUploadApk) {
                    val uploadText = "去上传>"
                    val allReplyText = "$replyText $uploadText"
                    replyText = SpanBuilder(allReplyText)
                        .color(mContext, 0, 5, R.color.theme_font)
                        .click(
                            mContext,
                            replyText.length + 1,
                            allReplyText.length,
                            R.color.theme_font,
                            false
                        ) {
                            val isUserUploaded = versionVoteEntity.me?.requestsVersionApkUploaded ?: false
                            if (isUserUploaded) {
                                Utils.toast(mContext, "您已上传安装包，正在加急制作中~")
                            } else {
                                mContext.ifLogin("下载游戏-求版本-[去上传]") {
                                    versionVoteEntity.id?.let {
                                        mUploadPosition = position
                                        showSelectDialog(it)
                                    }
                                }
                            }
                        }.build()
                    holder.binding.voteItemReply.movementMethod = CustomLinkMovementMethod.getInstance()
                } else {
                    replyText = SpanBuilder(replyText)
                        .color(mContext, 0, 5, R.color.theme_font).build()
                }
                holder.binding.voteItemReply.text = replyText
                holder.binding.voteItemReply.visibility = View.VISIBLE
            } else {
                holder.binding.voteItemReply.visibility = View.GONE
            }
            holder.binding.voteItemName.text = versionVoteEntity.name
            holder.binding.voteItemCount.text = mContext.getString(
                R.string.vote_count,
                versionVoteEntity.num
            )
            holder.binding.progressbar.layoutParams = layoutParams

            val link = versionVoteEntity.link
            if (link.type == EntranceConsts.HOST_GAME) {
                val exposureEvent =
                    ExposureEvent.createEvent(
                        GameEntity(link.link).apply {
                            sequence = position
                        },
                        listOf(ExposureSource("下载面板", "求版本"))
                    )
                mExposureEventSparseArray.put(position, exposureEvent)
            }

            holder.binding.voteItemBtn.setOnClickListener {
                if (versionVoteEntity.open) {
                    voteCallback.invoke(versionVoteEntity.id)
                } else {
                    val entrance = "(游戏求版本)"
                    when (link.type ?: "") {
                        EntranceConsts.HOST_GAME -> {
                            startGameDetailActivity(
                                mContext,
                                link.link!!, entrance, -1,
                                isSkipGameComment = false,
                                scrollToLibao = false,
                                openVideoStreaming = false,
                                openPlatformWindow = true,
                                link.platform,
                                link.packageName,
                                traceEvent = mExposureEventSparseArray[position]
                            )
                        }
                        EntranceConsts.HOST_ARTICLE -> mContext.startActivity(
                            NewsDetailActivity.getIntentById(
                                mContext,
                                link.link,
                                entrance
                            )
                        )
                        else ->
                            directToLinkPage(mContext, link, entrance, "")
                    }
                }
            }
        }
        if (holder is FooterViewHolder) {
            initFooterViewHolder(holder)
        }
    }

    private fun initFooterViewHolder(viewHolder: FooterViewHolder) {
        if (mIsNetworkError) {
            viewHolder.loading.visibility = View.GONE
            viewHolder.hint.setText(R.string.loading_failed_retry)
            viewHolder.hint.setTextColor(R.color.text_B3B3B3.toColor(mContext))
            viewHolder.hint.textSize = 12F
            viewHolder.hint.removeDrawable()
            viewHolder.itemView.isClickable = true
            viewHolder.itemView.setPadding(0, 0, 0, 0)
            viewHolder.itemView.layoutParams = viewHolder.itemView.layoutParams.apply { height = 48F.dip2px() }
        } else if (mIsOver) {
            viewHolder.loading.visibility = View.GONE
            viewHolder.hint.run {
                text = "添加选项"
                setTextColor(R.color.theme_font.toColor(mContext))
                textSize = 14F
                setDrawableStart(R.drawable.ic_add_vote)
                compoundDrawablePadding = 4F.dip2px()
            }
            viewHolder.itemView.isClickable = false
            viewHolder.itemView.setOnClickListener { addVoteCallback.invoke() }
            viewHolder.itemView.setPadding(0, 0, 0, 16F.dip2px())
            viewHolder.itemView.layoutParams = viewHolder.itemView.layoutParams.apply { height = 64F.dip2px() }
        } else {
            viewHolder.loading.visibility = View.VISIBLE
            viewHolder.hint.setText(R.string.loading)
            viewHolder.hint.setTextColor(R.color.text_B3B3B3.toColor(mContext))
            viewHolder.hint.textSize = 12F
            viewHolder.hint.removeDrawable()
            viewHolder.itemView.isClickable = false
            viewHolder.itemView.setPadding(0, 0, 0, 0)
            viewHolder.itemView.layoutParams = viewHolder.itemView.layoutParams.apply { height = 48F.dip2px() }
        }
    }

    override fun getItemCount() = if (mEntityList.isNullOrEmpty()) 0 else mEntityList.size + FOOTER_ITEM_COUNT

    fun getDataList(): List<VersionVoteEntity?>? {
        return mEntityList
    }

    fun updateDataWhenUploadSuccess() {
        if (mUploadPosition != -1) {
            if (mEntityList[mUploadPosition].me == null) {
                mEntityList[mUploadPosition].me = MeEntity(requestsVersionApkUploaded = true)
            } else {
                mEntityList[mUploadPosition].me?.requestsVersionApkUploaded = true
            }
        }
    }

    fun updateHighLightView(versionVoteEntity: VersionVoteEntity, position: Int) {
        mEntityList.forEachIndexed { index, entity ->
            if (entity.isHighLight) {
                entity.isHighLight = false
                notifyItemChanged(index)
            }
        }
        versionVoteEntity.isHighLight = true
        notifyItemChanged(position)
    }

    fun updateVote(isNewVote: Boolean, id: String, name: String?) {
        val userDataEntity = MeEntity()
        userDataEntity.isVersionRequested = true
        if (isNewVote) {
            var isExists = false
            for (versionVoteEntity in mEntityList) {
                versionVoteEntity.isHighLight = false
                if (id == versionVoteEntity.id) {
                    versionVoteEntity.num = versionVoteEntity.num + 1
                    isExists = true
                    versionVoteEntity.me = userDataEntity
                    break
                }
            }
            if (!isExists) {
                val voteEntity = VersionVoteEntity()
                voteEntity.me = userDataEntity
                voteEntity.id = id
                voteEntity.name = name
                voteEntity.num = 1
                mEntityList.add(voteEntity)
                loadChange(LoadStatus.INIT_OVER)
            }
        } else {
            for (versionVoteEntity in mEntityList) {
                versionVoteEntity.isHighLight = false
                if (id == versionVoteEntity.id) {
                    versionVoteEntity.num = versionVoteEntity.num + 1
                    versionVoteEntity.me = userDataEntity
                    break
                }
            }
        }
        notifyDataSetChanged()
    }

    private fun showSelectDialog(id: String) {
        val view = View.inflate(mContext, R.layout.dialog_suggest_game, null)
        val recyclerView = view.findViewById<RecyclerView>(R.id.dialog_suggest_game_rv)
        val back = view.findViewById<View>(R.id.dialog_suggest_game_back)
        val pb = view.findViewById<ProgressBar>(R.id.dialog_suggest_game_load)
        val manualBtn = view.findViewById<TextView>(R.id.dialog_suggest_manual)
        val titleTv = view.findViewById<TextView>(R.id.titleTv)
        recyclerView.layoutManager = GridLayoutManager(mContext, 4)
        recyclerView.adapter = SelectGameAdapter(fragment, pb, id)
        titleTv.text = "请选择你要上传的游戏"
        manualBtn.text = "从设备上选择"

        mSelectGameDialog = Dialog(mContext)
        mSelectGameDialog?.apply {
            requestWindowFeature(Window.FEATURE_NO_TITLE)
            setCanceledOnTouchOutside(false)
            setContentView(view)
            show()
        }

        back.setOnClickListener {
            MtaHelper.onEvent("游戏上传", "安装包", "关闭")
            mSelectGameDialog?.cancel()
        }
        manualBtn.setOnClickListener {
            MtaHelper.onEvent("游戏上传", "安装包", "从设备上选择")
            val intent = CleanApkActivity.getIntent(mContext, true, id)
            fragment.startActivityForResult(intent, GameUploadFragment.CHOOSE_LOCAL_APK)
        }
    }

    override fun getEventByPosition(pos: Int): ExposureEvent? {
        return mExposureEventSparseArray.get(pos)
    }

    override fun getEventListByPosition(pos: Int): List<ExposureEvent>? {
        return null
    }
}