//
//  CCSpatialShootController.swift
//  SwiftProject
//
//  Created by Zhang, Joyce on 2024/2/29.
//

import UIKit
import AVFoundation
import Photos
import AVKit
import VideoToolbox
import SVProgressHUD
import Firebase
import CoreMotion

//class ZVideoData:NSObject {
//    var leftSampleBuffer:CMSampleBuffer?
//    var rightSampleBuffer:CMSampleBuffer?
//    var audioSampleBuffer:CMSampleBuffer?
//    var isReady:Bool {
//        get {
//            return leftSampleBuffer != nil && rightSampleBuffer != nil && audioSampleBuffer != nil
//        }
//    }
//    
//    override init() {
//        super.init()
//    }
//}

class CCSpatialShootController: BaseController  {
    
    let writeVideoQueuen = dispatch_queue_serial_t(label: "ccspatial writeVideoQueuen")//创建一个串行队列
    
    let kNowTimeToUserDefaultKey_SpatialShootController:String = "kNowTimeToUserDefaultKey_SpatialShootController"
    var wideAngleCameraDevice:AVCaptureDevice?//测试使用
    var isTakePhoto = false//是否点击拍照按钮
    var isTakePhoto_ultraCamera = false
    var isTakePhoto_wideCamera = false
    let takePhotoSemaphore = DispatchSemaphore(value: 1)
    var isRecordingVideoData = false //是否正在录像
//    var videoData:ZVideoData = ZVideoData()
    lazy var svdWriter:SpatialVideoDataWriter = {
        let writer = SpatialVideoDataWriter()
        writer.outputVideoURL = outputVideoURL
        return writer
        
    }()
    
    //AVCaptureSession --- 单摄像头
    var session = AVCaptureMultiCamSession()//多摄像头
    var wideAngleCameraDeviceInput: AVCaptureDeviceInput?//广角摄像头 .builtInWideAngleCamera
    var ultraWideCameraDeviceInput: AVCaptureDeviceInput?//超广角 .builtInUltraWideCamera
    
    
    var wideAngleCameraVideoPreviewLayer: AVCaptureVideoPreviewLayer?//广角摄像头
    var ultraWideCameraVideoPreviewLayer: AVCaptureVideoPreviewLayer?//超广角
    
//    var wideAngleCameraMovieOutput: AVCaptureMovieFileOutput?
//    var ultraWideCameraMovieOutput: AVCaptureMovieFileOutput?
    
    
    var wideAngleCameraVideoDataOutput:AVCaptureVideoDataOutput?
    var ultraWideCameraVideoDataOutput:AVCaptureVideoDataOutput?
    var wuCameraAudioDataOutput:AVCaptureAudioDataOutput?
    
    
    var isRecording = false
    var imageCGImagePropertyOrientation:CGImagePropertyOrientation = CGImagePropertyOrientation.left//由于cgimage无法保留图像的方向
    var deviceOrientation = 1//监听设备方向 1,表示竖屏；2，表示横屏
    
    var leftEyeVideoURL:URL?
    var rightEyeVideoURL:URL?
    let outputVideoURL: URL = URL.documentsDirectory.appendingPathComponent("output.MOV")
    let motionManager = CMMotionManager()
    var imgs:NSMutableArray = NSMutableArray() //存放广角、主摄照片数组
//    let spatialVideoWriter = SpatialVideoWriter()
    //================================
    
    //当前相机模式
    var shootingMode:CCShootingMode = .CCShootingMode_Camera
    
    //记录拍摄时长
    var timer: Timer?
    
    lazy var spaceAlbumPopView: CCSpaceAlbumFilterPopView2 = {
        let view = CCSpaceAlbumFilterPopView2.init(frame: CGRectMake(0, 0, KScreenWidth, KScreenHeight))
        return view
    }()
    
    lazy var tipsLabel: UILabel = {
        let label = UILabel.init(frame: CGRectMake((KScreenWidth - 320)/2, KNavigationBarHeight+KStatusBarHeight + 20, 320, 36))
        label.backgroundColor = UIColor.darkGray
        label.font = KFont_Medium(12)
        label.textColor = KTextColor_White
        label.text = ""//你只需捕捉美好，转码交给我们"
        label.textAlignment = .center
        label.alpha = 1.0
        label.layer.cornerRadius = 8
        label.clipsToBounds = true
        label.isHidden = true
        return label
    }()
    
    lazy var horizontalImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage.init(named: "horizontal_rotate_img")
        imageView.alpha = 0.0
        imageView.isHidden = true
        return imageView
    }()
    
    lazy var effectView: UIVisualEffectView = {
        let effect = UIBlurEffect(style: .light)
        let view = UIVisualEffectView.init(effect: effect)
        view.backgroundColor = .clear
        view.alpha = 0.0
        view.isHidden = true
        return view
    }()
    
    
    lazy var horizontalLabel: UILabel = {
        let label = UILabel()
        label.backgroundColor = UIColor.clear
        label.font = KFont_Medium(14)
        label.textColor = KTextColor_White
        label.text = NSLocalizedString("将iPhone旋转为横向", comment: "")
        label.alpha = 0.0
        label.isHidden = true
        return label
    }()
    
    lazy var shutterRingView: UIView = {
        let view = UIView()
        view.frame = CGRect(x:0,y:0,width:66,height:66)
        view.backgroundColor = .clear
        view.layer.cornerRadius = 33
        view.layer.masksToBounds = true
        view.layer.borderWidth = 3
        view.layer.borderColor = UIColor.white.cgColor
        view.center = CGPointMake(KScreenWidth/2, KScreenHeight - KTabbarSafeBottomMargin - 50 - 33)
        return view
    }()
    
    lazy var shutterPhotoButton: UIButton = {
        let botton = UIButton()
        botton.frame = CGRect(x:0,y:0,width:56,height:56)
        botton.backgroundColor = .white
        botton.layer.cornerRadius = 28
        botton.layer.masksToBounds = true
        botton.center = CGPointMake(33, 33)
        botton.addTarget(self, action: #selector(shutterPhotoButtonAction), for: .touchUpInside)
        return botton
    }()
    
    lazy var shutterVideoButton: UIButton = {
        let botton = UIButton()
        botton.frame = CGRect(x:0,y:0,width:56,height:56)
        botton.backgroundColor = UIColor(hexString: "#FF3B2F")
        botton.layer.cornerRadius = 28
        botton.layer.masksToBounds = true
        botton.center = CGPointMake(33, 33)
        botton.addTarget(self, action: #selector(shutterVideoButtonAction(_:)), for: .touchUpInside)
        botton.isHidden = true
        return botton
    }()
    
    
    
    
    lazy var albumButton: UIButton = {
        let botton = UIButton()
        botton.frame = CGRect(x:0,y:0,width:48,height:48)
        botton.layer.cornerRadius = 8
        botton.layer.masksToBounds = true
        botton.center = CGPointMake(shutterRingView.center.x - 92 - 24, shutterRingView.center.y)
        botton.addTarget(self, action: #selector(albumButtonAction), for: .touchUpInside)
        botton.contentMode = .scaleAspectFill
        return botton
    }()
    
    
    lazy var lightButton: UIButton = {
        let botton = UIButton()
        botton.frame = CGRect(x:0,y:0,width:40,height:40)
        botton.setImage(UIImage.init(named: "light_button_normal"), for: .normal)
        botton.center = CGPointMake( shutterRingView.center.x + 103 + 20, shutterRingView.center.y)
        botton.addTarget(self, action: #selector(lightButtonAction), for: .touchUpInside)
        return botton
    }()
    
    
    lazy var switchBackView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hexString: "#ffffff", alpha: 0.6)
        view.layer.cornerRadius = 20
        view.layer.masksToBounds = true
        return view
    }()
    
    lazy var vipLogoView:UIImageView = {
       let imgView = UIImageView()
        imgView.image = UIImage(named: "camera_vip")
        return imgView
    }()
    
    lazy var cameraButton: UIButton = {
        let botton = UIButton()
        botton.tag = 1001
        botton.backgroundColor = UIColor(hexString: "#000000", alpha: 0.3)
        botton.setImage(UIImage(named: "camera_button_selected"), for: .normal)
        botton.layer.cornerRadius = 16
        botton.layer.masksToBounds = true
        botton.addTarget(self, action: #selector(switchButtonAction(_:)), for: .touchUpInside)
        return botton
    }()
    
    lazy var videoButton: UIButton = {
        let botton = UIButton()
        botton.tag = 1002
        botton.backgroundColor = .clear
        botton.setImage(UIImage(named: "video_button_normal"), for: .normal)
        botton.layer.cornerRadius = 16
        botton.layer.masksToBounds = true
        botton.addTarget(self, action: #selector(switchButtonAction(_:)), for: .touchUpInside)
        return botton
    }()
    
    lazy var cameraLabel: UILabel = {
        let label = UILabel()
        label.backgroundColor = UIColor.clear
        label.font = KFont_Medium(12)
        label.textColor = UIColor(hexString: "#ffffff", alpha: 0.6)
        label.text = NSLocalizedString("拍照", comment: "")
        label.isHidden = false
        return label
    }()
    
    lazy var videoLabel: UILabel = {
        let label = UILabel()
        label.backgroundColor = UIColor.clear
        label.font = KFont_Medium(12)
        label.textColor = UIColor(hexString: "#ffffff", alpha: 0.6)
        label.text = NSLocalizedString("摄像", comment: "")
        label.isHidden = true
        return label
    }()
    
    //=================================
    //MARK: - viewWillAppear
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        
        self.setNavgationBarColor(color: UIColor.clear)
        self.setNavgationBarLine(color: .clear)
    }
    
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        let sec:TimeInterval = ZZHHelper.getSecFromUserDefaultByKey(kNowTimeToUserDefaultKey_SpatialShootController)
        Analytics.logEvent("capture_pv", parameters: ["refer_page":"相机拍摄页面","duration":sec])
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        ZZHHelper.setNowTimeToUserDefaultWithKey(kNowTimeToUserDefaultKey_SpatialShootController)
 
        configureSession() // 设置相机参数
        
        setUI()
        self.view.bringSubviewToFront(navtionImgView!)
        
        //判断当前是否是横屏
        let isLandscape = UIDevice.current.orientation.isLandscape
        if !isLandscape {
            showHorizontalScreenTips()
        }
        
        if motionManager.isDeviceMotionAvailable {
            motionManager.startDeviceMotionUpdates(to: OperationQueue.main) {[weak self] motion, error in
              if let motion = motion {

                // 处理设备方向变化
                  self?.dealDeviceScreenOrientationByMotaion(motion)
              }
            }
        }
        
        
        
        //读取相册第一张照片
        getAlbumFirstPhoto()
        enableShutterBtn(false)
        //进入页面的首选项调整为视频拍摄
        switchButtonAction(videoButton)
    }
    
    private func setUI() {
        
        self.view.addSubview(effectView)
        self.view.addSubview(horizontalImageView)
        self.view.addSubview(horizontalLabel)
        self.view.bringSubviewToFront(horizontalImageView)
        self.view.bringSubviewToFront(horizontalLabel)
        
        //快门按钮
        self.view.addSubview(shutterRingView)
        
        shutterRingView.addSubview(shutterPhotoButton)
        shutterRingView.addSubview(shutterVideoButton)
        
        self.view.addSubview(albumButton)
        self.view.addSubview(lightButton)
        
        self.view.addSubview(switchBackView)
        switchBackView.addSubview(cameraButton)
        
        switchBackView.addSubview(videoButton)
        if !UserInfo.sharedInstance.isMemberShip {
            self.view.addSubview(vipLogoView)
        }
        
        
        self.view.addSubview(cameraLabel)
        self.view.addSubview(videoLabel)
        self.setRightOneBtnTitle(string: "4K·3D")
        
        effectView.snp.makeConstraints { (make) in
            make.top.leading.bottom.trailing.equalTo(self.view)
        }
        
        horizontalImageView.snp.makeConstraints { (make) in
            make.centerY.equalTo(self.view.snp.centerY)
            make.centerX.equalTo(self.view.snp.centerX)
            make.width.equalTo(28)
            make.height.equalTo(28)
        }
        
        horizontalLabel.snp.makeConstraints { (make) in
            make.top.equalTo(self.horizontalImageView.snp.bottom).offset(16)
            make.centerX.equalTo(self.view.snp.centerX)
        }
        
        switchBackView.snp.makeConstraints { (make) in
            make.bottom.equalTo(shutterRingView.snp.top).offset(-32)
            make.centerX.equalTo(self.view.snp.centerX)
            make.width.equalTo(128)
            make.height.equalTo(40)
        }
        if !UserInfo.sharedInstance.isMemberShip {
            vipLogoView.snp.makeConstraints { make in
                make.width.equalTo(25)
                make.height.equalTo(12)
                make.left.equalTo(switchBackView.snp.right).offset(-22)
                make.bottom.equalTo(switchBackView.snp.top).offset(12)
            }
        }
        
        
        
        cameraButton.snp.makeConstraints { (make) in
            make.centerY.equalTo(switchBackView.snp.centerY)
            
            make.trailing.equalTo(switchBackView.snp.trailing).offset(-4)
            make.width.equalTo(56)
            make.height.equalTo(32)
        }
        
        
        
        videoButton.snp.makeConstraints { (make) in
            make.centerY.equalTo(switchBackView.snp.centerY)
            make.leading.equalTo(switchBackView.snp.leading).offset(4)
            make.width.equalTo(56)
            make.height.equalTo(32)
        }
        
        cameraLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(switchBackView.snp.top).offset(-8)
            
            make.centerX.equalTo(switchBackView.snp.trailing).offset(-32)
        }
        
        videoLabel.snp.makeConstraints { (make) in
            make.bottom.equalTo(switchBackView.snp.top).offset(-8)
            make.centerX.equalTo(switchBackView.snp.leading).offset(32)
        }
    }
    
  
    

    
    func showHorizontalScreenTips() {
        self.horizontalImageView.isHidden = false
        self.horizontalLabel.isHidden = false
        
        //模糊遮罩
        self.effectView.isHidden = false
        
        UIView.animate(withDuration: 0.5) {
            self.horizontalImageView.alpha = 1.0
            self.horizontalLabel.alpha = 1.0
            //模糊遮罩
            self.effectView.alpha = 1.0
            
        }
        
    }
    
    func hidenHorizontalScreenTips() {
        UIView.animate(withDuration: 0.5) {
            self.horizontalImageView.alpha = 0.0
            self.horizontalLabel.alpha = 0.0
            //模糊遮罩
            self.effectView.alpha = 0.0
            
        }completion: { finished in
            self.horizontalImageView.isHidden = true
            self.horizontalLabel.isHidden = true
            //模糊遮罩
            self.effectView.isHidden = true
            
        }
        
    }
    
    
    //MARK: - action
    @objc func albumButtonAction() {
        //        let vc:CCSpaceAlbumController = CCSpaceAlbumController()
        //        self.present(vc, animated: true, completion: nil)
        self.view.addSubview(spaceAlbumPopView)
        spaceAlbumPopView.show()
        
        //选择图片
        spaceAlbumPopView.selectedImageHandler = { [self] data,asset in
            print("回调")
            
            let vc = CCSpatialPhotoDisplayController()
            vc.photoOriginalData = data
            vc.imageAsset = asset
            
            self.navigationController?.pushViewController(vc, animated: true)
        }
        //选择视频
        spaceAlbumPopView.selectedVideoHandler = { url,asset in
            if (asset.duration > 60 ) {
                if !UserInfo.sharedInstance.isMemberShip {
                    let vc:MembershipVC = MembershipVC()
                    let nav = UINavigationController(rootViewController: vc)
                    nav.modalTransitionStyle = UIModalTransitionStyle.coverVertical
                    nav.modalPresentationStyle = .fullScreen
                    self.present(nav, animated: true)
                    return
                }
            }
            let vc = CCSpatialVideoDisplayController()
            vc.sourceVideoURL = url
            vc.videoOriginalPHAsset = asset
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
    }
    
    
    
    
    @objc func lightButtonAction() {
        
        guard let device = AVCaptureDevice.default(for: .video) else {
            print("无法获取到您的设备")
            return
        }
        if device.hasTorch && device.isTorchAvailable{
            try? device.lockForConfiguration()
            
            device.torchMode = device.torchMode == .off ? .on : .off
            
            device.unlockForConfiguration()
        }
    }
    
    @objc func switchButtonAction(_ sender: UIButton){
        if sender.tag == 1001 {
            if UserInfo.sharedInstance.isMemberShip {
                //拍照
                shootingMode = .CCShootingMode_Camera
                
                shutterPhotoButton.isHidden = false
                shutterVideoButton.isHidden = true
                changeSwitchstatus()
            }
            else {//前往内购订阅页面
                let vc:MembershipVC = MembershipVC()
                let nav = UINavigationController(rootViewController: vc)
                nav.modalTransitionStyle = UIModalTransitionStyle.coverVertical
                nav.modalPresentationStyle = .fullScreen
                self.present(nav, animated: true)
                //统计
                Analytics.logEvent("capture_unvip_pv", parameters: nil)
                
            }
            
        }else if sender.tag == 1002 {
            //录像
            shootingMode = .CCShootingMode_Video
            
            shutterPhotoButton.isHidden = true
            shutterVideoButton.isHidden = false
            changeSwitchstatus()
        }
        
        
    }
    
    
    //MARK: - 屏幕旋转监听
    func dealDeviceScreenOrientationByMotaion(_ motion:CMDeviceMotion){
        
        let x = motion.gravity.x
        let y = motion.gravity.y
        
        if (fabs(y) >= fabs(x)){
            
            if deviceOrientation != 1 {
                enableShutterBtn(false)
                deviceOrientation = 1
                print("竖屏");
                autoStopRecordVideo()
                showHorizontalScreenTips()
            }
            
        }
        else{
            
            if deviceOrientation != 2 {
                enableShutterBtn(true)
                deviceOrientation = 2
                hidenHorizontalScreenTips()
                print("横屏");
            }
            if x >= 0{//右横屏
                imageCGImagePropertyOrientation = .right
            }
            else{//左横屏
                imageCGImagePropertyOrientation = .left
            }
        }

    }
    
  
    
    //当屏幕转向发生改变时，自动结束录像
    func autoStopRecordVideo(){
        if self.isRecording {
            stopRVideo()
        }
    }
    
    
    
    
    deinit {
        // 移除通知
//        // 结束生成设备旋转方向通知
        print("shootcontroller deinit....")
        if let timer = self.timer {
            // 当视图控制器被释放时，取消定时器
            timer.invalidate()
        }
    }
}
