//
//  MPPositive_BaseViewController.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/4/18.
//

import UIKit
///b面基类控制器
class MPPositive_BaseViewController: MP_BaseViewController, UIGestureRecognizerDelegate {
    //导航栏标题
    private lazy var navTitleLabel:UILabel = createLabel(font:  .systemFont(ofSize: 20*width, weight: .regular), textColor: .white, textAlignment: .center)
    //pop按钮
    private lazy var popBtn:UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "Pop‘logo"), for: .normal)
        btn.addTarget(self, action: #selector(popActionClick(_ :)), for: .touchUpInside)
        return btn
    }()
    //网络加载失败的View
    private lazy var errorView:UIView = createErrorView()
    ///报错回调
    var errorBlock:(() -> Void)?
    ///重试回调
    var retryBlock:(() -> Void)?
    
    //导航View
    lazy var navView:UIView = setTitleView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.interactivePopGestureRecognizer?.delegate = self
        view.addSubview(navView)
    }
    deinit {
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(errorAction(_ :)), notificationName: .netWork_error_deal)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
    //设置顶部titleView
    private func setTitleView() -> UIView {
        let topView = UIView(frame: .init(x: 0, y: statusBarHeight, width: screen_Width, height: 50*width))
        topView.backgroundColor = .clear
        topView.addSubview(navTitleLabel)
        navTitleLabel.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        return topView
    }
    ///设置导航栏title
    func setTitle(_ text:String) {
        navTitleLabel.text = text
    }
    ///设置导航栏popBtn
    func setPopBtn() {
        navView.addSubview(popBtn)
        popBtn.snp.makeConstraints { make in
            make.width.height.equalTo(42*width)
            make.centerY.equalToSuperview()
            make.left.equalTo(16*width)
        }
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        //当页面布局完成后,将navView移动至最上层
        view.bringSubviewToFront(navView)
    }
    //pop上一个页面
    @objc func popActionClick(_ sender:UIButton) {
        MPPositive_Debouncer.shared.call(0.1) {
            [weak self] in
            guard let self = self else {return}
            navigationController?.popViewController(animated: true)
        }
    }
    //报错errorView
    private func createErrorView() -> UIView{
        let errorView = UIView()
        errorView.layer.masksToBounds = true
        errorView.layer.borderColor = UIColor(hex: "#80F988").cgColor
        errorView.layer.borderWidth = 1*width
        errorView.layer.cornerRadius = 18*width
        errorView.backgroundColor = .clear
        //使用其他内容
        //一个提示框
        let iconImageView = UIImageView(image: .init(named: "empty"))
        errorView.addSubview(iconImageView)
        iconImageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().multipliedBy(0.65)
            make.width.equalTo(211*width)
            make.height.equalTo(172*width)
        }
        let label = createLabel("Weak connection. Please check your network", font: .systemFont(ofSize: 13*width, weight: .regular), textColor: .white, textAlignment: .center)
        errorView.addSubview(label)
        label.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(iconImageView.snp.bottom).offset(8*width)
        }
        let retryBtn:UIButton = .init()
        retryBtn.setTitle("Retry", for: .normal)
        retryBtn.setTitleColor(.white, for: .normal)
        retryBtn.titleLabel?.font = .systemFont(ofSize: 15*width, weight: .medium)
        retryBtn.backgroundColor = .init(hex: "#80F988")
        retryBtn.layer.masksToBounds = true
        retryBtn.layer.cornerRadius = 16*width
        retryBtn.addTarget(self, action: #selector(retryClick(_ :)), for: .touchUpInside)
        errorView.addSubview(retryBtn)
        retryBtn.snp.makeConstraints { make in
            make.width.equalTo(180*width)
            make.height.equalTo(45*width)
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-15*width)
        }
        return errorView
    }
    //设置报错View
    func setErrorView() {
        view.addSubview(errorView)
        errorView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(300*width)
            make.height.equalTo(280*width)
        }
    }
    //移除报错View
    func removeErrorView() {
        if errorView.superview != nil {
            errorView.removeFromSuperview()
        }
    }
    //处理报错
    @objc private func errorAction(_ sender:Notification){
        DispatchQueue.main.async {
            [weak self] in
            guard let self = self else {return}
            MP_HUD.text("Weak connection.", delay: 1.0){ [weak self] in
                //执行报错回调闭包
                if self?.errorBlock != nil {
                    self?.errorBlock!()
                }
            }
        }
    }
    @objc private func retryClick(_ sender:UIButton) {
        if retryBlock != nil {
            retryBlock!()
        }
    }
    //MARK：- UIGestureRecognizerDelegate
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        if gestureRecognizer === self.navigationController?.interactivePopGestureRecognizer {
            // 当是 UINavigationController 的滑动返回手势时，根据需要进行判断
            // 例如需要至少有两个视图控制器在导航堆栈中才允许滑动返回
            return self.navigationController?.viewControllers.count ?? 0 > 1
        }
        return true
    }
    
}
