//
//  UIView+Ex.swift
//  KittensTravelNotes
//
//  Created by 100Years on 2025/7/6.
//

public extension UIView {
    // 部分圆角（必须Frame已知）
    func makeCorner(_ corners: UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = bounds
        maskLayer.path = path.cgPath
        layer.mask = maskLayer
    }
    
    /// 给 view 增加阴影
    /// - Parameters:
    ///   - cornerRadius: 视图圆角
    ///   - shadowColor: 阴影颜色
    ///   - shadowOffset: 阴影偏移量
    ///   - shadowRadius: 阴影扩散距离
    ///   - shadowOpacity: 阴影透明度
    @discardableResult
    public func addShadow(shadowColor: CGColor?,
                          shadowOffset: CGSize,
                          shadowRadius: CGFloat,
                          shadowOpacity: Float){
        layer.shadowColor = shadowColor
        layer.shadowOffset = shadowOffset
        layer.shadowOpacity = shadowOpacity
        layer.shadowRadius = shadowRadius
    }
    
    /// 增加渐变背景，需要先确定当前 view 的 frame
    /// - Parameters:
    ///   - colors: 渐变背景颜色数组
    ///   - startPoint: 渐变启示位置
    ///   - endPoint: 渐变结束位置
    ///   - layerSize: 指定 layer 的 size，否则和自己当前一样大
    public func addGradientBg(colors: [CGColor],
                       startPoint: CGPoint = .zero,
                       endPoint: CGPoint = CGPoint(x: 1, y: 1),
                       layerSize: CGSize? = nil) {
        let gl = CAGradientLayer()
        gl.colors = colors
        gl.startPoint = startPoint
        gl.endPoint = endPoint
        gl.frame = CGRect(origin: .zero, size: layerSize ?? self.bounds.size)
        gl.zPosition =  -1 // 将 gradientLayer 放在底层
        layer.insertSublayer(gl, at: 0)
    }
}

public extension UIView {
    func removeAllSubViews() {
        subviews.forEach { subview in
            subview.removeFromSuperview()
        }
    }
}
