package com.jishisongfu.duobibi.util

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import android.widget.Toast
import java.net.URLEncoder

/**
 * 比价擂台"去最低价平台搜"。先把商品名复制到剪贴板兜底,再逐级尝试调起目标平台搜索页:
 *   1) app 私有 deeplink → 2) 公开 https 网页 → 3) 都失败则 Toast 提示手动搜。
 *
 * **裸调** ACTION_VIEW,不带任何推广 / 联盟参数。失败链路兜底,不崩,只降级。
 */
object PlatformSearch {

    private const val TAG = "DUOBIBI-SEARCH"

    fun copyAndSearch(ctx: Context, platform: String, productName: String) {
        copyToClipboard(ctx, productName)
        val q = runCatching { URLEncoder.encode(productName, "UTF-8") }.getOrDefault(productName)
        for (intent in buildIntents(platform, q)) {
            if (tryStart(ctx, intent)) {
                Toast.makeText(ctx, "已复制商品名,正在打开$platform", Toast.LENGTH_SHORT).show()
                return
            }
        }
        Toast.makeText(ctx, "商品名已复制,请打开 $platform App 搜索", Toast.LENGTH_LONG).show()
    }

    private fun copyToClipboard(ctx: Context, text: String) {
        val cm = ctx.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager ?: return
        cm.setPrimaryClip(ClipData.newPlainText("多比比-商品名", text))
    }

    private fun buildIntents(platform: String, q: String): List<Intent> = when (platform) {
        "淘宝" -> listOf(
            intent("taobao://s.taobao.com/search?q=$q"),
            intent("https://s.taobao.com/search?q=$q"),
        )
        "京东" -> listOf(
            intent("openapp.jdmobile://virtual?params=%7B%22category%22%3A%22jump%22%2C%22des%22%3A%22productSearchListNJ%22%2C%22keyword%22%3A%22$q%22%7D"),
            intent("https://search.jd.com/Search?keyword=$q"),
        )
        "拼多多" -> listOf(
            intent("pinduoduo://com.xunmeng.pinduoduo/search_result.html?search_key=$q"),
            intent("https://mobile.yangkeduo.com/search_result.html?search_key=$q"),
        )
        "抖音" -> listOf(
            intent("snssdk1128://search?keyword=$q"),
        )
        else -> emptyList()
    }

    private fun intent(uri: String): Intent =
        Intent(Intent.ACTION_VIEW, Uri.parse(uri)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

    private fun tryStart(ctx: Context, intent: Intent): Boolean = try {
        ctx.startActivity(intent); true
    } catch (e: Exception) {
        Log.d(TAG, "tryStart failed ${intent.data}: ${e.message}"); false
    }
}
