//
//   UIView+Extension.swift
//  PhoneManager
//
//  Created by zxhy on 2025/3/19.
//

import UIKit
import StoreKit

var blurKey = "blurKey"

extension UIView {
    
    func addTopShadow() {
        layer.masksToBounds = false
        layer.shadowColor = UIColor(red: 0, green: 0.51, blue: 1, alpha: 0.15).cgColor
        layer.shadowOpacity = 1
        layer.shadowOffset = CGSize(width: 0, height: -2) // 负值使阴影显示在顶部
        layer.shadowRadius = 14
    }
    
    func responderViewController() -> UIViewController? {

        for view in sequence(first: self.superview, next: { $0?.superview }) {

            if let responder = view?.next {

                if responder.isKind(of: UIViewController.self){

                    return responder as? UIViewController
                }

            }

        }

        return nil
    }
    
    func cornerCut(radius:CGFloat,corner:UIRectCorner){
        let maskPath = UIBezierPath.init(roundedRect: bounds, byRoundingCorners: corner, cornerRadii: CGSize.init(width: radius, height: radius))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = bounds
        maskLayer.path = maskPath.cgPath
        layer.mask = maskLayer
    }
    
    func setShadow(
        cornerRadius:CGFloat = 4,
        sColor:UIColor = UIColor.colorWithHex(hexStr: blackColor, alpha: 0.08),
        offset:CGSize = CGSize(width: 0, height: 0),
        opacity:Float = 1,
        radius:CGFloat = 8
    ) {
        //设置阴影颜色
        self.layer.shadowColor = sColor.cgColor
        //设置透明度
        self.layer.shadowOpacity = opacity
        //设置阴影半径
        self.layer.shadowRadius = radius
        //设置阴影偏移量
        self.layer.shadowOffset = offset
        //
        self.layer.cornerRadius = cornerRadius
    }
    
    var x :CGFloat {
        
        get {
            
            return frame.origin.x
        }
        
        set {
            
            var frame1:CGRect = frame
            frame1.origin.x = newValue
            frame = frame1
        }
    }
    
    var y :CGFloat {
        
        get {
            
            return frame.origin.y
        }
        
        set {
            
            var frame1:CGRect = frame
            frame1.origin.y = newValue
            frame = frame1
            
        }
    }
    var width :CGFloat {
        
        get {
            
            return frame.size.width
        }
        
        set {
            
            var frame1:CGRect = frame
            frame1.size.width = newValue
            frame = frame1
            
        }
    }
    
    var height :CGFloat {
        
        get {
            
            return frame.size.height
        }
        
        set {
            
            var frame1:CGRect = frame
            frame1.size.height = newValue
            frame = frame1
            
        }
    }
    
    var size :CGSize {
        
        get {
            
            return frame.size
        }
        
        set {
            
            var frame1:CGRect = frame
            frame1.size = newValue
            frame = frame1
            
        }
    }
    
    var centerX :CGFloat {
        
        get {
            
            return center.x
        }
        
        set {
            
            var center1:CGPoint = center
            center1.x = newValue
            center = center1
        }
    }
    
    var centerY :CGFloat {
        
        get {
            
            return center.y
        }
        
        set {
            
            var center1:CGPoint = center
            center1.y = newValue
            center = center1
        }
    }
    
    func gradient(colors: [UIColor], direction: GradientDirection = .leftToRight, cornerRadius: CGFloat = 0) {
            // 移除已有的渐变图层
            self.layer.sublayers?.filter { $0 is CAGradientLayer }.forEach { $0.removeFromSuperlayer() }

            // 创建渐变图层
            let gradientLayer = CAGradientLayer()
            gradientLayer.colors = colors.map { $0.cgColor }
            gradientLayer.locations = [0.0, 1.0] // 渐变位置
            gradientLayer.startPoint = direction.startPoint
            gradientLayer.endPoint = direction.endPoint
            gradientLayer.frame = self.bounds
            gradientLayer.cornerRadius = cornerRadius

            // 将渐变图层添加到视图的最底层
            self.layer.insertSublayer(gradientLayer, at: 0)

        }
    
    var blur:UIVisualEffectView {
        set {
            objc_setAssociatedObject(self, &blurKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get {
            var blurs = objc_getAssociatedObject(self, &blurKey) as? UIVisualEffectView
            if blurs == nil {
                let blurEffect = UIBlurEffect(style: .dark)
                blurs = UIVisualEffectView(effect: blurEffect)
                blurs?.alpha = 0
                self.blur = blurs!
            }
            return blurs!
        }
    }
    
    func showBlur() -> Void {
        self.addSubview(blur)
        blur.frame = self.bounds
        UIView.animate(withDuration: AniDuration) {
            self.blur.alpha = 1
        }
    }
    
    func hideBlur() -> Void {
        UIView.animate(withDuration: AniDuration) {
            self.blur.alpha = 0
        } completion: { su in
            self.blur.removeFromSuperview()
        }
    }
    
    /// 视图最右边的x坐标（origin.x + width）
     var rightX: CGFloat {
         return frame.maxX
     }
     
     /// 视图最底部的y坐标（origin.y + height）
     var bottomY: CGFloat {
         return frame.maxY
     }
}


enum GradientDirection {
    case leftToRight
    case topToBottom
    case topLeftToBottomRight
    case topRightToBottomLeft

    var startPoint: CGPoint {
        switch self {
        case .leftToRight:
            return CGPoint(x: 0.0, y: 0.5)
        case .topToBottom:
            return CGPoint(x: 0.5, y: 0.0)
        case .topLeftToBottomRight:
            return CGPoint(x: 0.0, y: 0.0)
        case .topRightToBottomLeft:
            return CGPoint(x: 1.0, y: 0.0)
        }
    }

    var endPoint: CGPoint {
        switch self {
        case .leftToRight:
            return CGPoint(x: 1.0, y: 0.5)
        case .topToBottom:
            return CGPoint(x: 0.5, y: 1.0)
        case .topLeftToBottomRight:
            return CGPoint(x: 1.0, y: 1.0)
        case .topRightToBottomLeft:
            return CGPoint(x: 0.0, y: 1.0)
        }
    }
}

extension Date {
    
    func string(_ format:String = "") -> String {
        let dateforametter = DateFormatter()
        dateforametter.dateFormat = format
        return dateforametter.string(from: self)
    }
    
    func operation( year:Int = 0,
                    month:Int = 0,
                    day:Int = 0,
                    houre:Int = 0,
                    minte:Int = 0,
                    sec:Int = 0,
                    week:Int = 0) -> Date? {
        let calendar = Calendar.current
        let currentDate = self
        var dateComponent:DateComponents = calendar.dateComponents([.year,.month,.day,.hour,.minute,.second,.weekday], from: currentDate)
        dateComponent.year! += year
        dateComponent.month! += month
        dateComponent.day! += day
        dateComponent.hour! += houre
        dateComponent.minute! += minte
        dateComponent.second! += sec
        dateComponent.weekday! += week
        guard let toDate = calendar.date(from: dateComponent) else { return self }
        return toDate
    }
    
    
    
    
}

extension SKProduct {
    var localizedPrice: String {
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.locale = priceLocale
        formatter.maximumFractionDigits = 2
        guard let priceNumber:NSNumber = price as? NSNumber else {
            return ""
        }
        return formatter.string(from: priceNumber) ?? ""
    }
}

var borderWKey = "borderWKey"
var borderCKey = "borderCKey"

@IBDesignable
extension UIView {
    
    @IBInspectable var Radius:Double {
        set {
            self.layer.cornerRadius = newValue
            self.clipsToBounds = true
        }
        get {
            return 0
        }
    }
    
    @IBInspectable var borderColor:UIColor {
        set {
            self.layer.borderColor = newValue.cgColor
            self.layer.borderWidth = self.borderWidth
            self.clipsToBounds = true
            objc_setAssociatedObject(self, &borderCKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get {
            return objc_getAssociatedObject(self, &borderCKey) as? UIColor ?? UIColor.clear
        }
    }
    
    @IBInspectable var borderWidth:Double {
        set {
            self.layer.borderColor = self.borderColor.cgColor
            self.layer.borderWidth = newValue
            self.clipsToBounds = true
            objc_setAssociatedObject(self, &borderWKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        get {
            return objc_getAssociatedObject(self, &borderWKey) as? Double ?? 0.0
        }
    }
}
