package com.ym.library.activity

import android.os.SystemClock
import android.util.Log
import com.bx.adsdk.CampaignCallback
import com.bx.adsdk.CampaignFragment
import com.bytedance.sdk.openadsdk.*
import com.google.gson.Gson
import com.qq.e.ads.rewardvideo.RewardVideoAD
import com.qq.e.ads.rewardvideo.RewardVideoADListener
import com.qq.e.comm.managers.GDTADManager
import com.qq.e.comm.util.AdError
import com.umeng.analytics.MobclickAgent
import com.ym.library.Constant
import com.ym.library.R
import com.ym.library.module.ReportEntity
import com.ym.library.net.*
import com.ym.library.utils.EventUtils
import com.ym.library.utils.SettingPreference
import com.ym.library.utils.Utils
import kotlinx.android.synthetic.main.activity_xiaoman.*

class XiaoManActivity : BaseActivity() {

    override fun layoutID(): Int = R.layout.activity_xiaoman

    private var campaignFragment: CampaignFragment? = null
    private var rewardVideoAD: RewardVideoAD? = null

    override fun init() {
        id_tv_title.text = intent.data?.getQueryParameter("title")

        /**
         * @param userId 用户id，必传，不能为空，不能为0
         * @param placeId 资源位id：必传
         * @param callback CampaignCallback 回调
         */
        campaignFragment = CampaignFragment.newInstance(com.ym.modulecommon.utils.SettingPreference.getToken())
        campaignFragment?.setPlaceId("2773")
        campaignFragment?.setCallback(object : CampaignCallback() {
            override fun showAd(params: String) {
                super.showAd(params)
                val bridgeBean: XiaoManEntity = Gson().fromJson(params, XiaoManEntity::class.java)
                val adType: String = bridgeBean.adType.toString()
                val pId: String = bridgeBean.pid.toString()
                val requestId: String = bridgeBean.requestId.toString()
                if (adType.equals("1")) {
                    showTTAd("5116010", pId, requestId)
                } else {
                    showGDTAd("1111153326", pId, requestId)
                }
            }
        })
//        campaignFragment?.canGoBack()//webview 是否可以返回上一页
//        campaignFragment?.goBack()//webview 返回上一页
        supportFragmentManager.beginTransaction().add(R.id.id_activity_fragment_content, campaignFragment!!).commitAllowingStateLoss()

        id_iv_back.setOnClickListener {
            finish()
        }
    }

    /**
     * 穿山甲广告
     */
    fun showTTAd(appId: String, pId: String, requestId: String) {
        //强烈建议在应用对应的Application#onCreate()方法中调用，避免出现content为null的异常
        TTAdSdk.init(
            this@XiaoManActivity,
            TTAdConfig.Builder()
                .appId(appId)
                .useTextureView(true) //使用TextureView控件播放视频,默认为SurfaceView,当有SurfaceView冲突的场景，可以使用TextureView
                .appName(this@XiaoManActivity.getString(R.string.app_name))
                .titleBarTheme(TTAdConstant.TITLE_BAR_THEME_DARK)
                .allowShowNotify(true) //是否允许sdk展示通知栏提示
                .allowShowPageWhenScreenLock(true) //是否在锁屏场景支持展示广告落地页
                .debug(false) //测试阶段打开，可以通过日志排查问题，上线时去除该调用
                .directDownloadNetworkType(
                    TTAdConstant.NETWORK_STATE_WIFI,
                    TTAdConstant.NETWORK_STATE_3G
                ) //允许直接下载的网络状态集合
                .supportMultiProcess(false) //是否支持多进程，true支持
                //.httpStack(new MyOkStack3())//自定义网络库，demo中给出了okhttp3版本的样例，其余请自行开发或者咨询工作人员。
                .build()
        )

        val mTTAdNative = TTAdSdk.getAdManager().createAdNative(this@XiaoManActivity)
        val adSlot = AdSlot.Builder()
            .setCodeId(pId)
            .setSupportDeepLink(true)
            .setAdCount(2) //个性化模板广告需要设置期望个性化模板广告的大小,单位dp,激励视频场景，只要设置的值大于0即可
            .setExpressViewAcceptedSize(500f, 500f)
            .setImageAcceptedSize(1080, 1920)
            .setRewardName("金币") //奖励的名称
            .setRewardAmount(0) //奖励的数量
            //必传参数，表来标识应用侧唯一用户；若非服务器回调模式或不需sdk透传
            //可设置为空字符串
            .setUserID("")//userId
            .setOrientation(TTAdConstant.VERTICAL) //设置期望视频播放的方向，为TTAdConstant.HORIZONTAL或TTAdConstant.VERTICAL
//                        .setMediaExtra("media_extra") //用户透传的信息，可不传
            .build()

        mTTAdNative.loadRewardVideoAd(adSlot, object : TTAdNative.RewardVideoAdListener {
            override fun onError(code: Int, message: String) {
                campaignFragment?.setVideoError(requestId)
            }

            //视频广告加载后的视频文件资源缓存到本地的回调
            override fun onRewardVideoCached() {}

            //视频广告素材加载到，如title,视频url等，不包括视频文件
            override fun onRewardVideoAdLoad(ad: TTRewardVideoAd) {
                ad.setRewardAdInteractionListener(object :
                    TTRewardVideoAd.RewardAdInteractionListener {
                    override fun onAdShow() {
                        campaignFragment?.setVideoLoad(requestId)
                        EventUtils.onEvent("XIAO_MAN_CSJ_SHOW","小满穿山甲广告展示")
                    }
                    override fun onAdVideoBarClick() {
                        EventUtils.onEvent("XIAO_MAN_CSJ_CLICK","小满穿山甲广告点击")
                    }
                    override fun onAdClose() {
                        EventUtils.onEvent("XIAO_MAN_CSJ_CLOSE_CLICK","小满穿山甲广告关闭点击")
                        campaignFragment?.setVideoClose(requestId)
                    }
                    override fun onVideoError() {
                        campaignFragment?.setVideoError(requestId)
                    }
                    override fun onVideoComplete() {
                        campaignFragment?.setVideoComplete(requestId)
                    }
                    override fun onRewardVerify(rewardVerify: Boolean, rewardAmount: Int, rewardName: String?) {}
                    override fun onSkippedVideo() {}
                })
                ad.setDownloadListener(object : TTAppDownloadListener {
                    override fun onIdle() {}
                    override fun onDownloadActive(totalBytes: Long, currBytes: Long, fileName: String, appName: String) {}
                    override fun onDownloadPaused(totalBytes: Long, currBytes: Long, fileName: String, appName: String) {}
                    override fun onDownloadFailed(totalBytes: Long, currBytes: Long, fileName: String, appName: String) {}
                    override fun onDownloadFinished(totalBytes: Long, fileName: String, appName: String) {}
                    override fun onInstalled(fileName: String, appName: String) {}
                })
                ad.showRewardVideoAd(this@XiaoManActivity)
            }
        })
    }
    /**
     * 广点通广告
     */
    fun showGDTAd(appID: String, pId: String, requestId: String) {
        GDTADManager.getInstance().initWith(this@XiaoManActivity, appID)
        rewardVideoAD = RewardVideoAD(this@XiaoManActivity, pId, object : RewardVideoADListener {
            override fun onADExpose() {
            }
            override fun onADClick() {
                EventUtils.onEvent("XIAO_MAN_GDT_CLICK","小满广点通广告点击")
            }
            override fun onVideoCached() {
                if (!rewardVideoAD?.hasShown()!!) { //广告展示检查2：当前广告数据还没有展示过
                    val delta: Long = 1000 //建议给广告过期时间加个buffer，单位ms，这里demo采用1000ms的buffer
                    //广告展示检查3：展示广告前判断广告数据未过期
                    if (SystemClock.elapsedRealtime() < rewardVideoAD!!.getExpireTimestamp() - delta) {
                        rewardVideoAD?.showAD()
                    } else {//激励视频广告已过期，请再次请求广告后进行广告展示！
                    }
                } else {//此条广告已经展示过，请再次请求广告后进行广告展示！
                }
            }
            override fun onReward() {
            }
            override fun onADClose() {
                EventUtils.onEvent("XIAO_MAN_GDT_CLOSE_CLICK","小满广点通广告关闭点击")
                campaignFragment?.setVideoClose(requestId)
            }
            override fun onADLoad() {
                campaignFragment?.setVideoLoad(requestId)
            }
            override fun onVideoComplete() {
                campaignFragment?.setVideoComplete(requestId)
            }
            override fun onError(p0: AdError?) {
                campaignFragment?.setVideoError(requestId)
            }
            override fun onADShow() {
                EventUtils.onEvent("XIAO_MAN_GDT_SHOW","小满广点通广告展示")
            }
        })
        rewardVideoAD?.loadAD()
    }
//    /**
//     * 广点通广告
//     */
//    fun showGDTAd(appID: String, pId: String, requestId: String) {
//        GDTADManager.getInstance().initWith(this@XiaoManActivity, requestId)
////        rewardVideoAD = RewardVideoAD(this, appID, pId, object : RewardVideoADListener {
////                override fun onADLoad() {
////                    if (rewardVideoAD != null) rewardVideoAD?.showAD()
////                    campaignFragment?.setVideoLoad(requestId)
////                }
////                override fun onVideoCached() {}
////                override fun onADShow() {
////                    EventUtils.onEvent("XIAO_MAN_GDT_SHOW","小满广点通广告展示")
////                }
////                override fun onADExpose() {}
////                override fun onReward() {}
////                override fun onADClick() {
////                    EventUtils.onEvent("XIAO_MAN_GDT_CLICK","小满广点通广告点击")
////                }
////                override fun onVideoComplete() {
////                    campaignFragment?.setVideoComplete(requestId)
////                }
////                override fun onADClose() {
////                    EventUtils.onEvent("XIAO_MAN_GDT_CLOSE_CLICK","小满广点通广告关闭点击")
////                    campaignFragment?.setVideoClose(requestId)
////                }
////                override fun onError(adError: AdError) {
////                    campaignFragment?.setVideoError(requestId)
////                }
////            })
////        rewardVideoAD?.loadAD()
//
//
//        var rewardVideoAD = RewardVideoAD(this, pId, object : RewardVideoADListener {
//            override fun onADExpose() {
////                listener.onAdShow()
//            }
//
//            override fun onADClick() {
//                EventUtils.onEvent("XIAO_MAN_GDT_CLICK","小满广点通广告点击")
//            }
//
//            override fun onVideoCached() {
//            }
//
//            override fun onReward() {
//
//            }
//
//            override fun onADClose() {
//                EventUtils.onEvent("XIAO_MAN_GDT_CLOSE_CLICK","小满广点通广告关闭点击")
//                campaignFragment?.setVideoClose(requestId)
//            }
//
//
//            //如果这里
//            override fun onADLoad() {
//                if (rewardVideoAD != null) rewardVideoAD?.showAD()
//                campaignFragment?.setVideoLoad(requestId)
//            }
//
//            override fun onVideoComplete() {
//                campaignFragment?.setVideoComplete(requestId)
//            }
//
//            override fun onError(p0: AdError?) {
//                campaignFragment?.setVideoError(requestId)
//            }
//
//            override fun onADShow() {
//                EventUtils.onEvent("XIAO_MAN_GDT_SHOW","小满广点通广告展示")
//            }
//
//        }) // 有声播放
//        rewardVideoAD.loadAD()
//    }

    override fun onResume() {
        super.onResume()
//        EventUtils.onEvent("page_status", Utils.obj2Str(ReportEntity(Constant.ReportSessionId, "XiaoManActivity", "onResume")))
        MobclickAgent.onResume(this)
    }

    override fun onPause() {
        super.onPause()
//        EventUtils.onEvent("page_status", Utils.obj2Str(ReportEntity(Constant.ReportSessionId, "XiaoManActivity", "onPause")))
        MobclickAgent.onPause(this)
    }

    class XiaoManEntity {
        var adType: String? = ""
        var requestId: String? = ""
        var pid: String? = ""
    }

    /**
     * 看视频上报
     */
    fun videoClick() {
//        ApiClient.userApi.videoReport().compose(
//            RxSchedulers.observableIO2Main()).subscribe(object : BaseObserver<String>() {
//            override fun onSuccess(result: String?) {}
//            override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {}
//        })


    }

    fun videoShow(){


    }

    fun videoCloseClick(){


    }

}