//
//  CompressCompletedViewController.swift
//  PhoneManager
//
//  Created by edy on 2025/4/2.
//

import Foundation
import Photos
import Lottie

class CompressCompletedViewController : BaseViewController{
    
    // MARK: 属性
    var model : AssetModel?
    
    var comDataSource : [Data] = [] {
        didSet{
            if let data = comDataSource.first{
                DispatchQueue.main.async {
                    self.preImageView.image = UIImage(data: data)
                    self.infoView.isHidden = true
                }
            }
        }
    }
    
    var comVideoDataSource : [URL] = []{
        didSet{
            if let url = comVideoDataSource.first{
                let vc = VideoViewController()
                vc.url = url
                self.addChild(vc)
                vc.view.frame = self.infoView.bounds
                self.infoView.addSubview(vc.view)
                vc.didMove(toParent: self)
            
                DispatchQueue.main.async {
                    self.infoView.playVideo(from: url)
                    self.preImageView.isHidden = true
                }
            }
        }
    }
    
    var currentMediaType : CompressType = .compressPhoto {
        didSet{
            if currentMediaType == .compressPhoto {
                self.deleteButton.setTitle("Delete the original photo", for: .normal)
                self.keepButton.setTitle("Keep two photos", for: .normal)
            }else {
                self.deleteButton.setTitle("Delete the original video", for: .normal)
                self.keepButton.setTitle("Keep two videos", for: .normal)
            }
            
        }
    }
    
    var completedSize : Double = 0.0 {
        didSet{
            DispatchQueue.main.async {
                if let model = self.model {
                    self.sizeToplabel.text = formatFileSize(model.assetSize - self.completedSize)
                }
            }
        }
    }
    
    
    
    // MARK: 懒加载
    
    lazy var topImageView: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "Group")
        return view
    }()
    
    lazy var tipLabel: UILabel = {
        let label = UILabel()
        label.text = "Congratulations!"
        label.textAlignment = .center
        label.textColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
        label.font = UIFont.systemFont(ofSize: 20, weight: .semibold)
        label.backgroundColor = .clear
        return label
    }()
    
    lazy var detailTiplabel: UILabel = {
        let label = UILabel()
        label.text = "Preview"
        label.textColor = UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1)
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
        label.backgroundColor = .clear
        return label
    }()
    lazy var infoView: SecretVideoPlayer = {
        let view = SecretVideoPlayer()
        view.backgroundColor = .white
        view.clipsToBounds = true
        view.layer.cornerRadius = 12
        return view
    }()
    
    lazy var preImageView: UIImageView = {
        let view = UIImageView()
        view.layer.cornerRadius = 12
        view.contentMode = .scaleAspectFit
        view.clipsToBounds = true
        return view
    }()
    
    lazy var tipTopLabel: UILabel = {
        let label = UILabel()
        label.text = "You have saved a total after compression"
        label.textAlignment = .center
        label.textColor = UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 1)
        label.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        label.backgroundColor = .clear
        return label
    }()
    lazy var sizeToplabel: UILabel = {
        let label = UILabel()
        label.text = "511MB"
        label.textColor = UIColor(red: 0, green: 0.51, blue: 1, alpha: 1)
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 20, weight: .medium)
        label.backgroundColor = .clear
        return label
    }()
    
    lazy var keepButton : UIButton = {
        let view = UIButton()
        view.setTitle("Keep two videos", for: UIControl.State.normal)
        view.setTitleColor(UIColor(red: 1, green: 1, blue: 1, alpha: 1), for: .normal)
        view.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        view.clipsToBounds = true
        view.layer.cornerRadius = 25.5
        view.backgroundColor = UIColor(red: 0, green: 0.51, blue: 1, alpha: 1)
        view.addTarget(self, action: #selector(keepButtonAction), for: .touchUpInside)
        return view
    }()
    
    lazy var deleteButton : UIButton = {
        let view = UIButton()
        view.setTitle("Delete the original photo", for: UIControl.State.normal)
        view.setTitleColor(UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1), for: .normal)
        view.clipsToBounds = true
        view.layer.cornerRadius = 25.5
        view.backgroundColor = .clear
        view.addTarget(self, action: #selector(deleteButtonAction), for: .touchUpInside)
        return view
    }()
    
    
    // MARK: 系统方法
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(red: 0.95, green: 0.96, blue: 0.99, alpha: 1)
        self.titleView.isHidden = true
        self.setUI()
    }
    
    // MARK: 设置UI
    func setUI(){
        self.view.addSubview(self.topImageView)
        self.view.addSubview(self.tipLabel)
        self.view.addSubview(self.detailTiplabel)
        self.view.addSubview(self.infoView)
        self.view.addSubview(self.preImageView)
        self.view.addSubview(self.tipTopLabel)
        self.view.addSubview(self.sizeToplabel)
        self.view.addSubview(self.keepButton)
        self.view.addSubview(self.deleteButton)
        
        
        self.topImageView.snp.makeConstraints { make in
            make.top.equalTo(statusBarHeight + 19)
            make.width.height.equalTo(55)
            make.centerX.equalToSuperview()
        }
        self.tipLabel.snp.makeConstraints { make in
            make.top.equalTo(self.topImageView.snp.bottom).offset(12)
            make.width.equalTo(159)
            make.height.equalTo(28)
            make.centerX.equalToSuperview()
        }
        self.detailTiplabel.snp.makeConstraints { make in
            make.top.equalTo(self.tipLabel.snp.bottom).offset(4)
            make.width.equalTo(159)
            make.height.equalTo(22)
            make.centerX.equalToSuperview()
        }
        self.infoView.snp.makeConstraints { make in
            make.top.equalTo(self.detailTiplabel.snp.bottom).offset(14)
            make.width.equalTo(244)
            make.height.equalTo(316)
            make.centerX.equalToSuperview()
        }
        self.preImageView.snp.makeConstraints { make in
            make.top.equalTo(self.detailTiplabel.snp.bottom).offset(14)
            make.width.equalTo(244)
            make.height.equalTo(316)
            make.centerX.equalToSuperview()
        }
        self.tipTopLabel.snp.makeConstraints { make in
            make.top.equalTo(self.preImageView.snp.bottom).offset(32)
            make.width.equalTo(333)
            make.height.equalTo(22)
            make.centerX.equalToSuperview()
        }
        self.sizeToplabel.snp.makeConstraints { make in
            make.top.equalTo(self.tipTopLabel.snp.bottom).offset(4)
            make.width.equalTo(333)
            make.height.equalTo(28)
            make.centerX.equalToSuperview()
        }
        self.keepButton.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(-safeHeight - 78)
            make.height.equalTo(51)
            make.width.equalTo(304)
            make.centerX.equalToSuperview()
        }
        self.deleteButton.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(-safeHeight - 27)
            make.height.equalTo(51)
            make.width.equalTo(304)
            make.centerX.equalToSuperview()
        }
    }
    
    // MARK: 事件方法
    
    /// 保留两个
    @objc func keepButtonAction(){
        if currentMediaType == .compressPhoto {
            if let imageData = self.comDataSource.first {
                PHPhotoLibrary.shared().performChanges({
                    let creationRequest = PHAssetCreationRequest.forAsset()
                    creationRequest.addResource(with: .photo, data: imageData, options: nil)
                }) { success, error in
                    if(success){
                        print("保存照片成功")
                    }
                    self.showDeleteSuccess(fileCount: 1, fileSize: Int64(self.completedSize))
                }
            }else {
                self.showDeleteSuccess(fileCount: 1, fileSize: Int64(self.completedSize))
            }
            
        }else{
            // 保存视频到相册
            PHPhotoLibrary.shared().performChanges({
                if let url = self.comVideoDataSource.first{
                    PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url as URL)
                }
            }) { (success, saveError) in
                if success {
                    print("保存视频成功")
                }else{
                    if let error = saveError {
                        print("保存视频时出错: \(error.localizedDescription)")
                    }
                }
                self.showDeleteSuccess(fileCount: 1, fileSize: Int64(self.completedSize))
            }
        }
    }
    
    
    /// 删除原数据
    @objc func deleteButtonAction(){
        if let model = self.model {
            let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [model.localIdentifier], options: nil)
            PHPhotoLibrary.shared().performChanges ({
                PHAssetChangeRequest.deleteAssets(fetchResult as NSFastEnumeration)
            }){ success, error in
                if(success){
                    PhotoManager.shared.removeDataWhenDeleteInPage(data: [self.model!])
                    print("删除文件成功")
                }
                self.showDeleteSuccess(fileCount: 1, fileSize: Int64(self.completedSize))
            }
        }else {
            self.showDeleteSuccess(fileCount: 1, fileSize: Int64(self.completedSize))
        }
    }
    
    
    
    // MARK: 辅助方法
    
    // 删除成功页面
    func showDeleteSuccess(fileCount:Int,fileSize:Int64){
        DispatchQueue.main.async {
            self.jumpToRootVC()
            let vc = DelSuccessViewController()
            vc.delType = fileCount > 1 ? "photos" : "photo"
            vc.fileSzie = fileSize
            vc.fileCount = fileCount
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: true)
        }
    }
    
    
    /// 返回压缩控制器
    func jumpToRootVC(){
        DispatchQueue.main.async {
            if let targetVC = self.navigationController?.viewControllers.first(where: { $0 is CompressController }) {
                self.navigationController?.popToViewController(targetVC, animated: true)
            }
        }
    }
}
