package com.zswc.creativity.wxapi

import android.app.Activity
import android.os.Bundle
import android.util.Log
import com.hwangjr.rxbus.RxBus
import com.zswc.creativity.config.ConfigRx
import com.zswc.creativity.utils.WeChatUtil
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.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.ysnows.base.utils.Toasts

/**
 *Created by shihuiyun
 *on 2020/9/10
 */
class WXEntryActivity : Activity(), IWXAPIEventHandler {

    override fun onResp(baseResp: BaseResp?) {
        //微信主动请求我们

        when (baseResp?.errCode) {
            BaseResp.ErrCode.ERR_OK -> {
                if (baseResp is SendAuth.Resp) {
                    //微信登录的回调
                    //获取微信传回的code
                    val code = baseResp.code
                    RxBus.get().post(ConfigRx.ADD_SEND_CODE, code)
                    finish()
                    return
                }
                if (baseResp?.getType() == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX) {
                    Toasts.toast(this@WXEntryActivity, "分享成功")
                }
            }
            BaseResp.ErrCode.ERR_USER_CANCEL -> {
            }
            BaseResp.ErrCode.ERR_AUTH_DENIED -> {
            }
            else -> {
            }
        }


        prompt()
    }

    override fun onReq(baseResp: BaseReq?) {

//    override fun onReq(baseResp: BaseReq) {

        Log.e("-shy-", "wxcode=: " + baseResp.hashCode())

        when (baseResp.hashCode()) {
            BaseResp.ErrCode.ERR_OK -> {
                if (baseResp is SendAuth.Resp) {
                    //微信登录的回调
                    val newResp = baseResp as SendAuth.Resp
                    //获取微信传回的code
                    val code = newResp.code

                    Log.e("-shy-", "wxcode1=: " + code)
                    RxBus.get().post(ConfigRx.ADD_SEND_CODE, code)

                    return
                }
                if (baseResp?.getType() == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX) {
                    Toasts.toast(this@WXEntryActivity, "分享成功")
                }
            }
            BaseResp.ErrCode.ERR_USER_CANCEL -> {
            }
            BaseResp.ErrCode.ERR_AUTH_DENIED -> {
            }
            else -> {
            }
        }

        prompt()
    }

    fun prompt() {
        finish()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        RxBus.get().register(this)
        val mWXApi = WXAPIFactory.createWXAPI(this, WeChatUtil.WECHAT_APP_ID, true)
        mWXApi.handleIntent(intent, this)

    }

    override fun onDestroy() {
        super.onDestroy()
        RxBus.get().unregister(this)
    }
}
