package com.gh.gamecenter.energy.view

import android.content.Context
import android.graphics.Paint
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.gamecenter.common.baselist.ListAdapter
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.provider.IDirectProvider
import com.gh.gamecenter.core.provider.ITimeUtilProvider
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.energy.R
import com.gh.gamecenter.energy.databinding.CommodityItemBinding
import com.gh.gamecenter.energy.entity.CommodityCategoryEntity
import com.gh.gamecenter.energy.entity.CommodityEntity
import com.gh.gamecenter.energy.utils.IntegralLogHelper
import io.reactivex.disposables.Disposable

class CommodityAdapter(
    context: Context,
    val entrance: String,
    val category: CommodityCategoryEntity
) : ListAdapter<CommodityEntity>(context) {

    private val mTimers = ArrayList<Disposable?>()

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

    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 {
        return when (viewType) {
            ItemViewType.ITEM_BODY -> {
                CommodityItemViewHolder(parent.toBinding())
            }
            else -> {
                FooterViewHolder(mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false))
            }
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is CommodityItemViewHolder -> {
                holder.binding.run {
                    if (entrance == "光能中心") {
                        container.layoutParams = (container.layoutParams as ViewGroup.MarginLayoutParams).apply {
                            val top = if (position == 0 || position == 1) 4F.dip2px() else 8F.dip2px()
                            topMargin = top
                        }
                    }

                    if (entrance == "光能屋") {
                        root.layoutParams = (root.layoutParams as ViewGroup.MarginLayoutParams).apply {
                            val top = if (position == 0 || position == 1) 8F.dip2px() else 0
                            topMargin = top
                        }
                    }

                    val commodity = mEntityList[position]
                    ImageUtils.display(coverImageView, commodity.coverImage)
                    name.text = commodity.name
                    energy.text = commodity.energy.toString()
                    originEnergy.goneIf(!commodity.showOriginEnergy)
                    originEnergy.text = "${commodity.originEnergy}光能"
                    exchangeCountTv.text = "已兑${commodity.totalExchangeNum}件"

                    if (commodity.tag != null && commodity.tag.id.isNotBlank()) {
                        tagTv.visibility = View.VISIBLE
                        tagTv.text = commodity.tag.name
                    } else {
                        tagTv.visibility = View.GONE
                    }

                    originEnergy.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
                    originEnergy.paint.isAntiAlias = true

                    root.setOnClickListener {
                        IntegralLogHelper.run {
                            logCommodity(
                                "click_goods",
                                entrance,
                                commodity?.id ?: "",
                                category.id,
                                category.name
                            )

                            log("view_goods_detail", "商品详情页")
                        }

                        val directUtils = ARouter.getInstance().build(RouteConsts.provider.directUtils)
                            .navigation() as? IDirectProvider
                        directUtils?.directToCommodityDetail(mContext, commodity.id)
                    }

                    val timeUtil =
                        ARouter.getInstance().build(RouteConsts.provider.timeUtil).navigation() as? ITimeUtilProvider

                    // 判断是否显示倒计时
                    when {
                        // 显示上架时间
                        commodity.showShelveTimer
                                && commodity.shelveTimestamp > (timeUtil?.currentTime()
                            ?: (System.currentTimeMillis() / 1000).toInt())
                                && commodity.shelveTimestamp - (commodity.shelveTimerBeforeDays * 86400) < (timeUtil?.currentTime()
                            ?: (System.currentTimeMillis() / 1000).toInt()) -> {
                            exchangeCountTv.visibility = View.GONE
                            timerContainer.visibility = View.VISIBLE
                            timerContainer.setBackgroundResource(R.drawable.bg_shelve_timer)
                            timerIv.setImageResource(R.drawable.ic_shelve)
                            timerTv.setTextColor(R.color.theme_yellow.toColor())
                            val duration = commodity.shelveTimestamp - (timeUtil?.currentTime()
                                ?: (System.currentTimeMillis() / 1000).toInt())
                            if (duration > 86400) {
                                val durationDay = duration / 86400
                                timerTv.text = "${durationDay}天 后开抢"
                            } else {
                                val timer = countDownTimer(duration) { finish, time ->
                                    if (finish) {
                                        exchangeCountTv.visibility = View.VISIBLE
                                        timerContainer.visibility = View.GONE
                                    } else {
                                        var formatTime = TimeUtils.formatDuration(time)
                                        timerTv.text = "$formatTime 后开抢"
                                    }
                                }
                                mTimers.add(timer)
                            }
                        }

                        // 显示下架时间
                        commodity.showOffShelveTimer
                                && commodity.offShelveTimestamp > (timeUtil?.currentTime()
                            ?: (System.currentTimeMillis() / 1000).toInt())
                                && commodity.offShelveTimestamp - (commodity.offShelveTimerBeforeDays * 86400) < (timeUtil?.currentTime()
                            ?: (System.currentTimeMillis() / 1000).toInt()) -> {
                            exchangeCountTv.visibility = View.GONE
                            timerContainer.visibility = View.VISIBLE
                            timerContainer.setBackgroundResource(R.drawable.bg_off_shelve_timer)
                            timerIv.setImageResource(R.drawable.ic_off_shelve)
                            timerTv.setTextColor(R.color.theme_red.toColor())
                            val duration = commodity.offShelveTimestamp - (timeUtil?.currentTime()
                                ?: (System.currentTimeMillis() / 1000).toInt())
                            if (duration > 86400) {
                                val durationDay = duration / 86400
                                timerTv.text = "${durationDay}天 后结束"
                            } else {
                                val timer = countDownTimer(duration) { finish, time ->
                                    if (finish) {
                                        exchangeCountTv.visibility = View.VISIBLE
                                        timerContainer.visibility = View.GONE
                                    } else {
                                        val formatTime = TimeUtils.formatDuration(time)
                                        timerTv.text = "$formatTime 后结束"
                                    }
                                }
                                mTimers.add(timer)
                            }
                        }

                        else -> {
                            exchangeCountTv.visibility = View.VISIBLE
                            timerContainer.visibility = View.GONE
                        }
                    }
                }
            }

            is FooterViewHolder -> {
                holder.itemView.layoutParams = (holder.itemView.layoutParams as StaggeredGridLayoutManager.LayoutParams)
                    .apply {
                        isFullSpan = true
                    }
                if (entrance == "光能中心") {
                    holder.itemView.setPadding(0, 0, 0, 40F.dip2px())
                    holder.itemView.layoutParams = holder.itemView.layoutParams.apply {
                        height = 88F.dip2px()
                    }
                }
                holder.initFooterViewHolder(mIsLoading, mIsNetworkError, mIsOver)
            }
        }
    }

    fun disposeAllTimer() {
        for (i in 0 until mTimers.size) {
            if (mTimers[i] != null && !mTimers[i]!!.isDisposed) {
                mTimers[i]!!.dispose()
                mTimers[i] = null
            }
        }
    }

    inner class CommodityItemViewHolder(val binding: CommodityItemBinding) : BaseRecyclerViewHolder<Any>(binding.root)
}