package com.zxhl.cms.utils

import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.util.Log
import com.zx.ad.modulecommon.net.EventApiClient
import com.zx.ad.utils.AdEventUtils
import com.zxhl.cms.common.Constant
import com.zxhl.cms.net.ApiClient
import com.zxhl.cms.net.RxSchedulers
import com.zxhl.cms.net.callback.BaseObserver
import com.zxhl.cms.net.callback.BaseObserver2
import com.zxhl.cms.net.model.qy.ConvertLinkEntity
import com.zxhl.cms.net.model.qy.ConvertLinkEntityDetail
import com.zxhl.cms.net.model.qy.TbGoodsEntity
import com.zxhl.cms.net.model.qy.TbGoodsItemEntity
import com.zxhl.cms.widget.CenterDialog
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.net.URLEncoder

/**
 * @author (wangXuewei)
 * @datetime 2022-06-23 11:15 GMT+8
 * @detail :监测淘口令
 */
object ClipboardManagerUtil {


    fun getTbLink(context: Activity) {
        if (!Constant.Switch.isOpenVip) {
            return
        }
        if (context.localClassName.contains("SplashActivity")) {
            return
        }
//        Log.d("wxw", "activityName" + context.localClassName)
        Handler().postDelayed({
            // 获取系统剪贴板
            var clipboard: ClipboardManager =
                context.application.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager;
//            Log.d("wxw", "hasPrimaryClip " + clipboard.hasPrimaryClip())
            if (clipboard.hasPrimaryClip()) {
                // 返回数据
                var clipData: ClipData? = clipboard.primaryClip
                if (clipData != null && clipData.itemCount > 0) {
                    // 从数据集中获取（粘贴）第一条文本数据
                    if (clipData.getItemAt(0).coerceToText(context) == null) {
                        return@postDelayed
                    }
                    var textStr = clipData.getItemAt(0).coerceToText(context).toString()
                    Log.d("wxw", "textStr" + textStr)
                    if (textStr.length > 10) {
                        if (textStr != copyLink) {
                            getGoodsGuideLink(context, textStr)
                            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
                                clipboard.clearPrimaryClip()
                            } else {
                                try {
                                    clipData = ClipData.newPlainText(null, null)
                                    clipboard.setPrimaryClip(clipData)
                                } catch (e: Exception) {

                                }
                            }
                        }
                    }
                } else {
                    Log.d("wxw", "无内容")
                }
            }
        }, 200)
    }

    //获取商品详情
    fun getGoodsGuideLink(context: Activity, str: String) {

//        val encode = URLEncoder.encode(str)
//        Log.d("wxw","urlCode : ${encode}")

        var url =
            "http://api.vephp.com/hcapi?vekey=V00006899Y22696189&para=${URLEncoder.encode(str)}&detail=1";
        ApiClient.homeApi.requestUrl(url)
            .compose(RxSchedulers.observableIO2Main())
            .subscribe(object : BaseObserver2<TbGoodsItemEntity>() {
                override fun onSuccess(result: TbGoodsItemEntity?) {
                    if (result != null) {
                        copy(context, result.global_tbk_pwd ?: "")
                        CenterDialog.showTbGoodsDetail(
                            context,
                            result
                        )
                    }
                }

                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {

                }
            })
    }

    private var copyLink = ""
    fun copy(context: Activity, string: String) {
        if (string.isNullOrEmpty()) {
            return
        }
        copyLink = string
        Log.d("wxw", "copyLink ${copyLink}")
        //获取剪贴板管理器：
        val cm: ClipboardManager =
            context?.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        val mClipData: ClipData =
            ClipData.newPlainText("Label", string)
//            ClipData.newIntent("Label", Intent())
        cm.setPrimaryClip(mClipData)
    }

}