//
//  YHBlurredAvatarView.swift
//  galaxy
//
//  Created by alexzzw on 2024/12/10.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import VisualEffectView
import UIKit

class YHBlurredAvatarView: UIView {
    private let imageView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .scaleAspectFill
        iv.clipsToBounds = true
        return iv
    }()
    
    private lazy var effectView: VisualEffectView = {
        let visualEffectView = VisualEffectView()
        visualEffectView.colorTint = UIColor(hex: 0xAFAFAF).withAlphaComponent(0.15)
        visualEffectView.blurRadius = 16
        visualEffectView.scale = 1
        return visualEffectView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    private func setupUI() {
        // 添加图片视图
        addSubview(imageView)
        imageView.frame = bounds
        
        // 添加模糊视图
        addSubview(effectView)
        effectView.frame = bounds
        imageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        effectView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    func setImage(_ image: UIImage?) {
        imageView.image = image
    }
    
    func setImageUrl(_ url: String, completion: @escaping (Bool) -> Void) {
        imageView.kf.setImage(with: URL(string: url)) { [weak self] result in
            guard let self = self else {
                completion(false)
                return
            }
            switch result {
            case .success(let value):
                self.imageView.image = value.image
                completion(true)
            case .failure:
                completion(false)
            }
        }
    }
}
