//
//  PQHeartAnimation.swift
//  PQSpeed
//
//  Created by SanW on 2020/6/11.
//  Copyright © 2020 BytesFlow. All rights reserved.
//

import UIKit

public class PQHeartAnimation: NSObject {
    static let angleArr: [CGFloat] = [CGFloat.pi / 4.0, -CGFloat.pi / 4.0, 0.0]
    var isRepeat: Bool = false

    static public func showAnimation(isRepeat: Bool = false, point: CGPoint, size: CGFloat = 80.0, baseView: UIView, completeHander: @escaping (_ isFinised: Bool) -> Void) {
        if isRepeat, baseView.viewWithTag(cHeartTag) != nil {
            return
        }
        let imgV = UIImageView(frame: CGRect(x: point.x - size / 2.0, y: point.y - size / 2.0, width: size, height: size))
        imgV.tag = cHeartTag
        imgV.image = UIImage.init().BF_Image(named:  "ic_heart")
        imgV.contentMode = .scaleAspectFill
        baseView.addSubview(imgV)

        // 偏移角度
        var num = 2
        if !isRepeat {
            num = Int(arc4random_uniform(3))
        }
//      BFLog(message: "num = \(num)")
        imgV.transform = CGAffineTransform(rotationAngle: angleArr[num])
        // 放大动画
        let animation = CAKeyframeAnimation(keyPath: "transform.scale")
        animation.duration = 0.5
        animation.calculationMode = CAAnimationCalculationMode.cubic
        animation.values = [1.3, 0.8, 1.0]
        imgV.layer.add(animation, forKey: "transform.scale")

        UIView.animate(withDuration: 1, delay: 0.5, options: .layoutSubviews, animations: {
            imgV.alpha = 0.0
            var newFrame = imgV.frame
            newFrame.origin.x -= (isRepeat ? -cDefaultMargin * 2 : cDefaultMargin)
            newFrame.origin.y -= 45.0
            newFrame.size.height += 10.0
            newFrame.size.width += 10.0
            imgV.frame = newFrame
        }) { isOK in
            imgV.layer.removeAllAnimations()
            imgV.removeFromSuperview()
            completeHander(isOK)
        }
    }
}
