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.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 android.os.Handler
import android.provider.Settings
import com.ccwangluo.accelerator.utils.AcceleratorUtils
import com.ccwangluo.accelerator.utils.ShareUtils
import com.ccwangluo.accelerator.utils.SysUtils
import com.ccwangluo.accelerator.utils.datareport.DataRePortUtils
import com.github.shadowsocks.bg.AuthManager
import com.github.shadowsocks.bg.BaseService
import com.tencent.bugly.beta.Beta


/**
 * 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 {
            xPageFragment.context?.let { it1 ->
                LoginUtils.login(it1) {
                    LoginUtils.token?.let {
                        agentWeb.getJsAccessEntrace()
                                .quickCallJs("userToken", it)
                    }
                }
            }
        }
    }

    /**
     * 打开外部系统浏览器
     */
    @JavascriptInterface
    fun goSysBrowser(url: String?) {
        val uri = Uri.parse(url)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        xPageFragment.context?.startActivity(intent)
    }

    /**
     * 跳转协议
     */
    @JavascriptInterface
    fun openWebviewByWholeUrl(url: String) {
        val params = Bundle()
        if (url.startsWith("http:") || url.startsWith("https:")) {
            params.putString(CommonWebViewFragment.WEBVIEW_URL_KEY, url)
        } else {
            params.putString(
                    CommonWebViewFragment.WEBVIEW_URL_KEY,
                    HttpConfig.HTML_HOST_PRIVACY + url
            )
        }

        xPageFragment.openPage(CommonWebViewFragment::class.java, params)
    }

    //打开系统设置
    @JavascriptInterface
    fun openSysSetting() {
        xPageFragment.startActivity(Intent(Settings.ACTION_SETTINGS));
    }

    @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) {
        xPageFragment.context?.let { it1 ->
            LoginUtils.login(it1) {
                LoginUtils.token?.let {
                    agentWeb.getJsAccessEntrace()
                            .quickCallJs(callback, it)
                }
            }
        }
    }

    /**
     * 获取token
     */
    @JavascriptInterface
    fun getToken(callback: String) {
        agentWeb.getJsAccessEntrace()
                .quickCallJs(callback, LoginUtils.token)
    }

    /**
     * 检查是否有更新
     */
    @JavascriptInterface
    fun getUpdateInfo(callback: String) {
        Beta.getUpgradeInfo()?.let {
            //是否有更新：1有 0没有
            //最新安装包的版本名称
            agentWeb.jsAccessEntrace
                    .quickCallJs(callback, "1", AppUtils.getAppVersionName(), it.versionName)

        } ?: let {
            agentWeb.jsAccessEntrace
                    .quickCallJs(
                            callback,
                            "0",
                            AppUtils.getAppVersionName(),
                            AppUtils.getAppVersionName()
                    )
        }
    }

    /**
     * 当前加速状态 1 加速中，0 未加速
     */
    @JavascriptInterface
    fun getAccelerateState(callback: String) {
        if (BaseService.State.Connected == AcceleratorUtils.state) {
            agentWeb.jsAccessEntrace
                    .quickCallJs(callback, "1")
        } else {
            agentWeb.jsAccessEntrace
                    .quickCallJs(callback, "0")
        }
    }

    private val handler: Handler = Handler()

    /**
     * 点击游戏主页下面的加速按钮调用
     */
    @JavascriptInterface
    fun clickAccelerateBtn() {
        handler.post {
            xPageFragment.setFragmentResult(500, Intent())
            xPageFragment.popToBack()
        }
    }

    /**
     * 点击更新
     */
    @JavascriptInterface
    fun doAppUpdate() {
        Beta.checkUpgrade(true, false)
    }

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


    /**
     * 智能极限加速
     */
    @JavascriptInterface
    fun getSmartAccStatus(callback: String) {
        agentWeb.getJsAccessEntrace()
                .quickCallJs(callback, AuthManager.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)
    }

    @JavascriptInterface
    fun dataReport(event: String, data: String) {
        DataRePortUtils.report(event, if (data.isBlank()) null else data)
    }

    @JavascriptInterface
    fun share() {
        xPageFragment.activity?.let {
            DataRePortUtils.report("st_share_clk", mapOf("scene" to "4"))
            ShareUtils().share(it)
        }
    }


}