//
//  UIView+Animation.swift
//  KittensTravelNotes
//
//  Created by 100Years on 2025/7/7.
//
import UIKit
extension UIView {
    private struct AssociatedKeys {
        static var timerKey = "UIView.timerKey"
        static var imagesKey = "UIView.imagesKey"
        static var currentIndexKey = "UIView.currentIndexKey"
    }
    
    private var transitionTimer: Timer? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.timerKey) as? Timer
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.timerKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    private var transitionImages: [Any]? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.imagesKey) as? [UIImage]
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.imagesKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    private var currentImageIndex: Int {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.currentIndexKey) as? Int ?? 0
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.currentIndexKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    /// 开始图片循环切换动画
    /// - Parameters:
    ///   - images: 要切换的图片数组
    ///   - interval: 切换间隔时间，默认2秒
    ///   - duration: 溶解动画持续时间，默认0.5秒
    func startImageTransitionAnimation(index:Int = 0, datas: [Any], interval: TimeInterval = 4.0, duration: TimeInterval = 2.0,setImageHandle:@escaping (Int,Any?)->Void) {
        guard datas.count > 0 else { return }
        
        // 停止已有的动画
        stopImageTransitionAnimation()
        
        // 保存图片数组
        transitionImages = datas
        currentImageIndex = index
        
        setImageHandle(currentImageIndex,datas.first)
        
        // 启动定时器
        transitionTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in
            guard let self = self else { return }
            
            self.currentImageIndex = (self.currentImageIndex + 1) % datas.count
            
            UIView.transition(with: self,
                              duration: duration,
                              options: [.transitionCrossDissolve, .curveEaseInOut],
                              animations: {
                                    setImageHandle(self.currentImageIndex,datas[self.currentImageIndex])
                              },
                              completion: nil)
        }
    }
    
    /// 停止图片循环切换动画
    func stopImageTransitionAnimation() {
        transitionTimer?.invalidate()
        transitionTimer = nil
        transitionImages = nil
        currentImageIndex = 0
    }
}
