//
//  UIView+A.swift
//  Pods
//
//  Created by 100Years on 2025/3/6.
//

import UIKit

public extension UIView {
    // MARK: - 旋转动画控制
    /// 开始旋转动画
    /// - Parameters:
    ///   - duration: 单圈旋转时间（默认 1 秒）
    ///   - clockwise: 是否顺时针旋转（默认 true）
    ///   - repeatCount: 重复次数（默认无限循环 .greatestFiniteMagnitude）
    func startRotating(duration: CFTimeInterval = 1.0,
                     clockwise: Bool = true,
                     repeatCount: Float = .greatestFiniteMagnitude) {
        // 同步移除已有旋转动画
        self.stopRotating()
        
        DispatchQueue.main.async {
            // 创建旋转动画
            let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
            rotationAnimation.fromValue = 0
            rotationAnimation.toValue = clockwise ? CGFloat.pi * 2.0 : -CGFloat.pi * 2.0
            rotationAnimation.duration = duration
            rotationAnimation.isCumulative = true
            rotationAnimation.repeatCount = repeatCount
            rotationAnimation.timingFunction = CAMediaTimingFunction(name: .linear)
            
            // 防止动画结束后恢复初始状态
            rotationAnimation.fillMode = .forwards
            rotationAnimation.isRemovedOnCompletion = false
            
            // 添加动画到视图的 layer
            self.layer.add(rotationAnimation, forKey: "rotationAnimation")
        }
    }
    
    /// 停止旋转动画
    func stopRotating() {
        // 同步移除旋转动画
        DispatchQueue.main.async {
            self.layer.removeAnimation(forKey: "rotationAnimation")
        }
    }

}
