package com.cheng.BoLe.wxapi

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.cheng.blzb.common.Constants
import com.cheng.blzb.event.PayStatusEnum
import com.cheng.blzb.event.PayStatusEvent
import com.example.base.common.RxBus
import com.example.base.extensions.toast
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory

class WXPayEntryActivity : AppCompatActivity(), IWXAPIEventHandler {

    private var api: IWXAPI? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        api = WXAPIFactory.createWXAPI(this, Constants.WechatAppId)
        api?.handleIntent(intent, this)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
        api?.handleIntent(intent, this)
    }

    override fun onReq(p0: BaseReq?) {

    }

    override fun onResp(resp: BaseResp) {
        if (resp.type == ConstantsAPI.COMMAND_LAUNCH_WX_MINIPROGRAM) {
            val launchMiniProgramResp = resp as WXLaunchMiniProgram.Resp
            val text = String.format(
                "openid=%s\nextMsg=%s\nerrStr=%s",
                launchMiniProgramResp.openId, launchMiniProgramResp.extMsg, launchMiniProgramResp.errStr
            )
            toast(text)
        }
        if (resp.type == ConstantsAPI.COMMAND_PAY_BY_WX) {
            when (resp.errCode) {
                0 -> {
                    RxBus.defaultInstance.post(PayStatusEvent(PayStatusEnum.PAY_SUCCESS))
                    finish()
                }

                -2 -> {
                    RxBus.defaultInstance.post(PayStatusEvent(PayStatusEnum.PAY_CANCEL))
                    finish()
                }

                else -> {
                    RxBus.defaultInstance.post(PayStatusEvent(PayStatusEnum.PAY_ERROR, resp.errStr ?: ""))
                    finish()
                }
            }
        } else {
            finish()
        }
    }

}