package com.ym.library.activity

import android.app.Activity
import android.app.AlertDialog
import android.app.DownloadManager
import android.content.ComponentName
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.PowerManager
import android.provider.Settings
import android.util.Base64
import android.util.Log
import android.webkit.JavascriptInterface
import android.webkit.WebView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.FileProvider
import com.ym.library.Constant
import com.ym.library.module.NewsEntity
import com.ym.library.net.ApiClient
import com.ym.library.net.RxSchedulers
import com.ym.library.rxbus.RxBusConstant
import com.ym.library.rxbus.RxBusUtil
import com.ym.library.utils.*
import com.ym.modulecommon.AppliContext
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody
import org.jetbrains.anko.runOnUiThread
import org.json.JSONArray
import org.json.JSONObject
import retrofit2.Response
import java.io.File
import java.io.IOException

abstract class JavaInterface {
    var act: Activity?
    private val mWebView: WebView

    constructor(act: Activity, web: WebView) {
        this.act = act
        this.mWebView = web
    }

    @JavascriptInterface
    fun closeView() {
        act?.finish()
    }

    @JavascriptInterface
    fun getNovelUid(): String? {
        System.out.println("getNovelUid()")
        return com.ym.modulecommon.utils.SettingPreference.getUid()
    }

    @JavascriptInterface
    fun getUserInfo(): String? {
        var entity = SettingPreference.getUserInfoData()
        if (entity != null) {
            var data = Utils.obj2Str(entity)
            System.out.println("getUserInfoData():$data")
            return data
        }
        return ""
    }

    /**
     * 获取状态栏高度
     */
    @JavascriptInterface
    fun getStatusBarHeight(): Int {
        return Utils.px2dip(Utils.getStatusBarHeightFloat())
    }

    /**
     * 获取token
     */
    @JavascriptInterface
    fun getToken(): String {
        return com.ym.modulecommon.utils.SettingPreference.getToken()
    }

    /**
     * 获取金币总数
     */
    @JavascriptInterface
    fun availCoins(): Int {

        var user = SettingPreference.getUserInfoData()
        println("availCoins()-------------$user-----")

        return user?.availCoins ?: 0
    }

    /**
     * 获取版本号名称
     */
    @JavascriptInterface
    fun getVersionName(): String {
        return PhoneUtils.getAppVersionName(AppliContext.get())
    }

    /**
     * H5缓存数据
     */
    @JavascriptInterface
    fun saveVideoData(data: String) {
        println("saveVideoData()-------------$data-----")
        SettingPreference.saveVideoData(data)
    }

    /**
     * H5获取数据
     */
    @JavascriptInterface
    fun getVideoData(): String {
        println("getVideoData()----------------：" + SettingPreference.getVideoData())
        return SettingPreference.getVideoData()
    }

    /**
     * 下载 并安装 App
     * @param url 下载地址
     */
    @JavascriptInterface
    fun InstallAPP(url: String) {
        var last = url.lastIndexOf("/") + 1
        var apkName = url.substring(last)
        if (!apkName.contains(".apk")) {
            if (apkName?.length > 10) {
                apkName = apkName.substring(apkName.length - 10)
            }
            apkName += ".apk"
        }
        if (ActivityCompat.checkSelfPermission(
                AppliContext.get(),
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            checkDownloadStatus(url, apkName)
        } else {
            openAppDetails()
        }
    }

    /**
     * 检查下载状态
     *
     * @param url
     * @param apkName
     */
    private fun checkDownloadStatus(url: String, apkName: String) {
        var isLoading = false
        var query: DownloadManager.Query = DownloadManager.Query()
        var downloadManager: DownloadManager =
            AppliContext.get().getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        var c: Cursor = downloadManager.query(query)
        if (c.moveToFirst()) {
            var LoadingUrl = c.getString(c.getColumnIndex(DownloadManager.COLUMN_URI))
            if (url.equals(LoadingUrl)) {
                isLoading = true
                var status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS))
                when (status) {
                    DownloadManager.STATUS_PAUSED -> Toast.makeText(
                        AppliContext.get(),
                        "正在下载",
                        Toast.LENGTH_SHORT
                    ).show()
                    DownloadManager.STATUS_PENDING -> Toast.makeText(
                        AppliContext.get(),
                        "正在下载",
                        Toast.LENGTH_SHORT
                    ).show()
                    DownloadManager.STATUS_RUNNING -> Toast.makeText(
                        AppliContext.get(),
                        "正在下载",
                        Toast.LENGTH_SHORT
                    ).show()
                    DownloadManager.STATUS_SUCCESSFUL -> {
                        Log.i("DownLoadService", ">>>下载完成")
                        var str = c.getString(c.getColumnIndex(DownloadManager.COLUMN_URI))
                        Log.i("DownLoadService", str)
                        val file = File(
                            Environment.getExternalStorageDirectory()
                                .getAbsolutePath() + "/" + Environment.DIRECTORY_DOWNLOADS,
                            apkName
                        )
                        isLoading
                        if (!file.exists()) {
                            isLoading = false
                        } else {
                            installAPK(
                                file, apkName
                            )
                        }

                    }
                    DownloadManager.STATUS_FAILED -> {
                        Log.i("DownLoadService", ">>>下载失败")
                    }

                }
            }
        }

        if (!isLoading) {
            val data = NewsEntity()
            data.url = url
            ZxDownLoadServices.startActionFoo(AppliContext.get(), data)
        }
    }

    /**
     * 打开 APP 的详情设置
     */
    private fun openAppDetails() {
        var builder = AlertDialog.Builder(act)
        builder.setMessage("你还未获取存储权限哦，现在去获取？");   // 取消后可到 “应用信息 -> 权限” 中授予"
        builder.setPositiveButton("确定", object : DialogInterface.OnClickListener {
            override fun onClick(dialog: DialogInterface, which: Int) {
                var intent = Intent()
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                intent.setData(Uri.parse("package:" + AppliContext.get()?.getPackageName()))
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
                intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
                AppliContext.get().startActivity(intent)
            }
        })
        builder.setNegativeButton("取消", null)
        builder.show()
    }

    /**
     * 打开 App
     * @param packageName 包名
     */
    @JavascriptInterface
    fun OpenAPP(packageName: String) {
        doStartApplicationWithPackageName(packageName)
    }

    /**
     * 打开微信
     */
    @JavascriptInterface
    fun openWechat() {
        try {
            var intent = Intent()
            var cmp = ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI")
            intent.setAction(Intent.ACTION_MAIN)
            intent.addCategory(Intent.CATEGORY_LAUNCHER)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.setComponent(cmp)
            AppliContext.get().startActivity(intent)
        } catch (e: Exception) {

        }
    }

    /**
     * 打开app
     *
     * @param packagename
     */
    private fun doStartApplicationWithPackageName(packagename: String) {
        // 通过包名获取此APP详细信息，包括Activities、services、versioncode、name等等
        var packageinfo: PackageInfo? = null
        try {
            packageinfo = AppliContext.get().packageManager.getPackageInfo(packagename, 0);
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        if (packageinfo == null) {
            return
        }

        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        var resolveIntent = Intent(Intent.ACTION_MAIN, null)
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER)
        resolveIntent.setPackage(packageinfo.packageName)

        // 通过getPackageManager()的queryIntentActivities方法遍历
        var resolveinfoList: List<ResolveInfo> =
            AppliContext.get().packageManager.queryIntentActivities(resolveIntent, 0)
        var resolveinfo: ResolveInfo = resolveinfoList.iterator().next()
        if (resolveinfo != null) {
            // packagename = 参数packname
            val packageName = resolveinfo.activityInfo.packageName
            // 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式：packagename.mainActivityname]
            val className = resolveinfo.activityInfo.name
            // LAUNCHER Intent
            var intent = Intent(Intent.ACTION_MAIN)
            intent.addCategory(Intent.CATEGORY_LAUNCHER)

            // 设置ComponentName参数1:packagename参数2:MainActivity路径
            val cn = ComponentName(packageName, className)

            intent.component = cn
            act?.startActivity(intent)
        }
    }

    /**
     * 判断指定包名的app是否已经安装，并且把结果返回给H5
     *
     * @param packageName
     */
/*    @JavascriptInterface
    fun CheckInstall(packageName: String) {
        val isInstalled = SystemUtil.isInstalled(AppliContext.get(), packageName)
        if (isInstalled) {
            mWebView?.post(Runnable { mWebView?.loadUrl("javascript:CheckInstall_Return(1)") })
        } else {
            mWebView?.post(Runnable { mWebView?.loadUrl("javascript:CheckInstall_Return(0)") })
        }
    }*/

//    fun checkInstall(packageName: String): Boolean {
//        //判断app是否安装
//        if (TextUtils.isEmpty(packageName)) {
//            return false
//        }
//        try {
//            AppliContext.get().getPackageManager().getPackageInfo(packageName, 0)
//            return true
//        } catch (e: PackageManager.NameNotFoundException) {
//            return false
//        }
//
//    }
    /**
     * 打开浏览器试玩
     *
     * @param url
     */
    @JavascriptInterface
    fun openBrowser(url: String) {
        Log.i("open:", url + "...")
        //另一种下载方式
        var intent = Intent()
        intent.action = "android.intent.action.VIEW"
        var content_url = Uri.parse(url)
        intent.setData(content_url)
        act?.startActivity(intent)
    }

    /**
     * 网页游戏
     * @param url 网址
     */
    @JavascriptInterface
    fun Browser(url: String) {
        var intent = Intent()
        intent.setAction("android.intent.action.VIEW")
        var content_url = Uri.parse(url)
        intent.setData(content_url);
        if (intent.resolveActivity(AppliContext.get().getPackageManager()) != null) {
            var componentName = intent.resolveActivity(AppliContext.get().getPackageManager())
            AppliContext.get().startActivity(Intent.createChooser(intent, "请选择浏览器"))
        } else {
            Toast.makeText(AppliContext.get(), "没有匹配的程序", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 下载安装APP，有两种方法
     * 1.使用系统下载，贵公司需要集成到app中
     * 2.直接打开浏览器下载
     *
     * @param url
     */
    @JavascriptInterface
    fun AwallDownLoad(url: String) {
        Log.i("open:", url + "...");
        //另一种下载方式
        val intent = Intent()
        intent.setAction("android.intent.action.VIEW");
        var content_url = Uri.parse(url)
        intent.setData(content_url)
        act?.startActivity(intent)
    }

    /**
     * 打开指定包名App
     *
     * @param packageName
     */
    @JavascriptInterface
    fun AwallOpen(packageName: String) {
        Log.i("open:", "$packageName...")
        doStartApplicationWithPackageName(packageName)
    }

    private fun installAPK(context: Context, file: File?) {
        if (file == null || !file.exists()) return
        val intent = Intent(Intent.ACTION_VIEW)
        val uri: Uri
        // 判断版本大于等于7.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // 即是在清单文件中配置的authorities
            uri = FileProvider.getUriForFile(
                context,
                context.packageName + ".fileprovider",
                file
            )//newfile
            // 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK)

        } else {
            uri = Uri.parse("file://" + file.toString())
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        }
        intent.setDataAndType(uri, "application/vnd.android.package-archive")
        //在服务中开启activity必须设置flag,后面解释
        context.startActivity(intent)
    }

    /**
     * 下载到本地后执行安装
     */
    private fun installAPK(file: File, apkName: String) {
        if (!file.exists())
            return
        var intent = Intent(Intent.ACTION_VIEW)
        var uri: Uri
        // 判断版本大于等于7.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // 即是在清单文件中配置的authorities
            uri = FileProvider.getUriForFile(
                AppliContext.get(),
                Constant.Param.mPacketName + ".fileprovider",
                file
            )
            // 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

        } else {
            uri = Uri.parse("file://" + file.toString())
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        }
        intent.setDataAndType(uri, "application/vnd.android.package-archive")
        //在服务中开启activity必须设置flag,后面解释
        act?.startActivity(intent)
    }

    @JavascriptInterface
    fun getAnalysisParams(): String {

        val params = JSONObject()
        val ts = System.currentTimeMillis()
        params.put(Constant.Device.ts, ts)
        params.put(Constant.Device.uid, com.ym.modulecommon.utils.SettingPreference.getUid())
        params.put(Constant.Device.token,com.ym.modulecommon.utils.SettingPreference.getToken())

        params.put(Constant.Device.aid, com.ym.modulecommon.utils.SettingPreference.getAndroidId())
        params.put(Constant.Device.imei, com.ym.modulecommon.utils.SettingPreference.getImei())
        params.put(Constant.Device.device, com.ym.modulecommon.utils.SettingPreference.getDevice())
        params.put(Constant.Device.mac, com.ym.modulecommon.utils.SettingPreference.getMac())
        params.put(Constant.Device.platform, "android")
        params.put(Constant.Device.carrier, com.ym.modulecommon.utils.SettingPreference.getCarrier())
        params.put(Constant.Device.w, com.ym.modulecommon.utils.SettingPreference.getW())
        params.put(Constant.Device.vendor, Build.MANUFACTURER)
        params.put(Constant.Device.h, com.ym.modulecommon.utils.SettingPreference.getH())
        params.put(Constant.Device.ip, com.ym.modulecommon.utils.SettingPreference.getIp())
        params.put(Constant.Device.imsi, com.ym.modulecommon.utils.SettingPreference.getImsi())
        params.put(Constant.Device.model, com.ym.modulecommon.utils.SettingPreference.getModel())
        params.put(Constant.Device.vn, com.ym.modulecommon.utils.SettingPreference.getVN())
        params.put(Constant.Device.ntt, com.ym.modulecommon.utils.SettingPreference.getNTT())
        params.put(Constant.Device.vc, com.ym.modulecommon.utils.SettingPreference.getVC())
        params.put(Constant.Device.source, com.ym.modulecommon.utils.SettingPreference.getSource())
        params.put(Constant.Device.ua, com.ym.modulecommon.utils.SettingPreference.getUA())
        params.put(Constant.Device.svn, com.ym.modulecommon.utils.SettingPreference.getSVN())
        var param = obj2Array(params)
        System.out.println("-------------:$param")
        return params.toString()
    }

    fun obj2Array(obj: JSONObject): String {
        var array = JSONArray()
        obj.keys().forEach {
            val params = JSONObject()
            params.put(it, obj.get(it))
            array.put(params)
        }
        return array.toString()
    }

    @JavascriptInterface
    fun apiClientPost(url: String, tag: String) {
        Log.d("wxw", "url$url");
        ApiClient.userApi.webApiPost(url).compose(RxSchedulers.observableIO2Main())
            .subscribe(object :
                Observer<Response<ResponseBody>> {
                override fun onSubscribe(d: Disposable) {

                }

                override fun onNext(responseBodyResponse: Response<ResponseBody>) {
                    try {
                        if (responseBodyResponse.body() != null) {
                            val str = responseBodyResponse.body()!!.string()
                            println("onNext str :$str")
                            mWebView.loadUrl(
                                "javascript:onApiSuc('${
                                    Base64.encodeToString(
                                        str?.toByteArray(),
                                        Base64.URL_SAFE
                                    )
                                }','$tag')"
                            )
                        } else {
//                        mWebView.loadUrl("javascript:onApiFail($tag)")
                            mWebView.loadUrl("javascript:onApiFail('$tag')")
                        }
                    } catch (e: IOException) {
                        mWebView.loadUrl("javascript:onApiFail('$tag')")
                        e.printStackTrace()
                    }

                }

                override fun onError(e: Throwable) {
                    mWebView.loadUrl("javascript:onApiFail('$tag')")
                }

                override fun onComplete() {

                }
            })
    }

    @JavascriptInterface
    fun apiClientGet(url: String, tag: String) {
        println("url:$url-------------tag:$tag")
        ApiClient.userApi.webApiGet(url).compose(RxSchedulers.observableIO2Main())
            .subscribe(object :
                Observer<Response<ResponseBody>> {
                override fun onSubscribe(d: Disposable) {

                }

                override fun onNext(responseBodyResponse: Response<ResponseBody>) {
                    try {
                        mWebView?.post {
                            if (responseBodyResponse.body() != null) {
                                val str = responseBodyResponse.body()?.string()
                                mWebView.loadUrl(
                                    "javascript:onApiSuc('${
                                        Base64.encodeToString(
                                            str?.toByteArray(),
                                            Base64.URL_SAFE
                                        )
                                    }','$tag')"
                                )
                            } else {
                                mWebView.loadUrl("javascript:onApiFail('$tag')")
                            }
                        }
                    } catch (e: IOException) {
                        mWebView?.post {
                            mWebView?.loadUrl("javascript:onApiFail('$tag')")
                        }
                        e.printStackTrace()
                    }

                }

                override fun onError(e: Throwable) {
                    mWebView?.post {
                        mWebView?.loadUrl("javascript:onApiFail('$tag')")
                    }
                }

                override fun onComplete() {

                }
            })
    }

    @JavascriptInterface
    fun adJump(str: String) {
        Log.d("glc", "adJump:" + str)
        val data = Utils.str2Obj(str, NewsEntity::class.java) as NewsEntity?

        if (data != null) {
            JumpUtils.adJump(data, act)
        }
    }

    @JavascriptInterface
    fun videoPlay() {
        mWebView.post {
            mWebView.loadUrl("javascript:videoPlay()")
        }
    }

    @JavascriptInterface
    fun signIn() {
        Log.d("qbs", "signIn---------------------------------------------------------------")
        RxBus.get().post("sign", 0)
    }

    @JavascriptInterface
    fun getSignSessionId(): String {
        return SettingPreference.getSignSessionId()
    }

    @JavascriptInterface
    fun jumpSetting() {
        JumpUtils.jumpSettingActivity()
    }

    @JavascriptInterface
    fun withDraw() {
        val token =com.ym.modulecommon.utils.SettingPreference.getToken()
        if (token.isEmpty()) {
            WxImplUtils().onAuth(act, object : WxImplUtils.IWxLoginCallback {
                override fun onWxSuccess(token: String?, openid: String?) {
                    Utils.showToast(act, "登录成功")
                    EventUtils.onEvent("wx_h5_login_success", "h5吊起微信登录成功")
                }

                override fun onWxFail(mes: String?) {
                    EventUtils.onEvent("wx_h5_login_fail", "h5吊起微信登录失败$mes")
                }
            })
        } else {
            // 通过Handler发送消息
            mWebView.post { // 注意调用的JS方法名要对应上
                // 调用javascript的callJS()方法
                mWebView.loadUrl("javascript:wechat_login_cb()")
            }
        }
//        UserApiClient.userApi.getIsBindWithdrawWx(token)
//            .compose(RxSchedulers.observableIO2Main())
//            .subscribe(object : BaseObserver<UserInfoEntity>() {
//                override fun onSuccess(data: UserInfoEntity) {
//
//                    act?.runOnUiThread {
//                        if (data?.isBind == true) {
////                            val userInfoData = SettingPreference.getUserInfoData()
////                            userInfoData.isBind = true
////                            SettingPreference.saveUserInfo(userInfoData)
////                   userInfoData          var sessionId = ""
//                                if (mData?.ifUse == 1) {
//                                    showToast("已提现")
//                                } else {
//                                    if (mData?.id != null) {
//                                        mPresenter?.requestWxWithdraw(mData?.id!!)
//                                    }
//                                }
//                            mWebView?.loadUrl("javascript:wechat_login_cb()")

//                        } else {
//                            WxImplUtils().onAuth(
//                                act
//                            ) { token, openid ->
//                                Log.i("WxImplUtils", "onWxSuccess")
//                                Utils.showToast(act, "登录成功")
//                            }
//                            WxImplUtils().onAuth(act,null)

//                        }
//                    }
//                }
//
//                override fun onFailure(e: Throwable, code: String, errorMsg: String?) {
//                    if (null != errorMsg) {
//                        // mView.wxBindFailure(errorMsg?:"")
//                    }
//                }
//            })
    }

//    @JavascriptInterface
//    fun onRewardVideo(codeId: String, coins: String) {
//        mWebView?.post {
//            AdDataSupport.h5RewardVideo(codeId, coins.toInt(), object : TTAdNative.RewardVideoAdListener {
//                override fun onRewardVideoAdLoad(ad: TTRewardVideoAd?) {
//                    ad?.setRewardAdInteractionListener(object : TTRewardVideoAd.RewardAdInteractionListener {
//                        override fun onRewardVerify(p0: Boolean, p1: Int, p2: String?) {
//                        }
//
//                        override fun onSkippedVideo() {
//                        }
//                        override fun onAdShow() {
//                            Log.d("qbs","onAdShow")
//                            EventUtils.onEvent("exciting_video_play",codeId)
//                        }
//
//                        override fun onAdVideoBarClick() {
//                            Log.d("qbs","onAdVideoBarClick")
//                            EventUtils.onEvent("exciting_video_ad_click", codeId)
//
//                        }
//
//                        override fun onVideoComplete() {
//
//                        }
//                        override fun onAdClose() {
//                            mWebView.post {
//                                mWebView.loadUrl("javascript:onAdClose()")
//                            }
//                        }
//
//                        override fun onVideoError() {
//                        }
//                    })
//                    ad?.showRewardVideoAd(act)
//                }
//
//                override fun onRewardVideoCached() {
//                }
//
//                override fun onError(p0: Int, p1: String?) {
//                }
//            })
//        }
//    }

    /**
     * 是否填写身体数据
     */
    @JavascriptInterface
    fun getStepSettingType(): String {
        return SettingPreference.getStepSettingType()
    }

    @JavascriptInterface
    fun ignoreBatteryOptimization() {
        try {
            val powerManager =
                AppliContext.get().getSystemService(Context.POWER_SERVICE) as PowerManager
            val hasIgnored = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                powerManager?.isIgnoringBatteryOptimizations(AppliContext.get().getPackageName())
            } else {
                true
            }
            if (!hasIgnored) {
                val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setData(Uri.parse("package:" + AppliContext.get().getPackageName()));
                act?.startActivity(intent)
            }
        } catch (e: Exception) {

        }
    }

    @JavascriptInterface
    fun jumpStartInterface() {
        var intent: Intent
        try {
            intent = getAutostartSettingIntent(act as Context)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            act?.startActivity(intent)
        } catch (e: Exception) {//抛出异常就直接打开设置页面
            intent = Intent(Settings.ACTION_SETTINGS)
            act?.startActivity(intent)
        }
    }

    /**
     * 获取自启动管理页面的Intent
     * @param context context
     * @return 返回自启动管理页面的Intent
     */
    private fun getAutostartSettingIntent(context: Context): Intent {
        var componentName: ComponentName? = null
        val brand = Build.MANUFACTURER
        val intent = Intent()
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        when (brand.toLowerCase()) {
            "samsung"//三星
            -> componentName = ComponentName(
                "com.samsung.android.sm",
                "com.samsung.android.sm.app.dashboard.SmartManagerDashBoardActivity"
            )
            "huawei"//华为
            ->
                intent.setAction("huawei.intent.action.HSM_BOOTAPP_MANAGER")
            //荣耀V8，EMUI 8.0.0，Android 8.0上，以下两者效果一样
//            componentName=  ComponentName.unflattenFromString("com.huawei.systemmanager/.startupmgr.ui.StartupNormalAppListActivity")
            "xiaomi"//小米
            -> componentName =
                ComponentName(
                    "com.miui.securitycenter",
                    "com.huawei.systemmanager.optimize.process.ProtectActivity"
                )
            "vivo"//VIVO
            ->
                //            componentName = new ComponentName("com.iqoo.secure", "com.iqoo.secure.safaguard.PurviewTabActivity");
                componentName =
                    ComponentName(
                        "com.iqoo.secure",
                        "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity"
                    )
            "oppo"//OPPO
            ->
                //            componentName = new ComponentName("com.oppo.safe", "com.oppo.safe.permission.startup.StartupAppListActivity");
                componentName = ComponentName(
                    "com.coloros.oppoguardelf",
                    "com.coloros.powermanager.fuelgaue.PowerUsageModelActivity"
                )
            "yulong", "360"//360
            -> componentName = ComponentName(
                "com.yulong.android.coolsafe",
                "com.yulong.android.coolsafe.ui.activity.autorun.AutoRunListActivity"
            )
            "meizu"//魅族
            -> componentName =
                ComponentName("com.meizu.safe", "com.meizu.safe.permission.SmartBGActivity")
            "oneplus"//一加
            -> componentName = ComponentName(
                "com.oneplus.security",
                "com.oneplus.security.chainlaunch.view.ChainLaunchAppListActivity"
            )
            "letv"//乐视
            -> {
                intent.action = "com.letv.android.permissionautoboot"
                intent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
                intent.data = Uri.fromParts("package", context.packageName, null)
            }
            else//其他
            -> {
                intent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
                intent.data = Uri.fromParts("package", context.packageName, null)
            }
        }//            componentName = new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity");//目前看是通用的
        if (componentName != null) {
            intent.component = componentName
        }
        return intent
    }

    /**
     * 打开推送设置页面
     */
    @JavascriptInterface
    fun openPushSetteing() {
        if (act != null)
            Utils.requestNotify(act)
    }

    /**
     * 判断是否打开推送权限
     */
    @JavascriptInterface
    fun isPushOpen(): Boolean {
        return NotificationManagerCompat.from(AppliContext.get()).areNotificationsEnabled()
    }

    /**
     * 跳到兑换商店页
     */
    @JavascriptInterface
    fun jumpShop() {
        act?.runOnUiThread(Runnable {
            RxBusUtil.getDefault().send(RxBusConstant.RX_MAIN_ACTIVITY_TAB, 1)
            act?.finish()
            // Constant.Utils.ExchangeShopFragmentBackFlag = false
        })
    }

    /**
     * 跳转web阅读页
     */
    @JavascriptInterface
    fun jumpWebActivity(json: String) {
        act?.runOnUiThread(Runnable {
            val newsEntity: NewsEntity = Utils.str2Obj(json, NewsEntity::class.java) as NewsEntity
            JumpUtils.adJump(newsEntity, act)
            /*JumpUtils.webH5Jump(
                newsEntity.title,
                newsEntity.url,
                newsEntity.delay.toString(),
                newsEntity.sid.toString(),
                newsEntity.deep_url_re,
                newsEntity.timeTrigger,
                newsEntity.slot_id,
                newsEntity.incentive_level.toString(),
                newsEntity.alert,
                newsEntity.alertRenderType
            )*/
        })
    }

    /**
     * 上报
     */
    @JavascriptInterface
    fun eventUtils(action: String) {
        EventUtils.onEvent(action)
    }

    /**
     * h5跳h5
     */
    @JavascriptInterface
    fun h5Jump(h5: String) {
        act?.finish()
        JumpUtils.h5Jump("", h5, false, act)
        //  mWebView?.loadUrl(h5)
    }

    /**
     * 获取金币弹窗
     * type 1水滴  2金币
     */
    @JavascriptInterface
    fun showDialog(waterDropCount: Int, type: Int) {
        if (act == null) return
        mWebView.context.runOnUiThread {
            CenterDialog.showgetWaterDrop(
                act,
                type,
                waterDropCount,
                "web_task",
                DialogInterface.OnCancelListener {
                    mWebView.context.runOnUiThread {
                        mWebView?.loadUrl("javascript:onResume()")
                    }
                },
                mWebView
            )
        }
    }

    /**
     * 提现成功弹窗
     */
    @JavascriptInterface
    fun showWithdrawSucces(cashStr: String) {
        mWebView.context.runOnUiThread {
            if(act!=null){
                CenterDialog.showGuideGetMoney(act,"提现成功",cashStr,mWebView)
            }
        }
    }

}