package com.ym.library.utils


import android.app.Activity
import android.util.Log
import com.umeng.analytics.MobclickAgent
import com.ym.admodule.config.AdManager
import com.ym.admodule.config.ZXADSizeConfig
import com.ym.library.module.NewsEntity
import com.ym.library.module.StatusEntity
import com.ym.library.net.*
import com.ym.modulecommon.AppliContext
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 EventUtils {


    val EVENT = "guazinovel"
    val ACTION_RECOMMENDLIST = "recommendList"
    val ACTION_SEARCH = "search_data"
    val ACTION_CHANNELCLICK = "channelChange"
    val ACTION_GENDER = "gender"
    val MODEL_BEHAVIOR = "behavior"
    val ACTION_TAB_SWITCH = "tab_imp"
    val ACTION_AD_HOME = "ad_home"
    val ACTION_AD_COLLECT = "ad_collect"

    val ACTION_LOGIN = "clickLogin"

    val ACTION_CLICK_RANKING_LIST = "clickRankingList"//排行榜
    val ACTION_CLICK_CLASSFICATION = "clickClassification"//分类
    val ACTION_CLICK_LOOK = "clickLook"//抢先看
    val ACTION_CLICK_END = "clickEnd"//完结

    val ACTION_CLICK_RECOMMEND = "clickRecommend"//推荐
    val ACTION_CLICK_BOY = "clickBoy"//男频
    val ACTION_CLICK_GIRL = "clickGirl"//女频
    val ACTION_CLICK_NEW_BOOK = "clickNewBook"//爆品新书

    val ACTION_PAGE_STAY = "pageStay"//进入页面停留时间
    val EVENT_APP_LIST = "applist"


    val BOOKRACK_CLICK = "bookrack_click"//进入页面停留时间
    val DOUBLE_DONG_CLICK = "dongdong_click"//进入动动页面停留时间
    val INFORMATION_CLICK = "informain_click"//进入页面停留时间
    val TASK_CLICK = "task_click"//进入页面停留时间
    val LOOK_CLICK = "look_click"//进入页面停留时间
    val TEAM_CLICK = "team_click"//进入页面停留时间
    val USER_CLICK = "user_click"//进入页面停留时间
    val ZHUAN_CLICK = "zhuanpan_click"//进入页面停留时间
    val SHAVE_CLICK = "shave_click"//进入页面停留时间

    val INFORMATION_NEWS = "information_news"//进入页面停留时间
    val INFORMATION_VIDEO = "information_video"//进入页面停留时间
    val BUBBLE_CLICK = "bubble_click"//进入页面停留时间
    val HELP_CLICK = "help_click"//进入页面停留时间
    val QUICK_DRAW_CLICK = "quick_draw_click"//进入页面停留时间
    val HOME_HEALTH_CLICK = "home_health_click"//进入页面停留时间
    val HOME_DONGDONG_CLICK = "home_dongdong_click"//进入页面停留时间


    fun onEvent(action: String) {
        val jsonObj = getJSON(action)
        apiClient(jsonObj)
        MobclickAgent.onEvent(AppliContext.get(), action)
    }

    fun onEvent(action: String, value: String) {
        val jsonObj = getJSON(action)
        jsonObj.put("value", value)
        apiClient(jsonObj)
        MobclickAgent.onEvent(AppliContext.get(), action, value)
    }
    //广告成功展示
    fun onEventShow(entity: NewsEntity) {
        if (entity?.imp_tracking != null && entity?.imp_tracking.size >0) {
            apiClient(entity?.imp_tracking[0])
        }
    }
    //广告展示失败  渲染失败
    fun onEventShowFail(entity: NewsEntity) {
        if (entity?.showfail_tracking != null && entity?.showfail_tracking.size >0) {
            apiClient(entity?.showfail_tracking[0])
        }
    }
    //广告拉取成功
    fun onEventPullSuccess(entity: NewsEntity) {
        Log.d("EventUtils", "拉取成功： ")
        if (entity?.pullsucc_tracking != null && entity?.pullsucc_tracking.size >0) {
            apiClient(entity?.pullsucc_tracking[0])
        }
    }

    //广告拉取失败
    fun onEventPullFail(entity: NewsEntity) {
        Log.d("EventUtils", "拉取失败： ")
        if (entity?.pullfail_tracking != null && entity?.pullfail_tracking.size >0) {
            apiClient(entity?.pullfail_tracking[0])
        }
    }
    //广告点击
    fun onEventClick(entity: NewsEntity) {
        if (entity?.clk_tracking != null && entity?.clk_tracking.size >0) {
            apiClient(entity?.clk_tracking[0])
        }
    }


    fun onEventUM(action: String, value: String) {
        MobclickAgent.onEvent(AppliContext.get(), action, value)
    }
    fun onVideoEvent(action: String, id: String?, viewTime: Int, value: String) {
        val jsonObj = getJSON(action)
        jsonObj.put("viewTime", viewTime)
        jsonObj.put("videoId", id)
        apiClient(jsonObj)
        MobclickAgent.onEvent(AppliContext.get(), action, value)
    }

    /**
     * 用户点击按钮
     */
    fun onClick(text: String) {
        val jsonObj = getJSON(getAction(text))
        apiClient(jsonObj)

    }

    private fun getAction(text: String): String {
        var action: String = ""
        when (text) {
            "排行榜" -> {
                action = ACTION_CLICK_RANKING_LIST
            }
            "分类" -> {
                action = ACTION_CLICK_CLASSFICATION
            }
            "抢先看" -> {
                action = ACTION_CLICK_LOOK
            }
            "完结" -> {
                action = ACTION_CLICK_END
            }
            "推荐" -> {
                action = ACTION_CLICK_RECOMMEND
            }
            "男频" -> {
                action = ACTION_CLICK_BOY
            }
            "女频" -> {
                action = ACTION_CLICK_GIRL
            }
            "爆品新书" -> {
                action = ACTION_CLICK_NEW_BOOK
            }
        }
        println("getAction:$text")
//        MobclickAgent.onEvent(AppliContext.get(), action, text)
        return action
    }


    //    /**
//     * 统计新用户首次登陆  男女生
//     */
//    fun genderClickJson(gender: String): JSONObject {
//        val jsonObj = JSONObject()
//        jsonObj.put("gender", gender)
//        return jsonObj
//    }
    private var time: Long = 0

    fun starPageTime(page: String, start: String, session: String, bookName: String) {
        time = System.currentTimeMillis()
        val jsonObj = getJSON(ACTION_PAGE_STAY)
        jsonObj.put("page", page)
        jsonObj.put("start", start)
        jsonObj.put("session", session)
        jsonObj.put("bookName", bookName)
        apiClient(jsonObj)

//    MobclickAgent.onEvent(AppliContext.get(), ACTION_PAGE_STAY, jsonObj.toString())
    }


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

    private fun apiClient(data: JSONObject) {
        val str = data.toString()
        Log.d("EventUtils", str)
        val key = AESUtils.encrypt(str)
        Log.d("EventUtils", key)
        EventApiClient.cfgApi.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) {
                }
            })
    }

    fun apiClient(url: String?) {
        Log.d("EventUtils", "url =" + url)
        if (url != null && url != "") {
            try {
                EventApiClient.cfgApi.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()
            }
        }

    }

    fun onShare(type: Int) {
        Log.d("onShare", "onShare:----------" + type)
        val TYPE_QQ = 1
        val TYPE_WX = 2
        val TYPE_PYQ = 3
        val TYPE_QZONE = 4
        var text = ""
        when (type) {
            TYPE_QQ -> {
                text = "QQ好友"
            }
            TYPE_WX -> {
                text = "微信好友"
            }
            TYPE_PYQ -> {
                text = "微信朋友圈"
            }
            TYPE_QZONE -> {
                text = "QQ空间"
            }

        }
        onEvent("share", text)
    }
//    fun onAppUpload(context: Context) {
//        doAsync {
//            apiAppUpload(MODEL_BEHAVIOR, EVENT_APP_LIST, appListJson(context))
//        }
//    }
//    private fun appListJson(context: Context): JSONObject {
//        val jsonObj = JSONObject()
//        jsonObj.put("data", Utils.obj2Str(getAppList(context)))
//        return jsonObj
//    }
//
//    fun getAppList(context: Context): List<AppInfo> {
//        val list = ArrayList<AppInfo>()
//        val pm = context.applicationContext.packageManager
//        val pList = pm.getInstalledPackages(0)
//        for (i in pList) {
//            val app = AppInfo()
//            app.pkg = i.packageName
//            app.vn = i.versionName
//            app.vc = i.versionCode
//            app.install_time = i.firstInstallTime?.toString()
//            app.update_time = i.lastUpdateTime?.toString()
//            list.add(app)
//        }
//        return list
//    }

    fun apiAppUpload(module: String, event: String, data: JSONObject) {
        data.put("event", event)
        val str = data.toString()
        LogUtils.d("EventUtils", str)
        val key = AESUtils.encrypt(str)
        LogUtils.d("EventUtils", key)
        EventApiClient.cfgApi.requestEvent(module, 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) {
                }
            })
    }
}