package com.ccwangluo.accelerator.ui.web

import android.os.Bundle
import android.webkit.JavascriptInterface
import com.ccwangluo.accelerator.utils.LoginUtils
import com.github.shadowsocks.http.HttpConfig
import com.ccwangluo.cc_quickly.utils.SettingSPUtils
import com.ccwangluo.cc_quickly.utils.XToastUtils
import com.just.agentweb.core.AgentWeb
import com.karumi.dexter.Dexter
import com.karumi.dexter.MultiplePermissionsReport
import com.karumi.dexter.PermissionToken
import com.karumi.dexter.listener.PermissionRequest
import com.karumi.dexter.listener.multi.MultiplePermissionsListener
import com.xuexiang.xpage.base.XPageFragment
import com.xuexiang.xutil.app.AppUtils
import com.xuexiang.xutil.system.PermissionUtils
import android.content.Intent
import android.net.Uri
import com.hjq.toast.ToastUtils
import java.lang.Exception
import android.util.DisplayMetrics
import com.ccwangluo.accelerator.utils.SysUtils
import com.xuexiang.xutil.net.NetworkUtils
import java.util.*


/**
 * js注入的方法
 */
class AndroidInterface(val xPageFragment: XPageFragment, val agentWeb: AgentWeb) {

    @JavascriptInterface
    fun callAndroid(msg: String) {
        XToastUtils.toast("这是Js调用Android的方法，内容:$msg")
    }

    @JavascriptInterface
    fun close() {
        xPageFragment.popToBack()
    }

    @JavascriptInterface
    fun openNative(pageName: String) {
        xPageFragment.openPage(pageName)
    }

    @JavascriptInterface
    fun openWebview(url: String) {
        LoginUtils.token?.let {
            val params = Bundle()
            params.putString(CommonWebViewFragment.WEBVIEW_URL_KEY, HttpConfig.UI_MAIN_URL + url)
            xPageFragment.openPage(CommonWebViewFragment::class.java, params)
        } ?: let {
            LoginUtils.login(xPageFragment) {
                LoginUtils.token?.let {
                    agentWeb.getJsAccessEntrace()
                        .quickCallJs("userToken", it)
                }
            }
        }

    }

    //打开系统设置
    @JavascriptInterface
    fun openSysSetting() {
        NetworkUtils.openWirelessSettings()
    }

    @JavascriptInterface
    fun openAsideWebview(url: String) {
        val params = Bundle()
        params.putString(CommonWebViewFragment.WEBVIEW_URL_KEY, url)
        xPageFragment.openPage(CommonWebViewFragment::class.java, params)
    }

    @JavascriptInterface
    fun login(callback: String) {
        LoginUtils.login(xPageFragment, {
            if (it) {
                agentWeb.getJsAccessEntrace()
                    .quickCallJs(callback, LoginUtils.token)
            }
        })
    }

    /**
     * 智能极限加速
     */
    @JavascriptInterface
    fun setSmartAccOpen(isopen: Boolean) {
        SettingSPUtils.isSmartAccOpen = isopen
    }

    /**
     * 智能极限加速
     */
    @JavascriptInterface
    fun getSmartAccStatus(callback: String) {
        agentWeb.getJsAccessEntrace()
            .quickCallJs(callback, SettingSPUtils.isSmartAccOpen.toString())
    }

    /**
     * 清除token
     */
    @JavascriptInterface
    fun clearToken() {
        LoginUtils.clearToken()
    }


    /**
     * 检查权限
     */
    @JavascriptInterface
    fun getPermissionState(key: String, callback: String) {
        xPageFragment.context?.let {
            val hasPermission: Boolean = PermissionUtils.isGranted(key)
            agentWeb.getJsAccessEntrace()
                .quickCallJs(callback, key, hasPermission.toString())
        }
    }

    /**
     * 申请权限
     */
    @JavascriptInterface
    fun requirePermissionState(key: String, callback: String) {
        xPageFragment.context?.let {
            PermissionUtils.permission(key).rationale({
                PermissionUtils.openAppSettings()
            }).callback(object : PermissionUtils.FullCallback {
                override fun onGranted(permissionsGranted: MutableList<String>?) {
                    permissionsGranted?.forEach {
                        if (it.equals(key)) {
                            agentWeb.getJsAccessEntrace()
                                .quickCallJs(callback, key, "true")
                        }
                    }

                }

                override fun onDenied(
                    permissionsDeniedForever: MutableList<String>?,
                    permissionsDenied: MutableList<String>?
                ) {
                    permissionsDenied?.forEach {
                        if (it.equals(key)) {
                            agentWeb.getJsAccessEntrace()
                                .quickCallJs(callback, key, "false")
                        }
                    }
                    permissionsDeniedForever?.forEach {
                        if (it.equals(key)) {
                            PermissionUtils.openAppSettings()
                        }
                    }

                }

            }).request()
        }
    }

    /**
     * 检查安装包
     */
    @JavascriptInterface
    fun getPackageState(packageName: String, callback: String) {
        xPageFragment.context?.let {
            val packageInstall = SysUtils.isPackageInstall(it, packageName)
            agentWeb.getJsAccessEntrace()
                .quickCallJs(callback, packageName, packageInstall.toString())
        }
    }

    /**
     * 卸载程序
     */
    @JavascriptInterface
    fun uninstallPackge(pageName: String) {
        AppUtils.uninstallApp(pageName)
    }

    /**
     * 安装
     */
    @JavascriptInterface
    fun installPackge(pageName: String) {
//        AppUtils.installApp(pageName)
    }

    /**
     * 版本号
     */
    @JavascriptInterface
    fun getVersion(callback: String) {
        agentWeb.getJsAccessEntrace()
            .quickCallJs(
                callback,
                AppUtils.getAppVersionName(),
                AppUtils.getAppVersionCode().toString()
            )
    }

    /****************
     *
     * 发起添加群流程。
     * 调用 joinQQGroup(09Gg-vMtnaIfgr-slk1pOkjVIFmjI79U)
     */
    @JavascriptInterface
    fun joinQQGroup() {
        xPageFragment.context?.let {
            SysUtils.joinQQGroup(it)
        }

    }

    @JavascriptInterface
    fun getSystemVersion(callback: String) {
        agentWeb.getJsAccessEntrace()
            .quickCallJs(
                callback,
                android.os.Build.VERSION.RELEASE,
                SysUtils.getDpi(xPageFragment).toString(),android.os.Build.VERSION.SDK_INT.toString()
            )
    }

    /**
     * 获取android dpi
     */
    @JavascriptInterface
    fun getDpi(callback: String) {
        agentWeb.getJsAccessEntrace()
            .quickCallJs(callback, SysUtils.getDpi(xPageFragment).toString())
    }

    @JavascriptInterface
    fun closeApp() {
        LoginUtils.clearToken()
        System.exit(0)
    }

}