//
//  PQStuckPointLoadingView.swift
//  PQSpeed
//
//  Created by SanW on 2021/5/24.
//  Copyright © 2021 BytesFlow. All rights reserved.
//

import BFCommonKit
import BFUIKit
import Kingfisher
import UIKit

class PQStuckPointLoadingView: UIView {
    var cancelHandle: ((_ sender: UIButton) -> Void)?

    /// 同步进度显示
    lazy var loadingView: AnimatedImageView = {
        let videoLoadingView = AnimatedImageView()
        videoLoadingView.kf.setImage(with: URL(fileURLWithPath: (Bundle.current(moduleName: "BFStuckPointKit", isAssets: false)?.path(forResource: "stuckPoint_edit_loading", ofType: ".gif"))!))
        videoLoadingView.stopAnimating()
        return videoLoadingView
    }()

    lazy var navBarLeftBtn: UIButton = {
        let navBarLeftBtn = UIButton(type: .custom)
        navBarLeftBtn.frame = CGRect(x: 0, y: cDevice_iPhoneStatusBarHei, width: cDefaultMargin * 4, height: cDefaultMargin * 4)
        navBarLeftBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: -5, right: 0)
        navBarLeftBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: -5, right: 0)
        navBarLeftBtn.tintColor = BFConfig.shared.styleTitleColor
        navBarLeftBtn.setImage(imageInUIKit(by: "icon_detail_back")?.withRenderingMode(.alwaysTemplate), for: .normal)
        navBarLeftBtn.addTarget(self, action: #selector(cancelDownload(sender:)), for: .touchUpInside)
        return navBarLeftBtn
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.5)
        addSubViews()
        addLayout()

        loadingView.startAnimating()
    }

    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSubviews() {
        super.layoutSubviews()
    }

    func addSubViews() {
        addSubview(loadingView)
        addSubview(navBarLeftBtn)
    }

    func addLayout() {
        loadingView.snp.makeConstraints { make in
//            make.top.equalToSuperview().offset(cScreenWidth / 2.0 + cDevice_iPhoneStatusBarHei)
            make.centerX.equalTo(cScreenWidth / 2.0)
            make.centerY.equalTo(cScreenHeigth / 2.0)
            make.width.height.equalTo(cDefaultMargin * 10)
        }
    }

    func show() {
        if superview != nil {
            return
        }
        UIApplication.shared.keyWindow?.addSubview(self)
        loadingView.startAnimating()
    }

    /// 移除视图
    /// - Returns: <#description#>
    func removeMarskView() {
        loadingView.stopAnimating()

        if superview != nil {
            removeFromSuperview()
        }

        BFLog(message: "removeMarskViewremoveMarskViewremoveMarskViewremoveMarskView")
    }

    @objc func cancelDownload(sender: UIButton) {
        if cancelHandle != nil {
            cancelHandle!(sender)
            removeMarskView()
        }
    }

    deinit {
        BFLog(message: "销毁加载中视图1111111")
    }
}
