//
//  PQBaseViewController.swift
//  PQSpeed
//
//  Created by SanW on 2020/5/25.
//  Copyright © 2020 BytesFlow. All rights reserved.
//

// import MediaPlayer
import Alamofire
import UIKit
open class PQBaseViewController: UIViewController, UIGestureRecognizerDelegate {
    // 侧滑拦截返回
    public var popGestureHandle: (() -> Void)?
    public var naviTitle: String? // 标题
    public var rightButton: UIButton? // 右边按钮
    public var backButton: UIButton? // 左边按钮
    public var navTitleLabel: UILabel? // 标题
    public var navHeadImageView: UIImageView? // 导航条
    public var lineView: UIView? // 导航分隔线
    public var isHiddenStatus: Bool = false { // 更新状态栏
        didSet {
            setNeedsStatusBarAppearanceUpdate()
        }
    }

    /// <#Description#>
    public var isPresent: Bool {
        var isPresent = true
        let viewcontrollers = navigationController?.viewControllers
        if (viewcontrollers?.count ?? 0) > 1 {
            if viewcontrollers?[(viewcontrollers?.count ?? 1) - 1] == self {
                isPresent = false
            }
        }
        return isPresent
    }

    public lazy var manager: NetworkReachabilityManager? = {
        let manager = NetworkReachabilityManager(host: "www.baidu.com")
        manager?.listener = { status in
            if status == .reachable(.wwan) || status == .reachable(.ethernetOrWiFi) {}
        }
        return manager
    }()

    override open func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.isNavigationBarHidden = true
        view.backgroundColor = PQBFConfig.shared.styleBackGroundColor
        navHeadImageView = UIImageView(image: UIImage())
        navHeadImageView?.isUserInteractionEnabled = true
        navHeadImageView?.backgroundColor = PQBFConfig.shared.styleBackGroundColor
        navHeadImageView?.frame = CGRect(x: 0, y: 0, width: cScreenWidth, height: cDevice_iPhoneNavBarAndStatusBarHei)
        view.addSubview(navHeadImageView!)

        lineView = UIView(frame: CGRect(x: 0, y: (navHeadImageView?.frame.maxY ?? cDevice_iPhoneNavBarAndStatusBarHei) - 0.5, width: cScreenWidth, height: 0.5))
        lineView?.backgroundColor = PQBFConfig.shared.styleBackGroundColor
        view.addSubview(lineView!)
        UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
        automaticallyAdjustsScrollViewInsets = false
        navigationController?.interactivePopGestureRecognizer?.delegate = self
//        fd_prefersNavigationBarHidden = true
    }

    public func hiddenNavigation() {
        navHeadImageView?.isHidden = true
        lineView?.isHidden = true
    }

    public func showNavigation() {
        if navHeadImageView != nil {
            navHeadImageView?.isHidden = false
            lineView?.isHidden = false
            view.bringSubviewToFront(navHeadImageView!)
        }
    }

    open func leftBackButton() {
        leftButton(image: "icon_detail_back")
    }

    public func leftButton(image: String?, tintColor: UIColor? = nil) {
        let leftButton = UIButton(type: .custom)
        leftButton.frame = CGRect(x: 0, y: cDevice_iPhoneStatusBarHei, width: cDefaultMargin * 4, height: cDefaultMargin * 4)
        leftButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: -5, right: 0)
        if tintColor != nil {
            leftButton.tintColor = tintColor
            leftButton.setImage(UIImage().BF_Image(named: image ?? "icon_detail_back").withRenderingMode(.alwaysTemplate), for: .normal)
        } else {
            leftButton.setImage(UIImage().BF_Image(named: image ?? "icon_detail_back"), for: .normal)
        }
        leftButton.addTarget(self, action: #selector(backBtnClick), for: .touchUpInside)
        navHeadImageView?.addSubview(leftButton)
        backButton = leftButton
    }

    public func rightButtonItem(image: String?, title: String?) {
        let rightButtonItem = UIButton(type: .custom)
        var rightW: CGFloat = cDefaultMargin
        if title != nil, title?.count ?? 0 > 0 {
            rightW = rightW + sizeWithText(text: title ?? "", font: UIFont.systemFont(ofSize: 16), size: CGSize(width: CGFloat.greatestFiniteMagnitude, height: cDefaultMargin * 4)).width
            rightButtonItem.setTitle(title, for: .normal)
            rightButtonItem.setTitleColor(UIColor.hexColor(hexadecimal: "#242F44"), for: .normal)
            rightButtonItem.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        }
        if image != nil, image?.count ?? 0 > 0 {
            rightW = rightW + cDefaultMargin * 4
            rightButtonItem.setImage(UIImage(named: image ?? ""), for: .normal)
            rightButtonItem.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: (title != nil && title?.count ?? 0 > 0) ? 0 : -5, right: 0)
        }
        rightButtonItem.adjustsImageWhenHighlighted = false
        rightButtonItem.frame = CGRect(x: cScreenWidth - rightW, y: cDevice_iPhoneStatusBarHei, width: rightW, height: cDefaultMargin * 4)
        rightButtonItem.addTarget(self, action: #selector(rightBtnClick(sender:)), for: .touchUpInside)
        rightButtonItem.contentHorizontalAlignment = .center
        navHeadImageView?.addSubview(rightButtonItem)
        rightButton = rightButtonItem
    }

    public func setTitle(title: String?, color: UIColor = UIColor.white) {
        naviTitle = title
        if navTitleLabel == nil {
            let titleLabel = UILabel(frame: CGRect(x: cDefaultMargin * 5, y: cDevice_iPhoneStatusBarHei, width: cScreenWidth - 100, height: cDefaultMargin * 4))
            titleLabel.textColor = color
            titleLabel.textAlignment = .center
            navTitleLabel = titleLabel
            navHeadImageView?.addSubview(titleLabel)
        }
        navTitleLabel?.text = title
    }

    @objc open func rightBtnClick(sender _: UIButton) {}

    @objc open func backBtnClick() {
        if isPresent {
            dismiss(animated: true, completion: nil)
        } else {
            navigationController?.popViewController(animated: true)
        }
    }

    override open func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }

    override open func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        PQLoadingHUB.shared.dismissHUB()
    }

    override open func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)

        if view.viewWithTag(cGuideTag) != nil {
            view.viewWithTag(cGuideTag)?.removeFromSuperview()
        }
    }

    deinit {
        PQNotification.removeObserver(self)
        BFLog(message: "\(String(describing: type(of: self)))被销毁")
    }

    override open var preferredStatusBarStyle: UIStatusBarStyle {
        if PQBFConfig.shared.statusBarStyle == .dark {
            if #available(iOS 13.0, *) {
                return .darkContent
            } else {
                return .default
            }
        } else {
            return .lightContent
        }
    }

    override open var prefersStatusBarHidden: Bool {
        return isHiddenStatus
    }

    /// 禁止滑动返回
    /// - Returns: <#description#>
    public func disablePopGesture() -> PQBaseViewController {
        let traget = navigationController?.interactivePopGestureRecognizer?.delegate
        let pan = UIPanGestureRecognizer(target: traget, action: #selector(popGesture(panGes:)))
        view.addGestureRecognizer(pan)
        return self
    }

    /// 拦截侧滑手势
    /// - Returns: <#description#>
    @objc private  func popGesture(panGes: UIPanGestureRecognizer) {
        if panGes.state == .ended, popGestureHandle != nil {
            popGestureHandle!()
        }
    }

    open func gestureRecognizer(_: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if touch.view is UISlider {
            return false
        }
        return true
    }
}
