//
//  UIButton+Ex.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/20.
//

public extension UIButton {
    
    private struct AssociatedKeys {
        static var actionKey = "UIButtonActionKey"
    }

    // 存储回调闭包
    private var actionClosure: (() -> Void)? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.actionKey) as? (() -> Void)
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.actionKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    
    
    /// 快速创建 UIButton
    /// - Parameters:
    ///   - title: 按钮的标题
    ///   - image: 按钮的图标
    ///   - backgroundImage: 按钮的背景图
    ///   - backgroundColor: 按钮的背景色
    ///   - font: 按钮的字体
    ///   - titleColor: 按钮的字体颜色
    ///   - action: 按钮点击事件的回调
    static func createButton(title: String? = nil,
                             image: UIImage? = nil,
                             backgroundImage: UIImage? = nil,
                             backgroundColor: UIColor? = nil,
                             font: UIFont? = nil,
                             titleColor: UIColor? = nil,
                             corner:CGFloat = 0,
                             autoMirrored: Bool = true,
                             action: (() -> Void)? = nil) -> UIButton {
        let button = UIButton(type: .custom)
        button.setUpButton(title: title,
                           image: image,
                           backgroundImage: backgroundImage,
                           backgroundColor: backgroundColor,
                           font: font,
                           titleColor: titleColor,
                           corner:corner,
                           autoMirrored: autoMirrored,
                           action: action)
        return button
    }

    func setUpButton(title: String? = nil,
                             image: UIImage? = nil,
                             backgroundImage: UIImage? = nil,
                             backgroundColor: UIColor? = nil,
                             font: UIFont? = nil,
                             titleColor: UIColor? = nil,
                             corner:CGFloat = 0,
                             autoMirrored: Bool = true,
                             action: (() -> Void)? = nil){
        let button = self
        button.showsTouchWhenHighlighted = false
        button.adjustsImageWhenHighlighted = false
        // 设置标题
        if let title = title {
            button.setTitle(title, for: .normal)
        }
        
        // 设置图片
        if let image = image {
            if autoMirrored {
                button.setImage(image.mirrored, for: .normal)
            }else{
                button.setImage(image, for: .normal)
            }
        }
        
        // 设置背景图片
        if let backgroundImage = backgroundImage {
            if autoMirrored {
                button.setBackgroundImage(backgroundImage.mirrored, for: .normal)
            }else{
                button.setBackgroundImage(backgroundImage, for: .normal)
            }
        }
        
        // 设置背景色
        if let backgroundColor = backgroundColor {
            button.backgroundColor = backgroundColor
        }
        
        // 设置字体
        if let font = font {
            button.titleLabel?.font = font
        }
        
        // 设置字体颜色
        if let titleColor = titleColor {
            button.setTitleColor(titleColor, for: .normal)
        }
        
        if corner > 0 {
            button.cornerRadius = corner
        }

        if let action = action {
            button.actionClosure = action
            button.addTarget(button, action: #selector(buttonTapped), for: .touchUpInside)
        }

    }
    
    // 按钮点击事件
    @objc private func buttonTapped() {
        actionClosure?()
    }
    
    public func preventMultipleTaps(delay: Double = 0.75) {
        self.isEnabled = false
        DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
            self.isEnabled = true
        }
    }

}

public extension UIButton {
    
    public func setContentImageSpace(spacing:CGFloat = 4){
        if kIsRTL {
            contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: spacing) // 只调整 title 的 left
            imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -spacing) // 只调整 image 的 right
        }else{
            contentEdgeInsets = UIEdgeInsets(top: 0, left: spacing, bottom: 0, right: 0) // 只调整 title 的 left
            imageEdgeInsets = UIEdgeInsets(top: 0, left: -spacing, bottom: 0, right: 0) // 只调整 image 的 right
        }
    }
    
    public func setTitleImageSpace(spacing:CGFloat = 4){
        if kIsRTL {
            titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: spacing) // 只调整 title 的 left
            imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -spacing) // 只调整 image 的 right
        }else{
            titleEdgeInsets = UIEdgeInsets(top: 0, left: spacing, bottom: 0, right: 0) // 只调整 title 的 left
            imageEdgeInsets = UIEdgeInsets(top: 0, left: -spacing, bottom: 0, right: 0) // 只调整 image 的 right
        }
    }
    
}
public class TSUIExpandedTouchButton: UIButton {
    public var indexPath: IndexPath = IndexPath(item: 0, section: 0)
    
    override public func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        let buttonBounds = self.bounds
        let widthDelta = self.width * 0.5 // 增加点击区域的比例，这里增加了50%
        let heightDelta = self.height * 0.5
        let expandedBounds = buttonBounds.insetBy(dx: -widthDelta, dy: -heightDelta)
        return expandedBounds.contains(point)
    }
}


public class TSVerticalButton: UIButton {
    var spacing: CGFloat = 4 {
        didSet { setNeedsLayout() }
    }

    public override func layoutSubviews() {
        super.layoutSubviews()
        guard let imageView = imageView, let titleLabel = titleLabel else { return }

        // 图片居中靠上
        imageView.frame.origin.y = (bounds.height - imageView.frame.height - titleLabel.frame.height - spacing) / 2
        imageView.center.x = bounds.width / 2

        // 文字居中靠下
        titleLabel.frame.origin.y = imageView.frame.maxY + spacing
        titleLabel.center.x = bounds.width / 2
    }
}
