package com.halo.assistant.accelerator.repository

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Looper
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.Constants.SP_ACCELERATOR_MEMBERSHIP_EXPIRED
import com.gh.gamecenter.common.constant.Constants.SP_ACCELERATOR_RECHARGE_TIMESTAMP
import com.gh.gamecenter.common.retrofit.BiResponse
import com.gh.gamecenter.common.utils.singleToMain
import com.gh.gamecenter.core.provider.IAcceleratorProvider
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.feature.entity.AcctRecord
import com.gh.gamecenter.feature.entity.OrderEntity
import com.gh.gamecenter.feature.entity.VipEntity
import com.gh.gamecenter.gamedetail.accelerator.AccelerationDataBase
import com.therouter.TheRouter

/**
 * 单利：保存加速相关的一些全局信息
 * 如：vip状态，加速状态
 */
class AcceleratorDataHolder {

    private val iAcceleratorProvider = TheRouter.get(IAcceleratorProvider::class.java)

    private val listeners = mutableSetOf<OnDataHolderListener>()

    private var _hasAcctGameInfoInLocal = false
    val hasAcctGameInfoInLocal: Boolean
        get() = _hasAcctGameInfoInLocal

    private val handler = Handler(Looper.getMainLooper())

    var enableRefresh = true
        private set

    @SuppressLint("CheckResult")
    fun init() {
        AccelerationDataBase.instance.accelerationDao()
            .loadLatestRecord()
            .compose(singleToMain())
            .subscribe(object : BiResponse<AcctRecord>() {
                override fun onSuccess(data: AcctRecord) {
                    acctGameRecord = data
                }
            })
        AccelerationDataBase.instance.accelerationDao()
            .hasAnyAcctGameInfo()
            .compose(singleToMain())
            .subscribe(object : BiResponse<Boolean>() {
                override fun onSuccess(data: Boolean) {
                    _hasAcctGameInfoInLocal = data
                }
            })

        val lastRechargeTimeMillis = SPUtils.getLong(Constants.SP_ACCELERATOR_RECHARGE_TIMESTAMP)
        if (lastRechargeTimeMillis == 0L) {
            enableRefresh = true
        } else {
            val currentTimeMillis = System.currentTimeMillis()
            val difMinute = (currentTimeMillis - lastRechargeTimeMillis) / (1000 * 60)
            enableRefresh = difMinute >= 2
        }

        if (!enableRefresh) {
            startCountDown()
        }
    }

    // 最后一次加速的游戏id（失败或者成功都会记录）
    var acctGameRecord: AcctRecord? = null
        set(value) {
            _hasAcctGameInfoInLocal = true
            field = value
        }

    fun isCurrentGameAccelerating(gameId: String) =
        iAcceleratorProvider?.isCurAccSuccess() ?: false &&
                acctGameRecord?.gameId == gameId

    fun getAcceleratingGameId() = if (iAcceleratorProvider?.isCurAccSuccess() == true) {
        acctGameRecord?.gameId ?: ""
    } else {
        ""
    }

    var vipEntity: VipEntity? = null
        private set

    val isVip: Boolean
        get() = vipEntity?.vipStatus == true

    val isNewUser: Boolean
        get() = vipEntity?.isNewUser == true

    val isPaidVip: Boolean
        get() = vipEntity?.vipStatus == true && vipEntity?.isTryVip == false

    val memberType: String
        get() {
            val vip = vipEntity
            return when {
                vip == null -> MEMBER_TYPE_NOT_LOGIN
                vip.isMonthVip && vip.isDurationVip -> MEMBER_TYPE_BOTH
                vip.isMonthVip -> MEMBER_TYPE_MONTH
                vip.isDurationVip -> MEMBER_TYPE_DURATION
                vip.isTryVip -> MEMBER_TYPE_FREE
                else -> MEMBER_TYPE_NONE_MEMBER
            }
        }

    fun setVipEntity(newVip: VipEntity) {
        if (newVip.vipStatus != vipEntity?.vipStatus) {
            listeners.forEach {
                it.onVipStateChanged()
            }
        }
        vipEntity = newVip
    }

    fun addListener(listener: OnDataHolderListener) {
        listeners.add(listener)
    }

    fun removeListener(listener: OnDataHolderListener) {
        listeners.remove(listener)
    }

    /**
     * 由于奇游方支付成功之后，订单状态有最多一分钟的延时,这里支付完立马刷新，可能刷新不到最新状态
     * 所以刷新之后，还需要给这给用户一个临时状态，让用户在订单状态刷新之前能够正常启动加速器
     * 为了避免接口刷新导致状态异常,这里启动一个倒计时，两分钟以内不刷新vip状态
     *
     * 既然刷新不到最新的状态，为什么还要刷新？
     * 因为还用户可能本来是包月会员或者时长会员，然后又多下了一单，这里需要获取用户在下单以前的vip状态
     */
    fun handleUserRechargeSuccess(order: OrderEntity?) {
        enableRefresh = false
        iAcceleratorProvider?.loadQyUserPermissionData {
            // 默认一个月有效期，两分钟后会刷新
            val vipExpiredTime = System.currentTimeMillis() / 1000 + 60 * 60 * 24 * 30
            val temporaryVip = if (order?.type == OrderEntity.TYPE_USER) {
                // 重置包月会约临期提醒标记
                SPUtils.setLong(Constants.SP_ACCELERATOR_USER_REMAINING_REMIND, 0)
                VipEntity(
                    _vipStatus = true,
                    _isNewUser = false,
                    _isTryVip = false,
                    _vipExpireTime = vipExpiredTime,
                    _durationVipExpiredTime = vipEntity?.durationVipExpiredTime,
                    _durationExpiredTime = vipEntity?.durationVipExpiredTime,
                    _timestamp = vipEntity?.timestamp
                )
            } else {
                // 重置时长会员临期标记
                SPUtils.setLong(Constants.SP_ACCELERATOR_DURATION_REMAINING_HOURS, 0)
                SPUtils.setLong(Constants.SP_ACCELERATOR_DURATION_REMAINING_DAYS, 0)
                // 如果充值的时长套餐，默认为30小时
                val durationExpiredTime = 60 * 60 * 30L
                VipEntity(
                    _vipStatus = true,
                    _isNewUser = false,
                    _isTryVip = vipEntity?.isTryVip,
                    _vipExpireTime = vipEntity?.vipExpireTime,
                    _durationVipExpiredTime = vipExpiredTime,
                    _durationExpiredTime = durationExpiredTime,
                    _timestamp = vipEntity?.timestamp
                )
            }
            setVipEntity(temporaryVip)
            // 重置耗尽弹窗标记
            SPUtils.setBoolean(SP_ACCELERATOR_MEMBERSHIP_EXPIRED, false)
            // 保存用户充值时间
            SPUtils.setLong(SP_ACCELERATOR_RECHARGE_TIMESTAMP, System.currentTimeMillis())

            startCountDown()
        }


    }

    private fun startCountDown() {
        handler.removeCallbacksAndMessages(null)
        handler.postDelayed({
            enableRefresh = true
            TheRouter.get(IAcceleratorProvider::class.java)?.loadQyUserPermissionData()
        }, DISABLE_REFRESH_DURATION)
    }

    fun clear() {
        vipEntity = null
        listeners.clear()
    }

    companion object {
        private const val MEMBER_TYPE_MONTH = "包月会员"
        private const val MEMBER_TYPE_DURATION = "时长会员"
        private const val MEMBER_TYPE_BOTH = "both会员"
        private const val MEMBER_TYPE_FREE = "免费会员"
        private const val MEMBER_TYPE_NONE_MEMBER = "非会员"
        const val MEMBER_TYPE_NOT_LOGIN = "未登录"

        private const val DISABLE_REFRESH_DURATION = 1000 * 60 * 2L

        val instance by lazy {
            AcceleratorDataHolder()
        }
    }

    interface OnDataHolderListener {

        fun onVipStateChanged()
    }
}