//
//  UIImage+Ext.swift
//  PQSpeed
//
//  Created by SanW on 2020/6/19.
//  Copyright © 2020 BytesFlow. All rights reserved.
//

import Foundation

// MARK: - 刷新控件类型

/// 刷新控件类型
public enum moveDirection {
    case moveDirectionNormal
    case moveDirectionUp
    case moveDirectionDown
    case moveDirectionRight
    case moveDirectionLeft
}

public extension UIImage {
    // 从BFframwork bundle 中取图片
    func BF_Image(named: String) -> UIImage {
        let image: UIImage = UIImage(named: named, in: Bundle().BF_mainbundle(), compatibleWith: nil) ?? UIImage()
        return image
    }

    func cropImage(ratio: CGFloat) -> UIImage {
        // 计算最终尺寸
        let newSize: CGSize = CGSize(width: size.width, height: size.width * ratio)
        // 图片绘制区域
        var rect = CGRect.zero
        rect.size.width = size.width
        rect.size.height = size.height
        rect.origin.x = (newSize.width - size.width) / 2.0
        rect.origin.y = (newSize.height - size.height) / 2.0

        UIGraphicsBeginImageContext(newSize)
        draw(in: rect)
        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return scaledImage!
    }

    func cropImage(newSize: CGSize) -> UIImage {
        //// 图片绘制区域
        var rect = CGRect.zero
        rect.size.width = newSize.width
        rect.size.height = newSize.width * (size.height / size.width)
        // 绘制并获取最终图片
        UIGraphicsBeginImageContext(newSize)
        draw(in: rect)
        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return scaledImage!
    }

    func imageWithImage(scaledToSize newSize: CGSize) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
        draw(in: CGRect(origin: CGPoint.zero, size: newSize))
        let newImage = UIGraphicsGetImageFromCurrentImageContext() ?? self
        UIGraphicsEndImageContext()
        return newImage
    }

    /// 旋转角度
    /// - Parameter image: <#image description#>
    /// - Returns: <#description#>
    func rotateImage(rotate: Int, originWidth: CGFloat, originHeight: CGFloat) -> UIImage {
        let rotate: CGFloat = CGFloat(3 * Double.pi / 2)
        let rect = CGRect(x: 0, y: 0, width: originWidth, height: originHeight)
        let translateX: CGFloat = -rect.size.height
        let translateY: CGFloat = 0
        let scaleY = rect.size.width / rect.size.height
        let scaleX = rect.size.height / rect.size.width
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        //        context!.translateBy(x: 0.0, y: rect.size.height)
        //        context!.scaleBy(x: 1.0, y: -1.0)
        context!.rotate(by: rotate)
        context!.translateBy(x: translateX, y: translateY)
        context!.scaleBy(x: scaleX, y: scaleY)
        draw(in: CGRect(x: 0, y: 0, width: rect.size.width, height: rect.size.height))
        return UIGraphicsGetImageFromCurrentImageContext()!
    }

    /// 生成三角图
    /// - Parameters:
    ///   - size: <#size description#>
    ///   - tintColor: <#tintColor description#>
    ///   - convert:是否倒置
    /// - Returns: <#description#>
    class func triangleImage(size: CGSize, tintColor: UIColor, direction: moveDirection = .moveDirectionDown) -> UIImage {
        var startPoint: CGPoint = CGPoint.zero
        var middlePoint: CGPoint = CGPoint.zero
        var endPoint: CGPoint = CGPoint.zero
        switch direction {
        case .moveDirectionLeft:
            startPoint = CGPoint(x: size.width, y: 0)
            middlePoint = CGPoint(x: 0, y: size.height / 2.0)
            endPoint = CGPoint(x: size.width, y: size.height)
        case .moveDirectionRight:
            startPoint = CGPoint(x: 0, y: 0)
            middlePoint = CGPoint(x: size.width, y: size.height / 2.0)
            endPoint = CGPoint(x: 0, y: size.height)
        case .moveDirectionUp:
            startPoint = CGPoint(x: 0, y: size.height)
            middlePoint = CGPoint(x: size.width / 2.0, y: 0)
            endPoint = CGPoint(x: size.width, y: size.height)
        default:
            startPoint = CGPoint(x: 0, y: 0)
            middlePoint = CGPoint(x: size.width / 2.0, y: size.height)
            endPoint = CGPoint(x: size.width, y: 0)
        }
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        let ctx = UIGraphicsGetCurrentContext()
        let path = UIBezierPath()
        path.move(to: startPoint)
        path.addLine(to: middlePoint)
        path.addLine(to: endPoint)
        path.close()
        ctx?.setFillColor(tintColor.cgColor)
        path.fill()
        let image = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }

    /// 按照最短边缩放  add by ak
    /// - Parameter maxLength: 边长最大值
    func nx_scaleWithMaxLength(maxLength: CGFloat) -> UIImage {
        if size.width > maxLength || size.height > maxLength {
            var maxWidth: CGFloat = maxLength
            var maxHeight: CGFloat = maxLength

            if size.width != size.height {
                if size.width > size.height {
                    // 按照宽 来缩放
                    let imageScale: CGFloat = maxLength / size.width

                    maxHeight = size.height * imageScale
                } else if size.width < size.height {
                    let imageScale: CGFloat = maxLength / size.height

                    maxWidth = size.width * imageScale
                }
            }
            // 返回新的改变大小后的图片
            return nx_scaleToSize(size: CGSize(width: maxWidth, height: maxHeight))
        }

        return self
    }

    /// 缩放到指定大小 add by ak
    /// - Parameter size: 新的大小
    func nx_scaleToSize(size: CGSize) -> UIImage {
        var width: CGFloat = CGFloat(cgImage!.width)
        var height: CGFloat = CGFloat(cgImage!.height)

        let verticalRadio: CGFloat = size.height * 1.0 / height
        let horizontalRadio: CGFloat = size.width * 1.0 / width

        var radio: CGFloat = 1
        if verticalRadio > 1, horizontalRadio > 1 {
            radio = verticalRadio > horizontalRadio ? horizontalRadio : verticalRadio
        } else {
            radio = verticalRadio < horizontalRadio ? verticalRadio : horizontalRadio
        }

        width = width * radio
        height = height * radio

        let xPos: CGFloat = (size.width - width) / 2
        let yPos: CGFloat = (size.height - height) / 2

        // 创建一个bitmap的context
        // 并把它设置成为当前正在使用的context
        UIGraphicsBeginImageContext(size)

        // 绘制改变大小的图片
        var rect = CGRect.zero
        rect.size.width = width
        rect.size.height = height
        rect.origin.x = xPos
        rect.origin.y = yPos

        draw(in: rect)

        // 从当前context中创建一个改变大小后的图片
        let scaledImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!

        // 使当前的context出堆栈
        UIGraphicsEndImageContext()

        // 返回新的改变大小后的图片
        return scaledImage
    }

    // 将图片裁剪成指定比例（多余部分自动删除）let image3 = image.crop(ratio: 1) /将图片转成 1:1 比例（正方形）
    func nxcrop(ratio: CGFloat) -> UIImage {
        // 计算最终尺寸
        var newSize: CGSize!
        if size.width / size.height > ratio {
            newSize = CGSize(width: size.height * ratio, height: size.height)
        } else {
            newSize = CGSize(width: size.width, height: size.width / ratio)
        }

        ////图片绘制区域
        var rect = CGRect.zero
        rect.size.width = size.width
        rect.size.height = size.height
        rect.origin.x = (newSize.width - size.width) / 2.0
        rect.origin.y = (newSize.height - size.height) / 2.0

        // 绘制并获取最终图片
        UIGraphicsBeginImageContext(newSize)
        draw(in: rect)
        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return scaledImage!
    }

    /// 改变图片主题颜色
    /// - Parameters:
    ///   - color: <#color description#>
    ///   - blendMode: <#blendMode description#>
    /// - Returns: <#description#>
    func tintImage(color: UIColor, blendMode: CGBlendMode) -> UIImage? {
        let rect = CGRect(origin: CGPoint.zero, size: size)
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        color.setFill()
        UIRectFill(rect)
        draw(in: rect, blendMode: blendMode, alpha: 1.0)
        let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return tintedImage
    }
}
