package com.zx.ad.utils


import android.text.TextUtils
import android.util.Log
import com.zx.ad.modulecommon.module.NewsEntity
import com.zx.ad.modulecommon.net.EventApiClient
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import org.json.JSONObject

/**
 * Created by gaoleichao on 2019/1/11
 */
object AdEventUtils {

    val EVENT = "ad"
    val AD_MODEL_SPLAH = "splash"
    val AD_MODEL_REWARD = "reward"
    val AD_MODEL_FULL_VIDEO = "fullvideo"
    val AD_MODEL_BIGIMG = "bigimg"
    val AD_MODEL_SCREEN = "fullscreen"

    fun getJSON(action: String): JSONObject {
        var data = JSONObject()
        data.put("event", EVENT)
        data.put("action", action)
        return data
    }

    //广告拉取失败上报
    fun onEvent(newsEntity: NewsEntity, errorCode: Any?, errorMsg: String?) {
        val jsonObj = getJSON("pull_ad_error")
        jsonObj.put("codeId", newsEntity?.codeId)
        jsonObj.put("reqId", newsEntity.reqId)
        jsonObj.put("errorMsg", errorMsg)
        jsonObj.put("errorCode", errorCode)
        apiClient(jsonObj)
    }

    //广告成功展示
    fun onEventShowSuccess(entity: NewsEntity) {
        if (entity?.imp_tracking != null && entity?.imp_tracking.size > 0) {
            for (i in 0 until entity.imp_tracking?.size!!) {
                var newUrl =  entity.imp_tracking!![i]
                apiClient(newUrl)
            }
        }

        val json = getJSON("show")
        json.put("ad_model",entity?.slotName)
        json.put("ad_plantform",entity?.adPlatform?:"")
        json.put("code_id",entity?.codeId?:"")
        json.put("slot",entity?.actionName?:"")
        apiClient(json)
        if(!TextUtils.isEmpty(entity?.actionName)){
//            MobclickAgent.onEvent(AppliContext.get(), entity?.actionName, json.toString())
        }
    }

    //广告展示失败  渲染失败
    fun onEventShowFail(entity: NewsEntity) {
        if (entity?.showfail_tracking != null && entity?.showfail_tracking.size > 0) {
            for (i in 0 until entity.showfail_tracking?.size!!) {
                var newUrl =  entity.showfail_tracking!![i]
                apiClient(newUrl)
            }
        }
        val json = getJSON("showfail")
        json.put("ad_model",entity?.slotName)
        json.put("ad_plantform",entity?.adPlatform?:"")
        json.put("code_id",entity?.codeId?:"")
        json.put("slot",entity?.actionName?:"")
        apiClient(json)
        if(!TextUtils.isEmpty(entity?.actionName)){
//            MobclickAgent.onEvent(AppliContext.get(), entity?.actionName, json.toString())
        }

    }

    //广告拉取成功
    fun onEventPullSuccess(entity: NewsEntity) {
        if (entity?.pullsucc_tracking != null && entity?.pullsucc_tracking.size > 0) {
            for (i in 0 until entity.pullsucc_tracking?.size!!) {
                var newUrl =  entity.pullsucc_tracking!![i]
                apiClient(newUrl)
            }
        }

        val json = getJSON("pull_success")
        json.put("ad_model",entity?.slotName)
        json.put("ad_plantform",entity?.adPlatform?:"")
        json.put("code_id",entity?.codeId?:"")
        json.put("slot",entity?.actionName?:"")
        apiClient(json)
        if(!TextUtils.isEmpty(entity?.actionName)){
//            MobclickAgent.onEvent(AppliContext.get(), entity?.actionName, json.toString())
        }
    }

    //广告拉取失败
    fun onEventPullFail(entity: NewsEntity) {
        if (entity?.pullfail_tracking != null && entity?.pullfail_tracking.size > 0) {
            for (i in 0 until entity.pullfail_tracking?.size!!) {
                var newUrl =  entity.pullfail_tracking!![i]
                apiClient(newUrl)
            }
        }
        val json = getJSON("pull_fail")
        json.put("ad_model",entity.slotName)
        json.put("ad_plantform",entity?.adPlatform?:"")
        json.put("code_id",entity?.codeId?:"")
        json.put("slot",entity?.actionName?:"")
        apiClient(json)
        if(!TextUtils.isEmpty(entity?.actionName)){
//            MobclickAgent.onEvent(AppliContext.get(), entity?.actionName, json.toString())
        }
    }

    //广告展示完成  播放完成
    fun onEventComplete(entity: NewsEntity) {
        if (entity?.playcomplete_trackings != null && entity?.playcomplete_trackings.size > 0) {
            for (i in 0 until entity.playcomplete_trackings?.size!!) {
                var newUrl =  entity.playcomplete_trackings!![i]
                apiClient(newUrl)
            }
        }
        val json = getJSON("complete")
        json.put("ad_model",entity?.slotName)
        json.put("ad_plantform",entity?.adPlatform?:"")
        json.put("code_id",entity?.codeId?:"")
        json.put("slot",entity?.actionName?:"")
        apiClient(json)
        if(!TextUtils.isEmpty(entity?.actionName)){
//            MobclickAgent.onEvent(AppliContext.get(), entity?.actionName, json.toString())
        }
    }


    /**
     * {"event": "ad", "action": "click", "ad_model": "splash", "code_id": "58587854"}
     */
    fun onEventClick(entity: NewsEntity) {
        if (entity?.clk_tracking != null && entity?.clk_tracking.size > 0) {
            for (i in 0 until entity.clk_tracking?.size!!) {
                var newUrl =  entity.clk_tracking!![i]
                apiClient(newUrl)
            }
        }
        val json = getJSON("click")
        json.put("ad_model",entity?.slotName)
        json.put("ad_plantform",entity?.adPlatform?:"")
        json.put("code_id",entity?.codeId?:"")
        json.put("slot",entity?.actionName?:"")
        apiClient(json)
        if(!TextUtils.isEmpty(entity?.actionName)){
//            MobclickAgent.onEvent(AppliContext.get(), entity?.actionName, json.toString())
        }
    }


    private fun apiClient(url: String?) {
        if (url != null && url != "") {
            try {
                EventApiClient.adApi.requestEvent(url).subscribeOn(Schedulers.io())
                    .subscribe(object : Observer<Any> {
                        override fun onComplete() {}
                        override fun onSubscribe(d: Disposable) {}
                        override fun onNext(t: Any) {}
                        override fun onError(e: Throwable) { onEventUM("zxad_report_fail", url) }})
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

    }

    //事件上报
    private fun apiClient(data: JSONObject) {
        val str = data.toString()
        val key = AESUtils.encrypt(str)
        try {
            EventApiClient.adApi.requestEvent("behavior", key).subscribeOn(Schedulers.io())
                .subscribe(object : Observer<Any> {
                    override fun onComplete() {}
                    override fun onSubscribe(d: Disposable) {}
                    override fun onNext(t: Any) {}
                    override fun onError(e: Throwable) {}
                })
        }catch (e:Exception){ }

    }



    //上报友盟
    fun onEventUM(action: String, value: String) {
//        MobclickAgent.onEvent(AppliContext.get(), action, value)
    }

}