package com.composition.android.ad.csj.load.view

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.view.isVisible
import com.bytedance.sdk.openadsdk.TTAdConstant
import com.bytedance.sdk.openadsdk.TTAdDislike
import com.bytedance.sdk.openadsdk.TTNativeAd
import com.composition.android.ad.csj.R
import com.composition.android.ad.csj.impl.CSJAppDownloadListener
import com.composition.android.lib.ad.AdManager
import com.composition.android.lib.ad.basic.AdResult
import com.composition.android.lib.ad.basic.BasicAdView
import com.composition.android.lib.ad.basic.NativeAdViewHolder
import com.composition.android.lib.ad.util.adLog

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/9/13
 * description: 穿山甲原生模板广告View
 */
class CSJNativeAdView(context: Context?) : BasicAdView<View>(context) {

    private var viewHolder: NativeAdViewHolder? = null

    fun setViewHolder(viewHolder: NativeAdViewHolder) {
        this.viewHolder = viewHolder
    }

    override fun adContentView(): View? {
        if (adResult == null || viewHolder == null) {
            return null
        }

        populateNativeAdView(context, adResult = adResult!!, viewHolder = viewHolder!!, null)
        return viewHolder?.customLayoutRootView
    }

    override fun onResume() {

    }

    override fun onPause() {

    }

    override fun onDestroy() {
        val ttNativeAd = adResult?.adObject as? TTNativeAd
        ttNativeAd?.destroy()
        adResult?.adObject = null
    }

    companion object {

        fun populateNativeAdView(context: Context, adResult: AdResult.Success, viewHolder: NativeAdViewHolder, advertisersContainerView: ViewGroup?) {

            val ttNativeAd = adResult.adObject as TTNativeAd
            viewHolder.activity?.apply {
                ttNativeAd.getDislikeDialog(this).apply {
                    setDislikeInteractionCallback(object : TTAdDislike.DislikeInteractionCallback {
                        override fun onShow() {

                        }

                        override fun onSelected(p0: Int, p1: String?, p2: Boolean) {
                            adLog(msg = "穿山甲广告-原生-点击不喜欢按钮")
                            viewHolder.adListener?.onAdDisLike()
                        }

                        override fun onCancel() {
                        }
                    })
                    viewHolder.dislikeView?.setOnClickListener {
                        this.showDislikeDialog()
                    }
                }


            }

            viewHolder.titleView?.text = ttNativeAd.title
            (viewHolder.titleDescView as? AppCompatTextView)?.text = ttNativeAd.description


            val mediaImageViews = LayoutInflater.from(context).inflate(R.layout.csj_native_ad_media_image_views, null)

            val imageViewList = mutableListOf<View>()
            imageViewList.add(mediaImageViews.findViewById(R.id.id_ad_media_iv_1))
            imageViewList.add(mediaImageViews.findViewById(R.id.id_ad_media_iv_2))
            imageViewList.add(mediaImageViews.findViewById(R.id.id_ad_media_iv_3))


            viewHolder.contentMediaViewGroup?.apply {
                removeAllViews()
                addView(mediaImageViews)
            }
            if (ttNativeAd.imageList.isNullOrEmpty().not()) {

                for (i in 0..2) {
                    val imageItem = ttNativeAd.imageList.getOrNull(i)
                    if (imageItem != null) {
                        if (imageItem.isValid) {
                            viewHolder.mediaImageLoader?.displayImage(context, imageItem.imageUrl, imageViewList[i] as AppCompatImageView)
                        }
                    } else {
                        imageViewList.getOrNull(i)?.isVisible = false
                    }
                }
            }
            if (ttNativeAd.icon != null && ttNativeAd.icon.isValid && viewHolder.iconView != null) {
                viewHolder.iconImageLoader?.displayImage(context, ttNativeAd.icon.imageUrl, viewHolder.iconView as AppCompatImageView)
            }
            when (ttNativeAd.interactionType) {
                TTAdConstant.INTERACTION_TYPE_DOWNLOAD -> {
                    ttNativeAd.setActivityForDownloadApp(viewHolder.activity)
                    viewHolder.callActionButtonView?.isVisible = true
                    ttNativeAd.setDownloadListener(CSJAppDownloadListener(context, viewHolder))
                }
                TTAdConstant.INTERACTION_TYPE_DIAL -> {
                    viewHolder.callActionButtonView?.also {
                        it.isVisible = true
                        it.text = context.getString(R.string.call_now)
                    }
                }
                TTAdConstant.INTERACTION_TYPE_LANDING_PAGE -> {
                    viewHolder.callActionButtonView?.also {
                        it.isVisible = true
                        it.text = context.getString(R.string.check_the_details)
                    }
                }
                else -> {
                    viewHolder.callActionButtonView?.isVisible = false
                }
            }

            (viewHolder.advertiserLogoImageView as? AppCompatImageView)?.setImageBitmap(ttNativeAd.adLogo)

            val clickViewList = mutableListOf<View>()
            viewHolder.customLayoutRootView?.let { clickViewList.add(it) }


            val creativeViewList = mutableListOf<View>()
            viewHolder.callActionButtonView?.let {
                creativeViewList.add(it)
            }

            ttNativeAd.registerViewForInteraction(
                viewHolder.customLayoutRootView as ViewGroup,
                imageViewList,
                clickViewList,
                creativeViewList,
                viewHolder.dislikeView,
                object : TTNativeAd.AdInteractionListener {
                    override fun onAdClicked(p0: View?, p1: TTNativeAd?) {
                        adLog(msg = "穿山甲广告-原生-点击广告")
                        viewHolder.adListener?.onAdClick()
                    }

                    override fun onAdCreativeClick(p0: View?, p1: TTNativeAd?) {
                    }

                    override fun onAdShow(p0: TTNativeAd?) {
                        adLog(msg = "穿山甲广告-原生-广告展示")
                    }

                })

            ttNativeAd.setExpressRenderListener { view, width, height, isExpress ->
                adLog(AdManager.TAG, "穿山甲广告-原生-渲染成功 width:${width},height:${height}")
                viewHolder.adListener?.onAdShow(adResult.adBean)
//                (viewHolder.customLayoutRootView as? ViewGroup)?.let {
//                    val sWidth = context.getScreenWidth()
//                    val sHeight = (sWidth * height / width).toInt()
//                    it.removeAllViews()
//                    it.addView(ttNativeAd., sWidth, sHeight)
//                }
            }
            ttNativeAd.render()
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        adResult?.adObject = null
    }
}