package com.duben.microtribe.ad.banner

import android.app.Activity
import android.view.View
import android.widget.FrameLayout
import com.bytedance.sdk.openadsdk.*
import com.bytedance.sdk.openadsdk.mediation.ad.IMediationNativeAdInfo
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot
import com.bytedance.sdk.openadsdk.mediation.ad.MediationNativeToBannerListener
import com.duben.microtribe.BuildConfig
import com.duben.microtribe.MintsApplication
import com.duben.microtribe.manager.UserManager
import com.duben.microtribe.utils.LogUtil
import com.duben.microtribe.utils.UIUtils
import java.lang.ref.WeakReference

/**
 * banner
 */
object BannerManager {

    private val TAG = BannerManager::class.java.simpleName

    private var weakFrameLayout: WeakReference<FrameLayout>? = null
    private var weakActivity: WeakReference<Activity>? = null
    private var bannerAd: TTNativeExpressAd? = null

    fun loadAd(act: Activity?, view: FrameLayout?) {
        weakActivity = WeakReference<Activity>(act)
        weakFrameLayout = WeakReference<FrameLayout>(view)

        LogUtil.d(TAG, "gromore banner广告-> 1、进入加载")
        /** 这里是简单的banner请求adSlot设置，如果需要更多的设置，可参考AdUtils.kt中bannerAdSlot函数部分。 */
        var adSlot: AdSlot = AdSlot.Builder()
            .setCodeId(BuildConfig.GROMORE_BANNER_CODE)
//            .setImageAcceptedSize(UIUtils.dp2px(weakActivity?.get(), 300f), UIUtils.dp2px(weakActivity?.get(), 45f)) // 单位px
//            .setImageAcceptedSize(
//                UIUtils.getAdWidth2(MintsApplication.getContext()).toInt(),
//                0
//            )
            // 单位px
            .supportRenderControl() //支持模板样式
            .setExpressViewAcceptedSize(UIUtils.getAdWidth2(MintsApplication.getContext()), 0f)//设置模板宽高（dp）
            .setUserID("1234")
            .setMediationAdSlot(
                MediationAdSlot.Builder()
                    /**
                     * banner混出自渲染信息流时，需要提供该转换listener，将信息流自渲染素材转成view。模板类型无需处理
                     * 如果未使用banner混出信息流功能，则无需设置MediationNativeToBannerListener。
                     * 如要使用混出功能，可参考AdUtils.kt类中getCSJMBannerViewFromNativeAd函数部分。
                     */
                    .setMediationNativeToBannerListener(object : MediationNativeToBannerListener() {
                        override fun getMediationBannerViewFromNativeAd(adInfo: IMediationNativeAdInfo): View? {
                            return null
                        }
                    })
                    .build()
            )
            .build()

        var adNativeLoader: TTAdNative = TTAdSdk.getAdManager().createAdNative(weakActivity?.get())
        adNativeLoader.loadBannerExpressAd(adSlot, object : TTAdNative.NativeExpressAdListener {
            override fun onNativeExpressAdLoad(ads: MutableList<TTNativeExpressAd>?) {
                LogUtil.d(TAG, "banner广告-> 2、 load success: " + if (ads == null) "0" else ads?.size)

                ads?.let {
                    if (it.size > 0) {
                        val ad: TTNativeExpressAd = it[0]
                        bannerAd = ad
                        bannerAd?.setExpressInteractionListener(object :
                            TTNativeExpressAd.ExpressAdInteractionListener {
                            override fun onAdClicked(view: View?, type: Int) {
                            }

                            override fun onAdShow(view: View?, type: Int) {
                            }

                            override fun onRenderFail(view: View?, msg: String?, code: Int) {
                            }

                            override fun onRenderSuccess(view: View?, width: Float, height: Float) {
                            }

                        })
                        bannerAd?.setDislikeCallback(
                            weakActivity?.get(),
                            object : TTAdDislike.DislikeInteractionCallback {
                                override fun onShow() {
                                }

                                override fun onSelected(
                                    position: Int,
                                    value: String?,
                                    enforce: Boolean
                                ) {
                                    weakFrameLayout?.get()?.removeAllViews()
                                }

                                override fun onCancel() {
                                }

                            })

                        showAd()
                    }
                }
            }

            override fun onError(code: Int, message: String?) {
                LogUtil.e(TAG, "banner广告-> 2、 load fail: $code, $message")
            }
        })
    }

    private fun showAd() {
        val bannerView: View? = bannerAd?.expressAdView
        if (bannerView != null && weakFrameLayout != null) {
            val bannerContainer = weakFrameLayout!!.get()
            bannerContainer!!.removeAllViews()
            bannerContainer!!.addView(bannerView)
        }
    }
}