//
//  UIView+.swift
//  YTBase_Example
//
//  Created by YouT on 2020/9/16.
//  Copyright © 2020 CocoaPods. All rights reserved.
//

import UIKit

public extension UIView {
    var width: CGFloat {
        return bounds.size.width
    }
    
    var height: CGFloat {
        return bounds.size.height
    }
    
    //  圆角
    func makeRadius(value: CGFloat, type: UIRectCorner = .allCorners, widthValue: CGFloat = 0, borderColor: UIColor = .clear) {
        let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: type, cornerRadii: CGSize(width: value, height: value))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = self.bounds
        maskLayer.path = maskPath.cgPath
        if widthValue == 0 || borderColor == .clear {
            layer.mask = maskLayer
        }else{
            maskLayer.fillColor = UIColor.clear.cgColor
            maskLayer.strokeColor = borderColor.cgColor
            maskLayer.lineWidth = widthValue
            layer.addSublayer(maskLayer)
        }
    }
    
    //  圆角
    func makeLayerRadius(value: CGFloat, type: CACornerMask = [.layerMaxXMaxYCorner,.layerMaxXMinYCorner,.layerMinXMaxYCorner,.layerMinXMinYCorner]) {
        layer.cornerRadius = value
        if #available(iOS 11.0, *) {
            layer.maskedCorners = type
        }
        layer.masksToBounds = true
    }
    
    //  毛玻璃效果
    func makeBlurEffect(_ style: UIBlurEffect.Style) {
        let blurEffect = UIBlurEffect(style: style)
        let visualEffectView = UIVisualEffectView(effect: blurEffect)
        visualEffectView.frame = self.bounds
        self.addSubview(visualEffectView)
    }
    
    //边框阴影
    func setShadow(_ sColor:UIColor,offset:CGSize,opacity:Float,radius:CGFloat) {
           //设置阴影颜色
        self.layer.shadowColor = sColor.cgColor
           //设置透明度
        self.layer.shadowOpacity = opacity
           //设置阴影半径
        self.layer.shadowRadius = radius
           //设置阴影偏移量
        self.layer.shadowOffset = offset
    }
    
    /// 部分圆角
    ///
    /// - Parameters:
    ///   - corners: 需要实现为圆角的角，可传入多个
    ///   - radii: 圆角半径
    func corner(byRoundingCorners corners: UIRectCorner, radii: CGFloat) {
        let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radii, height: radii))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = self.bounds
        maskLayer.path = maskPath.cgPath
        self.layer.mask = maskLayer
    }
    
    //截图
    func getCurrentFrameImage() -> UIImage? {
        defer {
            UIGraphicsEndImageContext()
        }
        UIGraphicsBeginImageContext(bounds.size)
        layer.render(in: UIGraphicsGetCurrentContext()!)
        let endImage = UIGraphicsGetImageFromCurrentImageContext()
        return endImage
    }
    
    /// 背景线性渐变 默认横向渐变 point -> 0 - 1
    /// let gradients:[(UIColor,Float)] = [(UIColor.red,0),(UIColor.yellow,1)]
    /// view.cd.gradient(layer: gradients)
    /// 文字渐变 view.gradient(layerAxial: ...,
    func gradient(layerAxial gradients:[(color:UIColor,location:Float)], point:(start:CGPoint, end:CGPoint) = (start:CGPoint(x: 0, y: 0), end:CGPoint(x: 1, y: 0)), at: UInt32 = 0, updateIndex:Int? = nil) {
        
       func gradient(_ layer:CAGradientLayer) {
            self.layoutIfNeeded()
            layer.colors = gradients.map{$0.color.cgColor}
            layer.locations = gradients.map{NSNumber(value:$0.location)}
            layer.startPoint = point.start
            layer.endPoint = point.end
            layer.frame = self.bounds
        }
        
        let layers:[CAGradientLayer] = self.layer.sublayers?.filter{$0.isKind(of: CAGradientLayer.self)}.map{$0} as? [CAGradientLayer] ?? []
        if layers.count <= at {
            let layer = CAGradientLayer()
            gradient(layer)
            self.layer.insertSublayer(layer, at: at)
        }else{
            gradient(layers[updateIndex ?? 0])
        }
    }
    
    //切圆角
    func addCorner(conrners: UIRectCorner , radius: CGFloat) {
            let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: conrners, cornerRadii: CGSize(width: radius, height: radius))
            let maskLayer = CAShapeLayer()
            maskLayer.frame = self.bounds
            maskLayer.path = maskPath.cgPath
            self.layer.mask = maskLayer
        }
    
    
    /**
     * 绘制虚线
       view1.drawDottedLine(view1.bounds, 7, UIColor.gray)
     */
    func drawDottedLine(_ rect: CGRect, _ radius: CGFloat, _ color: UIColor) {
        let layer = CAShapeLayer()
        layer.bounds = CGRect(x: 0, y: 0, width: rect.width, height: rect.height)
        layer.position = CGPoint(x: rect.midX, y: rect.midY)
        layer.path = UIBezierPath(rect: layer.bounds).cgPath
        layer.path = UIBezierPath(roundedRect: layer.bounds, cornerRadius: radius).cgPath
        layer.lineWidth = 1/UIScreen.main.scale
        //虚线边框
        layer.lineDashPattern = [NSNumber(value: 5), NSNumber(value: 5)]
        layer.fillColor = UIColor.clear.cgColor
        layer.strokeColor = color.cgColor
        
        self.layer.addSublayer(layer)
    }
    
    func drawDashLine(_ rect: CGRect,strokeColor: UIColor, lineWidth: CGFloat = 1, lineLength: Int = 10, lineSpacing: Int = 5) {
           let shapeLayer = CAShapeLayer()
//           shapeLayer.bounds = self.bounds
           shapeLayer.bounds = CGRect(x: 0, y: 0, width: rect.width, height: rect.height)
   //        shapeLayer.anchorPoint = CGPoint(x: 0, y: 0)
           shapeLayer.position = CGPoint(x: rect.midX, y: rect.midY)
           shapeLayer.fillColor = UIColor.clear.cgColor
           shapeLayer.strokeColor = strokeColor.cgColor
           shapeLayer.lineWidth = lineWidth
           shapeLayer.lineJoin = CAShapeLayerLineJoin.round
           shapeLayer.lineDashPhase = 0 //从哪个位置开始
           //每一段虚线长度 和 每两段虚线之间的间隔
           shapeLayer.lineDashPattern = [NSNumber(value: lineLength), NSNumber(value: lineSpacing)]
           let path = CGMutablePath()
           path.move(to: CGPoint(x: 0, y: 0))
           path.addLine(to: CGPoint(x: rect.width, y: 0))
           shapeLayer.path = path
           self.layer.addSublayer(shapeLayer)
       }
}

extension YTBase where Base: UIView{
    
}

//seachbar
extension UISearchBar {
    func setupSearchBar(background: UIColor = .white, inputText: UIColor = .black, placeholderText: UIColor = .gray, image: UIColor = .black) {

        self.searchBarStyle = .minimal

        self.barStyle = .default

        // IOS 12 and lower:
        for view in self.subviews {

            for subview in view.subviews {
                if subview is UITextField {
                    if let textField: UITextField = subview as? UITextField {

                        // Background Color
                        textField.backgroundColor = background

                        //   Text Color
                        textField.textColor = inputText

                        //  Placeholder Color
                        textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor : placeholderText])

                        //  Default Image Color
                        if let leftView = textField.leftView as? UIImageView {
                            leftView.image = leftView.image?.withRenderingMode(.alwaysTemplate)
                            leftView.tintColor = image
                        }

                        let backgroundView = textField.subviews.first
                        backgroundView?.backgroundColor = background
                        backgroundView?.layer.cornerRadius = 10.5
                        backgroundView?.layer.masksToBounds = true

                    }
                }
            }

        }

        // IOS 13 only:
        if let textField = self.value(forKey: "searchField") as? UITextField {

            // Background Color
            textField.backgroundColor = background

            //   Text Color
            textField.textColor = inputText

            //  Placeholder Color
            textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor : placeholderText])

            //  Default Image Color
            if let leftView = textField.leftView as? UIImageView {
                leftView.image = leftView.image?.withRenderingMode(.alwaysTemplate)
                leftView.tintColor = image
            }

        }

    }

}
