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

import Kingfisher

class TSCommonloadingView: TSBaseView {
    
    lazy var imageView: UIImageView = {
        let imageView = UIImageView.createImageView(imageName: "failed_big")
        imageView.isHidden = true
        return imageView
    }()
    
    lazy var animatedImageView: AnimatedImageView = {
        let animatedImageView = AnimatedImageView()
        animatedImageView.autoPlayAnimatedImage = false
        if let gifURL = Bundle.main.url(forResource: "rotatingAnimation", withExtension: "gif") {
            animatedImageView.kf.setImage(with: gifURL, options: [.cacheOriginalImage]) { result in
                switch result {
                case .success(let value):
                    print("GIF 加载成功: \(value.source.url?.absoluteString ?? "")")
                case .failure(let error):
                    print("GIF 加载失败: \(error.localizedDescription)")
                }
            }
        }
        
        return animatedImageView
    }()
    
    lazy var textLabel: UILabel = {
        let textLabel = UILabel.createLabel(font: .font(size: 12),textColor: .fromHex("#FFFFFF",alpha: 0.6),textAlignment: .center)
        return textLabel
    }()
    
    
    lazy var cancelBtn: UIButton = {
        let textColor = UIColor.white.withAlphaComponent(0.4)
        let cancelBtn = UIButton.createButton(title:"Cancel".localized,backgroundColor: "#171717".uiColor,font: UIFont.font(size: 16,weight: .regular),titleColor:textColor,corner: 24)
        cancelBtn.layer.borderWidth = 1
        cancelBtn.layer.borderColor = UIColor.white.withAlphaComponent(0.15).cgColor
        return cancelBtn
    }()
    private var targetView: UIView = UIView()
    
    override func creatUI() {
        
        let blurEffect = createBlurEffectView(style: .dark)
        contentView.addSubview(blurEffect)
        
        contentView.addSubview(imageView)
        imageView.snp.makeConstraints { make in
            make.width.height.equalTo(200.0)
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(-60)
        }
        
        contentView.addSubview(animatedImageView)
        animatedImageView.snp.makeConstraints { make in
            make.width.height.equalTo(200.0)
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(-60)
        }
  
        contentView.addSubview(textLabel)
        textLabel.snp.makeConstraints { make in
            make.height.equalTo(18.0)
            make.top.equalTo(imageView.snp.bottom).offset(16)
            make.leading.trailing.equalToSuperview()
        }
        
        contentView.addSubview(cancelBtn)
        cancelBtn.snp.makeConstraints { make in
            make.height.equalTo(48.0)
            make.top.equalTo(textLabel.snp.bottom).offset(36)
            make.width.equalTo(200.0)
            make.centerX.equalToSuperview()
        }
    }
    
    
    override func dealThings() {
        // 监听应用生命周期事件
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(handleAppDidEnterBackground),
            name: UIApplication.didEnterBackgroundNotification,
            object: nil
        )
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(handleAppWillEnterForeground),
            name: UIApplication.willEnterForegroundNotification,
            object: nil
        )
    }
    
    
    lazy var isRotating = false{
        didSet{
            if isRotating == true{
                startRotating(view: imageView)
            }else{
                stopRotating(view: imageView)
            }
        }
    }
    
    
    /// 开始旋转
    func startRotating(view:UIView,duration: Double = 2.0) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            self.animatedImageView.startAnimating()
        }
    }

    /// 停止旋转
    func stopRotating(view:UIView) {
        animatedImageView.stopAnimating()
    }
    
    func showLoading(text:String){
        animatedImageView.isHidden = false
        imageView.isHidden = true
        
        textLabel.text = text
        isRotating = true
    }
    
    func showError(text:String){
        animatedImageView.isHidden = true
        
        imageView.isHidden = false
        imageView.image = UIImage(named: "failed_big")
        
        textLabel.text = text
        isRotating = false
    }
    
    @objc private func handleAppDidEnterBackground() {
        stopRotating(view: targetView)
    }

    @objc private func handleAppWillEnterForeground() {
        isRotating = isRotating
    }
}
