package com.gh.gamecenter.gamedetail

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.gh.gamecenter.common.constant.Constants.SP_ACCELERATOR_MEMBERSHIP_EXPIRED
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.BaseEntity
import com.gh.gamecenter.feature.entity.TrialEntity
import com.gh.gamecenter.feature.entity.VipEntity
import com.gh.gamecenter.livedata.Event
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.login.user.UserRepository
import com.halo.assistant.accelerator.AccelerationUseCase
import com.halo.assistant.accelerator.repository.AcceleratorDataHolder
import com.therouter.TheRouter
import io.reactivex.disposables.CompositeDisposable

class StartingAcceleratorViewModel : ViewModel() {

    private val compositeDisposable = CompositeDisposable()

    val useCase = AccelerationUseCase()

    private val _restartingAcceleratorAction = MutableLiveData<Event<Unit>>()
    val restartingAcceleratorAction: LiveData<Event<Unit>> = _restartingAcceleratorAction
    fun loadAcceleratorToken() {
        val userId = UserManager.getInstance().userId
        if (userId.isNotBlank()) {
            UserRepository.getInstance().setAcceleratorToken(userId) {
                // 这里就算setToken失败，也要调用启动加速，失败会走正常的日志上报
                _restartingAcceleratorAction.value = Event(Unit)
            }
        }
    }

    private val _rechargeTrailResult = MutableLiveData<Event<Boolean>>()
    val rechargeTrailResult: LiveData<Event<Boolean>> = _rechargeTrailResult
    fun rechargeTrial() {
        val userId = UserManager.getInstance().userId
        useCase.rechargeTrial(userId)
            .compose(singleToMain())
            .subscribe(object : BiResponse<BaseEntity<TrialEntity>>() {
                override fun onSuccess(data: BaseEntity<TrialEntity>) {
                    if (data.data?.result == true) {
                        // 试用三小时下单成功
                        val permissionEntity = VipEntity(
                            _vipStatus = true,
                            _isNewUser = false,
                            _isTryVip = true,
                        )
                        AcceleratorDataHolder.instance.setVipEntity(permissionEntity)
                        TheRouter.get(IAcceleratorProvider::class.java)?.loadQyUserPermissionData()
                        SPUtils.setBoolean(SP_ACCELERATOR_MEMBERSHIP_EXPIRED, false)
                        _rechargeTrailResult.value = Event(true)
                    } else {
                        _rechargeTrailResult.value = Event(false)
                    }
                }

                override fun onFailure(exception: Exception) {
                    super.onFailure(exception)
                    _rechargeTrailResult.value = Event(false)
                }
            }).let(compositeDisposable::add)
    }

    private val _vipEntity = MutableLiveData<Event<VipEntity?>>()
    val vipEntity: LiveData<Event<VipEntity?>> = _vipEntity
    fun loadVipStatus() {
        val enableRefreshVipStatus = AcceleratorDataHolder.instance.enableRefresh
        if (enableRefreshVipStatus) {
            useCase.loadVipStatus()
                .compose(singleToMain())
                .subscribe(object : BiResponse<BaseEntity<VipEntity>>() {
                    override fun onSuccess(data: BaseEntity<VipEntity>) {
                        val vip = data.data
                        if (vip != null) {
                            AcceleratorDataHolder.instance.setVipEntity(vip)
                        }
                        _vipEntity.value = Event(vip)
                    }

                    override fun onFailure(exception: Exception) {
                        super.onFailure(exception)
                        _vipEntity.value = Event(null)
                    }
                }).let(compositeDisposable::add)
        } else {
            _vipEntity.value = Event(AcceleratorDataHolder.instance.vipEntity)
        }

    }

    override fun onCleared() {
        super.onCleared()
        compositeDisposable.clear()
    }
}