package com.yidianling.dynamic.trendsDetail

import android.content.Context
import androidx.viewpager.widget.PagerAdapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydl_image.module.GlideApp
import com.ydl.ydl_router.manager.YDLRouterManager
import com.ydl.ydlcommon.utils.BuryPointUtils
import com.ydl.ydlcommon.utils.ScreenUtil
import com.yidianling.dynamic.R
import com.yidianling.dynamic.common.net.DynamicApiUtils
import com.yidianling.dynamic.model.Command
import com.yidianling.dynamic.model.TrendsDetailInfoBean
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.dynamic_item_trend_detail_ad.view.*

/**
 * 动态广告图展示
 * Created by zqk on 17-7-10.
 */
class AdViewPagerAdapter(private val context: Context, private val adList: MutableList<TrendsDetailInfoBean.Ad>) : PagerAdapter() {

    var onClickListener: View.OnClickListener? = null

    override fun isViewFromObject(view: View, `object`: Any): Boolean = view == `object`

    override fun getCount() = adList.size

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val view = LayoutInflater.from(context).inflate(R.layout.dynamic_item_trend_detail_ad, container, false)
        view.ivAd.layoutParams.height = ScreenUtil.getDisplayWidth() * 19 / 66
        val ad = adList[position]
        GlideApp.with(context)
                .load(ad.adImg)
                .placeholder(R.drawable.dynamic_default_img)
                .into(view.ivAd)
        view.setOnClickListener {

            if (YDLRouterManager.router(ad.url)) {

            }else{
                val h5Params = H5Params(ad.url, null, ad.share)
                NewH5Activity.start(context, h5Params)
                DynamicApiUtils.adClickCount(Command.AdClickCount(ad.focId))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe({}, {})
                BuryPointUtils.getInstance().createMap()
                        .put("dynamic_ad_name",ad.share?.title)
                        .put("dynamic_ad_location","${position+1}")
                        .burryPoint("Dynamic_AD_Click")
            }
        }
        container.addView(view)
        view.ivAd.requestLayout()
        return view
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        val view = `object` as View
        container.removeView(view)
    }


}
