//
//  CLImageViews.swift

//
//  Created by Leon on 2025/7/20.
//
import UIKit
import SnapKit

class CLAnimatedImage: UIImageView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

    override init(image: UIImage?) {
        super.init(image: image)
        setupViews()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupViews()
    }

    private func setupViews() {
        contentMode = .scaleAspectFill
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        layer.cornerRadius = bounds.size.height * 0.5
        layer.masksToBounds = true
    }
}

class CLImageView: UIImageView {
    convenience init(){
        self.init(frame: .zero)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

    override init(image: UIImage?) {
        super.init(image: image)
        setupViews()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupViews()
    }

    private func setupViews() {
        contentMode = .scaleAspectFill
    }
}

/// 约束时,请不要给定底部的约束
class AutoRatioImageView: CLImageView {
    
    // 用来保存宽高比约束
    private var aspectRatioConstraint: Constraint?
    
    convenience init() {
        self.init(frame: .zero)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }
    
    private func setupView() {
        contentMode = .scaleAspectFill
        clipsToBounds = true // 裁剪多余部分
        
        self.snp.makeConstraints { make in
            make.height.equalTo(self.snp.width).priority(.low)
        }
    }
    
    /// 设置本地图片
    func setImage(_ image: UIImage?) {
        self.image = image
        updateAspectRatio(for: image?.size)
    }
    
    /// 设置网络图片
    func setImage(with url: URL?, placeholder: UIImage? = nil) {
        self.kf.setImage(with: url, placeholder: placeholder, completionHandler: { [weak self] result in
            switch result {
            case .success(let value):
                self?.updateAspectRatio(for: value.image.size)
            case .failure:
                self?.updateAspectRatio(for: placeholder?.size)
            }
        })
    }

    
    /// 更新宽高比约束
    private func updateAspectRatio(for size: CGSize?) {
        guard let size = size, size.width > 0 else { return }
        let ratio = size.height / size.width
        
        // 先移除旧的约束
        aspectRatioConstraint?.deactivate()
        
        // 高度 = 宽度 * 比例
        self.snp.makeConstraints { make in
            aspectRatioConstraint = make.height.equalTo(self.snp.width).multipliedBy(ratio).constraint
        }
    }
}
