package com.narutohuo.xindazhou.common.router

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.launcher.ARouter

/**
 * 路由管理器
 * 
 * 统一封装 ARouter 路由跳转，提供便捷的路由调用方式
 * 
 * 使用方式：
 * ```kotlin
 * // 基础跳转
 * RouterHelper.navigate("/user/profile")
 * 
 * // 带参数跳转
 * RouterHelper.navigate("/user/profile") {
 *     putString("userId", "123")
 *     putString("userName", "张三")
 * }
 * 
 * // 带结果回调跳转
 * RouterHelper.navigateForResult(activity, "/user/select", 1001) {
 *     putString("type", "user")
 * }
 * 
 * // 获取服务
 * val pushService = RouterHelper.getService<IPushService>()
 * ```
 */
object RouterHelper {
    
    /**
     * 基础跳转
     * 
     * @param path 路由路径
     */
    fun navigate(path: String) {
        ARouter.getInstance()
            .build(path)
            .navigation()
    }
    
    /**
     * 带参数跳转
     * 
     * @param path 路由路径
     * @param params 参数构建器
     */
    fun navigate(path: String, params: (Bundle.() -> Unit)? = null) {
        val postcard = ARouter.getInstance().build(path)
        
        params?.let {
            val bundle = Bundle().apply(it)
            postcard.with(bundle)
        }
        
        postcard.navigation()
    }
    
    /**
     * 带参数跳转（使用 RouteBuilder）
     * 
     * @param path 路由路径
     * @return RouteBuilder，用于链式调用
     */
    fun build(path: String): RouteBuilder {
        return RouteBuilder(path)
    }
    
    /**
     * 带结果回调跳转（Activity）
     * 
     * @param activity Activity 实例
     * @param path 路由路径
     * @param requestCode 请求码
     * @param params 参数构建器（可选）
     */
    fun navigateForResult(
        activity: Activity,
        path: String,
        requestCode: Int,
        params: (Bundle.() -> Unit)? = null
    ) {
        val postcard = ARouter.getInstance().build(path)
        
        params?.let {
            val bundle = Bundle().apply(it)
            postcard.with(bundle)
        }
        
        postcard.navigation(activity, requestCode)
    }
    
    /**
     * 注册带结果回调的路由跳转（Fragment - 新 API）
     * 
     * 使用 ActivityResultLauncher，推荐使用此方法
     * 
     * 使用方式：
     * ```kotlin
     * // 在 Fragment 中注册
     * private val resultLauncher = RouterHelper.registerForResult(this) { result ->
     *     if (result.resultCode == Activity.RESULT_OK) {
     *         val data = result.data
     *         // 处理结果
     *     }
     * }
     * 
     * // 跳转
     * RouterHelper.navigateForResult(resultLauncher, "/user/select") {
     *     putString("type", "user")
     * }
     * ```
     * 
     * @param fragment Fragment 实例
     * @param onResult 结果回调
     * @return ActivityResultLauncher，配合 navigateForResult(launcher, path, params) 使用
     */
    fun registerForResult(
        fragment: Fragment,
        onResult: (androidx.activity.result.ActivityResult) -> Unit
    ): ActivityResultLauncher<Intent> {
        return fragment.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            onResult(result)
        }
    }
    
    /**
     * 带结果回调跳转（使用 ActivityResultLauncher - 新 API）
     * 
     * 配合 registerForResult() 使用
     * 
     * @param launcher ActivityResultLauncher（通过 registerForResult() 获取）
     * @param path 路由路径
     * @param params 参数构建器（可选）
     */
    fun navigateForResult(
        launcher: ActivityResultLauncher<Intent>,
        path: String,
        params: (Bundle.() -> Unit)? = null
    ) {
        val postcard = ARouter.getInstance().build(path)
        
        params?.let {
            val bundle = Bundle().apply(it)
            postcard.with(bundle)
        }
        
        val intent = postcard.navigation() as? Intent
        if (intent != null) {
            launcher.launch(intent)
        }
    }
    
    /**
     * 带结果回调跳转（Fragment - 已废弃）
     * 
     * @deprecated 使用 registerForResult() 替代
     * @param fragment Fragment 实例
     * @param path 路由路径
     * @param requestCode 请求码
     * @param params 参数构建器（可选）
     */
    @Deprecated(
        message = "使用 registerForResult() 替代",
        replaceWith = ReplaceWith(
            "val launcher = RouterHelper.registerForResult(fragment) { result -> /* 处理结果 */ }\n" +
            "val intent = ARouter.getInstance().build(path).with(bundle).navigation() as Intent\n" +
            "launcher.launch(intent)"
        )
    )
    @Suppress("DEPRECATION")
    fun navigateForResult(
        fragment: Fragment,
        path: String,
        requestCode: Int,
        params: (Bundle.() -> Unit)? = null
    ) {
        val postcard = ARouter.getInstance().build(path)
        
        params?.let {
            val bundle = Bundle().apply(it)
            postcard.with(bundle)
        }
        
        fragment.startActivityForResult(postcard.navigation() as Intent, requestCode)
    }
    
    /**
     * 获取服务实例
     * 
     * @param path 服务路径（可选，如果为 null 则通过类型查找）
     * @return 服务实例，如果未找到返回 null
     */
    inline fun <reified T> getService(path: String? = null): T? {
        return try {
            if (path != null) {
                ARouter.getInstance().build(path).navigation() as? T
            } else {
                ARouter.getInstance().navigation(T::class.java)
            }
        } catch (e: Exception) {
            null
        }
    }
    
    /**
     * 路由构建器（链式调用）
     */
    class RouteBuilder(private val path: String) {
        private val bundle = Bundle()
        
        /**
         * 添加字符串参数
         */
        fun withString(key: String, value: String): RouteBuilder {
            bundle.putString(key, value)
            return this
        }
        
        /**
         * 添加整数参数
         */
        fun withInt(key: String, value: Int): RouteBuilder {
            bundle.putInt(key, value)
            return this
        }
        
        /**
         * 添加布尔参数
         */
        fun withBoolean(key: String, value: Boolean): RouteBuilder {
            bundle.putBoolean(key, value)
            return this
        }
        
        /**
         * 添加长整数参数
         */
        fun withLong(key: String, value: Long): RouteBuilder {
            bundle.putLong(key, value)
            return this
        }
        
        /**
         * 添加 Parcelable 参数
         */
        fun withParcelable(key: String, value: android.os.Parcelable): RouteBuilder {
            bundle.putParcelable(key, value)
            return this
        }
        
        /**
         * 添加 Serializable 参数
         */
        fun withSerializable(key: String, value: java.io.Serializable): RouteBuilder {
            bundle.putSerializable(key, value)
            return this
        }
        
        /**
         * 执行跳转
         */
        fun navigate() {
            ARouter.getInstance()
                .build(path)
                .with(bundle)
                .navigation()
        }
        
        /**
         * 执行跳转（带结果回调）
         */
        fun navigateForResult(activity: Activity, requestCode: Int) {
            ARouter.getInstance()
                .build(path)
                .with(bundle)
                .navigation(activity, requestCode)
        }
    }
}

