package com.yidian.shenghuoquan.bmanagercenter.wallet.ui

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.core.content.ContextCompat
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.bean.SHARE_MEDIA
import com.yidian.bcommon.constant.XRouterPathConstants
import com.yidian.bcommon.app.YdBaseApplication
import com.yidian.bcommon.base.BaseActivity
import com.yidian.bcommon.extensions.clickAntiShake
import com.yidian.bcommon.extensions.initTitleBar
import com.yidian.bcommon.utils.AuthUtils
import com.yidian.bcommon.utils.CheckApkExistUtil
import com.yidian.news.util.LogUtils
import com.yidian.shenghuoquan.bmanagercenter.R
import com.yidian.shenghuoquan.bmanagercenter.databinding.ActivityWechatAuthBinding
import com.yidian.utils.ToastUtil
import com.yidian.xpage.XPageManager

/**
 * 微信授权
 */
class WeChatAuthActivity : BaseActivity<ActivityWechatAuthBinding>() {

  override fun createViewBinding(): ActivityWechatAuthBinding {
    return ActivityWechatAuthBinding.inflate(layoutInflater)
  }

  override fun getXPageName(): String {
    return XRouterPathConstants.WECHAT_AUTH
  }

  override fun init(savedInstanceState: Bundle?) {
    super.init(savedInstanceState)
    initView()
    initClick()
  }

  private fun initView() {
    initTitleBar(viewBind.include.toolbar, viewBind.include.tvTitle, "")
    viewBind.include.toolbar.background = ContextCompat.getDrawable(this, R.color.white)
  }

  private fun initClick() {
    // 重新获取验证码
    viewBind.tvToAuth.clickAntiShake {
      requestWeChatAuth()
    }
  }

  private fun requestWeChatAuth() {
    if (!CheckApkExistUtil.checkApkExist(YdBaseApplication.context, CheckApkExistUtil.weChatPkgName)) {
      Toast.makeText(YdBaseApplication.context, "授权失败，未安装【微信】", Toast.LENGTH_SHORT).show()
      return
    }
    val authMap = AuthUtils.toAuthorize(this, SHARE_MEDIA.WEIXIN)
    val accessToken = authMap["accessToken"]
    LogUtils.e("auth", "微信授权结果$accessToken")
    ToastUtil.showToast(this, "微信授权结果$accessToken")
    if (accessToken.isNullOrBlank()) {
      ToastUtil.showToast(this, "微信授权失败")
    } else {
      toWithdraw(accessToken)
    }
  }

  private fun toWithdraw(accessToken: String) {
    val hashMap = HashMap<String, String?>()
    hashMap["accessToken"] = accessToken
    XPageManager.push(XRouterPathConstants.WITHDRAW, hashMap)
    // 关闭当前页
    XPageManager.pop(null)
  }

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
  }

}
