
//
//  PQVideoPlayer.swift
//  PQSpeed
//
//  Created by SanW on 2020/6/3.
//  Copyright © 2020 BytesFlow. All rights reserved.
//

import BFAnalyzeKit
import BFCommonKit
import BFUploadKit
import UIKit

public class PQSingletoVideoPlayer: NSObject {
    public static let shared = PQSingletoVideoPlayer()
    public var isPlayEnd: Bool = false // 是否已播放完成
    public var isHomePageAllList: Bool = false // 首页加入/关注是否是全部列表
    public var lastPlaybackTime: Float = 0 // 上次上报播放时长
    public var isRealPlay: Bool = false // 是否已真实播放
    public var isSemiRealPlay: Bool = false // 是否已播放到十秒
    public var isPlayBegin: Bool = false // 是否已缓冲完成开始播放
    public var isFirstFrame: Bool = false // 是否已显示第一帧加载完成
    public var isPlayerError: Bool = false // 是否播放失败
    public var loadingTime: TimeInterval = 0 // 加载时长
    public var playId: String = getUniqueId(desc: "playId") // 播放ID
    /// 进度回调
    public var progressBloc: ((_ loadProgress: Float, _ playProgress: Float, _ duration: Float) -> Void)?
    /// 播放状态回调
    public var playStatusBloc: ((_ playStatus: PQVIDEO_PLAY_STATUS) -> Void)?
    public var playControllerView: UIView?
    public var playVideoData: BFVideoItemProtocol?
    public var isPlaying: Bool {
        return player.isPlaying()
    }

    public var autoResumePlayWhenEnterForeground: Bool = true
    var shouldResumePlayWhenEnterForeground: Bool = false

    public lazy var player: TXVodPlayer = {
        let player = TXVodPlayer()
        let config = TXVodPlayConfig()
        config.cacheFolderPath = videoCacheDirectory
        config.maxCacheItems = 5
        player.config = config
        player.vodDelegate = self
        player.setRenderMode(.RENDER_MODE_FILL_SCREEN)
        return player
    }()

    /// 配置播放器
    /// - Parameters:
    ///   - videoData: <#videoData description#>
    ///   - controllerView: <#controllerView description#>
    public func configPlyer(videoData: BFVideoItemProtocol, controllerView: UIView, renderMode: TX_Enum_Type_RenderMode = .RENDER_MODE_FILL_SCREEN, isAllList: Bool = false) {
//        if playVideoData?.id == videoData.id {
//            return
//        }
        isHomePageAllList = isAllList
        isPlayEnd = false
        isRealPlay = false
        isSemiRealPlay = false
        isPlayBegin = false
        isFirstFrame = false
        isPlayerError = false
        loadingTime = Date().timeIntervalSince1970 * 1000
        player.setRenderMode(renderMode)
        player.stopPlay()
        player.removeVideoWidget()
        player.setupVideoWidget(controllerView, insert: 0)
        player.enableHWAcceleration = true
        playControllerView = controllerView
        playVideoData = videoData
        if playVideoData!.playProgress >= 0.0 {
            var progress: CGFloat = CGFloat(playVideoData!.playProgress)
            if progress > 5.0, progress < 20 {
                progress = progress - 5.0
                if progress <= 0 {
                    progress = 0
                }
            }
            BFLog(message: "xxx.playProgress =\(playVideoData!.playProgress),\(progress)")
            player.setStartTime(progress)
        }
        playId = getUniqueId(desc: "playId")
        lastPlaybackTime = 0
        BFLog(message: "\(String(describing: videoData.title)) 开始播放 \(videoData.videoPath ?? "")")
        if PQSingletoMemoryUtil.shared.playCount < 4 {
            PQSingletoMemoryUtil.shared.playCount = PQSingletoMemoryUtil.shared.playCount + 1
        }
    }

    public func reRenderView(newView: UIView) {
        player.removeVideoWidget()
        player.setupVideoWidget(newView, insert: 0)
    }

    /// 重制播放
    public func resetPlayer() {
        if playControllerView != nil {
            let playDuration = player.currentPlaybackTime() - lastPlaybackTime
            debugPrint("当前播放时长:\(player.currentPlaybackTime()),lastPlaybackTime:\(lastPlaybackTime),playDuration:\(playDuration)")
            if playDuration > 0 {
                var extParams: [String: Any]?
                if playVideoData?.pageSource == .sp_cmunit_joinTopic {
                    extParams = ["topicId": isHomePageAllList ? "all" : "\(playVideoData?.topicData?["id"] ?? "")"]
                } else if playVideoData?.pageSource == .sp_cmunit_follow {
                    extParams = ["followedUid": isHomePageAllList ? "all" : "\(playVideoData?.user?["uid"] ?? "")"]
                } else if playVideoData?.pageSource == .sp_cmunit_newTopicDetail || playVideoData?.pageSource == .sp_cmunit_hotTopicDetail {
                    extParams = ["topicId": "\(playVideoData?.topicData?["id"] ?? "")"]
                }
                BFEventTrackAdaptor.baseReportUpload(logType: .st_log_type_pLayaction, businessType: .bt_videoPlayDuration, objectType: nil, pageSource: playVideoData?.pageSource ?? .sp_cmunit_recommend, eventData: ["pageSource": (playVideoData?.pageSource ?? .sp_cmunit_recommend).rawValue, "playDuration": Int64(playDuration * 1000), "playId": playId, "uid": "\(playVideoData?.user?["uid"] ?? "")", "videoId": playVideoData?.id ?? 0], extParams: extParams, commonParams: commonParams())
                lastPlaybackTime = player.currentPlaybackTime()
            }
            player.removeVideoWidget()
            player.setupVideoWidget(playControllerView, insert: 0)
            if playVideoData!.playProgress >= 0.0 {
                //
                var progress: CGFloat = CGFloat(playVideoData!.playProgress)
                if progress > 5.0, progress < 20 {
                    progress = progress - 5.0
                    if progress <= 0 {
                        progress = 0
                    }
                }
                BFLog(message: "xxx.playProgress =\(playVideoData!.playProgress),\(progress)")
                player.setStartTime(progress)
            }
            playId = getUniqueId(desc: "playId")
            // 开始播放
            if let vc = bf_getCurrentViewController(), let playview = playControllerView {
                if playview.isDescendant(of: vc.view) {
                    startPlayr()
                }
            }
        }
    }

    /// 开始播放
    public func startPlayr() {
        BFLog(message: "开始播放 \(playVideoData?.videoPath ?? "")")
        if isValidURL(url: playVideoData?.videoPath) {
            player.startPlay(playVideoData?.videoPath)
        }
    }

    /// 暂停播放
    public func pausePlayer() {
        player.pause()
        let playDuration = player.currentPlaybackTime() - lastPlaybackTime
        debugPrint("当前播放时长:\(player.currentPlaybackTime()),lastPlaybackTime:\(lastPlaybackTime),playDuration:\(playDuration)")
        if playDuration > 0 {
            var extParams: [String: Any]?
            if playVideoData?.pageSource == .sp_cmunit_joinTopic {
                extParams = ["topicId": isHomePageAllList ? "all" : "\(playVideoData?.topicData?["id"] ?? "")"]
            } else if playVideoData?.pageSource == .sp_cmunit_follow {
                extParams = ["followedUid": isHomePageAllList ? "all" : "\(playVideoData?.user?["uid"] ?? "")"]
            } else if playVideoData?.pageSource == .sp_cmunit_newTopicDetail || playVideoData?.pageSource == .sp_cmunit_hotTopicDetail {
                extParams = ["topicId": "\(playVideoData?.topicData?["id"] ?? "")"]
            }
            BFEventTrackAdaptor.baseReportUpload(logType: .st_log_type_pLayaction, businessType: .bt_videoPlayDuration, objectType: nil, pageSource: playVideoData?.pageSource ?? .sp_cmunit_recommend, eventData: ["pageSource": (playVideoData?.pageSource ?? .sp_cmunit_recommend).rawValue, "playDuration": Int64(playDuration * 1000), "playId": playId, "uid": "\(playVideoData?.user?["uid"] ?? "")", "videoId": playVideoData?.id ?? 0], extParams: extParams, commonParams: commonParams())
            lastPlaybackTime = player.currentPlaybackTime()
        }
    }

    /// 继续播放
    public func resumePlayer(renderMode: TX_Enum_Type_RenderMode? = nil) {
        player.resume()
        if renderMode != nil {
            player.setRenderMode(renderMode!)
        }
        let playDuration = player.currentPlaybackTime() - lastPlaybackTime
        debugPrint("当前播放时长:\(player.currentPlaybackTime()),lastPlaybackTime:\(lastPlaybackTime),playDuration:\(playDuration)")
        if playDuration > 0 {
            var extParams: [String: Any]?
            if playVideoData?.pageSource == .sp_cmunit_joinTopic {
                extParams = ["topicId": isHomePageAllList ? "all" : "\(playVideoData?.topicData?["id"] ?? "")"]
            } else if playVideoData?.pageSource == .sp_cmunit_follow {
                extParams = ["followedUid": isHomePageAllList ? "all" : "\(playVideoData?.user?["uid"] ?? "")"]
            } else if playVideoData?.pageSource == .sp_cmunit_newTopicDetail || playVideoData?.pageSource == .sp_cmunit_hotTopicDetail {
                extParams = ["topicId": "\(playVideoData?.topicData?["id"] ?? "")"]
            }
            BFEventTrackAdaptor.baseReportUpload(logType: .st_log_type_pLayaction, businessType: .bt_videoPlayDuration, objectType: nil, pageSource: playVideoData?.pageSource ?? .sp_cmunit_recommend, eventData: ["pageSource": (playVideoData?.pageSource ?? .sp_cmunit_recommend).rawValue, "playDuration": Int64(playDuration * 1000), "playId": playId, "uid": "\(playVideoData?.user?["uid"] ?? "")", "videoId": playVideoData?.id ?? 0], extParams: extParams, commonParams: commonParams())
            lastPlaybackTime = player.currentPlaybackTime()
        }
    }

    /// 停止播放
    /// - Parameter isRemove: 是否移除载体视图
    public func stopPlayer(isRemove: Bool = true) {
        player.stopPlay()
        if isRemove {
            player.removeVideoWidget()
            playControllerView = nil
            playVideoData = nil
        }
        let playDuration = player.currentPlaybackTime() - lastPlaybackTime
        debugPrint("当前播放时长:\(player.currentPlaybackTime()),lastPlaybackTime:\(lastPlaybackTime),playDuration:\(playDuration)")
        if playDuration > 0 {
            var extParams: [String: Any]?
            if playVideoData?.pageSource == .sp_cmunit_joinTopic {
                extParams = ["topicId": isHomePageAllList ? "all" : "\(playVideoData?.topicData?["id"] ?? "")"]
            } else if playVideoData?.pageSource == .sp_cmunit_follow {
                extParams = ["followedUid": isHomePageAllList ? "all" : "\(playVideoData?.user?["uid"] ?? "")"]
            } else if playVideoData?.pageSource == .sp_cmunit_newTopicDetail || playVideoData?.pageSource == .sp_cmunit_hotTopicDetail {
                extParams = ["topicId": "\(playVideoData?.topicData?["id"] ?? "")"]
            }
            BFEventTrackAdaptor.baseReportUpload(logType: .st_log_type_pLayaction, businessType: .bt_videoPlayDuration, objectType: nil, pageSource: playVideoData?.pageSource ?? .sp_cmunit_recommend, eventData: ["pageSource": (playVideoData?.pageSource ?? .sp_cmunit_recommend).rawValue, "playDuration": Int64(playDuration * 1000), "playId": playId, "uid": "\(playVideoData?.user?["uid"] ?? "")", "videoId": playVideoData?.id ?? 0], extParams: extParams, commonParams: commonParams())
            lastPlaybackTime = player.currentPlaybackTime()
        }
    }

    /// seek
    /// - Parameter time: <#time description#>
    public func seek(time: Float) {
        player.seek(time)
    }

    override private init() {
        super.init()

        NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: nil) { _ in
            if self.isPlaying {
                self.pausePlayer()
                self.shouldResumePlayWhenEnterForeground = true
            }
        }
        NotificationCenter.default.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: nil) { _ in

            if self.autoResumePlayWhenEnterForeground, self.shouldResumePlayWhenEnterForeground {
                if let vc = bf_getCurrentViewController(), let playview = self.playControllerView {
                    if playview.isDescendant(of: vc.view) {
                        self.shouldResumePlayWhenEnterForeground = false
                        self.resumePlayer()
                    }
                }
            }
        }
    }

    override public func copy() -> Any {
        return self
    }

    override public func mutableCopy() -> Any {
        return self
    }
}

extension PQSingletoVideoPlayer: TXVodPlayListener {
    /// 播放进度回调
    /// - Parameters:
    ///   - player: <#player description#>
    ///   - EvtID: <#EvtID description#>
    ///   - param: <#param description#>
    public func onPlayEvent(_ player: TXVodPlayer!, event: Int32, withParam param: [AnyHashable: Any]!) {
        if event != PLAY_EVT_PLAY_PROGRESS.rawValue {
            BFLog(message: "播放器状态回调：event:\(event),status:\(EventID(event)),param:\(param ?? [:])")
        }
        switch event {
        case PLAY_EVT_PLAY_PROGRESS.rawValue: // 播放进度
            // 加载进度, 单位是秒
            let loadProgress: Float = param[EVT_PLAYABLE_DURATION] as! Float
            // 播放进度, 单位是秒
            let playProgress: Float = param[EVT_PLAY_PROGRESS] as! Float
            // 总长度, 单位是秒
            let duration: Float = param[EVT_PLAY_DURATION] as! Float
            if player.currentPlaybackTime() >= 10.0, player.currentPlaybackTime() <= 10.1 {
                // 10.0上报
                if !isSemiRealPlay, playVideoData != nil {
                    isSemiRealPlay = true
                    // 播放上报
                    var extParams: [String: Any]?
                    if isHomePageAllList {
                        if playVideoData?.pageSource == .sp_cmunit_joinTopic {
                            extParams = ["topicId": "all"]
                        } else if playVideoData?.pageSource == .sp_cmunit_follow {
                            extParams = ["followedUid": "all"]
                        }
                    }
                    BFEventTrackAdaptor.videoRelationReportUpload(reportLogType: .reportLogType_Action, videoData: playVideoData, pageSource: nil, businessType: .bt_videoSemiRealPlay, objectType: nil, extParams: extParams, shareId: nil, videoIds: nil, playId: playId, headVideoId: (playVideoData as? PQVideoListModel)?.headVideoId, projectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.projectId ?? "", parentProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentProjectId ?? "", rootProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.rootProjectId ?? "", canProduce: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.canReproduce ?? 0, parentVideoId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentVideoId ?? "", commonParams: commonParams())
                }
            }
            if player.currentPlaybackTime() >= 20.0 || ((playProgress / duration) >= 0.3) {
                // 视频播放到20s或播放到总时长30%，哪个先到为准
                if !isRealPlay, playVideoData != nil {
                    isRealPlay = true
                    // 播放上报
                    var extParams: [String: Any]?
                    if isHomePageAllList {
                        if playVideoData?.pageSource == .sp_cmunit_joinTopic {
                            extParams = ["topicId": "all"]
                        } else if playVideoData?.pageSource == .sp_cmunit_follow {
                            extParams = ["followedUid": "all"]
                        }
                    }
                    BFEventTrackAdaptor.videoRelationReportUpload(reportLogType: .reportLogType_realPlay, videoData: playVideoData, pageSource: nil, businessType: .bt_videoRealPlay, objectType: nil, extParams: extParams, shareId: nil, videoIds: nil, playId: playId, headVideoId: (playVideoData as? PQVideoListModel)?.headVideoId, projectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.projectId ?? "", parentProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentProjectId ?? "", rootProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.rootProjectId ?? "", canProduce: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.canReproduce ?? 0, parentVideoId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentVideoId ?? "", commonParams: commonParams())
                }
            }
            playVideoData?.playProgress = Float64(playProgress)
            if progressBloc != nil {
                progressBloc!(loadProgress, playProgress, duration)
            }
        case PLAY_EVT_RCV_FIRST_I_FRAME.rawValue:
            // 首帧完成开始播放
            if !isPlayBegin, playVideoData != nil {
                isPlayBegin = true
                // 播放上报
                var extParams: [String: Any]?
                if isHomePageAllList {
                    if playVideoData?.pageSource == .sp_cmunit_joinTopic {
                        extParams = ["topicId": "all"]
                    } else if playVideoData?.pageSource == .sp_cmunit_follow {
                        extParams = ["followedUid": "all"]
                    }
                }
                BFEventTrackAdaptor.videoRelationReportUpload(reportLogType: .reportLogType_Action, videoData: playVideoData, pageSource: nil, businessType: .bt_videoPlaySuccess, objectType: nil, extParams: extParams, shareId: nil, videoIds: nil, playId: playId, headVideoId: (playVideoData as? PQVideoListModel)?.headVideoId, projectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.projectId ?? "", parentProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentProjectId ?? "", rootProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.rootProjectId ?? "", canProduce: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.canReproduce ?? 0, parentVideoId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentVideoId ?? "", commonParams: commonParams())
            }

        case PLAY_EVT_PLAY_LOADING.rawValue: // 视频播放loading
            if playStatusBloc != nil {
                playStatusBloc!(.PQVIDEO_PLAY_STATUS_LOADING)
            }
        case PLAY_EVT_PLAY_BEGIN.rawValue: // 开始播放
            if playStatusBloc != nil {
                playStatusBloc!(.PQVIDEO_PLAY_STATUS_BEGIN)
            }
            // 首帧加载完成
            if !isFirstFrame, playVideoData != nil {
                isFirstFrame = true
                // 播放上报
                var extParams: [String: Any]?
                if isHomePageAllList {
                    if playVideoData?.pageSource == .sp_cmunit_joinTopic {
                        extParams = ["topicId": "all"]
                    } else if playVideoData?.pageSource == .sp_cmunit_follow {
                        extParams = ["followedUid": "all"]
                    }
                }
                BFEventTrackAdaptor.videoRelationReportUpload(reportLogType: .reportLogType_play, videoData: playVideoData, pageSource: nil, businessType: nil, objectType: nil, extParams: extParams, shareId: nil, videoIds: nil, playId: playId, headVideoId: (playVideoData as? PQVideoListModel)?.headVideoId, projectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.projectId ?? "", parentProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentProjectId ?? "", rootProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.rootProjectId ?? "", canProduce: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.canReproduce ?? 0, parentVideoId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentVideoId ?? "", commonParams: commonParams())
                let duration = Int((Date().timeIntervalSince1970 * 1000) - loadingTime)
                BFLog(message: "加载时长：\(duration)")
                // 加载时间上报
                var timeExtParams: [String: Any] = ["duration": duration, "proxyEnable": "0", "url": playVideoData?.videoPath ?? "", "videoId": playVideoData?.uniqueId ?? "0"]
                if extParams != nil {
                    timeExtParams.merge(extParams!) { keyValue, _ in
                        keyValue
                    }
                }
                BFEventTrackAdaptor.videoRelationReportUpload(reportLogType: .reportLogType_Frontend, videoData: playVideoData, pageSource: nil, businessType: .bt_videoPlaySuccessTime, objectType: nil, extParams: timeExtParams, shareId: nil, videoIds: nil, playId: playId, headVideoId: (playVideoData as? PQVideoListModel)?.headVideoId, projectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.projectId ?? "", parentProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentProjectId ?? "", rootProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.rootProjectId ?? "", canProduce: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.canReproduce ?? 0, parentVideoId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentVideoId ?? "", commonParams: commonParams())
            }
            BFLog(message: "首帧加载完成")
        case PLAY_EVT_PLAY_END.rawValue: // 播放结束
            player.pause()
            playId = getUniqueId(desc: "playId")
            if playStatusBloc != nil {
                playStatusBloc!(.PQVIDEO_PLAY_STATUS_END)
            }
            if !isPlayEnd, playVideoData != nil {
                isPlayEnd = true
                // 播放结束上报
                var extParams: [String: Any]?
                if isHomePageAllList {
                    if playVideoData?.pageSource == .sp_cmunit_joinTopic {
                        extParams = ["topicId": "all"]
                    } else if playVideoData?.pageSource == .sp_cmunit_follow {
                        extParams = ["followedUid": "all"]
                    }
                }
                BFEventTrackAdaptor.videoRelationReportUpload(reportLogType: .reportLogType_Action, videoData: playVideoData, pageSource: nil, businessType: .bt_videoPlayEnd, objectType: nil, extParams: extParams, shareId: nil, videoIds: nil, playId: playId, headVideoId: (playVideoData as? PQVideoListModel)?.headVideoId, projectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.projectId ?? "", parentProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentProjectId ?? "", rootProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.rootProjectId ?? "", canProduce: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.canReproduce ?? 0, parentVideoId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentVideoId ?? "", commonParams: commonParams())
            }
            let playDuration = player.currentPlaybackTime() - lastPlaybackTime
            debugPrint("当前播放时长:\(player.currentPlaybackTime()),lastPlaybackTime:\(lastPlaybackTime),playDuration:\(playDuration)")
            if playDuration > 0 {
                var extParams: [String: Any]?
                if playVideoData?.pageSource == .sp_cmunit_joinTopic {
                    extParams = ["topicId": isHomePageAllList ? "all" : "\(playVideoData?.topicData?["id"] ?? "")"]
                } else if playVideoData?.pageSource == .sp_cmunit_follow {
                    extParams = ["followedUid": isHomePageAllList ? "all" : "\(playVideoData?.user?["uid"] ?? "")"]
                } else if playVideoData?.pageSource == .sp_cmunit_newTopicDetail || playVideoData?.pageSource == .sp_cmunit_hotTopicDetail {
                    extParams = ["topicId": "\(playVideoData?.topicData?["id"] ?? "")"]
                }
                BFEventTrackAdaptor.baseReportUpload(logType: .st_log_type_pLayaction, businessType: .bt_videoPlayDuration, objectType: nil, pageSource: playVideoData?.pageSource ?? .sp_cmunit_recommend, eventData: ["pageSource": (playVideoData?.pageSource ?? .sp_cmunit_recommend).rawValue, "playDuration": Int64(playDuration * 1000), "playId": playId, "uid": "\(playVideoData?.user?["uid"] ?? "")", "videoId": playVideoData?.id ?? 0], extParams: extParams, commonParams: commonParams())
                lastPlaybackTime = player.currentPlaybackTime()
            }
        case PLAY_ERR_NET_DISCONNECT.rawValue, -2301: // 重连失败
            if playStatusBloc != nil {
                playStatusBloc!(.PQVIDEO_PLAY_STATUS_DISCONNECT)
            }
            if !isPlayerError, playVideoData != nil {
                isPlayerError = true
                // 播放失败
                var extParams: [String: Any] = ["pageSource": playVideoData!.pageSource.rawValue, "networkType": networkStatus(), "extra": "0", "hasRetry": true, "url": playVideoData?.videoPath ?? "", "videoId": playVideoData?.uniqueId ?? "0", "what": event]
                if isHomePageAllList {
                    if playVideoData?.pageSource == .sp_cmunit_joinTopic {
                        extParams["topicId"] = "all"
                    } else if playVideoData?.pageSource == .sp_cmunit_follow {
                        extParams["followedUid"] = "all"
                    }
                }
                BFEventTrackAdaptor.videoRelationReportUpload(reportLogType: .reportLogType_Action, videoData: playVideoData, pageSource: nil, businessType: .bt_videoPlayError, objectType: nil, extParams: extParams, shareId: nil, videoIds: nil, playId: playId, headVideoId: (playVideoData as? PQVideoListModel)?.headVideoId, projectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.projectId ?? "", parentProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentProjectId ?? "", rootProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.rootProjectId ?? "", canProduce: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.canReproduce ?? 0, parentVideoId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentVideoId ?? "", commonParams: commonParams())
            }
        case PLAY_ERR_FILE_NOT_FOUND.rawValue: // 播放文件不存在
            if playStatusBloc != nil {
                playStatusBloc!(.PQVIDEO_PLAY_STATUS_NOT_FOUND)
            }
            if !isPlayerError, playVideoData != nil {
                isPlayerError = true
                // 播放失败
                var extParams: [String: Any] = ["pageSource": playVideoData!.pageSource.rawValue, "networkType": networkStatus(), "extra": "0", "hasRetry": false, "url": playVideoData?.videoPath ?? "", "videoId": playVideoData?.uniqueId ?? "0", "what": event]
                if isHomePageAllList {
                    if playVideoData?.pageSource == .sp_cmunit_joinTopic {
                        extParams["topicId"] = "all"
                    } else if playVideoData?.pageSource == .sp_cmunit_follow {
                        extParams["followedUid"] = "all"
                    }
                }
                BFEventTrackAdaptor.videoRelationReportUpload(reportLogType: .reportLogType_Action, videoData: playVideoData, pageSource: nil, businessType: .bt_videoPlayError, objectType: nil, extParams: extParams, shareId: nil, videoIds: nil, playId: playId, headVideoId: (playVideoData as? PQVideoListModel)?.headVideoId, projectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.projectId ?? "", parentProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentProjectId ?? "", rootProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.rootProjectId ?? "", canProduce: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.canReproduce ?? 0, parentVideoId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentVideoId ?? "", commonParams: commonParams())
            }
        case PLAY_ERR_HEVC_DECODE_FAIL.rawValue, PLAY_ERR_HLS_KEY.rawValue, PLAY_ERR_GET_PLAYINFO_FAIL.rawValue, PLAY_WARNING_VIDEO_DECODE_FAIL.rawValue, PLAY_WARNING_AUDIO_DECODE_FAIL.rawValue: // H265解码失败,HLS解码key获取失败,获取点播文件信息失败,当前视频解码失败,当前音频解码失败
            if playStatusBloc != nil {
                playStatusBloc!(PQVIDEO_PLAY_STATUS.PQVIDEO_PLAY_STATUS_FAUILE)
            }
            if !isPlayerError, playVideoData != nil {
                isPlayerError = true
                // 播放失败
                var extParams: [String: Any] = ["pageSource": playVideoData!.pageSource.rawValue, "networkType": networkStatus(), "extra": "0", "hasRetry": false, "url": playVideoData?.videoPath ?? "", "videoId": playVideoData?.uniqueId ?? "0", "what": event]
                if isHomePageAllList {
                    if playVideoData?.pageSource == .sp_cmunit_joinTopic {
                        extParams["topicId"] = "all"
                    } else if playVideoData?.pageSource == .sp_cmunit_follow {
                        extParams["followedUid"] = "all"
                    }
                }
                BFEventTrackAdaptor.videoRelationReportUpload(reportLogType: .reportLogType_Action, videoData: playVideoData, pageSource: nil, businessType: .bt_videoPlayError, objectType: nil, extParams: extParams, shareId: nil, videoIds: nil, playId: playId, headVideoId: (playVideoData as? PQVideoListModel)?.headVideoId, projectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.projectId ?? "", parentProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentProjectId ?? "", rootProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.rootProjectId ?? "", canProduce: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.canReproduce ?? 0, parentVideoId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentVideoId ?? "", commonParams: commonParams())
            }
        case PLAY_WARNING_RECONNECT.rawValue: // 断线重连已启动重新连接
            if playStatusBloc != nil {
                playStatusBloc!(.PQVIDEO_PLAY_STATUS_RECONNECT)
            }
            var extParams: [String: Any] = ["pageSource": playVideoData!.pageSource.rawValue, "networkType": networkStatus(), "extra": "0", "hasRetry": true, "url": playVideoData?.videoPath ?? "", "videoId": playVideoData?.uniqueId ?? "0", "what": event]
            if isHomePageAllList {
                if playVideoData?.pageSource == .sp_cmunit_joinTopic {
                    extParams["topicId"] = "all"
                } else if playVideoData?.pageSource == .sp_cmunit_follow {
                    extParams["followedUid"] = "all"
                }
            }
            BFEventTrackAdaptor.videoRelationReportUpload(reportLogType: .reportLogType_Action, videoData: playVideoData, pageSource: nil, businessType: .bt_videoPlayException, objectType: nil, extParams: extParams, shareId: nil, videoIds: nil, playId: playId, headVideoId: (playVideoData as? PQVideoListModel)?.headVideoId, projectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.projectId ?? "", parentProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentProjectId ?? "", rootProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.rootProjectId ?? "", canProduce: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.canReproduce ?? 0, parentVideoId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentVideoId ?? "", commonParams: commonParams())
        case PLAY_WARNING_RECV_DATA_LAG.rawValue, PLAY_WARNING_VIDEO_PLAY_LAG.rawValue: // 网络来包不稳：可能是下行带宽不足 | 当前视频播放出现卡顿（用户直观感受）
            // 播放失败
            var extParams1: [String: Any] = ["pageSource": playVideoData!.pageSource.rawValue, "networkType": networkStatus(), "url": playVideoData?.videoPath ?? "", "videoId": playVideoData?.uniqueId ?? "0", "what": event, "position": player.currentPlaybackTime()]
            var extParams2: [String: Any] = ["pageSource": playVideoData!.pageSource.rawValue, "networkType": networkStatus(), "extra": "0", "hasRetry": true, "url": playVideoData?.videoPath ?? "", "videoId": playVideoData?.uniqueId ?? "0", "what": event]
            if isHomePageAllList {
                if playVideoData?.pageSource == .sp_cmunit_joinTopic {
                    extParams1["topicId"] = "all"
                    extParams2["topicId"] = "all"
                } else if playVideoData?.pageSource == .sp_cmunit_follow {
                    extParams1["followedUid"] = "all"
                    extParams2["topicId"] = "all"
                }
            }
            BFEventTrackAdaptor.videoRelationReportUpload(reportLogType: .reportLogType_Frontend, videoData: playVideoData, pageSource: nil, businessType: .bt_videoPlaySlow, objectType: nil, extParams: extParams1, shareId: nil, videoIds: nil, playId: playId, headVideoId: (playVideoData as? PQVideoListModel)?.headVideoId, projectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.projectId ?? "", parentProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentProjectId ?? "", rootProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.rootProjectId ?? "", canProduce: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.canReproduce ?? 0, parentVideoId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentVideoId ?? "", commonParams: commonParams())
            BFEventTrackAdaptor.videoRelationReportUpload(reportLogType: .reportLogType_Action, videoData: playVideoData, pageSource: nil, businessType: .bt_videoPlayException, objectType: nil, extParams: extParams2, shareId: nil, videoIds: nil, playId: playId, headVideoId: (playVideoData as? PQVideoListModel)?.headVideoId, projectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.projectId ?? "", parentProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentProjectId ?? "", rootProjectId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.rootProjectId ?? "", canProduce: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.canReproduce ?? 0, parentVideoId: (playVideoData as? PQVideoListModel)?.reCreateVideoData?.parentVideoId ?? "", commonParams: commonParams())
        default:
            break
        }
    }

    /// 网络状态回调
    /// - Parameters:
    ///   - player: <#player description#>
    ///   - param: <#param description#>
    public func onNetStatus(_: TXVodPlayer!, withParam _: [AnyHashable: Any]!) {
        // BFLog(message: "onNetStatus:\(param)")
    }
}
