//
//  CCSpatialShootController+CaputreAction.swift
//  SwiftProject
//
//  Created by aaa on 2024/5/20.
//

import Foundation

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

extension CCSpatialShootController {
    
    //拍照
    @objc func shutterPhotoButtonAction(){

        
        shutterPhotoButton.backgroundColor = .gray
        
        imgs.removeAllObjects()
        guard let wideAngleCameraVideoDataOutput,
              let ultraWideCameraVideoDataOutput else {
            print("Movie output not configured")
            return
        }
        
        
        //快门声音
        let soundID: SystemSoundID = 1108
        AudioServicesPlaySystemSound(soundID)
        
//        let time = Date().timeIntervalSince1970
//        let name1 = "wideAnglePhoto" + String(time) + ".mov"
//        let name2 = "ultraWidePhoto" + String(time) + ".mov"
//        let wideAngleCameraOutputURL = URL.documentsDirectory.appending(path:name1)
//        let ultraWideCameraOutputURL = URL.documentsDirectory.appending(path:name2)
//        
//        wideAngleCameraMovieOutput.startRecording(to: wideAngleCameraOutputURL, recordingDelegate: self)
//        ultraWideCameraMovieOutput.startRecording(to: ultraWideCameraOutputURL, recordingDelegate: self)
        
        //摄像头录像，取0.1秒长度，如果是拍摄照片去两张，拍摄成功会听到两次声音，所以这里用摄像的方式取图片
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {[weak self] in
            self?.shutterPhotoButton.backgroundColor = .white
            self?.isTakePhoto_wideCamera = true
            self?.isTakePhoto_ultraCamera = true
            self?.isTakePhoto = true
//            self.stopVideoRecording()
        }
    }
    
    //录像
    @objc func shutterVideoButtonAction(_ sender: UIButton){
        if !isRecordingVideoData {//开始录制
            writeVideoQueuen.async {[weak self] in//串行 异步执行
                if let weakSelf = self {
                    weakSelf.removeExistingFile(at: weakSelf.outputVideoURL)
                    weakSelf.isRecordingVideoData = true
                }
                
            }
            
        }
        else {//录制完毕
            writeVideoQueuen.async {[weak self] in//串行 异步执行
                if let weakSelf = self {
                    weakSelf.isRecordingVideoData = false
                    weakSelf.svdWriter.writeVideoDataDeInit {result, err in
                        //保存导出视频
                        weakSelf.saveVideoToLibrary(videoURL: weakSelf.outputVideoURL)
                    }
                }
            }
        }
        
        
        
        if !self.isRecording {
            //录像中
            print("录像中...")
            
            UIView.animate(withDuration: 0.3) {
                // 更新视图的transform属性，将其缩小
                self.shutterVideoButton.transform = CGAffineTransform(scaleX: 0.53, y: 0.53)
                self.shutterVideoButton.layer.cornerRadius = 4
            }completion: { finished in
                self.isRecording = true
                self.changeSwitchstatus()
            }
            
            
            //开启录制
            startRecordingTimer()
            startVideoRecording()
            
            
        }else{
            stopRVideo()
        }
    }
    
    func stopRVideo(){
        print("录像结束!!!")
        //停止录制
        stopRecordingTimer()
        stopVideoRecording()
        UIView.animate(withDuration: 0.3) {
            // 更新视图的transform属性，将其放大
            self.shutterVideoButton.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
            self.shutterVideoButton.layer.cornerRadius = 28
        }completion: { finished in
            self.isRecording = false
            self.changeSwitchstatus()
        }
    }
    
    // MARK: - 开始/停止录制
    private func startVideoRecording() {
        guard let wideAngleCameraVideoDataOutput,
              let ultraWideCameraVideoDataOutput else {
            print("Movie output not configured")
            return
        }
        
//        let time = Date().timeIntervalSince1970
//        let name1 = "wideAngleVideo" + String(time) + ".mov"
//        let name2 = "ultraWideVideo" + String(time) + ".mov"
//        leftEyeVideoURL = nil
//        rightEyeVideoURL = nil
//        let wideAngleCameraOutputURL = URL.documentsDirectory.appending(path:name1)
//        let fultraWideCameraOutputURL = URL.documentsDirectory.appending(path:name2)
//        
//        wideAngleCameraMovieOutput.startRecording(to: wideAngleCameraOutputURL, recordingDelegate: self)
//        ultraWideCameraMovieOutput.startRecording(to: fultraWideCameraOutputURL, recordingDelegate: self)
        
        
    }
    
    private func stopVideoRecording(){
//        guard let wideAngleCameraMovieOutput = wideAngleCameraMovieOutput,
//              let ultraWideCameraMovieOutput = ultraWideCameraMovieOutput else {
//            print("Movie output not configured")
//            return
//        }
//        
//        wideAngleCameraMovieOutput.stopRecording()
//        ultraWideCameraMovieOutput.stopRecording()
        
    }
    
    //MARK: - 改变按钮状态
    func changeSwitchstatus() {
        
        if isRecording {
            self.switchBackView.isHidden = true
            self.vipLogoView.isHidden = true
            cameraLabel.isHidden = true
            videoLabel.isHidden = true
        }else{
            self.switchBackView.isHidden = false
            if !UserInfo.sharedInstance.isMemberShip {
                self.vipLogoView.isHidden = false
            }
            
            if shootingMode == .CCShootingMode_Camera {
                //拍照
                cameraLabel.isHidden = false
                videoLabel.isHidden = true
                
                cameraButton.backgroundColor = UIColor(hexString: "#000000", alpha: 0.3)
                cameraButton.setImage(UIImage(named: "camera_button_selected"), for: .normal)
                
                videoButton.backgroundColor = .clear
                videoButton.setImage(UIImage(named: "video_button_normal"), for: .normal)
                
            }else if shootingMode == .CCShootingMode_Video {
                //录像
                cameraLabel.isHidden = true
                videoLabel.isHidden = false
                
                cameraButton.backgroundColor = .clear
                cameraButton.setImage(UIImage(named: "camera_button_normal"), for: .normal)
                
                videoButton.backgroundColor = UIColor(hexString: "#000000", alpha: 0.3)
                videoButton.setImage(UIImage(named: "video_button_selected"), for: .normal)
            }
        }
    }
    
    
    // MARK: - 开启/关闭定时器
    func startRecordingTimer() {
        var count = 0 // 初始化计数变量为0
        timer = Timer(timeInterval: 1, repeats: true, block: { timer in
            DispatchQueue.global().async {
                // 在后台线程中执行任务
                // 模拟耗时操作（这里只是打印当前计数）
                count += 1
                let timeText = self.transToHourMinSec(second: count)
                DispatchQueue.main.async {
//                    self.setNavgaionTitle(string: timeText)
                    self.setNavgationTitleForCaptureVC(string: timeText)
                }
            }
        })
        
        //录制过程中timer会被暂停，只有加入到runloop中才能执行
        RunLoop.main.add(timer!, forMode: .common)
    }
    
    func stopRecordingTimer() {
        self.setNavgaionTitle(string: "")
        if let timer = self.timer {
            // 当视图控制器被释放时，取消定时器
            timer.invalidate()
        }
    }
    
    
    
    // MARK: - 把秒数转换成时分秒（00:00:00）格式
    ///
    /// - Parameter second: 秒数
    /// - Returns: String
    func transToHourMinSec(second: Int) -> String {
        let allTime: Int = second
        var hours = 0
        var minutes = 0
        var seconds = 0
        var hoursText = ""
        var minutesText = ""
        var secondsText = ""
        
        hours = allTime / 3600
        hoursText = hours > 9 ? "\(hours)" : "0\(hours)"
        
        minutes = allTime % 3600 / 60
        minutesText = minutes > 9 ? "\(minutes)" : "0\(minutes)"
        
        seconds = allTime % 3600 % 60
        secondsText = seconds > 9 ? "\(seconds)" : "0\(seconds)"
        
        return "\(hoursText):\(minutesText):\(secondsText)"
    }
    
    
    //MARK: - 获取相册第一张图片
    func getAlbumFirstPhoto() {
        PHPhotoLibrary.requestAuthorization(for: .readWrite) {[weak self] (status) in
            if status == PHAuthorizationStatus.authorized {
                let fetchOptions = PHFetchOptions()
                fetchOptions.sortDescriptors = [NSSortDescriptor(key:"creationDate", ascending: false)]
                
                let image_assetsFetchResults: PHFetchResult<PHAsset>! = PHAsset.fetchAssets(with: .image, options: fetchOptions)
                
                let video_assetsFetchResults: PHFetchResult<PHAsset>! = PHAsset.fetchAssets(with: .video, options: fetchOptions)
                
                let imgAsset = image_assetsFetchResults.firstObject
                let videoAsset = video_assetsFetchResults.firstObject
                var defaultAsset:PHAsset?
                if let imgAsset {
                    defaultAsset = imgAsset
                }
                
                if let videoAsset{
                    if let temp = defaultAsset {
                        if (videoAsset.creationDate ?? Date.now > imgAsset?.creationDate ?? Date.now) {
                            defaultAsset = videoAsset
                        }
                    }
                    else {
                        defaultAsset = videoAsset
                    }
                }
                
                if let defaultAsset {
                    self?.getImageFromAsset(asset: defaultAsset)
                }
            }
        }
    }
    
    func getImageFromAsset(asset:PHAsset){
        //处理模型
        let requestOptions = PHImageRequestOptions()
        requestOptions.isSynchronous = false//设置成同步回调
        requestOptions.deliveryMode = .highQualityFormat
        PHImageManager.default().requestImageDataAndOrientation(for: asset, options: requestOptions) {[weak self] data, dataUTI, imagePropertyOrientation, info in
            if let hasData = data {
                DispatchQueue.main.async {
                    self?.albumButton.setBackgroundImage(UIImage(data: hasData), for: .normal)
                }
            }
            
        }
    }
    
    
    func enableShutterBtn(_ value:Bool) {
        shutterPhotoButton.isEnabled = value
        shutterVideoButton.isEnabled = value
    }
    
    
}
