//
//  MVThirdApiUtil.swift
//  MusicVideoPlus
//
//  Created by SanW on 2021/6/5.
//

import BFFramework
import Bugly
import UIKit

// MARK: - 友盟相关工具类

/// 友盟相关工具类
class MVThirdApiUtil: NSObject {
    // 注册
    class func registerBugly() {
        // 注册bugly
        let buglyConfig = BuglyConfig()
        buglyConfig.reportLogLevel = .warn
        #if DEBUG
            buglyConfig.version = versionName + ".6666"
        #else
            if PQENVUtil.shared.envMode == .ENVModeOnline {
                buglyConfig.version = versionName + "." + versionCode
            } else if PQENVUtil.shared.envMode == .ENVModePre {
                buglyConfig.version = versionName + ".8888"
            } else {
                buglyConfig.version = versionName + ".9999"
            }
        #endif
        buglyConfig.channel = PQBFConfig.shared.channelID
        buglyConfig.deviceIdentifier = BFLoginUserInfo.shared.isLogin() ? BFLoginUserInfo.shared.uid : getMachineCode()
        buglyConfig.unexpectedTerminatingDetectionEnable = true
        buglyConfig.blockMonitorEnable = true
        buglyConfig.blockMonitorTimeout = 2
        Bugly.start(withAppId: PQBFConfig.shared.buglyAppkey, config: buglyConfig)
    }

    class func registerUM() {
        // 注册友盟
        UMConfigure.setEncryptEnabled(true)
        // 初始化友盟所有组件产品
        UMConfigure.initWithAppkey(PQBFConfig.shared.umAppkey, channel: PQBFConfig.shared.channelID)
        #if DEBUG
            UMConfigure.setLogEnabled(true)
        #endif
        BFLog(message: "友盟版本号：\(UMConfigure.version())")
    }

    /// 页面时长统计
    /// - Parameters:
    ///   - pageName: 页面名称
    ///   - isBegin: 开始/结束
    /// - Returns: <#description#>
    class func pageAutoTimeAnalytics(pageName: String?, isBegin: Bool) {
        if pageName == nil || pageName?.count ?? 0 <= 0 {
            return
        }
        BFLog(message: "页面时长统计：isBegin = \(isBegin),pageName = \(pageName ?? "")")
        if isBegin {
            MobClick.beginLogPageView(pageName)
        } else {
            MobClick.endLogPageView(pageName)
        }
    }

    /// 事件统计
    /// - Parameters:
    ///   - eventId: 事件ID
    ///   - attributes: 事件属性
    /// - Returns: <#description#>
    class func eventAnalytics(eventId: String?, attributes: [String: Any]?) {
        if eventId == nil || eventId?.count ?? 0 <= 0 {
            return
        }
        BFLog(message: "自定义事件统计：eventId = \(eventId ?? ""),attributes = \(attributes ?? [:])")
        if attributes != nil && attributes?.count ?? 0 > 0 {
            MobClick.event(eventId!, attributes: attributes!)
        } else {
            MobClick.event(eventId!)
        }
    }

    /// 账号统计
    /// - Returns: <#description#>
    class func accountAnalytics() {
        if BFLoginUserInfo.shared.accessToken.count > 0 {
            MobClick.profileSignIn(withPUID: BFLoginUserInfo.shared.accessToken, provider: cPrimarykey)
        } else {
            MobClick.profileSignOff()
        }
    }
}
