//
//  CCSpatialVideoDisplayController.swift
//  SwiftProject
//
//  Created by Zhang, Joyce on 2024/3/2.
//

import UIKit
import AVFoundation
import Photos
import AVKit
import VideoToolbox
import Firebase
enum SpatialType : Int {
    
    /*
     单眼2D
     平行眼
     红蓝立体
     交叉眼
     
     */
    
    case monocular2D = 1
    case parallelEyes = 0
    case redBlueSolid = 2
    case crossedEyes = 3
    //以下两种标记：外部串流时使用
    case hsbs = 4
    case fsbs = 5
}

class CCSpatialVideoDisplayController: BaseController {
    var externalDispalylink:CADisplayLink?
    var externalVC:ZZHExternalViewController?
    var isAirPlayActive:Bool = false {
        didSet{
            //跟新selectedIndex、typeData的值
            if(isAirPlayActive){
                selectedIndex = .fsbs//在串流模式下，默认选项为hsbs
                typeData = [(icon:"type_check",title:"3D FSBS",isHiden:false),
                            (icon:"type_check",title:"3D HSBS",isHiden:false)
                                 ]
            }
            else{
                selectedIndex = .parallelEyes//在非串流模式下，默认选项为monocular2D
                typeData = [
                    (icon:"type_check",title:NSLocalizedString("平行眼", comment: ""),isHiden:false),
                    (icon:"type_check",title:NSLocalizedString("单眼2D", comment: ""),isHiden:false),
                            
                                 
                                 
                                 (icon:"type_check",title:NSLocalizedString("红蓝立体", comment: ""),isHiden:false),
                                 (icon:"type_check",title:NSLocalizedString("交叉眼", comment: ""),isHiden:false)]
            }
            //更新串流UI
//            DispatchQueue.main.asyncAfter(deadline: .now() + 5, execute: {
                self.setttinisScreenMirroring(isScreenMirroring: self.isAirPlayActive)
//            })
            
        }
        

    }
    
    lazy var maskLabel:UILabel = {
       let label = UILabel()
        label.numberOfLines = 0
        label.textColor = .white
        label.font = UIFont.systemFont(ofSize: 14)
        label.textAlignment = .center
        label.layer.cornerRadius = 6
        label.layer.masksToBounds = true
        label.backgroundColor = UIColor.colorWithRGB(_r: 60.0, _g: 60.0, _b: 60.0, alpha: 0.1)
        label.text = NSLocalizedString("外部串流中", comment: "")
        label.isHidden = true
        return label
    }()
    
    var assetReader:AVAssetReader?
    
    var assetOutput:AVAssetReaderTrackOutput?
    
    var assetTrack:AVAssetTrack?
    
    let kNowTimeToUserDefaultKey_VideoDisplayController:String = "kNowTimeToUserDefaultKey_VideoDisplayController"
    var link = false//是否已连接设备
    var isPlaying = false {//是否正在串流播放
        didSet {
            maskLabel.isHidden = !isPlaying
        }
    }
    
    var selectedIndex:SpatialType = .parallelEyes//记录当前选择的菜单选项
    {
        didSet{
            //进行相应解码操作，边解边播
        }
    }
    
    
    
    let videoTranserConvertor = PlayByTransferConvertor()
    
    lazy var videoOriginalAsset:AVAsset = {
        let asset = AVAsset(url: sourceVideoURL!)
        return asset
    }()

    var videoOriginalPHAsset:PHAsset?
    
    //图片源数据
    var sourceVideoURL:URL?
    var imgData:Data?

    var player:AVPlayer?
//    var needRestReaderTimeRange = false//标识是否需呀重置时间读取范围
    var playerController:AVPlayerViewController?
    
    lazy var mTopImgView:UIImageView = {
        //393*236
//        let view = UIImageView(frame: CGRect(x: 0, y: 0, width: SCREEN_Width, height: SCREEN_Height * 236/393))
        let view = UIImageView(frame: CGRect(x: 0, y: 0, width: SCREEN_Width, height: 236))
        
        view.image = UIImage.init(named: "BG_Top")
        return view
    }()
    
    lazy var transformButton: UIButton = {
        
        //76*56
        let transformButton = UIButton.init(type: UIButton.ButtonType.custom)
        
        transformButton.tag = 201
        transformButton.isSelected = false
        transformButton.backgroundColor = UIColor(hexString: "#5326D6")
        transformButton.addTarget(self, action: #selector(navgationButtonClick2(sender:)), for: UIControl.Event.touchUpInside)
        let img2:UIImage = UIImage.init(named: "transform_button" as String)!
        transformButton.setImage(img2, for: UIControl.State.normal)
        transformButton.frame = CGRect(x: 0, y: 0, width: 56, height: 36)
        transformButton.layer.cornerRadius = 18
        transformButton.layer.masksToBounds = true
        transformButton.centerY = StatuBar_Height + NavBar_Height * 0.5
        transformButton.right = SCREEN_Width - 24
        
        return transformButton
    }()
    
    lazy var mTopCenterTypeButton: UIButton = {
        //173*36
        let button = UIButton()
        button.backgroundColor = UIColor.hexStringToColor(hexString: "#1F1E20")
        button.tag = 202
        button.isSelected = false
        button.addTarget(self, action: #selector(navgationButtonClick2(sender:)), for: UIControl.Event.touchUpInside)
        button.frame = CGRect(x: 2, y: 10, width: SCREEN_Width * 0.4 + 20, height: 36)
        button.centerY = StatuBar_Height + NavBar_Height * 0.5
        button.centerX = SCREEN_Width * 0.5
        button.clipsToBounds = true
        button.layer.cornerRadius = 18
        button.layer.borderWidth = 1
        button.layer.borderColor = UIColor.white.cgColor
        button.setTitle(NSLocalizedString("平行眼", comment: ""), for: UIControl.State.normal)
        button.setImage(UIImage.init(named: "type_button_arrow_down"), for: .normal)
        button.updateBtnEdgeInsets(style: .Right, space: 10)
        button.setTitleColor(UIColor.white, for: UIControl.State.normal)
        button.titleLabel?.font = KFont_Medium(14)
        return button
    }()
    
    
    
    var typeData:[(icon:String,title:String,isHiden:Bool)] = [(icon:"type_check",title:NSLocalizedString("平行眼", comment: ""),isHiden:false),
                                                              (icon:"type_check",title:NSLocalizedString("单眼2D", comment: ""),isHiden:false),
                                                              
                                                              (icon:"type_check",title:NSLocalizedString("红蓝立体", comment: ""),isHiden:false),
                                                              (icon:"type_check",title:NSLocalizedString("交叉眼", comment: ""),isHiden:false)]
    {
        didSet {
            menuView.setData(datas: self.typeData)
        }
    }
    
    lazy var menuView: CCSpatialDisplayTypeView = {
        //设置参数
        let parameters:[CCSpatialDisplayTypeConfigure] = [
            .PopMenuTextColor(UIColor.white),
            .popMenuItemHeight(40),
            .PopMenuTextFont(KFont_Medium(12)),
            .PopMenuBackgroudColor(UIColor(hexString: "#1F1E20"))
        ]
        
        
        //init  (test随机生成点位置，注意：arrow点是基于屏幕的位置)
        let pointOnScreen = navtionImgView!.convert(CGPointMake(navtionImgView!.centerX, navtionImgView!.bottom), to: KWindow)
        let popMenu = CCSpatialDisplayTypeView(menuWidth: SCREEN_Width * 0.4, arrow: pointOnScreen, datas: typeData,configures: parameters){[weak self] in
            //dissmiss回调
            self?.mTopCenterTypeButton.setImage(UIImage.init(named: "type_button_arrow_down"), for: .normal)
        }
        return popMenu
    }()
    
    lazy var progressView: UIProgressView = {
        var  view = UIProgressView (progressViewStyle:.default)
        view.frame = CGRect(x: 24, y: SCREEN_Height - KStatusBarHeight - 20, width: SCREEN_Width-48, height: 36)
        view.progress = 0.0  //默认进度50%
        return view
    }()
 
    
    lazy var tipsButton: UIButton = {
        
        //76*56
        let button = UIButton.init(type: UIButton.ButtonType.custom)
        button.tag = 203
        button.backgroundColor = .clear
        button.addTarget(self, action: #selector(navgationButtonClick2(sender:)), for: UIControl.Event.touchUpInside)
        let img2:UIImage = UIImage.init(named:  NSLocalizedString("displayvc_desc", comment: ""))!
        button.setImage(img2, for: UIControl.State.normal)
        button.frame = CGRect(x: 0, y: 0, width: 173, height: 42)
//        button.titleLabel?.font = KFont_Regular(14)
//        button.titleLabel?.adjustsFontSizeToFitWidth = true
//        button.updateBtnEdgeInsets(style: .Left, space: 8)
        button.centerY = progressView.top - 70
        button.centerX = self.view.centerX
        
        return button
    }()
    
    
    //监听播放完毕
    @objc func notification_PlayerEndTime(notification:Notification){
        print("PlayerEndTime....")
        player?.seek(to: .zero)
        player?.play()
//
//        self.playerController?.view.layer.sublayers?.forEach({ clayer in
//            print("clayer.......\(clayer.self)")
//            clayer.backgroundColor = UIColor.red.cgColor
//            clayer.sublayers?.forEach({ sclayer in
//                print("sclayer.......\(sclayer.self)")
//                sclayer.backgroundColor = UIColor.blue.cgColor
//                sclayer.sublayers?.forEach({ sscalyer in
//                    print("sscalyer.......\(sscalyer.self)")
//                    if let avPlayerLayer = sscalyer as? AVPlayerLayer {
//                        sscalyer.backgroundColor = UIColor.orange.cgColor
//                        sscalyer.sublayers?.forEach({ avSubLayer in
//                            print("avSubLayer.......\(avSubLayer.self)")
//                            avSubLayer.backgroundColor = UIColor.systemPink.cgColor
//                            if let avaPlayerLayer2 = avSubLayer as? AVPlayerLayer {
//                                avaPlayerLayer2.backgroundColor = UIColor.white.cgColor
//
//                            }
//                        })
//                    }
//
//                })
//            })
//        })
        
    }
    
    //监听拖动播放的进度事件
//    @objc func notification_PlayerTimeJump(notification:Notification){
////        needRestReaderTimeRange = true
//
//        print("time jump....")
//
//    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        configureUI()
        ZZHHelper.setNowTimeToUserDefaultWithKey(kNowTimeToUserDefaultKey_VideoDisplayController)
        Task {
            print("ccs viewdid load   ---------")
            await self.loadVideoAssetReader()
            DispatchQueue.main.asyncAfter(deadline: .now()+0.01) {[weak self] in
                self?.setUPPlayer()
                // 检查当前是否已连接到 AirPlay 设备
                self?.checkAirPlayStatus()
                
                
            }
        }
    }
    
    func setUPPlayer(){
        print("getPlayerItem  ========")
        player = AVPlayer()
        player?.allowsExternalPlayback = true
        player?.usesExternalPlaybackWhileExternalScreenIsActive = true
        
        print("getPlayerItem  >>>>>>>")
        
        playerController = AVPlayerViewController()
        playerController?.player = player
        playerController!.view.backgroundColor = .clear
        playerController?.view.frame = CGRect.init(x: 0, y: 170, width: self.view.frame.size.width, height: 400)
        
        self.addChild(playerController!)
        self.view.addSubview(playerController!.view)
        
        self.maskLabel.frame = playerController!.view.frame
        self.view.addSubview(self.maskLabel)
    }
    
    
    func configureUI(){
        self.view.backgroundColor = UIColor(hexString: "#060507")
        
        //设置返回按钮图片
        self.setLeftOneBtnImg(imgStr: "spatial_back_button")
        self.setNavgationBarColorImg(color: .clear)
        self.setNavgationBarLine(color: .clear)
        
        self.view.addSubview(mTopImgView)
        self.view.bringSubviewToFront(self.navtionBar!)
        
        navtionBar?.addSubview(transformButton)
        navtionBar?.addSubview(mTopCenterTypeButton)

        self.view.addSubview(tipsButton)
        
        
        
        
        // 监听 AirPlay 设备的连接状态
        //添加外接屏幕链接通知
        NotificationCenter.default.addObserver(self, selector: #selector(exScreenWillConnectNotification(notification:)), name: UIScene.willConnectNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(exScreenDisConnectNotification(notification:)), name: UIScene.didDisconnectNotification, object: nil)
        
        
        
       
        NotificationCenter.default.addObserver(self, selector: #selector(notification_PlayerEndTime(notification:)), name: AVPlayerItem.didPlayToEndTimeNotification, object: nil)
//        NotificationCenter.default.addObserver(self, selector: #selector(notification_PlayerTimeJump(notification:)), name: AVPlayerItem.timeJumpedNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(notificatin_failedToPlayToEndTimeNotification(notifiation: )), name: AVPlayerItem.failedToPlayToEndTimeNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(notificatin_failedToPlayToEndTimeNotification(notifiation: )), name: AVPlayerItem.newErrorLogEntryNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(notification_didEnterBackgroundNotification(notification: )), name: UIApplication.didEnterBackgroundNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(notification_didActiveNotification(notification: )), name: UIApplication.didBecomeActiveNotification, object: nil)
    }
    
    //屏幕进入后台
    @objc func notification_didEnterBackgroundNotification(notification:Notification) {
        player?.pause()
        
        print("ccs .....notification_didEnterBackgroundNotification")
    }
    //屏幕进入前台
    @objc func notification_didActiveNotification(notification:Notification) {
        self.checkAirPlayStatus()
        print("ccs .....notification_didEnterBackgroundNotification")
    }
    
    
    
    @objc func notificatin_failedToPlayToEndTimeNotification(notifiation:Notification) {
        print("notificatin_failedToPlayToEndTimeNotification....")
        
    }
    
    @objc func notificatin_newErrorLogEntryNotification(notifiation:Notification) {
        print("notificatin_newErrorLogEntryNotification....")
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        if externalVC != nil {
            externalVC?.playerLayer?.player = nil
        }
        player?.pause()
        releaseVideoComposition()
        
        let sec:TimeInterval = ZZHHelper.getSecFromUserDefaultByKey(kNowTimeToUserDefaultKey_VideoDisplayController)
        Analytics.logEvent("preview_pv", parameters: ["refer_page":"视频预览页面","duration":sec])
        
        print(".........ccs viewdid disappear....")
        
    }
    
  
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
       
        if self.player?.currentItem == nil {//此处需要判断是否为空:1,在didload的时候会设置一次,在viewDidDisappear的时候会被置空
            let playerItem = self.getPlayerItem()
            self.player?.replaceCurrentItem(with: playerItem)
        }
        
        if self.externalVC != nil {//恢复外接屏幕的视频播放
            if  self.externalVC?.playerLayer?.player == nil {
                self.activeSession()
                self.externalVC?.playerLayer?.player = self.player
            }
        }
        self.player?.play()
    }
    
    //MARK: - 监听设备投流
    @objc private func airPlayStatusDidChange(_ notification: Notification) {
        checkAirPlayStatus()
        if(isAirPlayActive) {
            Analytics.logEvent("streaming_live", parameters: ["refer_page":"视频预览页面"])
            ZZHHelper.setNowTimeToUserDefaultWithKey("kNowTimeToUserDefaultKey_VideoDisplayController_airplay")
        }
        else {
            let sec:TimeInterval = ZZHHelper.getSecFromUserDefaultByKey("kNowTimeToUserDefaultKey_VideoDisplayController_airplay")
            Analytics.logEvent("streaming_live", parameters: ["refer_page":"视频预览页面","duration":sec])
        }
    }
    
    @objc func exScreenWillConnectNotification(notification:Notification){
        print("exScreenWillConnectNotification>>>>>")
        airPlayStatusDidChange( notification)
    }
    
    @objc func exScreenDisConnectNotification(notification:Notification){
        print("exScreenDisConnectNotification>>>>>")
        airPlayStatusDidChange( notification)
    }
    
    
    private func checkAirPlayStatus() {
        print("设备连接变化")
        
        let currentRoute = AVAudioSession.sharedInstance().currentRoute
        self.isAirPlayActive = currentRoute.outputs.contains { output in
            return output.portType == AVAudioSession.Port.HDMI ||
            output.portType == AVAudioSession.Port.airPlay
        }
    }
    
    func setttinisScreenMirroring(isScreenMirroring:Bool){
        releaseVideoComposition()
        
                //已连接
                if(isScreenMirroring){
                    self.dealTaskWhenExternalScreenConnect()
                    
                    
                }else{
                    //未连接
                    self.dealTaskWhenExternalScreenDisConnect()
                }
        
        
    }
    
    //激活一下session
    func activeSession(){
        do {
            try AVAudioSession.sharedInstance().setActive(true)
            try AVAudioSession.sharedInstance().setCategory(.playback,options: .allowAirPlay)
        }
        catch {
            print("err: set audiosession:\(error)")
        }
    }
    
    //当外接屏幕连接时
    func dealTaskWhenExternalScreenConnect(){
//        if link == true {
//            return
//        }
        
        link = true
        isPlaying = true
        let playerItem = self.getPlayerItem()
        player?.replaceCurrentItem(with: playerItem)
        print("外接屏幕已连接.....")
        activeSession()
        
        UIApplication.shared.connectedScenes.forEach { us in
            print("uisence:\(us)\n")
            let ws = us as! UIWindowScene
            if ws.session.role.rawValue == "UIWindowSceneSessionRoleExternalDisplayNonInteractive"{
                externalVC = ws.windows.first?.rootViewController as? ZZHExternalViewController
                if externalVC != nil {
                    if let ed = externalDispalylink {
                        ed.invalidate()
                    }
                    externalDispalylink = ws.windows.first?.screen.displayLink(withTarget: self, selector: #selector(displayUpdate(caDisplayLink:)))
                    externalDispalylink?.add(to: RunLoop.main, forMode: RunLoop.Mode.common)
                }
            }
        }
        
        updateTopCenterButtonWhenIsPlayingChange()
        
    }
    
    //当处理外部设备连接状态时,串流状态更新
    func updateTopCenterButtonWhenIsPlayingChange()  {
        //串流播放中
        mTopCenterTypeButton.setImage(UIImage.init(named: "linked_button"), for: .normal)
        mTopCenterTypeButton.setTitleColor(UIColor(hexString: "#D0C0FF"), for: .normal)
        mTopCenterTypeButton.layer.borderColor = UIColor(hexString: "#D0C0FF").cgColor
        mTopCenterTypeButton.backgroundColor = UIColor(hexString: "#5326D6")
        mTopCenterTypeButton.updateBtnEdgeInsets(style: .Left, space: 5)
        

        //展示弹出列表尾部
        if isPlaying {
            //正在串流中 --- 按钮显示为【结束串流】
            menuView.showFooterView(isShow: true, showText: NSLocalizedString("结束串流", comment: ""))
            mTopCenterTypeButton.setTitle(NSLocalizedString("外部串流中", comment: ""), for: UIControl.State.normal)
        }else{
            //未串流 --- 按钮显示为【开始串流】
            menuView.showFooterView(isShow: true, showText: NSLocalizedString("开始串流", comment: ""))
            mTopCenterTypeButton.setTitle(NSLocalizedString("已连接外部设备", comment: ""), for: UIControl.State.normal)
        }
    }
    
    //当外接屏幕断开时
    func dealTaskWhenExternalScreenDisConnect(){
        print("外接屏幕已断开.....")
        let playerItem = self.getPlayerItem()
        player?.replaceCurrentItem(with: playerItem)
        
        link = false
        isPlaying = false
        // 当前未连接到 AirPlay 设备
        if self.selectedIndex == .monocular2D {
            mTopCenterTypeButton.setTitle(NSLocalizedString("单眼2D", comment: ""), for: UIControl.State.normal)
        }else if self.selectedIndex == .redBlueSolid {
            mTopCenterTypeButton.setTitle(NSLocalizedString("红蓝立体", comment: ""), for: UIControl.State.normal)
        }else if self.selectedIndex == .crossedEyes {
            mTopCenterTypeButton.setTitle(NSLocalizedString("交叉眼", comment: ""), for: UIControl.State.normal)
        }
        else if self.selectedIndex == .parallelEyes {
            mTopCenterTypeButton.setTitle(NSLocalizedString("平行眼", comment: ""), for: UIControl.State.normal)
        }
        
        mTopCenterTypeButton.setImage(UIImage.init(named: "type_button_arrow_down"), for: .normal)
        mTopCenterTypeButton.setTitleColor(UIColor.white, for: UIControl.State.normal)
        mTopCenterTypeButton.layer.borderColor = UIColor.white.cgColor
        mTopCenterTypeButton.backgroundColor = UIColor(hexString: "#1F1E20")
        mTopCenterTypeButton.updateBtnEdgeInsets(style: .Right, space: 10)
        
        //隐藏弹出列表尾部
        menuView.showFooterView(isShow: false, showText: "")
        externalVC?.playerLayer?.player = nil
        self.playerController?.player = player
        player?.play()
        externalVC = nil
    }
    
    @objc func displayUpdate(caDisplayLink:CADisplayLink) {
        if let has_exvc = externalVC {
            if has_exvc.playerLayer?.player == nil {
                has_exvc.imageView?.isHidden = true
                has_exvc.playerLayer?.isHidden = false
                self.playerController?.player = nil
                has_exvc.playerLayer?.player = player
                player?.play()
                externalDispalylink?.invalidate()
                externalDispalylink = nil
            }
        }
        
    }
    
    
    deinit {
        print("patialvideodisplaycontroler deinit......")
        releaseVideoComposition()
        assetReader?.cancelReading()
        NotificationCenter.default.removeObserver(self)
//        player?.removeObserver(self, forKeyPath: "status")
    }
    
    func releaseVideoComposition()  {
        if externalDispalylink != nil {
            externalDispalylink?.invalidate()
            externalDispalylink = nil
        }
        self.player?.currentItem?.videoComposition = nil
        self.player?.replaceCurrentItem(with: nil)
    }
    
    
    //MARK: - action
    @objc public func navgationButtonClick2(sender:UIButton){
        
        if sender.tag == 200 {
            //左边按钮
        }else if sender.tag == 201 {
            //右边按钮
            let transVC = VRVideoTransformController()
            transVC.videoOriginalPHAsset = self.videoOriginalPHAsset
            transVC.sourceVideoURL = sourceVideoURL
            self.navigationController?.pushViewController(transVC, animated: true)
            Analytics.logEvent("preview_trans_click", parameters: nil)
        }else if sender.tag == 202 {
            //中间按钮
            
            menuView.show()
            if link {
                //展示弹出列表尾部
                if isPlaying {
                    //正在串流中 --- 按钮显示为【结束串流】
                    menuView.showFooterView(isShow: true, showText: NSLocalizedString("结束串流", comment: ""))
                    mTopCenterTypeButton.setTitle(NSLocalizedString("外部串流中", comment: ""), for: UIControl.State.normal)
                }else{
                    //未串流 --- 按钮显示为【开始串流】
                    menuView.showFooterView(isShow: true, showText: NSLocalizedString("开始串流", comment: ""))
                    mTopCenterTypeButton.setTitle(NSLocalizedString("已连接外部设备", comment: ""), for: UIControl.State.normal)
                }
            }else{
                mTopCenterTypeButton.setImage(UIImage.init(named: "type_button_arrow_up"), for: .normal)
            }
            
                        
            //顶部中间的按钮选中某个选项后的回调click
            menuView.didSelectMenuBlock = { [weak self](index:Int)->Void in
                print("block select \(index)")
                self?.selectedSpatialType(selectedIndex: index)
                
                let title = self?.typeData[index].title
                self?.mTopCenterTypeButton.setTitle(title, for: UIControl.State.normal)
            }
            
            //开始、结束串流的回调
            menuView.tapFooterActionBlock = {[weak self] in
                self?.startOrEndExternalVR()
            }
            
        }else if sender.tag == 203 {
            //tips
                let view = CCDeviceOperationListView.init(frame: CGRectMake(0, 0, KScreenWidth, KScreenHeight))
                KWindow?.addSubview(view)
        }
    }
        
    func startOrEndExternalVR() {
        if(link == true){
            if isPlaying {//结束串流
                isPlaying = false
                if self.externalVC != nil {
                    externalVC?.playerLayer?.player = nil
                    player?.pause()
                    releaseVideoComposition()
                    DispatchQueue.main.asyncAfter(deadline: .now()+0.15, execute: {[weak self] in
                        let playerItem = self?.getPlayerItem()
                        self?.player?.replaceCurrentItem(with: playerItem)
                        self?.playerController?.player = self?.player
                        self?.player?.play()
                    })
                    
                }
            }
            else {//开始串流
                if self.externalVC != nil {
                    self.playerController?.player = nil
                    player?.pause()
                    releaseVideoComposition()
                    let playerItem = self.getPlayerItem()
                    player?.replaceCurrentItem(with: playerItem)
                    externalVC?.playerLayer?.player = player
                    player?.play()
                    isPlaying = true
                }
            }
            
        }
        
        
        updateTopCenterButtonWhenIsPlayingChange()
    }
    
    func selectedSpatialType(selectedIndex:Int){
        var si = selectedIndex
        if self.typeData.count == 2 {
            si = selectedIndex + 4
        }
        let rsi : SpatialType = SpatialType(rawValue: si) ?? .monocular2D
        self.selectedIndex = rsi
        
}

}
