package com.ym.library.net

import android.content.Context
import android.util.Log
import com.ym.commen.module.VideoEntity
import com.ym.library.module.NewsEntity
import com.ym.library.module.NovelEntity
import com.ym.library.module.ReportAd
import com.ym.library.utils.PhoneUtils
import io.reactivex.schedulers.Schedulers
import org.jetbrains.anko.doAsync
import java.lang.StringBuilder
import java.util.*
import kotlin.collections.ArrayList

/**
 * Created by gaoleichao on 2018/7/12.
 */
object AdUpload {

    var time: Long = 0
    fun onDeepLinkSuc(newsEntity: NovelEntity?) {
        if (newsEntity == null) {
            return
        }
        doAsync {
            if (!newsEntity.isDeeplinkSuc) {
                newsEntity.isDeeplinkSuc = true
                if (newsEntity?.deeplinkSucc != null && newsEntity?.deeplinkSucc?.size ?: 0 > 0) {
                    for (i in 0 until newsEntity?.deeplinkSucc?.size!!) {
                        var newUrl: String = PhoneUtils.replaceUrl(newsEntity?.deeplinkSucc!![i], newsEntity)
                        apiClient(newUrl, newsEntity, i, "")
                    }
                }
            }
        }
    }

    fun onDeepLinkSuc(newsEntity: NewsEntity?) {
        if (newsEntity == null) {
            return
        }
        doAsync {
            if (!newsEntity.isDeeplinkSuc) {
                newsEntity.isDeeplinkSuc = true
                if (newsEntity?.deeplinkSucc != null && newsEntity?.deeplinkSucc?.size ?: 0 > 0) {
                    for (i in 0 until newsEntity?.deeplinkSucc?.size!!) {
                        var newUrl: String = PhoneUtils.replaceUrl(newsEntity?.deeplinkSucc!![i], newsEntity)
                        apiClient(newUrl, null, i, "")
                    }
                }
            }
        }
    }

    fun onAdImpression(context: Context, entity: NovelEntity?) {
        if (entity == null) {
            return
        }
        doAsync {
            if (!entity?.isShow) {
                entity?.isShow = true
                if (entity?.imp_tracking != null && entity?.imp_tracking?.size ?: 0 > 0) {
                    for (i in 0 until entity?.imp_tracking?.size!!) {
                        var newUrl: String = PhoneUtils.replaceUrl(entity?.imp_tracking!![i], entity)
                        apiClient(newUrl, entity, i, "")
                    }
                }
            }
        }
    }

    fun onAdClick(newsEntity: NovelEntity?) {
        if (newsEntity == null) {
            return
        }
        doAsync {
            if (!newsEntity.isClick) {
                newsEntity.isClick = true
                if (newsEntity?.clk_tracking != null && newsEntity?.clk_tracking?.size ?: 0 > 0) {
                    for (i in 0 until newsEntity?.clk_tracking?.size!!) {
                        var newUrl: String = PhoneUtils.replaceUrl(newsEntity?.clk_tracking!![i], newsEntity)
                        apiClient(newUrl, newsEntity, i, "")
                    }
                }
            }
        }
    }

    fun onDownloadStart(data: NewsEntity?) {
        if (data == null) {
            return
        }
        doAsync {
            if (!data.isDowanload) {
                data.isDowanload = true
                data?.startDownload?.forEach {
                    apiClient(PhoneUtils.replaceUrl(it, data), null, 0, "")
                }
            }
        }
    }

    fun onDownloadEnd(data: NewsEntity?) {
        if (data == null) {
            return
        }
        doAsync {
            if (!data.isDowanloadSuc) {
                data.isDowanloadSuc = true
                data?.downloadSucc?.forEach {
                    apiClient(PhoneUtils.replaceUrl(it, data), null, 0, "")
                }
            }
        }
    }

    fun onInstallStart(data: NewsEntity?) {
        if (data == null) {
            return
        }
        doAsync {
            if (!data.isInstall) {
                data.isInstall = true
                data?.startInstall?.forEach {
                    apiClient(PhoneUtils.replaceUrl(it, data), null, 0, "")
                }
            }
        }
    }

    fun onAdImpression(entity: NewsEntity?) {
        if (entity == null) {
            return
        }
        doAsync {
            if (!entity?.isShow) {
                entity?.isShow = true
                if (entity?.imp_tracking != null && entity?.imp_tracking?.size ?: 0 > 0) {
                    for (i in 0 until entity?.imp_tracking?.size!!) {
                        Log.d("onAdImpression", "slotName:" + entity?.slot_id)
                        var newUrl: String = PhoneUtils.replaceUrl(entity?.imp_tracking!![i], entity)
                        apiClient(newUrl, null, i, "")
                    }
                }
            }
        }
    }

    fun onAdImpressionVideo(entity: VideoEntity?) {
        if (entity == null) {
            return
        }
        doAsync {
            if (!entity?.isShow) {
                entity?.isShow = true
                if (entity?.imp_tracking != null && entity?.imp_tracking?.size ?: 0 > 0) {
                    for (i in 0 until entity?.imp_tracking?.size!!) {
//                        Log.d("onAdImpression", "slotName:" + entity?.slot_id)
                        var newUrl: String = PhoneUtils.replaceUrl(entity?.imp_tracking!![i], entity)
                        apiClient(newUrl, null, i, "")
                    }
                }
            }
        }
    }

    fun onVideoImpression(entity: VideoEntity?) {
        if (entity == null) {
            return
        }
        doAsync {
            if (entity?.imp_tracking != null && entity?.imp_tracking?.size ?: 0 > 0) {
                for (i in 0 until entity?.imp_tracking?.size!!) {
                    var newUrl: String = entity?.imp_tracking!![i]
                    apiClient(newUrl, null, i, "")
                }
            }
        }
    }

    fun onVideoClick(newsEntity: VideoEntity?) {
        if (newsEntity == null) {
            return
        }
        doAsync {
            if (newsEntity?.clk_tracking != null && newsEntity?.clk_tracking?.size ?: 0 > 0) {
                for (i in 0 until newsEntity?.clk_tracking?.size!!) {
                    var newUrl: String = newsEntity?.clk_tracking!![i]
                    Log.d("glc", newUrl)
                    apiClient(newUrl, null, i, "")
                }
            }
        }
    }

    fun onVideoLike(newsEntity: VideoEntity?) {
        if (newsEntity == null) {
            return
        }
        doAsync {
            if (newsEntity?.like_tracking != null && newsEntity?.like_tracking?.size ?: 0 > 0) {
                for (i in 0 until newsEntity?.like_tracking?.size!!) {
                    var newUrl: String = newsEntity?.like_tracking!![i]
                    Log.d("glc", newUrl)
                    apiClient(newUrl, null, i, "")
                }
            }
        }
    }

    fun onAdClick(newsEntity: NewsEntity?) {
        if (newsEntity == null) {
            return
        }
        doAsync {
            if (!newsEntity.isClick) {
                newsEntity.isClick = true
                if (newsEntity?.clk_tracking != null && newsEntity?.clk_tracking?.size ?: 0 > 0) {
                    for (i in 0 until newsEntity?.clk_tracking?.size!!) {
                        var newUrl: String = PhoneUtils.replaceUrl(newsEntity?.clk_tracking!![i], newsEntity)
                        Log.d("glc", newUrl)
                        apiClient(newUrl, null, i, "")
                    }
                }
            }
        }
    }

    fun onAdtrack(data: List<String>?) {
        if (data == null) {
            return
        }
        val list: MutableList<String> = ArrayList()
        list.addAll(data)
        list?.forEach {
            Log.d("InstalledReceiver", "onAdtrack")
            apiClient(it, null, 0, "")
        }
    }


}

fun onDeepClick(entity: NovelEntity) {
//        doAsync {
//            var list: MutableList<ReportAd> = ArrayList()
//            list.add(ReportAd(ReportAd.DEEPCLICK, entity.slot_id
//                    ?: "", entity.sid.toString(), 3, System.currentTimeMillis().toString()))
//
//            AdClient.apiAdInfoApi.uploadAd(list).subscribeOn(Schedulers.io()).subscribe(object : BaseAdOberver<Response<Any>>() {
//                override fun onSuccess(result: Response<Any>?) {
//                }
//
//                override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
//                }
//            })
//        }
}

fun onDownload(entity: NovelEntity) {
    var list: MutableList<ReportAd> = ArrayList()
    list.add(
        ReportAd(
            ReportAd.DOWNLOAD, entity.slot_id
                ?: "", entity.sid.toString(), 3, System.currentTimeMillis().toString()
        )
    )

//        AdClient.apiAdInfoApi.uploadAd(list).subscribeOn(Schedulers.io()).subscribe(object : BaseAdOberver<Response<Any>>() {
//            override fun onSuccess(result: Response<Any>?) {
//            }
//
//            override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
//            }
//        })
}

fun onInstall(entity: NovelEntity) {
    var list: MutableList<ReportAd> = ArrayList()
    list.add(
        ReportAd(
            ReportAd.INSTALL, entity.slot_id
                ?: "", entity.sid.toString(), 3, System.currentTimeMillis().toString()
        )
    )

//        AdClient.apiAdInfoApi.uploadAd(list).subscribeOn(Schedulers.io()).subscribe(object : BaseAdOberver<Response<Any>>() {
//            override fun onSuccess(result: Response<Any>?) {
//            }
//
//            override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
//            }
//        })
}

fun onVideoImp(entity: NovelEntity) {
    var list: List<String> = entity?.showFromFeed!!
    var showParams: MutableMap<String, String> = sortMapByKey(entity?.showParams!!)!!//按照key排序参数

    if (list.isNotEmpty() && showParams.isNotEmpty()) {
        for (feed: String in list) {
            var url = getUrl(feed, showParams, entity.tab_id);

//                AdClient.apiAdInfoApi.showAd(url).subscribeOn(Schedulers.io()).subscribe(object : BaseAdOberver<Any>() {
//                    override fun onSuccess(result: Any?) {
//                    }
//
//                    override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
//                        EventUtils.onAdTrackiError(entity?.slot_id
//                                ?: "", entity?.sid.toString(), entity?.type.toString(), EventUtils.AD_SHOW, url, entity?.reqId
//                                ?: "")
//                    }
//                })
        }
    }
}

fun onVideoClick(entity: NovelEntity?) {
    var list: List<String> = entity?.playFromFeed!!
    var playParams: MutableMap<String, String> = sortMapByKey(entity?.playParams!!)!!//按照key排序参数

    if (list.isNotEmpty() && playParams.isNotEmpty()) {
        for (feed: String in list) {
            var url = getUrl(feed, playParams, entity.tab_id);

//                AdClient.apiAdInfoApi.showAd(url).subscribeOn(Schedulers.io()).subscribe(object : BaseAdOberver<Any>() {
//                    override fun onSuccess(result: Any?) {
//                    }
//
//                    override fun onFailure(e: Throwable?, code: String?, errorMsg: String?) {
//                        EventUtils.onAdTrackiError(entity?.slot_id
//                                ?: "", entity?.sid.toString(), entity?.type.toString(), EventUtils.AD_CLICK, url, entity?.reqId
//                                ?: "")
//                    }
//                })
        }
    }

}

/**
 * 使用 Map按key进行排序
 * @param map
 * @return
 */
fun sortMapByKey(map: MutableMap<String, String>?): MutableMap<String, String>? {
    if (map == null || map.isEmpty()) {
        return null
    }

    val sortMap = TreeMap<String, String>(
        MapKeyComparator()
    )
    sortMap.putAll(map)

    return sortMap
}

fun getUrl(feed: String?, map: MutableMap<String, String>?, tab_id: String): String {
    var random1: String = "13149876"
    var random2: String = "98761314"

    var mStringBuilder: StringBuilder = StringBuilder();//拼接m报文
    mStringBuilder.append("${random1}")

    var requestBuilder: StringBuilder = StringBuilder();//拼接请求地址
    requestBuilder.append(feed)
    requestBuilder.append("?")
    for ((k, v) in map!!) {//替换参数信息
        if (v.contains("__TAB_ID__")) {
            map!![k] = v.replace("__TAB_ID__", tab_id)
        } else if (v.contains("__UTC_TS__")) {
            map!![k] = v.replace("__UTC_TS__", System.currentTimeMillis().toString())
        }
    }

    var i: Int = 1
    for ((k, v) in map!!) {
        if (i == 1) {
            requestBuilder.append(k + "=" + v)
        } else {
            requestBuilder.append("&" + k + "=" + v)
        }
        mStringBuilder.append(k + "=" + v)
        i++
    }
    mStringBuilder.append("${random2}")

//        var mMd5 = Md5Util.encode(mStringBuilder.toString())

//        requestBuilder.append("&m=" + mMd5)

    return requestBuilder.toString()
}


private fun apiClient(url: String, entity: NovelEntity?, index: Int, clickOrShow: String) {
    ZXADClient.adApi.showAd(url).subscribeOn(Schedulers.io()).subscribe(object : BaseAdOberver<Any>() {
        override fun onSuccess(result: Any) {

        }

        override fun onFailure(e: Throwable, code: String, errorMsg: String?) {
//                entity?.trackFailIndex.add(index)
//                if (errorMsg?.contains("请求被重定向到其他页面") == false) {
//                    EventUtils.onAdTrackiError(entity?.slot_id
//                            ?: "", entity?.sid.toString(), entity?.type.toString(), clickOrShow, url, entity?.reqId
//                            ?: "")
//                }
        }

    })
}



