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


import UIKit

extension UIView {
    
    @IBInspectable
    var cornerRadius: CGFloat {
        set {
            clipsToBounds = true
            layer.cornerRadius = newValue
        }
        get {
            layer.cornerRadius
        }
    }
    
    @IBInspectable
    var borderWidth: CGFloat {
        set {
            layer.borderWidth = newValue
        }
        get {
            layer.borderWidth
        }
    }
    
    @IBInspectable
    var borderColor: UIColor? {
        set {
            layer.borderColor = newValue?.cgColor
        }
        get {
            if let cgColor = layer.borderColor {
                return UIColor(cgColor: cgColor)
            }
            return nil
        }
    }
    
    
    /// 增加渐变背景，需要先确定当前 view 的 frame
    /// - Parameters:
    ///   - colors: 渐变背景颜色数组
    ///   - startPoint: 渐变启示位置
    ///   - endPoint: 渐变结束位置
    ///   - layerSize: 指定 layer 的 size，否则和自己当前一样大
    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)
        layer.insertSublayer(gl, at: 0)
    }
    
    /// 慎用
    /// 给 view 增加圆角阴影，会改变视图结构，慎用，
    /// 需add 且确定frame后再调用
    /// > Note: 慎用
    /// - Parameters:
    ///   - cornerRadius: 视图圆角
    ///   - shadowColor: 阴影颜色
    ///   - shadowOffset: 阴影偏移量
    ///   - shadowRadius: 阴影扩散距离
    ///   - shadowOpacity: 阴影透明度
    @discardableResult
    func addCornerRadiusShadow(cornerRadius: CGFloat,
                               shadowColor: CGColor?,
                               shadowOffset: CGSize,
                               shadowRadius: CGFloat,
                               shadowOpacity: Float) -> UIView? {
        guard let supView = superview else {
            debugPrint("必须要先add，且确定了frame")
            return nil
        }
        
        let frame = self.frame
        
        let shadowView = UIView()
        shadowView.frame = frame
        shadowView.layer.shadowColor = shadowColor
        shadowView.layer.shadowOffset = shadowOffset
        shadowView.layer.shadowOpacity = shadowOpacity
        shadowView.layer.shadowRadius = shadowRadius
        
        supView.insertSubview(shadowView, belowSubview: self)
        
        shadowView.addSubview(self)
        self.frame = CGRect(origin: .zero, size: frame.size)
        self.clipsToBounds = false
        self.layer.masksToBounds = true
        self.layer.cornerRadius = cornerRadius
        
        return shadowView
        
    }
}



public extension UIScreen {
    static let size = {
        UIScreen.main.bounds.size
    }()
    
    static var width: CGFloat {
        return size.width
    }
    
    static var height: CGFloat {
        return size.height
    }
}

// Frame
public extension UIView {
    var x: CGFloat {
        set {
            frame.origin.x = newValue
        }
        get {
            return frame.origin.x
        }
    }
    
    var y: CGFloat {
        set {
            frame.origin.y = newValue
        }
        get {
            return frame.origin.y
        }
    }
    
    var width: CGFloat {
        set {
            frame.size.width = newValue
        }
        get {
            return frame.size.width
        }
    }
    
    var height: CGFloat {
        set {
            frame.size.height = newValue
        }
        get {
            return frame.size.height
        }
    }
    
    var size: CGSize {
        get { frame.size }
        set {
            var rect = frame
            rect.size = newValue
            frame = rect
        }
    }
    
    var centerX: CGFloat {
        set {
            let newCenter = CGPoint(x: newValue, y: center.y)
            center = newCenter
        }
        get {
            return center.x
        }
    }
    
    var centerY: CGFloat {
        set {
            let newCenter = CGPoint(x: center.x, y: newValue)
            center = newCenter
        }
        get {
            return center.y
        }
    }
    
    var bottom: CGFloat {
        get {
            return frame.origin.y + frame.size.height
        }
    }
    
    var viewController: UIViewController? {
        var next = superview
        while next != nil {
            let nextResponder = next?.next
            if nextResponder is UINavigationController ||
                nextResponder is UIViewController {
                return nextResponder as? UIViewController
            }
            next = next?.superview
        }
        return nil
    }
    
    func convertedToImage(rect: CGRect = .zero) -> UIImage? {
        var size = bounds.size
        var origin = bounds.origin
        if !size.equalTo(rect.size) && !rect.isEmpty {
            size = rect.size
            origin = CGPoint(x: -rect.minX, y: -rect.minY)
        }
        let format = UIGraphicsImageRendererFormat()
        format.opaque = false
        format.scale = UIScreen._scale
        let renderer = UIGraphicsImageRenderer(size: size, format: format)
        let image = renderer.image { context in
            drawHierarchy(in: CGRect(origin: origin, size: bounds.size), afterScreenUpdates: true)
        }
        return image
    }
    
    func cornersRound(radius: CGFloat, corner: UIRectCorner) {
        if #available(iOS 11.0, *) {
            layer.cornerRadius = radius
            layer.maskedCorners = corner.mask
        } else {
            let path = UIBezierPath(
                roundedRect: bounds,
                byRoundingCorners: corner,
                cornerRadii: CGSize(width: radius, height: radius)
            )
            let mask = CAShapeLayer()
            mask.path = path.cgPath
            layer.mask = mask
        }
    }
}

extension UIRectCorner {
    var mask: CACornerMask {
        switch self {
        case .allCorners:
            return [.layerMinXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMinYCorner, .layerMaxXMaxYCorner]
        default:
            return .init(rawValue: rawValue)
        }
    }
}

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
    }
}

extension UIView {
    /// 为视图添加高斯模糊效果
    /// - Parameters:
    ///   - blurRadius: 模糊半径（默认 10.0）
    ///   - fillColor: 填充颜色（可选，默认透明）
    func applyGaussianBlur(blurRadius: CGFloat = 10.0, fillColor: UIColor? = nil) {
        // 移除已有的模糊效果
        self.removeBlurEffect()
        
        // 创建模糊效果
        let blurEffect = UIBlurEffect(style: .light)
        let blurView = UIVisualEffectView(effect: blurEffect)
        blurView.frame = self.bounds
        blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        
        // 设置模糊强度
        if blurRadius != 10.0 {
            let blurAnimator = CABasicAnimation(keyPath: "inputRadius")
            blurAnimator.fromValue = blurRadius
            blurAnimator.toValue = blurRadius
            blurAnimator.duration = 0
            blurView.layer.add(blurAnimator, forKey: nil)
        }
        
        // 如果指定了填充颜色，添加一个覆盖视图
        if let color = fillColor {
            let colorOverlay = UIView(frame: self.bounds)
            colorOverlay.backgroundColor = color
            colorOverlay.autoresizingMask = [.flexibleWidth, .flexibleHeight]
            colorOverlay.isUserInteractionEnabled = false
            blurView.contentView.addSubview(colorOverlay)
        }
        
        self.addSubview(blurView)
    }
    
    /// 移除模糊效果
    func removeBlurEffect() {
        for subview in subviews {
            if subview is UIVisualEffectView {
                subview.removeFromSuperview()
            }
        }
    }
}
