package com.game.gamecenter.alipay

import android.app.Activity
import com.alipay.sdk.app.PayTask
import com.gh.gamecenter.core.provider.IAliPayProvider
import com.gh.gamecenter.feature.eventbus.EBPayState
import io.reactivex.Single

@com.therouter.inject.ServiceProvider
class AliPayProviderImpl : IAliPayProvider {
    override fun sendRequest(activity: Activity, orderNo: String): Single<Int> {
        return Single.create {
            val pay = PayTask(activity)
            val result = pay.payV2(orderNo, true)
            val statusCode = result[KEY_RESULT_STATUS]
            val resultCode = when (statusCode) {
                PAY_RESULT_CODE_SUCCESS, PAY_RESULT_CODE_HANDLING, PAY_RESULT_CODE_UNKNOWN -> 0

                PAY_RESULT_CODE_CANCEL -> 1

                else -> 2

            }
            it.onSuccess(resultCode)
        }
    }

    companion object {
        // 订单支付成功。
        private const val PAY_RESULT_CODE_SUCCESS = "9000"

        // 正在处理中，支付结果未知（有可能已经支付成功），请查询商家订单列表中订单的支付状态
        private const val PAY_RESULT_CODE_HANDLING = "8000"

        // 支付结果未知（有可能已经支付成功），请查询商家订单列表中订单的支付状态
        private const val PAY_RESULT_CODE_UNKNOWN = "6004"

        private const val PAY_RESULT_CODE_CANCEL = "6001"

        private const val KEY_RESULT_STATUS = "resultStatus"

        private const val DELAY_DURATION = 1000L
    }
}
