package com.gh.common.provider

import android.annotation.SuppressLint
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.common.utils.singleToMain
import com.gh.gamecenter.core.provider.IWechatPayResultProvider
import com.gh.gamecenter.feature.entity.OrderEntity
import com.gh.gamecenter.feature.eventbus.EBPayState
import com.halo.assistant.accelerator.repository.AccelerationRepository
import com.halo.assistant.accelerator.repository.AcceleratorDataHolder
import org.greenrobot.eventbus.EventBus

@com.therouter.inject.ServiceProvider
class WechatPayResultProviderImpl : IWechatPayResultProvider {

    private val repository = AccelerationRepository.newInstance()

    @SuppressLint("CheckResult")
    override fun onPayComplete(nonceStr: String, order: Any?) {
        val orderEntity = order as? OrderEntity
        repository.getWechatPayResult(nonceStr)
            .compose(singleToMain())
            .subscribe({
                // 支付成功
                EventBus.getDefault().post(EBPayState.PaySuccess)

                // 先刷新本地状态，支付成功
                AcceleratorDataHolder.instance.handleUserRechargeSuccess(orderEntity)

                SensorsBridge.trackMemberRechargeResult(
                    AccelerationRepository.PAYMENT_TYPE_WECHAT,
                    orderEntity?.setMenuName ?: "",
                    orderEntity?.paymentAmount ?: "",
                    AccelerationRepository.RECHARGE_RESULT_SUCCESS
                )
            }, {
                // 支付失败
                EventBus.getDefault().post(EBPayState.PayFail)
                SensorsBridge.trackMemberRechargeResult(
                    AccelerationRepository.PAYMENT_TYPE_WECHAT,
                    orderEntity?.setMenuName ?: "",
                    orderEntity?.paymentAmount ?: "",
                    AccelerationRepository.RECHARGE_RESULT_FAILURE
                )
            })
    }
}