//
//  VRVideoTransformController.swift
//  SwiftProject
//
//  Created by Zhang, Joyce on 2024/2/19.
//

import AVFoundation
import UIKit
import AVKit
import DeviceKit

import CoreImage
import Foundation
import Observation
import VideoToolbox
import Photos
import SVProgressHUD
import Firebase
//比例
enum VideoBitsPerPixel : CGFloat {
    case best = 1.0
    case high = 0.8
    case medium = 0.5
    case low = 0.25
}
//3D format
enum Video3DFormat : Int {
    
    /*
     3D HSBS（半宽左右格式）
     3D FSBS（全款左右格式）
     3D HOU（半高上下格式）
     3D FOU（全高上下格式）
     */
    
    case HSBS
    case FSBS
    case HOU
    case FOU
}

class VRVideoTransformController: BaseController {
    let kNowTimeToUserDefaultKey_VideoTransformController:String = "kNowTimeToUserDefaultKey_VideoTransformController"
    
    var heroAsset1:AVAsset?
    var videoOriginalPHAsset:PHAsset?
    
    var sourceVideoURL:URL?
    //    private var myPlayer: AVPlayer!
    
    var mTopImgView:UIImageView?
    var mAvPlayer:AVPlayerViewController?
    
    var mCenView:UIView?
    var mCenLab1:UILabel?
    var mCenLab2:UILabel?
    var mCenBtn:UIButton?
    
    var mLabel:UILabel?
    var mTabView:CCSpatialPlayView?
    
    var mBottomBtn:UIButton?
    lazy var progressView:CCTransformProgressPopView? = {
        let pv = CCTransformProgressPopView.init(frame: view.bounds)
        pv.closeActionBlock = { [weak self] in
            self?.navigationController?.popToRootViewController(animated: true)
            pv.removeFromSuperview()
        }
        pv.transformActionBlock = {
            pv.isHidden = true
        }
        return pv
    }()
    
    //长宽
    var videoWidth:Int = 1440
    var videoHeight:Int = 1440
    //分辨率
    var selectedPreset:AVOutputSettingsPreset = .mvhevc1440x1440
    //bit
    var selectedBitsPerPixel:VideoBitsPerPixel = .best
    
    //3D 格式
    var selected3DFormat:Video3DFormat = .HSBS
    let spatialVideoConver = SpatialVideoConvertor()
    /*
     编码
     HEVC(H.265、MPEG-H Part 2) 是一种视频编码格式，全称为High Efficiency Video Coding，也被称为H.265和MPEG-H Part 2
     HEVC是作为H.264/AVC（高级视频编码）的继任者而设计的，旨在提供更高效的视频压缩和更好的视频质量。在同等视频质量下，HEVC相比H.264能够减小文件大小高达40%，因此被广泛应用于视频流媒体和存储中。158
     */
    var selectedCodecType:AVVideoCodecType = AVVideoCodecType.h264
    
    //显示进度条
    func showProgress() {
        if self.progressView?.superview == nil {
            self.view.addSubview(self.progressView!)
        }
        //还未处理完毕...
        self.progressView?.resetUI()
        self.progressView?.isHidden = false
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.setNavgationBarColor(color: UIColor.clear)
        
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        let sec:TimeInterval = ZZHHelper.getSecFromUserDefaultByKey(kNowTimeToUserDefaultKey_VideoTransformController)
        Analytics.logEvent("transcode_video_pv", parameters: ["refer_page":"视频转码页面","duration":sec])
    }
    
    deinit {
        print("deinit--class:\(String(describing: object_getClass(self))) objc:\(self)")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        ZZHHelper.setNowTimeToUserDefaultWithKey(kNowTimeToUserDefaultKey_VideoTransformController)
        self.view.backgroundColor = UIColor.black
        self.navLine?.isHidden = true
        self.setNavgaionTitle(string: "视频转码")
        
        //393*236
        mTopImgView = UIImageView(frame: CGRect(x: 0, y: 0, width: SCREEN_Width, height: SCREEN_Height * 236/393))
        view.addSubview(mTopImgView!)
        mTopImgView?.image = UIImage.init(named: "BG_Top")
        self.view.bringSubviewToFront(self.navtionBar!)
        
        
        //345*200
        mAvPlayer = AVPlayerViewController()
        mAvPlayer?.view.frame = CGRect(x: 24, y: Int(SafeAreaTop_Height) + 24, width: Int(SCREEN_Width) - 48, height: (Int(SCREEN_Width) - 48) * 200/345)
        self.addChild(mAvPlayer!)
        self.view.addSubview(mAvPlayer!.view)
//        mAvPlayer?.view.backgroundColor = UIColor.hexStringToColor(hexString: "#666666")
        mAvPlayer?.view.backgroundColor = UIColor.clear
        mAvPlayer!.view.clipsToBounds = true
        mAvPlayer!.view.layer.cornerRadius = 8
        
        if sourceVideoURL != nil {
            let player = AVPlayer(url: sourceVideoURL!)
            mAvPlayer!.player = player
            player.play()
        }else{
            let path = Bundle.main.path(forResource: "IMG_0071", ofType: "MOV")
            let videoURL = URL.init(filePath: path!)
            sourceVideoURL = videoURL
            let player = AVPlayer(url: videoURL)
            mAvPlayer!.player = player
            player.play()
        }
        
        
        
        self.creatUI()
        setSpatialParametersListData()
    }
    
    
    func creatUI() {
        mBottomBtn = UIButton.init(type: UIButton.ButtonType.custom)
        self.view.addSubview(mBottomBtn!)
        mBottomBtn!.backgroundColor = UIColor.hexStringToColor(hexString: "#5326D6")
        mBottomBtn?.tag = 1000
        mBottomBtn?.isSelected = false
        mBottomBtn?.addTarget(self, action: #selector(navgationButtonClick2(sender:)), for: UIControl.Event.touchUpInside)
        mBottomBtn?.frame = CGRect(x: 24, y: 10, width: SCREEN_Width - 48, height: 54)
        mBottomBtn!.bottom = SCREEN_Height - SafeAreaBottom_Height - 30
        mBottomBtn!.clipsToBounds = true
        mBottomBtn!.layer.cornerRadius = 8
        mBottomBtn!.setTitle("转码导出", for: UIControl.State.normal)
        mBottomBtn!.setTitleColor(UIColor.white, for: UIControl.State.normal)
        mBottomBtn!.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        
        
        mCenView = UIView()
        self.view.addSubview(mCenView!)
        mCenView?.frame = CGRect(x: 24, y: Int(mAvPlayer!.view.bottom) + 16, width: Int(SCREEN_Width) - 48, height: 70)
        mCenView?.clipsToBounds = true
        mCenView?.layer.cornerRadius = 12
        mCenView?.backgroundColor = UIColor.colorWithRGB(_r: 18, _g: 7, _b: 68)
        
        mCenLab1 = UILabel()
        mCenLab1!.bounds = CGRect(x: 0, y: 0, width: 100, height: 0)
        mCenLab1!.textColor = UIColor.hexStringToColor(hexString: "#ffffff")
        mCenLab1!.font = UIFont.systemFont(ofSize: 14)
        mCenView!.addSubview(mCenLab1!)
        mCenLab1!.text = "--"
        mCenLab1!.text = videoOriginalPHAsset?.value(forKey: "filename") as? String
        mCenLab1!.sizeToFit()

        if(mCenLab1!.width > mCenView!.width - 140){
            mCenLab1!.width = mCenView!.width - 140
        }
        mCenLab1!.top = 12
        mCenLab1!.left = 16
        
        
        mCenLab2 = UILabel()
        mCenLab2!.bounds = CGRect(x: 0, y: 0, width: 100, height: 0)
        mCenLab2!.textColor = UIColor.hexStringToColor(hexString: "#67617A")
        mCenLab2!.font = UIFont.systemFont(ofSize: 12)
        mCenView!.addSubview(mCenLab2!)
        let durationStr:String = ZZHHelper.formatVideoTime(second: Int(videoOriginalPHAsset?.duration ?? 0))
 
        let ar:PHAssetResource = PHAssetResource.assetResources(for: videoOriginalPHAsset!).first!
        let fileSize:Double = ar.value(forKey: "fileSize") as! Double
        let videoSize = Double(fileSize) / 1024 / 1024
        mCenLab2!.text = String(format: "\(durationStr) · %.1f MB",videoSize)
        
        mCenLab2!.sizeToFit()
        if(mCenLab2!.width > mCenView!.width - 140){
            mCenLab2!.width = mCenView!.width - 140
        }
        mCenLab2!.top = 38
        mCenLab2!.left = 16
        
        mCenBtn = UIButton.init(type: UIButton.ButtonType.custom)
        mCenView!.addSubview(mCenBtn!)
        mCenBtn!.backgroundColor = UIColor.hexStringToColor(hexString: "#5326D6")
        mCenBtn?.tag = 1001
        mCenBtn?.isSelected = false
        mCenBtn?.addTarget(self, action: #selector(navgationButtonClick2(sender:)), for: UIControl.Event.touchUpInside)
        mCenBtn?.frame = CGRect(x: 24, y: 10, width: 84, height: 36)
        mCenBtn!.centerY = mCenView!.height * 0.5
        mCenBtn!.right = mCenView!.width - 16
        mCenBtn!.clipsToBounds = true
        mCenBtn!.layer.cornerRadius = 10
        mCenBtn!.setTitle("MV-HEVC", for: UIControl.State.normal)
        mCenBtn!.setTitleColor(UIColor.white, for: UIControl.State.normal)
        mCenBtn!.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        
        
        mLabel = UILabel()
        mLabel!.bounds = CGRect(x: 0, y: 0, width: 100, height: 0)
        mLabel!.textColor = UIColor.hexStringToColor(hexString: "#6A696A")
        mLabel!.font = UIFont.systemFont(ofSize: 14)
        self.view.addSubview(mLabel!)
        mLabel!.text = "格式"
        mLabel!.sizeToFit()
        mLabel!.top = mCenView!.bottom + 32
        mLabel!.left = 24
        
        let maxHi = mBottomBtn!.top - mCenView!.bottom - 110
        var hi = 62.0*5
        if(hi > maxHi){hi = maxHi}
        mTabView = CCSpatialPlayView.init(frame: CGRect(x: 24, y: mCenView!.bottom + 70, width: SCREEN_Width - 48, height: hi))
        self.view.addSubview(mTabView!)
        mTabView!.backgroundColor = UIColor.hexStringToColor(hexString: "#1F1E20")
        mTabView?.clipsToBounds = true
        mTabView?.layer.cornerRadius = 12
        mTabView?.handle = {dic in
            print(dic)
            self.selectedCellAction(dic)
        }
    }
    
    
    func setSpatialParametersListData() {
        let popData = [
            (type:CCTransformParameterType.format3D,title:"3D 格式",name:"3D HSBS"),
            (type:CCTransformParameterType.resolution,title:"分辨率",name:"原始"),
            (type:CCTransformParameterType.bitRate,title:"比特率",name:"最佳"),
            (type:CCTransformParameterType.formatVideoEncoding,title:"视频编码格式",name:"H.265"),
            (type:CCTransformParameterType.horizontalDialogueAdjustment,title:"水平视差调整",name:"0")]
        
        mTabView?.setSpatialParametersData(data: popData)
    }
    
    
    //MARK: - click
    @objc public func navgationButtonClick2(sender:UIButton){
        
        print("nihao")
        
        
        if(sender.tag == 1000){
            //转码
            self.videoTransformAction()
        }else if(sender.tag == 1001){
            //格式选择
        }
        
    }
    //MARK: - 刷新界面
    func according3DFormatShowList(format:Video3DFormat) {
        var presetText = "原始"
        switch self.selectedPreset {
        case .mvhevc1440x1440:
            presetText = "原始"
            break
        case .hevc3840x2160:
            presetText = "4K"
            break
        case .hevc1920x1080:
            presetText = "1080p"
            break
        case .preset1280x720:
            presetText = "720p"
            break
        default:
            break
        }
        
        
        
        var bitText = "最佳"
        switch self.selectedBitsPerPixel {
        case .best:
            bitText = "最佳"
            break
        case .high:
            bitText = "高"
            break
        case .medium:
            bitText = "中"
            break
        case .low:
            bitText = "低"
            break
        }
        
        
        
        
        var codecTypeText = "H.265"
        switch self.selectedCodecType {
        case AVVideoCodecType.hevc:
            codecTypeText = "H.265"
            break
        case AVVideoCodecType.h264:
            codecTypeText = "264"
            break
        default:
            break
        }
        
        
        
        
        //列表数据
        var popData = [
            (type:CCTransformParameterType.format3D,title:"3D 格式",name:"3D HSBS"),
            (type:CCTransformParameterType.resolution,title:"分辨率",name:presetText),
            (type:CCTransformParameterType.bitRate,title:"比特率",name:bitText),
            (type:CCTransformParameterType.formatVideoEncoding,title:"视频编码格式",name:codecTypeText),
            (type:CCTransformParameterType.horizontalDialogueAdjustment,title:"水平视差调整",name:"0")]
        
        
        switch format {
        case .HSBS:
            popData = [
                (type:CCTransformParameterType.format3D,title:"3D 格式",name:"3D HSBS"),
                (type:CCTransformParameterType.resolution,title:"分辨率",name:presetText),
                (type:CCTransformParameterType.bitRate,title:"比特率",name:bitText),
                (type:CCTransformParameterType.formatVideoEncoding,title:"视频编码格式",name:codecTypeText),
                (type:CCTransformParameterType.horizontalDialogueAdjustment,title:"水平视差调整",name:"0")]
            
            break
        case .FSBS:
            popData = [
                (type:CCTransformParameterType.format3D,title:"3D 格式",name:"3D FSBS"),
                (type:CCTransformParameterType.resolution,title:"分辨率",name:presetText),
                (type:CCTransformParameterType.bitRate,title:"比特率",name:bitText),
                (type:CCTransformParameterType.formatVideoEncoding,title:"视频编码格式",name:codecTypeText)]
            
            break
        case .HOU:
            popData = [
                (type:CCTransformParameterType.format3D,title:"3D 格式",name:"3D HOU"),
                (type:CCTransformParameterType.resolution,title:"分辨率",name:presetText),
                (type:CCTransformParameterType.bitRate,title:"比特率",name:bitText),
                (type:CCTransformParameterType.formatVideoEncoding,title:"视频编码格式",name:codecTypeText),
                (type:CCTransformParameterType.horizontalDialogueAdjustment,title:"水平视差调整",name:"0")]
            
            break
        case .FOU:
            popData = [
                (type:CCTransformParameterType.format3D,title:"3D 格式",name:"3D FOU"),
                (type:CCTransformParameterType.resolution,title:"分辨率",name:presetText),
                (type:CCTransformParameterType.bitRate,title:"比特率",name:bitText),
                (type:CCTransformParameterType.formatVideoEncoding,title:"视频编码格式",name:codecTypeText)]
            
            break
        }
        
        
        
        
        mTabView?.setSpatialParametersData(data: popData)
        
    }
    
    //MARK: - action
    func selectedCellAction(_ model:(type:CCTransformParameterType,title:String,name:String)) {
        
        
        let device = Device.current
        var alert = UIAlertController.init()
        if device.isPhone {
            alert = UIAlertController(title:nil, message: nil, preferredStyle: .actionSheet)
        }else{
            alert = UIAlertController(title:nil, message: nil, preferredStyle: .alert)
        }
        
        switch model.type {
        case .format3D:
            print("3D 格式")
//            print("3D 格式")
            /*
             3D HSBS（半宽左右格式）
             3D FSBS（全款左右格式）
             3D HOU（半高上下格式）
             3D FOU（全高上下格式）
             */
            let action1 = UIAlertAction(title: "3D HSBS（半宽左右格式）" , style: .default) { (action:UIAlertAction) in
                self.selected3DFormat = .HSBS
                self.according3DFormatShowList(format: .HSBS)
            }
            let action2 = UIAlertAction(title: "3D FSBS（全宽左右格式）" , style: .default) { (action:UIAlertAction) in
                self.selected3DFormat = .FSBS
                self.according3DFormatShowList(format: .FSBS)
            }
            let action3 = UIAlertAction(title: "3D HOU（半高上下格式）" , style: .default) { (action:UIAlertAction) in
                self.selected3DFormat = .HOU
                self.according3DFormatShowList(format: .HOU)
            }
            let action4 = UIAlertAction(title: "3D FOU（全高上下格式）" , style: .default) { (action:UIAlertAction) in
                self.selected3DFormat = .FOU
                self.according3DFormatShowList(format: .FOU)
            }
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            alert.addAction(action1)
            alert.addAction(action2)
            alert.addAction(action3)
            alert.addAction(action4)
            alert.addAction(cancelAction)
            self.present(alert, animated: true, completion: nil)
            
            break
        case .resolution:
            print("分辨率")
            
            /*
             720P 的分辨率为 1280x720 像素。
             1080P 的分辨率为 1920x1080 像素。
             4K 的分辨率为 3840x2160 像素。1
             */
            
            let action1 = UIAlertAction(title: "原始" , style: .default) { (action:UIAlertAction) in
                self.selectedPreset = .mvhevc1440x1440
                self.videoWidth = 1440
                self.videoHeight = 1440
                self.according3DFormatShowList(format: self.selected3DFormat)
            }
            let action2 = UIAlertAction(title: "4K" , style: .default) { (action:UIAlertAction) in
                self.selectedPreset = .hevc3840x2160
                self.videoWidth = 3840
                self.videoHeight = 2160
                self.according3DFormatShowList(format: self.selected3DFormat)
            }
            let action3 = UIAlertAction(title: "1080p" , style: .default) { (action:UIAlertAction) in
                self.selectedPreset = .hevc1920x1080
                self.videoWidth = 1920
                self.videoHeight = 1080
                self.according3DFormatShowList(format: self.selected3DFormat)
            }
            let action4 = UIAlertAction(title: "720p" , style: .default) { (action:UIAlertAction) in
                self.selectedPreset = .preset1280x720
                self.videoWidth = 1280
                self.videoHeight = 720
                self.according3DFormatShowList(format: self.selected3DFormat)
            }
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            alert.addAction(action1)
            alert.addAction(action2)
            alert.addAction(action3)
            alert.addAction(action4)
            alert.addAction(cancelAction)
            self.present(alert, animated: true, completion: nil)
            
            
            break
        case .bitRate:
            print("比特率")
            /*
             最佳（最佳比特率，与原视频一致）
             高（约为原视频80%）
             中（约为原视频50%）
             低（约为原视频25%）
             
             */
            let action1 = UIAlertAction(title: "最佳" , style: .default) { (action:UIAlertAction) in
                self.selectedBitsPerPixel = .best
                self.according3DFormatShowList(format: self.selected3DFormat)
            }
            let action2 = UIAlertAction(title: "高" , style: .default) { (action:UIAlertAction) in
                self.selectedBitsPerPixel = .high
                self.according3DFormatShowList(format: self.selected3DFormat)
            }
            let action3 = UIAlertAction(title: "中" , style: .default) { (action:UIAlertAction) in
                self.selectedBitsPerPixel = .medium
                self.according3DFormatShowList(format: self.selected3DFormat)
            }
            let action4 = UIAlertAction(title: "低" , style: .default) { (action:UIAlertAction) in
                self.selectedBitsPerPixel = .low
                self.according3DFormatShowList(format: self.selected3DFormat)
            }
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            alert.addAction(action1)
            alert.addAction(action2)
            alert.addAction(action3)
            alert.addAction(action4)
            alert.addAction(cancelAction)
            self.present(alert, animated: true, completion: nil)
            
            
            break
        case .formatVideoEncoding:
            print("视频编码格式")
            /*
             H.265
             H.264
             
             */
            let action1 = UIAlertAction(title: "H.265" , style: .default) { (action:UIAlertAction) in
                //HEVC 也被称为H.265和MPEG-H Part 2
                self.selectedCodecType = AVVideoCodecType.hevc
                self.according3DFormatShowList(format: self.selected3DFormat)
            }
            let action2 = UIAlertAction(title: "H.264" , style: .default) { (action:UIAlertAction) in
                self.selectedCodecType = AVVideoCodecType.h264
                self.according3DFormatShowList(format: self.selected3DFormat)
            }
            
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            alert.addAction(action1)
            alert.addAction(action2)
            alert.addAction(cancelAction)
            self.present(alert, animated: true, completion: nil)
            
            
            break
        case .horizontalDialogueAdjustment:
            print("水平视差调整")
            break
            //        default:
            //            print("未知的媒体类型")
            //            break
        default:
            break
        }
        
    }
}


extension VRVideoTransformController {
    
    @objc private func videoTransformAction() {
        self.mAvPlayer?.player?.pause()
        
        let videoOriginalAsset:AVAsset? = AVAsset(url: sourceVideoURL!)
        if !ZZHHelper.isSpatialVideo(asset: videoOriginalAsset!) {
            SVProgressHUD.showInfo(withStatus: "非空间视频不能转码")
            return
        }
        
        self.showProgress()
        
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let outputURL = documentsDirectory.appendingPathComponent("output_path.mov")
        
        do {
            try FileManager.default.removeItem(atPath: outputURL.path)
            print("视频文件删除成功")
        } catch {
            print("删除视频文件出错：\(error)")
        }
        
        
        //长宽
        let width = self.videoWidth
        let height = self.videoHeight
        
        //计算比特率
        let pixelsCount:CGFloat = CGFloat(videoWidth * videoHeight)
        let bitsPerPixel = self.selectedBitsPerPixel
        let bitsPerSecond = pixelsCount*bitsPerPixel.rawValue
        let dataRate:Int = Int(bitsPerSecond)
        //视频编码
        let codecType = self.selectedCodecType
        
        let horizontalDisparity: Float = 0.0
        let horizontalFieldOfView: Float = 90.0
        let outputVideoURL =  URL.documentsDirectory.appending(path:"convertor_one.mov")
        
        Task {
            try await spatialVideoConver.convertVideo(asset: videoOriginalAsset!, outputFile: outputVideoURL ,type: self.selected3DFormat) { [weak self] (progress,state) in
                if(state){
                    DispatchQueue.main.async {
                        self?.progressView?.updateProgress(value: 0.8)
                    }
                    
                    // 要执行的任务
                    self?.exportVideo(url: outputVideoURL, outputURL: outputURL, width: width, height: height,codecType:codecType, dataRate: dataRate, horizontalDisparity: horizontalDisparity, horizontalFieldOfView: horizontalFieldOfView) {  exportedAsset in
                    }
                }
                else {
                    print(".....out pro:\(progress)")
                    DispatchQueue.main.async {
                        print(".....in pro:\(progress)")
                        self?.progressView?.updateProgress(value: progress)
                    }
                    
                }
            }
        }
    }
    
  
    private func exportVideo(url: URL, outputURL: URL, width: Int, height: Int,codecType:AVVideoCodecType, dataRate: Int, horizontalDisparity: Float, horizontalFieldOfView: Float, completion: @escaping (AVAsset?) -> Void) {
        let asset = AVAsset(url: url)
        
        guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetPassthrough) else {
//            print("Failed to create export session")
            DispatchQueue.main.async {
                self.progressView?.updateInfo(title: "转码失败", desc: "导出会话创建失败")
            }
            
            completion(nil)
            return
        }
        
        let composition = AVMutableComposition()
        let videoTrack = composition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)
        
        guard let assetTrack = asset.tracks(withMediaType: .video).first else {
//            print("Failed to get video track from asset")
            DispatchQueue.main.async {
                self.progressView?.updateInfo(title: "转码失败", desc: "未能成功加载视频轨道")
            }
            completion(nil)
            return
        }
        
        do {
            try videoTrack?.insertTimeRange(CMTimeRange(start: .zero, duration: asset.duration), of: assetTrack, at: .zero)
        } catch {
//            print("Failed to insert video track into composition")
            DispatchQueue.main.async {
                self.progressView?.updateInfo(title: "转码失败", desc: "未能成功插入视频轨道")
            }
            completion(nil)
            return
        }
        //分辨率
        //        var videoSettings = AVOutputSettingsAssistant(preset: .mvhevc1440x1440)?.videoSettings
        var videoSettings = AVOutputSettingsAssistant(preset: self.selectedPreset)?.videoSettings
        //长宽
        videoSettings?[AVVideoWidthKey] = width
        videoSettings?[AVVideoHeightKey] = height
        //视频编码AVVideoCodecType
//        videoSettings?[AVVideoCodecKey] = codecType.rawValue
        videoSettings?[AVVideoCodecKey] = AVVideoCodecType.hevc
        //设置视频缩放方式
        videoSettings?[AVVideoScalingModeKey] = AVVideoScalingModeResizeAspectFill
        /*
         AVVideoCompressionPropertiesKey对应下面的参数
         
         1.AVVideoAverageBitRateKey：比特率 --- 视频尺寸*比率，10.1相当于AVCaptureSessionPresetHigh，数值越大，显示越精细
         2.AVVideoExpectedSourceFrameRateKey 帧率
         3.AVVideoProfileLevelKey:
         4.AVVideoMaxKeyFrameIntervalKey：关键帧最大间隔，1为每个都是关键帧，数值越大压缩率越高
         */
        
        /*
         CMVideoCodecType：编码类型，kCMVideoCodecType_H264 对应 H.264
         kVTCompressionPropertyKey_ProfileLevel：指定编码比特流的配置文件和级别。直播一般使用 baseline，可减少由于 b 帧带来的延时
         kVTCompressionPropertyKey_RealTime：是否实时编码
         kVTCompressionPropertyKey_AverageBitRate：平均码率
         kVTCompressionPropertyKey_AllowTemporalCompression：是否开启帧间压缩
         kVTCompressionPropertyKey_MaxKeyFrameInterval：设置 GOP 大小，每隔 X 帧有一个关键帧
         kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration：关键帧之间的 duration，每 Y 秒有一个关键帧。这两个属性可以同时设置，满足其中一个即可。
         
         */
        
        var compressionProperties = videoSettings?[AVVideoCompressionPropertiesKey] as! [String: Any]
        
        //比特率(码率)：视频比特率是指每秒传送的比特(bit)数。单位为bps(Bit Per Second)，比特率越高，每秒传送 数据 就越多，画质就越清晰。
        compressionProperties[AVVideoAverageBitRateKey] = dataRate
        //视差
        compressionProperties[kCMFormatDescriptionExtension_HorizontalDisparityAdjustment as String] = horizontalDisparity
        //水平视场以千分之一度为单位(即123456是123.456度)。
        compressionProperties[kCMFormatDescriptionExtension_HorizontalFieldOfView as String] = horizontalFieldOfView
        
        
        videoSettings?[AVVideoCompressionPropertiesKey] = compressionProperties
        
        let writerInput = AVAssetWriterInput(mediaType: .video, outputSettings: videoSettings)
        writerInput.expectsMediaDataInRealTime = false
        
        guard let writer = try? AVAssetWriter(outputURL: outputURL, fileType: AVFileType.mp4) else {
            print("Failed to create AVAssetWriter")
//            DispatchQueue.main.async {
//                SVProgressHUD.showInfo(withStatus: "视频转码失败")
//            }
            DispatchQueue.main.async {
                self.progressView?.updateInfo(title: "转码失败", desc: "创建媒体写入失败")
            }
            completion(nil)
            return
        }
        
        writer.add(writerInput)
        DispatchQueue.main.async {
            self.progressView?.updateProgress(value: 1)
        }
        
        exportSession.videoComposition = AVMutableVideoComposition(propertiesOf: composition)
        exportSession.outputFileType = AVFileType.mov
        exportSession.outputURL = outputURL
        
        exportSession.exportAsynchronously { [self] in
            switch exportSession.status {
            case .completed:
                let exportedAsset = AVAsset(url: outputURL)
                DispatchQueue.main.async {
                    self.saveVideoToAlbum(url: outputURL)
                    completion(exportedAsset)
                }
            case .failed:
                if let error = exportSession.error {
                    print("Export failed with error: \(error.localizedDescription)")
                    DispatchQueue.main.async {
//                        SVProgressHUD.showInfo(withStatus: "视频导出失败：\(error.localizedDescription)")
                        self.progressView?.updateInfo(title: "转码完成", desc: "导出内容失败")
                    }
                } else {
                    print("Export failed")
                    DispatchQueue.main.async {
//                        SVProgressHUD.showInfo(withStatus: "视频导出失败")
                        self.progressView?.updateInfo(title: "转码完成", desc: "导出内容失败")
                    }
                    
                }
                completion(nil)
            case .cancelled:
                print("Export cancelled")
                DispatchQueue.main.async {
//                    SVProgressHUD.showInfo(withStatus: "视频导出失败 cancelled")
                    self.progressView?.updateInfo(title: "转码完成", desc: "导出内容失败")
                }
                completion(nil)
            default:
                break
            }
        }
    }
    
    
    func saveVideoToAlbum(url: URL) {
       PHPhotoLibrary.shared().performChanges {
           PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url)
       } completionHandler: { success, error in
           if success {
               print("Video saved to album")
               DispatchQueue.main.async {
                   //SVProgressHUD.showSuccess(withStatus: "视频转码成功，已保存到相册")
                   self.progressView?.updateInfo(title: "转码完成", desc: "导出内容已存储到相册中")
               }
           } else {
               print("Failed to save video to album: \(error?.localizedDescription ?? "Unknown error")")
               DispatchQueue.main.async {
                   //SVProgressHUD.showInfo(withStatus: "视频转码失败：\(error?.localizedDescription ?? "Unknown error")")
                   self.progressView?.updateInfo(title: "转码完成", desc: "导出内容失败")
               }
               
           }
       }
   }
    
}
