//
//  BsOverlayView.swift
//  BaiSiSMApp
//
//  Created by Davidhuang on 2022/11/22.
//  Copyright © 2022 www.davidhuang.com. All rights reserved.
//

import UIKit

class YhOverlayView: UIView {
    
    // MARK: - 属性
    
    public var overlayView: UIControl!  // 遮罩层view
    private var keyWindow: UIWindow?
    
    // MARK: - 生命周期函数
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupOverlayView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupOverlayView() {
        // 1 获取window
        if keyWindow == nil {
            self.keyWindow = UIApplication.shared.yhKeyWindow()
        }
        // 2.遮罩view
        overlayView = UIControl.init(frame: UIScreen.main.bounds)
        overlayView?.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.5)
        overlayView?.addTarget(self, action: #selector(hide), for: .touchUpInside)
        overlayView?.alpha = 0
    }
    
    // MARK: - ACTIONS
    // 显示
    public func show() {
        keyWindow?.addSubview(overlayView!)
        keyWindow?.addSubview(self)
        UIView.animate(withDuration: 0.25, animations: {
            self.overlayView?.alpha = 1.0
            var frame = self.frame
            frame.origin.y = UIScreen.main.bounds.size.height - self.bounds.size.height
            self.frame = frame
        }) { (_) in
            //
        }
    }
    
    // 隐藏
    @objc public func hide() {
        UIView.animate(withDuration: 0.25, animations: {
            self.overlayView?.alpha = 0
            var frame = self.frame
            frame.origin.y = UIScreen.main.bounds.size.height
            self.frame = frame
        }) { (_) in
            self.overlayView?.removeFromSuperview()
            self.removeFromSuperview()
        }
    }
    
    // MARK: - 私有方法
    
    // MARK: - 事件响应包括手势和按钮等
    
    // MARK: - UITableViewDataSource 和 UITableViewDelegate
    
}
