//
//  FadeOutTransition.swift
//  PhoneManager
//
//  Created by edy on 2025/5/19.
//

import Foundation
import UIKit

// 自定义转场动画（用于消失时的渐隐效果）
class FadeOutTransition: NSObject, UIViewControllerAnimatedTransitioning {
    
    // 动画时长（可自定义）
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.3 // 0.3秒渐隐
    }
    
    // 执行动画
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        // 获取即将消失的控制器（被弹出的控制器）
        guard let fromVC = transitionContext.viewController(forKey: .from),
              let toVC = transitionContext.viewController(forKey: .to) else { return }
        
        // 将目标控制器的视图添加到容器视图（确保转场后界面正确）
        transitionContext.containerView.addSubview(toVC.view)
        
        // 渐隐动画：将 fromVC 的视图透明度从 1 降到 0
        UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
            fromVC.view.alpha = 0
        }) { (_) in
            // 动画完成后，标记转场结束
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        }
    }
}


// 自定义转场动画（用于 pop 时的渐隐效果）
class FadeOutPopTransition: NSObject, UIViewControllerAnimatedTransitioning {
    
    // 动画时长
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.3 // 0.3秒渐隐
    }
    
    // 执行动画
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        // 获取当前视图控制器（即将消失的控制器）
        guard let fromVC = transitionContext.viewController(forKey: .from),
              let toVC = transitionContext.viewController(forKey: .to) else { return }
        
        // 将目标控制器（RootViewController）的视图添加到容器视图
        transitionContext.containerView.addSubview(toVC.view)
        
        // 渐隐动画：当前控制器视图透明度从 1 降到 0
        UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
            fromVC.view.alpha = 0
        }) { (_) in
            // 动画完成后，标记转场结束
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        }
    }
}
