//
//  CompressingViewController.swift
//  PhoneManager
//
//  Created by edy on 2025/5/21.
//

import UIKit
import Lottie

class CompressingViewController:  BaseViewController {
    
    var currentMediaType : CompressType = .compressPhoto
    
    var model : AssetModel? {
        didSet{
            if let model = model {
                DispatchQueue.main.async {
                    self.orgSizeLabel.text = formatFileSize(model.assetSize)
                }
            }
        }
    }
    
    var qualityType : CompressQualityType = .low {
        didSet{
            if let model = model {
                DispatchQueue.main.async {
                    self.targetSizeLabel.text = formatFileSize(model.assetSize * self.qualityType.rawValue)
                }
            }
        }
    }
    
    lazy var bacImageView : UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "Group_1171275114")
        return view
    }()
    
    lazy var animationViewBacView : UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "＊ 白色实心圆-小")
        view.backgroundColor = .clear
        return view
    }()
    
    let alert = EmailContentDelAlert(state: .endCompress)
    var alertShow : Bool = false
    
    lazy var animationView : LottieAnimationView = {
        let animationView = LottieAnimationView(name: "iOS压缩完成")
        animationView.layer.cornerRadius = 12
        animationView.backgroundColor = .clear
        animationView.loopMode = .loop
        return animationView
    }()
    
    
    
    lazy var tipLabel : UILabel = {
        let label = UILabel()
        label.text = "We're freeing up space on your device！"
        label.textColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
        label.font = UIFont.systemFont(ofSize: 18, weight: .medium)
        label.textAlignment = .center
        label.numberOfLines = 0
        return label
    }()
    
    lazy var orgSizeLabel : UILabel = {
        let label = UILabel()
        label.textColor = UIColor(red: 0.07, green: 0.07, blue: 0.07, alpha: 1)
        label.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        label.textAlignment = .left
        return label
    }()
    
    lazy var targetSizeLabel : UILabel = {
        let label = UILabel()
        label.textColor = UIColor(red: 0, green: 0.51, blue: 1, alpha: 1)
        label.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        label.textAlignment = .right
        return label
    }()
    
    lazy var progressBar : CustomCompressProgressBar = {
        let bar = CustomCompressProgressBar()
        bar.thumbImage = UIImage(named: "Group_1171275116")
        bar.layer.cornerRadius = 3.5
        bar.clipsToBounds = true
        return bar
    }()
    

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(red: 0.95, green: 0.96, blue: 0.99, alpha: 1)
        self.titleView.callBack = { text in
            // 弹框
            self.view.showBlur()
           
            self.alert.endCompressCallback = { idx in
                self.view.hideBlur()
                self.navigationController?.popViewController(animated: true)
            }
            self.alert.callblock = {idx in
                self.view.hideBlur()
            }
            self.alert.show()
            self.alertShow = true
        }
        
        setUI()
        
        startCompress()
    }
    
    
    
    // MARK: 压缩方法
    
    /// 开始压缩
    func startCompress(){
        if self.currentMediaType == .compressPhoto {
            self.compressPhoto(model: self.model)
        }else {
            self.compressVideo(model: self.model)
        }
    }
    
    
    /// 压缩单个图片
    /// - Parameter model: 资源
    private func compressPhoto(model : AssetModel?){
        if let model = model {
            var comDataSource : [Data] = []
            let manager : CompressViewModel = CompressViewModel()
            manager.compress(assets: [model], compressionQuality: qualityType.rawValue) {progress in
                DispatchQueue.main.async {
                    self.progressBar.updateProgress(to: CGFloat(progress))
                }
            } completion: { compressedDataArray, errorArray in
                var compressAllSize = 0.0
                for (_, data) in compressedDataArray.enumerated() {
                    if let data = data {
                        compressAllSize = compressAllSize + Double(data.count)
                        comDataSource.append(data)
                    }
                }
                self.progressBar.animationCompletion = {
                    // 不管成功失败都跳转下一页
                    self.updateNextView(compressAllSize,comDataSource,[])
                }
            }
        }
    }
    
    /// 压缩单个视频
    /// - Parameter model: 资源
    private func compressVideo(model : AssetModel?){
        if let model  = model {
            var compressAllSize : Double  = 0.0
            CompressViewModel.compressVideos(models: [model], quality: Float(qualityType.rawValue)) { progress in
                DispatchQueue.main.async {
                    self.progressBar.updateProgress(to: CGFloat(progress))
                }
            } completion: { (outputURLs, errors) in
                var finallyUrls : [URL] = []
                for (_, outputURL) in outputURLs.enumerated() {
                    if let outputURL = outputURL {
                        do {
                            let attributes = try FileManager.default.attributesOfItem(atPath: outputURL.path)
                            if let fileSize = attributes[.size] as? Int64 {
                                compressAllSize = compressAllSize + Double(fileSize)
                            }
                        } catch {
                            Print("获取视频文件大小失败")
                        }
                        finallyUrls.append(outputURL)
                    }
                }
                self.progressBar.animationCompletion = {
                    // 不管成功失败都跳转下一页
                    self.updateNextView(compressAllSize,[],finallyUrls)
                }
               
            }
        }
        
    }
    
    
    /// 压缩结果处理
    /// - Parameters:
    ///   - compressAllSize: 压缩后总大小
    ///   - comDataSource: 压缩后的图片数据数组
    ///   - comVideoDataSource: 压缩后的视频链接数组
    fileprivate func updateNextView(_ compressAllSize: Double,_ comDataSource : [Data],_ comVideoDataSource : [URL]) {
        DispatchQueue.main.async {
            if self.alertShow {
                self.view.hideBlur()
                self.alert.dismiss(animated: true) {
                    self.jumpNextPage(compressAllSize,comDataSource,comVideoDataSource)
                }
            }else {
                self.jumpNextPage(compressAllSize,comDataSource,comVideoDataSource)
            }
        }
    }
    func jumpNextPage(_ compressAllSize: Double,_ comDataSource : [Data],_ comVideoDataSource : [URL]){
        
        let vc = CompressCompletedViewController()
        vc.currentMediaType = self.currentMediaType
        vc.comDataSource = comDataSource
        vc.comVideoDataSource = comVideoDataSource
        vc.model = self.model
        vc.completedSize = compressAllSize
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    
    // MARK: 设置UI
    func setUI(){
        self.view.addSubview(self.bacImageView)
        self.bacImageView.snp.makeConstraints { make in
            make.height.equalTo(211)
            make.width.equalTo(264.7)
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(96 + statusBarHeight)
        }
        self.view.addSubview(self.animationViewBacView)
        self.animationViewBacView.snp.makeConstraints { make in
            make.top.equalTo(self.bacImageView.snp.top).offset(58)
            make.width.height.equalTo(108.75)
            make.centerX.equalToSuperview()
        }
        
        self.view.addSubview(self.animationView)
        self.animationView.snp.makeConstraints { make in
            make.width.height.equalTo(145)
            make.top.equalTo(self.bacImageView.snp.top).offset(40)
            make.centerX.equalToSuperview()
        }
        
        self.view.addSubview(self.tipLabel)
        self.tipLabel.snp.makeConstraints { make in
            make.width.equalTo(304)
            make.height.equalTo(50)
            make.centerX.equalToSuperview()
            make.top.equalTo(self.bacImageView.snp.bottom).offset(96)
        }
        self.view.addSubview(self.orgSizeLabel)
        self.orgSizeLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.height.equalTo(22)
            make.bottom.equalTo(-66 - safeHeight)
        }
        self.view.addSubview(self.targetSizeLabel)
        self.targetSizeLabel.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(22)
            make.bottom.equalTo(-66 - safeHeight)
        }
        self.view.addSubview(self.progressBar)
        self.progressBar.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(24)
            make.bottom.equalTo(-34 - safeHeight)
        }
        
        self.animationView.play(fromProgress: 0, toProgress: 1 , loopMode: .loop)
    }
}







