//
//  TSCommonloadingView.swift
//  AIEmoji
//
//  Created by 100Years on 2025/1/17.
//



class TSCommonloadingView: TSBaseView {
    
    lazy var imageView: UIImageView = {
        let imageView = UIImageView.createImageView(imageName: "image")
        return imageView
    }()
    
    lazy var textLabel: UILabel = {
        let textLabel = UILabel.createLabel(font: .font(size: 12),textColor: .fromHex("#FFFFFF",alpha: 0.6))
        return textLabel
    }()
    
    
    override func creatUI() {
        contentView.addSubview(imageView)
        imageView.snp.makeConstraints { make in
            make.width.height.equalTo(120.0)
            make.centerX.equalToSuperview()
            make.top.equalToSuperview()
        }
        
        contentView.addSubview(textLabel)
        textLabel.snp.makeConstraints { make in
            make.height.equalTo(18.0)
            make.top.equalTo(imageView.snp.bottom).offset(16)
            make.leading.bottom.trailing.equalToSuperview()
        }
    }
    
    
    lazy var isRotating = false{
        didSet{
            if isRotating == true{
                startRotating(view: imageView)
            }else{
                stopRotating(view: imageView)
            }
        }
    }
    
    
    /// 开始旋转
    func startRotating(view:UIView,duration: Double = 2.0) {
        stopRotating(view: view)
        let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotationAnimation.toValue = CGFloat.pi * 2
        rotationAnimation.duration = duration
        rotationAnimation.isCumulative = true
        rotationAnimation.repeatCount = .infinity

        view.layer.add(rotationAnimation, forKey: "rotationAnimation")
    }

    /// 停止旋转
    func stopRotating(view:UIView) {
        view.layer.removeAnimation(forKey: "rotationAnimation")
    }
    
    func showLoading(text:String){
        imageView.image = UIImage(named: "rotating")
        textLabel.text = text
        isRotating = true
    }
    
    func showError(text:String){
        imageView.image = UIImage(named: "failed")
        textLabel.text = text
        isRotating = false
    }

}
