//
//  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
        }
    }
    
    
    /// 设置渐变色背景
    /// - Parameters:
    ///   - colors: 渐变颜色数组（CGColor 类型）
    ///   - startPoint: 渐变的起点（单位坐标，范围 [0, 1]）
    ///   - endPoint: 渐变的终点（单位坐标，范围 [0, 1]）
    ///   - layerSize: 渐变层的大小（默认为视图的 bounds）
    func addGradientBg(colors: [CGColor],
                       startPoint: CGPoint = CGPoint(x: 0, y: 0),
                       endPoint: CGPoint = CGPoint(x: 1, y: 1),
                       layerSize: CGSize? = nil) {
        
        // 移除已有的渐变层，避免重复添加
        self.layer.sublayers?.removeAll(where: { $0 is CAGradientLayer })
        
        // 创建渐变层
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = colors
        gradientLayer.startPoint = startPoint
        gradientLayer.endPoint = endPoint
        gradientLayer.frame = CGRect(origin: .zero, size: layerSize ?? self.bounds.size)
        
        // 添加到视图的图层
        self.layer.insertSublayer(gradientLayer, 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
        
    }
    
    /// 移除所有子视图
    func removeAllSubviews() {
        self.subviews.forEach { $0.removeFromSuperview() }
    }

//    enum MaskContentMode {
//        case scaleToFill
//        case scaleAspectFit
//        case scaleAspectFill
//    }
//    
//    /// 设置图片蒙版，支持指定 `contentMode`
//    /// - Parameters:
//    ///   - image: 用作蒙版的图片
//    ///   - contentMode: 蒙版的内容模式
//    func setImageMask(image: UIImage, contentMode: MaskContentMode = .scaleAspectFit) {
//        // 创建一个 CALayer 来作为蒙版
//        let maskLayer = CALayer()
//        maskLayer.contents = image.cgImage
//        
//        // 计算蒙版的 frame
//        let viewSize = self.bounds.size
//        let imageSize = image.size
//        
//        var maskFrame: CGRect = .zero
//        
//        switch contentMode {
//        case .scaleToFill:
//            // 拉伸填充整个视图
//            maskFrame = CGRect(origin: .zero, size: viewSize)
//            
//        case .scaleAspectFit:
//            // 按比例缩放，适配视图并居中
//            let aspectWidth = viewSize.width / imageSize.width
//            let aspectHeight = viewSize.height / imageSize.height
//            let aspectRatio = min(aspectWidth, aspectHeight) // 按比例适配
//            
//            let scaledWidth = imageSize.width * aspectRatio
//            let scaledHeight = imageSize.height * aspectRatio
//            let xOffset = (viewSize.width - scaledWidth) / 2
//            let yOffset = (viewSize.height - scaledHeight) / 2
//            
//            maskFrame = CGRect(x: xOffset, y: yOffset, width: scaledWidth, height: scaledHeight)
//            
//        case .scaleAspectFill:
//            // 按比例缩放，填充视图并裁剪多余部分
//            let aspectWidth = viewSize.width / imageSize.width
//            let aspectHeight = viewSize.height / imageSize.height
//            let aspectRatio = max(aspectWidth, aspectHeight) // 按比例填充
//            
//            let scaledWidth = imageSize.width * aspectRatio
//            let scaledHeight = imageSize.height * aspectRatio
//            let xOffset = (viewSize.width - scaledWidth) / 2
//            let yOffset = (viewSize.height - scaledHeight) / 2
//            
//            maskFrame = CGRect(x: xOffset, y: yOffset, width: scaledWidth, height: scaledHeight)
//        }
//        
//        maskLayer.frame = maskFrame
//        
//        // 设置蒙版
//        self.layer.mask = maskLayer
//    }
    
    
    enum MaskContentMode {
            case scaleToFill
            case scaleAspectFit
            case scaleAspectFill
        }

        /// 设置图片蒙版，支持指定 `contentMode` 和缩小比例
        /// - Parameters:
        ///   - image: 用作蒙版的图片
        ///   - contentMode: 蒙版的内容模式
        ///   - scaleFactor: 缩小比例，默认 1.0 表示不缩放，0.8 表示缩小为 80%
        func setImageMask(image: UIImage, contentMode: MaskContentMode = .scaleAspectFit, scaleFactor: CGFloat = 1.0) {
            guard scaleFactor > 0 && scaleFactor <= 1 else {
                print("Invalid scaleFactor. It must be in the range (0, 1].")
                return
            }
            
            // 创建一个 CALayer 来作为蒙版
            let maskLayer = CALayer()
            maskLayer.contents = image.cgImage
            
            // 计算蒙版的 frame
            let viewSize = self.bounds.size
            let imageSize = image.size
            
            var maskFrame: CGRect = .zero
            
            switch contentMode {
            case .scaleToFill:
                // 拉伸填充整个视图
                maskFrame = CGRect(origin: .zero, size: viewSize)
                
            case .scaleAspectFit:
                // 按比例缩放，适配视图并居中
                let aspectWidth = viewSize.width / imageSize.width
                let aspectHeight = viewSize.height / imageSize.height
                let aspectRatio = min(aspectWidth, aspectHeight) // 按比例适配
                
                let scaledWidth = imageSize.width * aspectRatio * scaleFactor
                let scaledHeight = imageSize.height * aspectRatio * scaleFactor
                let xOffset = (viewSize.width - scaledWidth) / 2
                let yOffset = (viewSize.height - scaledHeight) / 2
                
                maskFrame = CGRect(x: xOffset, y: yOffset, width: scaledWidth, height: scaledHeight)
                
            case .scaleAspectFill:
                // 按比例缩放，填充视图并裁剪多余部分
                let aspectWidth = viewSize.width / imageSize.width
                let aspectHeight = viewSize.height / imageSize.height
                let aspectRatio = max(aspectWidth, aspectHeight) // 按比例填充
                
                let scaledWidth = imageSize.width * aspectRatio * scaleFactor
                let scaledHeight = imageSize.height * aspectRatio * scaleFactor
                let xOffset = (viewSize.width - scaledWidth) / 2
                let yOffset = (viewSize.height - scaledHeight) / 2
                
                maskFrame = CGRect(x: xOffset, y: yOffset, width: scaledWidth, height: scaledHeight)
            }
            
            maskLayer.frame = maskFrame
            
            // 设置蒙版
            self.layer.mask = maskLayer
        }
}



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