package com.gh.gamecenter.libao

import android.content.Context
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import com.gh.gamecenter.common.callback.OnListClickListener
import com.gh.gamecenter.common.callback.OnRequestCallBackListener
import com.gh.gamecenter.common.constant.ItemViewType
import com.gh.common.util.LibaoUtils
import com.gh.common.util.PlatformUtils
import com.gh.gamecenter.core.utils.StringUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.viewholder.FooterViewHolder
import com.gh.gamecenter.adapter.viewholder.LibaoNormalViewHolder
import com.gh.gamecenter.common.utils.setRootBackgroundColor
import com.gh.gamecenter.databinding.LibaoItemBinding
import com.gh.gamecenter.entity.LibaoEntity
import com.gh.gamecenter.entity.LibaoStatusEntity
import com.gh.gamecenter.common.retrofit.Response
import com.gh.gamecenter.game.GameItemViewHolder
import com.gh.gamecenter.retrofit.RetrofitManager
import com.lightgame.adapter.BaseRecyclerAdapter
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import retrofit2.HttpException
import java.util.*

/**
 * Created by khy on 5/09/17.
 */
class LibaoNewAdapter(
    context: Context, callBackListener: OnRequestCallBackListener<Any>,
    listListener: OnListClickListener,
    entrance: String?
) : BaseRecyclerAdapter<androidx.recyclerview.widget.RecyclerView.ViewHolder>(context) {

    private val mCallBackListener: OnRequestCallBackListener<Any> = callBackListener
    private val mListListener: OnListClickListener = listListener
    private val mLibaoList: MutableList<LibaoEntity> = ArrayList()

    private val mEntrance: String? = entrance

    private var skipPosition: Int = -1

    private var isLoading: Boolean = false
    private var isOver: Boolean = false
    private var isNetworkError: Boolean = false
    private var mPage: Int = 1

    init {
        mPage = 1
        addLibaoList()
    }

    fun addLibaoList() {
        if (isLoading) return
        isLoading = true
        notifyItemChanged(itemCount - 1)
        RetrofitManager.getInstance().getApi().getLibao(mPage).map { list ->
            // 去掉重复数据
            LibaoUtils.removeDuplicateData(mLibaoList, list)
        }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Response<List<LibaoEntity>>() {
                override fun onResponse(response: List<LibaoEntity>?) {
                    mLibaoList.addAll(response!!)
//                        notifyDataSetChanged()

                    if (response.size < 10) {
                        isOver = true
                        mCallBackListener.loadDone("TAG")
                    }

                    if (mLibaoList.size == 0) {
                        mCallBackListener.loadEmpty()
                    } else {
                        mCallBackListener.loadDone()
                    }

                    if (response.isNotEmpty()) {
                        getLibaoStatus(response)
                    }

                    mPage++
                    isLoading = false
                    isNetworkError = false
                }

                override fun onFailure(e: HttpException?) {
                    mCallBackListener.loadError()
                    isNetworkError = true
                    isLoading = false
                }
            })
    }

    /**
     * 重复领取实现 在可重复领取的情况下
     * 1.判断当前礼包是否可以领取或淘号，否，有领取记录以淘号优先，没领取记录则按照原来的规则显示
     * 2.记录最后一个领取时间，没有领取过则按照原来的规则显示
     * 3.判断最后领取时间是不是当天，不是则按照原来的规则显示
     * 4.定时刷新-游戏详情
     * 4-1：每次进来都要获取服务器时间
     * 4-2：获取当前时间到凌晨12点的差值 定时刷新
     */

    //获取礼包状态
    private fun getLibaoStatus(response: List<LibaoEntity>) {
        val builder = StringBuilder()
        var i = 0
        val size = response.size
        while (i < size) {
            builder.append(response[i].id)
            builder.append("-")
            i++
        }
        if (builder.isEmpty()) return
        builder.deleteCharAt(builder.length - 1)
        val ids = builder.toString()

        LibaoUtils.getLibaoStatus(ids, object : LibaoUtils.PostLibaoListener {
            override fun postSucceed(response: Any?) {
                val statusList = response as List<LibaoStatusEntity>

                LibaoUtils.initLiBaoEntity(statusList, mLibaoList)

                notifyDataSetChanged()
            }

            override fun postFailed(error: Throwable?) {

            }
        })
    }

    override fun getItemViewType(position: Int): Int {
        if (position == itemCount - 1) {
            return ItemViewType.LOADING
        } else {
            return ItemViewType.LIBAO_NORMAL
        }
    }


    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): androidx.recyclerview.widget.RecyclerView.ViewHolder {
        val view: View
        when (viewType) {
            ItemViewType.LOADING -> {
                view = mLayoutInflater.inflate(R.layout.refresh_footerview, parent, false)
                return FooterViewHolder(view)
            }
            else -> {
                view = mLayoutInflater.inflate(R.layout.libao_item, parent, false)
                return LibaoNormalViewHolder(LibaoItemBinding.bind(view), mListListener)
            }
        }
    }

    override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) {
        if (holder is LibaoNormalViewHolder) {
            initLibaoViewHolder(holder, position)
        } else if (holder is FooterViewHolder) {
            initFooterViewHolder(holder)
        }
    }

    override fun getItemCount(): Int {
        if (mLibaoList.size == 0) {
            return 0
        }
        return mLibaoList.size + 1 // + 搜索框和角布局
    }

    private fun initFooterViewHolder(holder: FooterViewHolder) {
        holder.initItemPadding()
        holder.initFooterViewHolder(isLoading, isNetworkError, isOver, R.string.load_history_libao_hint)
        holder.itemView.setOnClickListener(View.OnClickListener {
            if (isNetworkError) {
                isNetworkError = false
                notifyItemChanged(itemCount - 1)
                addLibaoList()
            }
        })
    }

    private fun initLibaoViewHolder(holder: LibaoNormalViewHolder, position: Int) {
        val libaoEntity = mLibaoList[position]
        holder.setClickData(libaoEntity)
        holder.binding.libaoName.text = libaoEntity.name
        holder.binding.root.setRootBackgroundColor(R.color.background_white)
        if (TextUtils.isEmpty(libaoEntity.platform)) {
            holder.binding.libaoGameName.text = libaoEntity.game?.name
        } else {
            holder.binding.libaoGameName.text = StringUtils.buildString(
                libaoEntity.game?.name, " - ", PlatformUtils.getInstance(mContext)
                    .getPlatformName(libaoEntity.platform)
            )
        }
        holder.binding.libaoGameIcon.displayGameIcon(libaoEntity.getIcon(), libaoEntity.getIconSubscript())

        val content: String
        if (libaoEntity.content!!.contains("<br/>")) {
            content = libaoEntity.content!!.replace("<br/>".toRegex(), " ")
        } else {
            content = libaoEntity.content!!
        }
        holder.binding.libaoDes.text = content

        if (libaoEntity.status != null) {
            LibaoUtils.initLibaoBtn(
                mContext, holder.binding.libaoBtnStatus, libaoEntity, false, null, true,
                mEntrance + "+(礼包中心:最新)"
            ) {
                notifyItemChanged(position)
            }
//            LibaoUtils.setLiBaoBtnStatusRound(holder.libaoBtnStatus, libaoEntity, true, mContext)
            if (!libaoEntity.packageName.isNullOrEmpty()) {
                holder.binding.libaoBtnStatus.setOnClickListener {
                    mListListener.onListClick(holder.binding.libaoBtnStatus, position, libaoEntity)
                }
            }
        }

        libaoEntity.game?.toGameEntity()?.let {
            GameItemViewHolder.initGameSubtitle(it, holder.binding.gameSubtitleTv)
        }
    }

    fun getLibaoListSize(): Int {
        return mLibaoList.size
    }

    fun getSkipPosition(): Int {
        return skipPosition
    }

    fun setSkipPosition(position: Int) {
        skipPosition = position
    }

    fun isOver(): Boolean {
        return isOver
    }

    fun isLoading(): Boolean {
        return isLoading
    }

    fun isNetworkError(): Boolean {
        return isNetworkError
    }
}