package com.gh.gamecenter

import com.gh.gamecenter.core.HaloApp
import com.gh.gamecenter.core.provider.IConfigProvider
import com.gh.gamecenter.core.provider.IWechatPayProvider
import com.gh.gamecenter.feature.entity.OrderEntity
import com.gh.gamecenter.feature.entity.WechatPayEntity
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.therouter.TheRouter

/**
 * 这里必须使用单例模式，需要保存 orderNo，以便后续查询订单使用
 */
@com.therouter.inject.ServiceProvider
class WechatPayProviderImpl : IWechatPayProvider {
    private var api: IWXAPI

    private var _orderNo: String = ""
    override val orderNo: String
        get() = _orderNo

    private var _order: OrderEntity? = null
    override val order: Any?
        get() = _order

    init {
        val config = TheRouter.get(IConfigProvider::class.java)
        api = WXAPIFactory.createWXAPI(HaloApp.getInstance().applicationContext, config?.getWechatAppId(), false)
    }

    override fun payRequest(order: Any, payRequest: Any) {
        if (order is OrderEntity) {
            _order = order
        }
        if (payRequest is WechatPayEntity) {
            _orderNo = payRequest.orderNo
            val request = PayReq().apply {
                appId = payRequest.appId
                partnerId = payRequest.partnerId
                prepayId = payRequest.prepayId
                packageValue = payRequest.packageValue
                nonceStr = payRequest.nonceStr
                timeStamp = payRequest.timestamp
                sign = payRequest.sign
            }
            api.sendReq(request)
        }
    }

    override fun clear() {
        _orderNo = ""
        _order = null
    }
}