//
//  SpeakEleLoading.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/11.
//

import UIKit

@IBDesignable
class SpeakEleLoading : UIView {
    
    // MARK: - 公开属性
    /// 圆点颜色
    @IBInspectable var dotColor: UIColor = .gray {
        didSet { dots.forEach { $0.backgroundColor = dotColor } }
    }
    
    /// 圆点大小
    @IBInspectable var dotSize: CGFloat = 8 {
        didSet { updateDotFrames() }
    }
    
    /// 圆点间距
    @IBInspectable var spacing: CGFloat = 8 {
        didSet { updateDotFrames() }
    }
    
    /// 动画持续时间（秒）
    @IBInspectable var animationDuration: TimeInterval = 0.4
    
    var contentInsets:UIEdgeInsets = UIEdgeInsets()
    
    // MARK: - 私有属性
    private var dots: [UIView] = []
    private var isAnimating = false
    
    // MARK: - 初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setup()
    }
    
    // MARK: - 视图设置
    private func setup() {
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(didBecomeActive(_:)),
            name: UIApplication.didBecomeActiveNotification,
            object: nil
        )
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(willEnterForeground(_:)),
            name: UIApplication.willEnterForegroundNotification,
            object: nil
        )
        // 创建三个圆点
        for _ in 0..<3 {
            let dot = UIView()
            dot.backgroundColor = dotColor
            dot.layer.cornerRadius = dotSize / 2
            dot.alpha = 0.3
            addSubview(dot)
            dots.append(dot)
        }
        
        updateDotFrames()
    }
    
    private func updateDotFrames() {
        guard dots.count == 3 else { return }
        
        let totalWidth = dotSize * 3 + spacing * 2
        let startX = (bounds.width - totalWidth) / 2
        
        for (index, dot) in dots.enumerated() {
            let x = startX + CGFloat(index) * (dotSize + spacing)
            dot.frame = CGRect(x: x, y: (bounds.height - dotSize) / 2, width: dotSize, height: dotSize)
        }
    }
    
    // MARK: - 动画控制
    func startAnimating() {
        guard !isAnimating else { return }
        isAnimating = true
        for (index, dot) in dots.enumerated() {
            let delay = Double(index) * animationDuration / Double(dots.count)
            animateDot(dot, withDelay: delay)
        }
    }
    
    func stopAnimating() {
        isAnimating = false
        dots.forEach { $0.layer.removeAllAnimations() }
        dots.forEach { $0.alpha = 0.3 }
    }
    
    private func animateDot(_ dot: UIView, withDelay delay: TimeInterval) {
        // 创建透明度动画
        let pulseAnimation = CABasicAnimation(keyPath: "opacity")
        pulseAnimation.fromValue = 0.3
        pulseAnimation.toValue = 1.0
        pulseAnimation.duration = animationDuration
        pulseAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
        pulseAnimation.repeatCount = .infinity
        pulseAnimation.autoreverses = true
        pulseAnimation.beginTime = CACurrentMediaTime() + delay
        dot.layer.add(pulseAnimation, forKey: "pulse")
    }
    
    // MARK: - 布局
    override func layoutSubviews() {
        super.layoutSubviews()
        updateDotFrames()
    }
    
    @objc private func didBecomeActive(_ notication:Notification) -> Void {
        self.startAnimating()
    }
    
    @objc private func willEnterForeground(_ notication:Notification) -> Void {
        self.stopAnimating()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
