//
//  INVideoExportController.swift
//  Introduce
//
//  Created by 胡志强 on 2021/11/29.
//

import BFAnalyzeKit
import BFCommonKit
import BFRecordScreenKit
import BFUIKit
import Foundation
import Photos
import SwiftUI
import UIKit

class INVideoExportController: BFBaseViewController {
    var avplayerTimeObserver: NSKeyValueObservation?
    let backV : UIView = {
        let v = UIView()
        v.backgroundColor = UIColor.hexColor(hexadecimal: "#1A1A1A")
        return v
    }()
    
    var hasExportAll = false
    var hasExportOnly = false
    var hasSaveAll = false
    var hasSaveOnly = false
    var saveAllUlr = URL(fileURLWithPath: "aaa")
    var saveOnlyUlr = URL(fileURLWithPath: "aaa")
    var playViewFrame: CGRect = CGRect.zero
    var isExporting = false {
        didSet {
            if isExporting {
                avplayer.pause()
            }
        }
    }
    var enterBackgroundCancleExport = false

    // 预览播放进度
    var sliderView: BFVideoPlayerSliderView?

    // 合成进度指示条
    lazy var progressView: UIView = {
        let v = UIView()
        v.backgroundColor = ThemeStyleColor
        return v
    }()

    // 合成进度百分比lable
    lazy var progressL: UILabel = {
        let la = UILabel()
        la.textColor = .white
        la.textAlignment = .center
        la.text = "0%"
        la.font = UIFont.systemFont(ofSize: 28)
        la.shadowColor = .black
        la.shadowOffset = CGSize(width: 1, height: 1)
        return la
    }()

    lazy var saveAllBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "export_saveall_n"), for: .normal)
        btn.setImage(UIImage(named: "export_saveall_h"), for: .selected)
        btn.addTarget(self, action: #selector(saveAllAction(btn:)), for: .touchUpInside)
        return btn
    }()

    lazy var saveOnlyBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "export_saveonly_n"), for: .normal)
        btn.setImage(UIImage(named: "export_saveonly_h"), for: .selected)
        btn.addTarget(self, action: #selector(saveOnlyAction(btn:)), for: .touchUpInside)
        return btn
    }()

    lazy var completeBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("回到首页", for: .normal)
        btn.setTitleColor(UIColor.hexColor(hexadecimal: "#B1B1B1"), for: .normal)
        btn.setTitleColor(.gray, for: .disabled)
        btn.addTarget(self, action: #selector(completeAction), for: .touchUpInside)
        return btn
    }()

    lazy var saveToPhotoBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle(" 保存到相册", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.setTitleColor(.lightGray, for: .disabled)
        btn.setImage(UIImage(named: "export_btn"), for: .normal)
        btn.adjustsImageWhenDisabled = true
        btn.backgroundColor = ThemeStyleColor
        btn.addCorner(roundingCorners: .allCorners, corner: 8)
        btn.addTarget(self, action: #selector(saveToPhotoNow), for: .touchUpInside)
        return btn
    }()

    lazy var bottomView: UIView = {
        let vv = UIView()
        vv.backgroundColor = .black
//        vv.isHidden = true
        return vv
    }()
    
    lazy var errorView : UIView = {
        let backV = UIView()
        backV.backgroundColor = .black
        backV.isHidden = true
        
        let titleL = UILabel()
        titleL.text = "合成失败"
        titleL.font = UIFont.systemFont(ofSize: 36)
        titleL.textColor = .white
        titleL.textAlignment = .center
        backV.addSubview(titleL)
        
        let subTitleL = UILabel()
        subTitleL.text = "请重新尝试"
        subTitleL.tag = 33000
        subTitleL.font = UIFont.systemFont(ofSize: 24)
        subTitleL.textColor = UIColor.hexColor(hexadecimal: "#A6A6A6")
        subTitleL.textAlignment = .center
        subTitleL.contentCompressionResistancePriority(for: NSLayoutConstraint.Axis.horizontal)
        subTitleL.numberOfLines = 0
        backV.addSubview(subTitleL)
        
        let retryBtn = UIButton()
        retryBtn.backgroundColor = ThemeStyleColor
        retryBtn.setTitle("重试", for: .normal)
        retryBtn.setTitleColor(.white, for: .normal)
        retryBtn.addCorner(corner:5)
        retryBtn.addTarget(self, action: #selector(retryAction), for: .touchUpInside)
        backV.addSubview(retryBtn)
        
        retryBtn.snp.makeConstraints { make in
            make.width.equalTo(245)
            make.height.equalTo(50)
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(10)
        }
        subTitleL.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(retryBtn.snp.top).offset(-30)
        }
        titleL.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(70)
            make.bottom.equalTo(subTitleL.snp.top)
        }
        
        
        return backV
    }()

    var playerLayer: AVPlayerLayer!
    lazy var avplayer: AVPlayer = {
        let avplayer = AVPlayer()
        avplayerTimeObserver = avplayer.addPeriodicTimeObserver(forInterval: CMTime(value: 1, timescale: 100), queue: DispatchQueue.global()) { [weak self, weak avplayer] _ in
            //    进度监控
            if let item = avplayer?.currentItem, !(self?.sliderView?.isDragingProgressSlder ?? false) {
                DispatchQueue.main.async { [weak self, weak avplayer] in
                    if avplayer?.currentItem?.status != .readyToPlay {
                        self?.sliderView?.progress = 0
                    }else{
                        self?.sliderView?.progress = CMTimeGetSeconds(item.currentTime()) / CMTimeGetSeconds(item.duration)                        
                    }
                }
            }
        } as? NSKeyValueObservation

        NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: avplayer.currentItem, queue: .main) { [weak avplayer, weak self] _ in
            avplayer?.seek(to: CMTime.zero)
            self?.sliderView?.playEnd()
//            self?.changeToOriginalFrame()
        }

        return avplayer
    }()

    lazy var export: BFRecordExport = {
        let export = BFRecordExport()

        export.progress = { [weak self] progress in
            DispatchQueue.main.async { [weak self] in
                if let sself = self {
//                    let width = export.data?.first?.width ?? 0
                    sself.progressL.text = String(format: "%d%%", Int(progress * 100))
                    sself.progressView.snp.updateConstraints { make in
                        make.width.equalTo(cScreenWidth * CGFloat(progress))
                    }
                }
            }
        }

        export.exportCompletion = { [weak self] error, url in
            DispatchQueue.main.async { [weak self] in
                guard let sself = self else {
                    return
                }
                UIApplication.shared.isIdleTimerDisabled = false

                sself.isExporting = false
//                sself.bottomView.isHidden = false
                
                sself.saveAllBtn.setImage(UIImage(named: "export_saveall_n"), for: .normal)
                sself.saveOnlyBtn.setImage(UIImage(named: "export_saveonly_n"), for: .normal)
                
                sself.saveAllBtn.isEnabled = true
                sself.saveOnlyBtn.isEnabled = true
                sself.saveToPhotoBtn.isEnabled = true
                sself.completeBtn.isEnabled = true

                sself.sliderView?.isHidden = false
                sself.progressView.isHidden = true
                sself.progressL.isHidden = true

                if let fileUrl = url {
                    let item = AVPlayerItem(url: fileUrl)
                    sself.avplayer.replaceCurrentItem(with: item)
                    sself.avplayer.play()
                    sself.playerLayer.borderColor = ThemeStyleColor.cgColor

                    if sself.saveAllBtn.isSelected {
                        sself.saveAllUlr = fileUrl
                        sself.hasExportAll = true
                    }

                    if sself.saveOnlyBtn.isSelected {
                        sself.saveOnlyUlr = fileUrl
                        sself.hasExportOnly = true
                    }
                    // 添加播放进度视图
                    self?.addVideoSliderView()
                }else {
                    if let l = sself.errorView.viewWithTag(33000) as? UILabel, let err = error as NSError? {
                        switch err.code {
                        case ExportError.FileNotExist.rawValue :
                            l.text = "原视频/图片文件被删除"
                        case ExportError.DiskNoSpace.rawValue :
                            l.text = "存储空间不足:" + (err.userInfo["msg"] as! String)
                        case ExportError.VoiceLost.rawValue :
                            l.text = "手机录音文件丢失"
                        default:
                            l.text = "请重新尝试"
                        }
                        l.sizeToFit()
                    }
                    sself.errorView.isHidden = false
                }
            }
            // 合成成功上报
            BFEventTrackAdaptor.baseReportUpload(businessType: nil, objectType: .ot_composeSuccess, pageSource: .sp_composePage, commonParams: commonParams())
        }
        return export
    }()

    deinit {
        avplayerTimeObserver?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        
        PQNotification.addObserver(self, selector: #selector(enterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
        PQNotification.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
        
        //进入活跃状态
        PQNotification.addObserver(self, selector: #selector(didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
        
        //进入非活跃状态
        PQNotification.addObserver(self, selector: #selector(willResignActive), name: UIApplication.willResignActiveNotification, object: nil)

        showNavigation()
        // 曝光上报
        BFEventTrackAdaptor.baseReportUpload(businessType: .bt_pageView, objectType: nil, pageSource: .sp_composePage, commonParams: commonParams())
    }
    @objc func didBecomeActive(){
        BFLog(message: "进入活跃状态")
        if let sbtn = sliderView?.viewWithTag(1) as? UIButton ,!isExporting {
            sbtn.isSelected = false
            avplayer.play()
        }
    }
    
    @objc func willResignActive(){
        BFLog(message: "进入非活跃状态")
        if let sbtn = sliderView?.viewWithTag(1) as? UIButton  , !isExporting{
            sbtn.isSelected = true
            avplayer.pause()
        }
    }
    
    
    @objc func enterBackground() {
        BFLog(message: "进入到后台")
        
        if isExporting {
            enterBackgroundCancleExport = true
            self.export.cancelExport()
        }else{
            if let sbtn = sliderView?.viewWithTag(1) as? UIButton {
                sbtn.isSelected = true
                avplayer.pause()
            }
        }

    }

    @objc func willEnterForeground() {
        BFLog(message: "进入到前台")
        if enterBackgroundCancleExport {
            export.startExprot(synthesisAll: saveAllBtn.isSelected)
            enterBackgroundCancleExport = false
        }else {
            //重启播放器
            if let sbtn = sliderView?.viewWithTag(1) as? UIButton {
                sbtn.isSelected = false
                avplayer.play()
            }
        }
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        PQNotification.removeObserver(self)
        UIApplication.shared.isIdleTimerDisabled = false
    }

    override func backBtnClick() {
        if isExporting {
            whetherCancelExport {
                self.export.cancelExport()
                super.backBtnClick()
            }
            return
        }
        if !(hasExportAll || hasExportOnly) {}
        export.cancelExport()
        super.backBtnClick()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .black
        navHeadImageView?.backgroundColor = .black
        leftButton(image: nil, imageName: nil, tintColor: UIColor.white)

//        backV.frame = CGRect(x: 0, y: navHeadImageView?.bottomY ?? 0, width: cScreenWidth, height: cScreenWidth)
//        backV.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(play)))

        addSubviews()

//        export.startExprot()
        // 默认保留录音合成
        saveAllBtn.isSelected = true

        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { [weak self] in
            self?.exportNow()
        }

    }

    func addSubviews() {
        view.addSubview(bottomView)
        view.addSubview(backV)
        view.addSubview(errorView)

        playerLayer = AVPlayerLayer(player: avplayer)
        playerLayer.borderWidth = 1
        playerLayer.borderColor = UIColor.hexColor(hexadecimal: "#1A1A1A").cgColor
        backV.layer.addSublayer(playerLayer)

        backV.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(playAction)))
        
        backV.addSubview(progressView)
        backV.addSubview(progressL)
        
        bottomView.addSubview(saveAllBtn)
        bottomView.addSubview(saveOnlyBtn)
        bottomView.addSubview(saveToPhotoBtn)
        bottomView.addSubview(completeBtn)
        
        errorView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        progressView.snp.makeConstraints { make in
            make.left.top.height.equalToSuperview()
            make.width.equalTo(0)
        }

        progressL.snp.makeConstraints { make in
            make.center.width.equalToSuperview()
            make.height.equalTo(28)
        }

        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            } else {
                make.bottom.equalToSuperview()
            }
        }

        completeBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.bottom.equalTo(-1 * cSafeAreaHeight - 3)
            make.height.equalTo(20)
        }

        saveToPhotoBtn.snp.makeConstraints { make in
            make.left.right.equalTo(completeBtn)
            make.height.equalTo(50)
            make.bottom.equalTo(completeBtn.snp.top).offset(-10)
        }

        saveAllBtn.snp.makeConstraints { make in
            make.left.equalTo(completeBtn)
            make.bottom.equalTo(saveToPhotoBtn.snp.top).offset(-21)
            make.height.equalTo(70)
            make.top.equalTo(28)
        }

        saveOnlyBtn.snp.makeConstraints { make in
            make.left.equalTo(saveAllBtn.snp.right).offset(16)
            make.top.height.width.equalTo(saveAllBtn)
            make.right.equalTo(completeBtn)
        }

        DispatchQueue.main.asyncAfter(deadline: .now() + 0) { [weak self] in
            guard let sself = self else {
                return
            }
            sself.backV.frame = CGRect(x: 0, y: sself.navHeadImageView?.frame.maxY ?? 0, width: sself.view.width, height: (sself.bottomView.frame.minY ) - (sself.navHeadImageView?.frame.maxY ?? 0))
            let width = sself.backV.height * (cScreenWidth / cScreenHeigth)
            sself.playerLayer.frame = CGRect(x: (sself.backV.width - width)/2, y: 0, width: width, height: sself.backV.height)
        }
    }

    /// 添加播放进度视图
    func addVideoSliderView() {
        if sliderView == nil {
            sliderView = BFVideoPlayerSliderView(frame: CGRect(x: (backV.frame.width - playerLayer.frame.width) / 2, y: backV.frame.height - 60, width: playerLayer.frame.width, height: 50),isShowFullScreen: false)
            sliderView?.valueChangeBloc = { [weak self] sender in
                let cmtime = CMTime(value: CMTimeValue(Float64(sender.value) * Float64(self?.avplayer.currentItem?.asset.duration.seconds ?? 0) * 1000.0), timescale: CMTimeScale(1000.0))
                BFLog(message: "cmtime == \(cmtime)，\(cmtime.seconds)")
                self?.avplayer.seek(to: cmtime, toleranceBefore: CMTime(seconds: 1, preferredTimescale: 1000), toleranceAfter: CMTime(seconds: 1, preferredTimescale: 1000))
                self?.avplayer.play()
            }
            sliderView?.slideBeginDrag = { [weak self] in
                self?.avplayer.pause()
            }
            sliderView?.btnClickBloc = { [weak self] sender in
                // 按钮点击
                if sender.tag == 1 {
                    self?.play(sender: sender)
                } else if sender.tag == 2 {
                    if sender.isSelected {
                        self?.changeToFullScreen()
                    } else {
                        self?.changeToOriginalFrame()
                    }
                }
            }
        }
        sliderView?.duration = avplayer.currentItem?.asset.duration.seconds ?? 0
        if sliderView?.superview == nil {
            backV.addSubview(sliderView!)
        }
    }

    // MARK: - 按钮事件
    @objc func retryAction(){
        errorView.isHidden = true
        exportNow()
    }
    
    func exportNow() {
        if isExporting {
            cShowHUB(superView: nil, msg: "正在合成中。。。")
            return
        }
        isExporting = true
        playerLayer.borderColor = UIColor.hexColor(hexadecimal: "#1A1A1A").cgColor
        avplayer.replaceCurrentItem(with: nil)
//        bottomView.isHidden = true
        
        if saveAllBtn.isSelected {
//            saveAllBtn.setImage(UIImage(named: "export_saveall_h"), for: .disabled)
            saveAllBtn.setImage(UIImage(named: "export_saveall_h"), for: .normal)
            saveOnlyBtn.setImage(UIImage(named: "export_saveonly_n"), for: .normal)
        }else{
//            saveAllBtn.setImage(UIImage(named: "export_saveall_n"), for: .disabled)
            saveAllBtn.setImage(UIImage(named: "export_saveall_n"), for: .normal)
            saveOnlyBtn.setImage(UIImage(named: "export_saveonly_h"), for: .normal)
        }
        
        saveAllBtn.isEnabled = false
        saveOnlyBtn.isEnabled = false
        saveToPhotoBtn.isEnabled = false
        completeBtn.isEnabled = false
        
        progressView.isHidden = false
        progressL.isHidden = false
        sliderView?.isHidden = true
        export.startExprot(synthesisAll: saveAllBtn.isSelected)
        UIApplication.shared.isIdleTimerDisabled = true
        // 开始合成上报
        BFEventTrackAdaptor.baseReportUpload(businessType: nil, objectType: .ot_startCompose, pageSource: .sp_composePage, commonParams: commonParams())
    }

    @objc func saveToPhotoNow() {
        if (saveAllBtn.isSelected && hasSaveAll) || saveOnlyBtn.isSelected && hasSaveOnly {
            cShowHUB(superView: nil, msg: "已保存过了")
            return
        }
        if let url = (avplayer.currentItem?.asset as? AVURLAsset)?.url {
            PHPhotoLibrary.shared().performChanges {
                PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url)
            } completionHandler: { [weak self] isFinished, _ in
                guard let sself = self else {
                    return
                }
                if isFinished {
                    DispatchQueue.main.async {
                        cShowHUB(superView: nil, msg: "保存成功")
                    }
                    if sself.saveAllBtn.isSelected {
                        sself.hasSaveAll = true
                    } else if sself.saveOnlyBtn.isSelected {
                        sself.hasSaveOnly = true
                    }
                }
            }
        }
        // 点击保存至相册上报
        BFEventTrackAdaptor.baseReportUpload(businessType: .bt_buttonClick, objectType: .ot_saveToAblum, pageSource: .sp_composePage, extParams: saveAllBtn.isSelected ? ["saveAll": true] : ["saveRecord": true], commonParams: commonParams())
    }

    @objc func saveAllAction(btn: UIButton) {
        if btn.isSelected {
            return
        }
        btn.isSelected = true
        saveOnlyBtn.isSelected = false
        avplayer.pause()
        if !hasExportAll {
            exportNow()
        } else {
            avplayer.pause()
            let item = AVPlayerItem(url: saveAllUlr)
            avplayer.replaceCurrentItem(with: item)
            if let sbtn = sliderView?.viewWithTag(1) as? UIButton {
                sbtn.isSelected = false
                avplayer.play()
                sliderView?.duration = avplayer.currentItem?.asset.duration.seconds ?? 0
            }
        }
    }

    @objc func saveOnlyAction(btn: UIButton) {
        if btn.isSelected {
            return
        }
        btn.isSelected = true
        saveAllBtn.isSelected = false
        avplayer.pause()
        if !hasExportOnly {
            exportNow()
        } else {
            avplayer.pause()
            let item = AVPlayerItem(url: saveOnlyUlr)
            avplayer.replaceCurrentItem(with: item)
            if let sbtn = sliderView?.viewWithTag(1) as? UIButton {
                sbtn.isSelected = false
                avplayer.play()
                sliderView?.duration = avplayer.currentItem?.asset.duration.seconds ?? 0
            }
        }
    }
    
    @objc func playAction(){
        if !isExporting {
            if let sbtn = sliderView?.viewWithTag(1) as? UIButton{
                sbtn.isSelected = !sbtn.isSelected
                if sbtn.isSelected {
                    avplayer.pause()
                }else{
                    avplayer.play()
                }
            }
        }
    }

    @objc func completeAction() {
        // MARK: 删除所有录制资源. 现在放在了选择相册展示时清理cache

        if (!hasSaveOnly && !saveOnlyUlr.absoluteString.contains("aaa"))
            || (!hasSaveAll && !saveAllUlr.absoluteString.contains("aaa")) {
            
            let alertController = UIAlertController(title: "你还未保存视频哦，是否需要保存视频再离开？",
                           message: "", preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "不保存", style: .default){[weak self] action in
                guard let sself = self else {
                    return
                }
                sself.export.cancelExport()
                sself.navigationController?.popToRootViewController(animated: true)
            }
            let okAction = UIAlertAction(title: "保存视频", style: .default) {[weak self] action in
                guard let sself = self else {
                    return
                }
                if sself.hasExportOnly {
                    PHPhotoLibrary.shared().performChanges {
                        PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: sself.saveOnlyUlr)
                    } completionHandler: { _, _ in
                    }
                }
                if sself.hasExportAll {
                    PHPhotoLibrary.shared().performChanges {
                        PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: sself.saveAllUlr)
                    } completionHandler: { _, _ in
                    }
                }
                sself.export.cancelExport()
                sself.navigationController?.popToRootViewController(animated: true)
            }
            alertController.addAction(cancelAction)
            alertController.addAction(okAction)

            self.present(alertController, animated: true, completion: nil)
            
//
//            let remindData = BFBaseModel()
//            remindData.summary = "合成的视频尚未保存到相册"
//            let alertV = BFRemindView(frame: view.bounds)
//            alertV.isBanned = true
//            alertV.confirmBtn.setTitle("不保存", for: .normal)
//            alertV.cancelBtn.setTitle("确认保存", for: .normal)
//            alertV.remindData = remindData
//            alertV.remindBlock = { [weak self] item, _ in
//                guard let sself = self else {
//                    return
//                }
//                if item.tag == 1 { // 确定返回到上一层
//                    if sself.hasExportOnly {
//                        PHPhotoLibrary.shared().performChanges {
//                            PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: sself.saveOnlyUlr)
//                        } completionHandler: { _, _ in
//                        }
//                    }
//                    if sself.hasExportAll {
//                        PHPhotoLibrary.shared().performChanges {
//                            PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: sself.saveAllUlr)
//                        } completionHandler: { _, _ in
//                        }
//                    }
//                }
//
//                sself.export.cancelExport()
//                sself.navigationController?.popToRootViewController(animated: true)
//            }
//            UIApplication.shared.keyWindow?.addSubview(alertV)
        } else {
            export.cancelExport()
            navigationController?.popToRootViewController(animated: true)
        }
    }

    @objc func play(sender: UIButton) {
        if isExporting {
            avplayer.pause()
            return
        }
        if avplayer.currentItem != nil {
            if avplayer.timeControlStatus == .playing || sender.isSelected {
                avplayer.pause()
            } else if avplayer.timeControlStatus == .paused {
                avplayer.play()
            }
        }
    }

    func whetherCancelExport(comfirm: (() -> Void)?) {
        let alertController = UIAlertController(title: "正在合成中，是否取消？",
                       message: "", preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: "继续合成", style: .default, handler: nil)
        let okAction = UIAlertAction(title: "取消合成", style: .default) {[weak self] action in
            guard let sself = self else {
                return
            }
            sself.export.cancelExport()
            comfirm?()
        }
        alertController.addAction(okAction)
        alertController.addAction(cancelAction)

        self.present(alertController, animated: true, completion: nil)
        
        
//        let remindData = BFBaseModel()
//        remindData.summary = "正在合成中，是否取消？"
//        let alertV = BFRemindView(frame: view.bounds)
//        alertV.isBanned = true
//        alertV.confirmBtn.setTitle("继续合成", for: .normal)
//        alertV.cancelBtn.setTitle("取消合成", for: .normal)
//        alertV.remindData = remindData
//        alertV.remindBlock = { [weak self] item, _ in
//            guard let sself = self else {
//                return
//            }
//            if item.tag == 1 { // 确定返回到上一层
//                sself.export.cancelExport()
//                comfirm?()
//            }
//        }
//        UIApplication.shared.keyWindow?.addSubview(alertV)
    }
}

extension INVideoExportController {
    @objc func changeToOriginalFrame() {
        if !(sliderView?.isFullScreen ?? false) {
            isHiddenStatus = false // (0.0, 64.0, 375.0, 401.0)
            navHeadImageView?.isHidden = false
            backV.frame = CGRect(x: 0, y: navHeadImageView?.frame.maxY ?? 0, width: view.width, height: bottomView.frame.minY - (navHeadImageView?.frame.maxY ?? 0))
            let width = backV.height * (cScreenWidth / cScreenHeigth)
            playerLayer.frame = CGRect(x: (backV.width - width)/2, y: 0, width: width, height: backV.height)
//            playerLayer.frame = CGRect(x: 0, y: 0, width: view.width, height: bottomView.frame.minY - (navHeadImageView?.frame.maxY ?? 0))
            sliderView?.frame = CGRect(x: 0, y: backV.frame.height - 60, width: view.frame.width, height: 50)
            UIView.animate(withDuration: 0.2, animations: { [weak self] in
                self?.changeOrientation(orientation: .portrait)
                self?.backV.center = CGPoint(x: (self?.backV.width ?? 0) / 2, y: (self?.backV.height ?? 0) / 2 + (self?.navHeadImageView?.frame.maxY ?? 0))
            }) { [weak self] _ in
            }
        }
    }

    func changeToFullScreen() {
        if sliderView?.isFullScreen ?? false {
            isHiddenStatus = true
            navHeadImageView?.isHidden = true
            backV.frame = CGRect(x: 0, y: 0, width: view.frame.height, height: view.frame.width)
            let width = view.width * (cScreenWidth / cScreenHeigth)
            playerLayer.frame = CGRect(x: (view.height - width)/2, y: 0, width: width, height: backV.width)
//            playerLayer.frame = backV.bounds
            sliderView?.frame = CGRect(x: 0, y: backV.frame.height - 60, width: backV.frame.width, height: 50)
            UIView.animate(withDuration: 0.2, animations: { [weak self] in
                let orientation = UIDevice.current.orientation
                if orientation == .landscapeRight {
                    self?.changeOrientation(orientation: .landscapeLeft)
                } else {
                    self?.changeOrientation(orientation: .landscapeRight)
                }
                self?.backV.center = CGPoint(x: (self?.view.frame.width ?? 0) / 2, y: (self?.view.frame.height ?? 0) / 2)
            }) { [weak self] _ in
            }
        }
    }

    func changeOrientation(orientation: UIInterfaceOrientation) {
        UIView.animate(withDuration: 0.2, animations: { [weak self] in
            self?.backV.transform = self?.transformRotation(orientation: orientation) as! CGAffineTransform
        }) { [weak self] _ in
        }
    }

    @objc func transformRotation(orientation: UIInterfaceOrientation) -> CGAffineTransform {
        if orientation == .portrait {
            return .identity
        } else if orientation == .landscapeLeft {
            return CGAffineTransform(rotationAngle: -CGFloat.pi / 2)
        } else if orientation == .landscapeRight {
            return CGAffineTransform(rotationAngle: CGFloat.pi / 2)
        }
        return .identity
    }
}
