package com.ydl.ydlcommon.utils.log

import com.aliyun.sls.android.producer.*
import com.apm.insight.log.VLog
import com.ydl.ydlcommon.base.BaseApp.Companion.getApp
import com.ydl.ydlcommon.data.PlatformDataManager.getRam
import com.ydl.ydlcommon.modular.ModularServiceManager.getPlatformUserService
import com.yidianling.common.tools.RxAppTool
import com.yidianling.common.tools.RxDeviceTool

/**
 * @author liupeng
 *
 * 阿里云埋点，携带基本参数，方便后续排查问题定位
 * */
class AliYunRichLogsHelper {
    companion object {
        var mConfig: LogProducerConfig? = null
        var mClient: LogProducerClient? = null
        fun getInstance(): AliYunRichLogsHelper {
            return Holder.INSTANCE
        }
    }

    constructor() {
        val endpoint = "cn-hangzhou.log.aliyuncs.com"
        val project = "ydl-app-log"
        val logstore = "ydl-app-log"
        val accesskeyid = "LTAI5tH6WGqWUqzo4u5GfrCS"
        val accesskeysecret = "uzccm79mr9d4rIsABu3xwfbdUdaeWT"
        try {
            mConfig = LogProducerConfig(endpoint, project, logstore, accesskeyid, accesskeysecret)
            mClient = LogProducerClient(mConfig)
        } catch (e: LogProducerException) {
            e.printStackTrace()
        }
    }

    private object Holder {
        val INSTANCE = AliYunRichLogsHelper()
    }

    /**
     *
     * @param key AliYunLogConfig 接口、登录、声网、WebView、支付、其他
     * @param value 具体的状态值
     * */
    fun sendRichLog(key: String, value: String) {
        VLog.i(key, value)
        val log = Log()
        val userInfo = getPlatformUserService()!!.getUser()

        log.putContent(key, value)
        log.putContent("ffrom", getRam().getChannelName())
        log.putContent("isFromApp", "1")
        log.putContent("osBuild", RxDeviceTool.getBuildBrandModel())
        log.putContent(RxDeviceTool.getSDKVersionName(), RxAppTool.getAppVersionName(getApp()))
        log.putContent("version", RxAppTool.getAppVersionName(getApp()))
        if (null != userInfo) {
            log.putContent("uid", userInfo.userId)
            log.putContent("accessToken", userInfo.token)
        }

        if (mClient != null) {
            val res: LogProducerResult = mClient!!.addLog(log)
        }
    }

    /**
     *
     * @param key AliYunLogConfig 接口、登录、声网、WebView、支付、其他
     * @param value 具体的状态值
     * */
    fun sendLog(key: String, value: String) {
        val log = Log()
        log.putContent(key, value)
        if (mClient != null) {
            val res: LogProducerResult = mClient!!.addLog(log)
        }
    }
}