package com.adealink.weparty.util

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.core.net.toUri
import androidx.fragment.app.FragmentActivity
import com.adealink.frame.base.AppBase
import com.adealink.frame.router.Router
import com.adealink.frame.util.DisplayUtil
import com.adealink.frame.util.PackageUtil
import com.adealink.frame.util.getParamsFromUri
import com.adealink.weparty.R
import com.adealink.weparty.commonui.dialogfragment.BaseDialogFragment
import com.adealink.weparty.commonui.toast.util.showToast
import com.adealink.weparty.module.webview.Web

fun goLocalLinkPage(context: Context?, link: String?) {
    if (context == null || link.isNullOrEmpty()) {
        return
    }

    try {
        // 判断版本号信息("partyoki://yoki/main?min_android_version=XXX&min_ios_version=XXX")
        val minAndroidVersion =
            getParamsFromUri(link.toUri())["min_android_version"]?.toIntOrNull()
        if (minAndroidVersion != null) {
            val currentVersion = PackageUtil.getVersionCode()
            if (currentVersion < minAndroidVersion) {
                //版本过低，提示用户更新
                showToast(R.string.common_version_too_old)
                return
            }
        }
        when {
            // 网页链接
            link.startsWith("http") || link.startsWith("https") -> handleHttpLink(context, link)
            //指定弹窗
            link.startsWith(AppBase.deeplinkScheme) && link.contains(INTENT_DIALOG) -> handleOpenDialogLink(context, link)
            // DeepLink
            link.startsWith(AppBase.deeplinkScheme) -> handleDeepLink(context, link)
            else -> {
                // nth
            }
        }
    } catch (e: Exception) {
        // nth
    }
}

private fun handleOpenDialogLink(context: Context, link: String) {
    //打开指定弹窗
    val activity = context as? FragmentActivity ?: return
    val uri = Uri.parse(link)
    val paramsMap = uri.queryParameterNames.associateWith { uri.getQueryParameter(it) }
    val routerPath = paramsMap["page"]?.let {
        if (it.startsWith("/")) it else "/$it"
    }
    val dialogTag = paramsMap["dialog_tag"] ?: ""
    if (!routerPath.isNullOrEmpty()) {
        Router.getRouterInstance<BaseDialogFragment>(routerPath)?.apply {
            arguments = Bundle().apply {
                for ((key, value) in paramsMap) {
                    if (value != null) {
                        putString(key, value)
                    }
                }
            }
        }?.show(activity.supportFragmentManager, dialogTag)
    }
}

private fun handleDeepLink(context: Context, link: String) {
    // 通过DeepLink 跳转的指定页面
    val intent = Intent(Intent.ACTION_VIEW, link.toUri())
    intent.setPackage(context.packageName)
    context.startActivity(intent)
}

private fun handleHttpLink(context: Context, link: String) {
    val params = getParamsFromUri(link.toUri())
    val aspectRatio = params["aspect_ratio"]?.toFloatOrNull() //高度/宽度
    val activity = context as? FragmentActivity
    val transparent = params["transparent"]?.toBoolean() ?: true //是否透明，默认为true
    val canceledOnTouchOutside =
        params["canceled_on_touch_outside"]?.toBoolean() ?: true //是否点击外部取消，默认为true
    if (activity != null && aspectRatio != null && aspectRatio > 0) {
        //有比例半屏加载
        val height = (aspectRatio * DisplayUtil.getScreenWidth()).toInt()
        val dialogTag = params["dialog_tag"] ?: ""
        // TODO: 实现web能力
//        WebViewDialogFragmentBuilder()
//            .height(height)
//            .transparent(transparent)
//            .canceledOnTouchOutside(canceledOnTouchOutside)
//            .dialogTag(dialogTag)
//            .build()
//            ?.showUrl(activity.supportFragmentManager, link)
    } else {
        //加载一个 web 页
        Router.build(context, Web.FullScreen.PATH)
            .putExtra(Web.Common.EXTRA_URL, link)
            .start()
    }

}


/**
 * 定义打开弹窗的deepLink
 */
const val INTENT_DIALOG = "open_dialog"