//
//  TSBaseVC.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/20.
//

import UIKit
import Combine

open class TSBaseVC: UIViewController {
  
    public var closePageComplete:(()->Void)?
    
    public var cancellable: [AnyCancellable] = []
    
    public lazy var contentView: UIView = {
        let view = UIView()
        return view
    }()
    
    
    public lazy var navBarContentView: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }()
    
    public lazy var normalNavBarView: TSNormalNavigationBarView = {
        let view = TSNormalNavigationBarView()
        return view
    }()
    
    
    public lazy var viewBgImageView: UIImageView = {
        let view = UIImageView()
        view.backgroundColor = .clear
        return view
    }()

    public lazy var netWorkView: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }()
    
    
    public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    required public init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    /// 提供一个无参数的默认初始化方法
    public init() {
        super.init(nibName: nil, bundle: nil)
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        setupSuperSomeView()
        createData()
        createView()
        dealThings()
    }
    
    private func setupSuperSomeView() {
        edgesForExtendedLayout = [.all]
        
        view.addSubview(contentView)
        view.addSubview(navBarContentView)
        
        contentView.snp.makeConstraints { make in
            make.top.equalTo(k_Nav_Height)
            make.leading.trailing.bottom.equalToSuperview()
        }
        
        navBarContentView.snp.makeConstraints { make in
            make.leading.top.trailing.equalToSuperview()
            make.height.equalTo(k_Nav_Height)
        }

        view.backgroundColor = .mainBg
        view.layoutIfNeeded()
    }
    
    
    public func setViewBgImageNamed(named:String){
        if viewBgImageView.superview == nil {
            view.insertSubview(viewBgImageView, at: 0)
            viewBgImageView.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        }
        viewBgImageView.image = UIImage(named: named)
    }
    
    
    //子类重写
    open func createData(){
        
        
    }
    open func createView(){
        
        
    }
    
    open func dealThings(){
        
        
    }
    
    public func addNormalNavBarView(){
        if normalNavBarView.superview != nil { return }
        navBarContentView.addSubview(normalNavBarView)
        normalNavBarView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }


    open override func viewWillAppear(_ animated: Bool) {
        debugPrint("进入------>\(String(describing: type(of: self)))")
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
        cancellable.removeAll()
        closePageComplete?()
        debugPrint("♻️♻️♻️ TGRootViewController -> \(type(of: self)) deinit ♻️♻️♻️")
    }

    // MARK: - 导航栏方法

    public func setTitleText(_ title: String) {
        addNormalNavBarView()
       _ = normalNavBarView.setTitleName(NSLocalizedString(title, comment: ""))
    }

    public func setPageTitle(_ title: String) {
        let pageTitle = title
        let backTitle = " "
        setTitleText(title)
        _ = setNavigationItem("", imageName: "navi_back", direction: .left, action: #selector(navBarClickLeftAction))
    }

    public func setNavigationItem(_ name: String, imageName: String, direction: NSTextAlignment, action: Selector) -> UIButton {
        if direction == .left {
            return normalNavBarView.setLeftNavigationItem(name: name, imageName: imageName, target: self, action: action)
        } else {
            return normalNavBarView.setRightNavigationItem(name: name, imageName: imageName, target: self, action: action)
        }
    }

    @objc open func navBarClickLeftAction() {
        debugPrint("navBarClickLeftAction -> \(type(of: self))")
        pop()
    }

    @objc public func pop() {
        if navigationController == nil {
            dismiss(animated: true, completion: nil)
        } else if navigationController?.presentingViewController != nil, navigationController?.viewControllers.count == 1 {
            navigationController?.dismiss(animated: true, completion: nil)
        } else {
            navigationController?.popViewController(animated: true)
        }
    }

}


extension TSBaseVC {
    
    public func setNavBarViewHidden(_ isHidden: Bool) {
        navBarContentView.snp.updateConstraints { make in
            make.height.equalTo(isHidden ? 0 : k_Nav_Height)
        }
        
        contentView.snp.updateConstraints { make in
            make.top.equalTo(isHidden ? 0 : k_Nav_Height)
        }
    }
    
    public var isViewVisible: Bool {
        return isViewLoaded && view.window != nil && presentedViewController == nil
    }
    
    public func addPullDownClosePage() {
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handleDismissPan(_:)))
        view.addGestureRecognizer(panGesture)
    }

    // 手势处理方法
     @objc public func handleDismissPan(_ gesture: UIPanGestureRecognizer) {
        let translation = gesture.translation(in: view)
        let progress = translation.y / view.bounds.height
        
        switch gesture.state {
        case .changed:
            view.transform = CGAffineTransform(translationX: 0, y: max(0, translation.y))
        case .ended:
            if progress > 0.5 || gesture.velocity(in: view).y > 1000 {
                dismiss(animated: true)
            } else {
                UIView.animate(withDuration: 0.3) {
                    self.view.transform = .identity
                }
            }
        default:
            break
        }
    }
}
