//
//  QSLWebController.swift
//  QuickSearchLocation
//
//  Created by Destiny on 2024/12/24.
//

import UIKit
import WebKit

class QSLWebViewController: QSLBaseController, WKNavigationDelegate {
    
    var isShowTop: Bool = false {
        didSet {
            updateTop()
        }
    }
    
    lazy var topView: QSLWebViewTopView = {
        
        let view = QSLWebViewTopView()
        return view
    }()
    
    var webUrl: String?

    var webView: WKWebView = WKWebView()

    var progressView:UIProgressView = UIProgressView()

    var closeBtn: UIButton?

    deinit {
        webView.removeObserver(self, forKeyPath:"estimatedProgress")
        webView.navigationDelegate = nil
    }

    override func viewDidLoad() {

        super.viewDidLoad()

        webView.addObserver(self, forKeyPath:"estimatedProgress", options: NSKeyValueObservingOptions.new, context:nil)
        webView.navigationDelegate = self
        // webview
        view.addSubview(webView)
        webView.snp.makeConstraints { (make)in
            make.edges.equalTo(0)
        }

        // progressview
        view.addSubview(progressView)
        progressView.snp.makeConstraints { (make)in
            make.width.equalToSuperview()
            make.height.equalTo(3)
            make.top.equalToSuperview()
        }

        progressView.tintColor = QSLColor.Color_202020
        progressView.isHidden = true
        
        // load url
        if webUrl != nil {
            webView.load(URLRequest(url:URL(string: webUrl!)!))
        }
    }
    
    func updateTop() {
        
        topView.titleLabel.text = self.title
        
        topView.backBtnBlock = {
            self.dismiss(animated: true)
        }
        
        view.addSubview(topView)
        topView.snp.makeConstraints { make in
            make.left.top.right.equalTo(0)
            make.height.equalTo(44)
        }
        
        webView.snp.remakeConstraints { make in
            make.top.equalTo(topView.snp.bottom)
            make.left.right.bottom.equalTo(0)
        }
        
        progressView.snp.remakeConstraints { (make)in
            make.width.equalToSuperview()
            make.height.equalTo(3)
            make.top.equalTo(topView.snp.bottom)
        }
    }

    override func viewWillAppear(_ animated:Bool) {
//        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: animated)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: animated)
    }

    override func observeValue(forKeyPath keyPath:String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        // 加载进度
        if keyPath == #keyPath(WKWebView.estimatedProgress) {

            let progress = Float(webView.estimatedProgress)
            // TODO: 更新进度条等UI，例如：
            progressView.progress = progress
        }
    }

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        progressView.isHidden = false
        progressView.progress = 0
    }
        
    func webView(_ webView:WKWebView, didFinish navigation: WKNavigation!) {

        progressView.isHidden = true
        progressView.setProgress(0, animated:false)
    }

    func webView(_ webView:WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        progressView.isHidden = true
        progressView.setProgress(0, animated:false)
    }

}

class QSLWebViewTopView: UIView {
    
    lazy var closeBtn: UIButton = {
       
        let btn = UIButton()
        btn.image(UIImage(named: "common_close_btn"))
        btn.addTarget(self, action: #selector(closeBtnAction), for: .touchUpInside)
        return btn
    }()
    
    lazy var titleLabel: UILabel = {
       
        let label = UILabel()
        label.boldFont(18)
        label.textColor = QSLColor.Color_202020
        return label
    }()
    
    var backBtnBlock: (() -> ())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(closeBtn)
        addSubview(titleLabel)
        
        closeBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 24, height: 24))
            make.right.equalTo(-12)
            make.centerY.equalToSuperview()
        }
        
        titleLabel.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func closeBtnAction() {
        if let backBtnBlock = self.backBtnBlock {
            backBtnBlock()
        }
    }
}

