package com.xty.base.h5

import android.Manifest
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.webkit.JavascriptInterface
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.GsonUtils
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.xty.base.act.BaseVmAct
import com.xty.network.model.ChooseAddressBean
import com.xty.base.model.ChooseCouponBean
import com.xty.base.model.CreateOrderBean
import com.xty.base.model.OpenWXBean
import com.xty.base.model.PsyTestSuccessBean
import com.xty.base.model.ScienceDetailBean
import com.xty.base.model.WatchReChangeBean
import com.xty.base.utils.PayUtils
import com.xty.common.Const
import com.xty.common.LogUtils
import com.xty.common.MMkvHelper
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import org.json.JSONObject
import pub.devrel.easypermissions.EasyPermissions

open class CloudJSBridge(val context: Context, val listener: IJsBridge) {
    private var baseActivity: BaseVmAct<*> = context as BaseVmAct<*>
    @JavascriptInterface
    fun getBaseInfoData(str: String?) {
      LogUtils.e("CloudJSBridge","getBaseInfoData str")
        str?.apply {
            val userId = if (MMkvHelper.getLong(Const.USER_ID).toString() == "0") {
                ""
            } else {
                MMkvHelper.getLong(Const.USER_ID).toString()
            }

            val jsonObject = JSONObject()
            jsonObject.put("statuHeight", WebUtils.getStatesBar())
            jsonObject.put("token", MMkvHelper.getString(Const.Auth_Id))
            jsonObject.put("dpi",WebUtils.getDensityDpi())

            jsonObject.put("userId", userId)
            jsonObject.put("isAPP", 1)
            LogUtils.e("CloudJSBridge",jsonObject.toString())
            listener.sendDataToJS("sendBaseInfo", jsonObject.toString())
        }
    }

    @JavascriptInterface
    fun getIsFromApp(str:String?){
        LogUtils.e("CloudJSBridge","getIsFromApp str")
        str?.let {
            val jsonObject = JSONObject()
            jsonObject.put("isAPP", 1)
            listener.sendDataToJS("sendIsFrom ", jsonObject.toString())
        }
    }

    @JavascriptInterface
    fun onBack(str: String?){
        LogUtils.e("CloudJSBridge","onBack str")
        baseActivity.finish()
    }
    @JavascriptInterface
    fun gotoElectronicFence(str: String?){
        LogUtils.e("CloudJSBridge","gotoElectronicFence str")
        //ToastUtils(context).showToast("敬请期待")
        RouteManager.goAct(ARouterUrl.ELECTRONIC_FENCE_SET_ACT)

    }

    @JavascriptInterface
    fun  gotoScienceDetail(str: String?){
        LogUtils.e("CloudJSBridge","gotoScienceDetail str")
        str?.let {
            var detailBean = GsonUtils.fromJson(it, ScienceDetailBean::class.java)
            var bundle = Bundle()
            bundle.putString("id",detailBean.id)
            RouteManager.goAct(ARouterUrl.SCIENCE_DETAIL, bundle)
        }
    }

    @JavascriptInterface
    fun watchRecharge(str: String?){
        str?.let {
            var watchBean = GsonUtils.fromJson(it,WatchReChangeBean::class.java)
            PayUtils(context).reChangeWatch(watchBean.pay_price,watchBean.orderId)
        }
    }

    @JavascriptInterface
    fun createOrder(str: String?){
        str?.let {
            if(MMkvHelper.getLong(Const.USER_ID).toString() == "0"){
            RouteManager.goAct(ARouterUrl.LOGIN_ACT)
            }else {
                var orderBean = GsonUtils.fromJson(it, CreateOrderBean::class.java)
                var bundle = Bundle()
                bundle.putParcelable("bean", orderBean)
                RouteManager.goAct(ARouterUrl.CREATE_SHOP_ORDER_ACT, bundle)
            }
        }
    }

    @JavascriptInterface
    fun selectAdd(str: String?){
        str?.let {
            var addressBean = GsonUtils.fromJson(it, ChooseAddressBean::class.java)
            baseActivity.bundle.clear()
            baseActivity.bundle.putParcelable("address", addressBean)
            baseActivity.intent.putExtras( baseActivity.bundle)
            baseActivity.setResult(AppCompatActivity.RESULT_OK, baseActivity.intent)
            baseActivity.finish()
        }
    }

    @JavascriptInterface
    fun selectCoupon(str: String?){
        str?.let {
            var couponBean = GsonUtils.fromJson(it, ChooseCouponBean::class.java)
            baseActivity.bundle.clear()
            baseActivity.bundle.putParcelable("coupon", couponBean)
            baseActivity.intent.putExtras( baseActivity.bundle)
            baseActivity.setResult(AppCompatActivity.RESULT_OK, baseActivity.intent)
            baseActivity.finish()
        }
    }

    @JavascriptInterface
    fun toHome(str: String?){
        baseActivity.finish()
    }

    @JavascriptInterface
    fun callTell(str: String?){
        if(EasyPermissions.hasPermissions(baseActivity,
                Manifest.permission.CALL_PHONE)){
            baseActivity.startActivity(Intent(Intent.ACTION_CALL, Uri.parse("tel:4000063365")))
        }else{
            EasyPermissions.requestPermissions(baseActivity,"",
                0x00011,
                Manifest.permission.CALL_PHONE)
        }
    }

    @JavascriptInterface
    fun jumpWallet(str: String?){
        str?.let {
            var wxBean = GsonUtils.fromJson(it, OpenWXBean::class.java)

            val appId = "wx032bacb749c0dcb0" // 填移动应用(App)的 AppId，非小程序的 AppID

            val api = WXAPIFactory.createWXAPI(baseActivity, appId)

            val req = WXLaunchMiniProgram.Req()
            req.userName = wxBean.id // 填小程序原始id

            req.path = wxBean.path ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。

            if(wxBean.type == 3){
                req.miniprogramType =
                    WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE // 可选打开 开发版，体验版和正式版
            }else{
                req.miniprogramType =
                    WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW // 可选打开 开发版，体验版和正式版
            }

            api.sendReq(req)
        }
    }

    @JavascriptInterface
    fun questionFunction(str: String?){
        LogUtils.e("CloudJSBridge","questionFunction:${str}")

        str?.let {
            var bean = GsonUtils.fromJson(it, PsyTestSuccessBean::class.java)
            baseActivity.bundle.clear()
            baseActivity.bundle.putLong("answerId", bean.data)
            RouteManager.goAct(ARouterUrl.PSYCHOLOGICAL_RESULT_ACT, baseActivity.bundle)
        }
    }

}