package com.yidianling.ydl_pay.pay

import android.app.Activity
import android.content.Context
import com.alipay.sdk.app.PayTask
import com.tencent.mm.opensdk.constants.Build
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.ydl.ydlcommon.data.http.CustomThrowable
import com.ydl.ydlcommon.utils.log.AliYunLogConfig
import com.ydl.ydlcommon.utils.log.AliYunRichLogsHelper
import com.yidianling.ydl_pay.common.bean.CommonWXPayBean
import com.yidianling.ydl_pay.common.bean.PayResult
import com.yidianling.ydl_pay.pay.bean.PayStatus
import com.yidianling.ydl_pay.pay.bean.WXPayEvent
import de.greenrobot.event.EventBus
import io.reactivex.Emitter
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers

/**
 * author : Zhangwenchao
 * e-mail : zhangwch@yidianling.com
 * time   : 2018/04/18
 */
object RxPay {

    init {
        EventBus.getDefault().register(this)
    }

    private var emitter: Emitter<PayStatus>? = null

    // 微信支付
    fun wxPay(context: Context, option: CommonWXPayBean.WXOption): Observable<PayStatus> {
        return Observable.create<PayStatus> { e ->
            val api = WXAPIFactory.createWXAPI(context, null)
            if (api.wxAppSupportAPI < Build.PAY_SUPPORTED_SDK_INT) {
                e.onError(CustomThrowable("目前您的微信版本过低或未安装微信，需要安装微信才能使用"))
                e.onComplete()
            }
            emitter = e

            api.registerApp(option.appid)
            val request = PayReq()
            request.appId = option.appid
            request.partnerId = option.partnerid
            request.prepayId = option.prepayid
            request.packageValue = "Sign=WXPay"
            request.nonceStr = option.noncestr
            request.timeStamp = option.timestamp
            request.sign = option.sign
            api.sendReq(request)
        }.subscribeOn(Schedulers.io())
    }

    // 支付宝支付
    fun aliPay(activity: Activity, aliSign: String): Observable<PayStatus> {
        return Observable.create<PayStatus> {
            val alipay = PayTask(activity)
            val result = alipay.payV2(aliSign, true)
            val payResult = PayResult(result)
            when {

                "9000" == payResult.resultStatus -> {
                    it.onNext(PayStatus(true))
                    AliYunRichLogsHelper.getInstance().sendRichLog(AliYunLogConfig.PAY, "支付宝支付成功")

                }
                else -> {
                    it.onError(CustomThrowable(payResult.memo))
                    AliYunRichLogsHelper.getInstance()
                        .sendRichLog(AliYunLogConfig.PAY, "支付宝支付失败  memo:${payResult.memo}")

                }
            }
            it.onComplete()
        }

    }

    fun onEvent(event: WXPayEvent) {
        if (event.status.success) {
            emitter?.onNext(event.status)
        } else {
            emitter?.onError(Throwable("支付失败", null))
        }
        emitter?.onComplete()
    }
}