//
//  YHNewWebViewController.swift
//  galaxy
//
//  Created by EDY on 2024/3/6.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import WebKit

class YHNewWebViewController: YHBaseViewController, WKUIDelegate, WKNavigationDelegate  {

    var webView = WKWebView()
    var progBar = UIProgressView()
    var url = "https://www.baidu.com"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navBackgroundColor = .clear
        gk_navShadowColor = .clear
        gk_navigationBar.isHidden = true
        // 创建wkwebview
        webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
        webView.navigationDelegate = self
        webView.uiDelegate = self
        // 创建网址
        let url = NSURL(string: url)
        // 创建请求
        let request = NSURLRequest(url: url! as URL)
        // 加载请求
        webView.load(request as URLRequest)
        // 添加wkwebview
        self.view.addSubview(webView)
        
        // 加载网页的进度条
        progBar = UIProgressView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 30))
        progBar.progress = 0.0
        progBar.tintColor = UIColor.brandMainColor
        webView.addSubview(progBar)
        // 监听网页加载的进度
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        webView.removeObserver(self, forKeyPath: "estimatedProgress")
    }
    
    // MARK: - WKNavigationDelegate
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.navigationItem.title = webView.title
    }
    
    // MARK: - WKUIDelegate
    
    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        // 实现非安全链接的跳转。如果目标主视图不为空,则允许导航
        if !(navigationAction.targetFrame?.isMainFrame != nil) {
            webView.load(navigationAction.request)
        }
        return nil
    }
    
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        // 修复弹窗弹出的问题
        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (_) -> Void in
            completionHandler()
        }))
        self.present(alert, animated: true, completion: nil)
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        printLog("\(navigationAction.request.url?.absoluteString ?? "")")
//    https://www.galaxy-immi.com/
         decisionHandler(.allow)
    }
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("页面开始加载")
    }
 
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        print("页面提交")
    }

    
    // MARK: - webview function
    
    @objc func toBack() {
        if webView.canGoBack {
            webView.goBack()
        }
    }
     
    @objc func toForward() {
        if webView.canGoForward {
            webView.goForward()
        }
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            self.progBar.alpha = 1.0
            progBar.setProgress(Float(webView.estimatedProgress), animated: true)
             //进度条的值最大为1.0
            if(self.webView.estimatedProgress >= 1.0) {
                UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseInOut, animations: { () -> Void in
                    self.progBar.alpha = 0.0
                }, completion: { (finished:Bool) -> Void in
                    self.progBar.progress = 0
                })
            }
        }
    }
    
    override class func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
    }
}
