//
//  YHWebViewViewController.swift
//  galaxy
//
//  Created by EDY on 2024/2/5.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
@preconcurrency import WebKit

class YHWebViewViewController: YHBaseViewController, WKUIDelegate, WKNavigationDelegate {
    
    var webview = WKWebView()
    var progBar = UIProgressView()
    var url = ""
    var navTitle = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        
        gk_navTitle = navTitle
        
        // 获取导航栏高度
        let navHeight = self.navigationController?.navigationBar.frame.height
        // 获取状态栏高度
        let statusHeight = k_Height_StatusBar
        
        // 创建wkwebview
        webview = WKWebView(frame: CGRect(x: 0, y: statusHeight + navHeight!, width: self.view.frame.width, height: self.view.frame.height - k_Height_NavigationtBarAndStatuBar))
        webview.navigationDelegate = self
        
        if let url = URL(string: url) {
            let request = URLRequest(url: url)
            webview.load(request)
        } else {
            let tmpUrl = YHURLEncodeHelper.urlEncodedString(url)
            if let url = URL(string: tmpUrl) {
                let request = URLRequest(url: url)
                webview.load(request)
            } else {
                printLog("url: 有问题")
            }
        }
        
        // 添加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)
        
    }
    
    deinit {
        webview.removeObserver(self, forKeyPath: "estimatedProgress")
    }
    
    // MARK: - WKNavigationDelegate
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        if navTitle.isEmpty {
            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)
    }
    
    // MARK: - KVO

    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: { () in
                    self.progBar.alpha = 0.0
                }, completion: { (_: Bool) in
                    self.progBar.progress = 0
                })
            }
        }
    }
    
    override class func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
        
    }
}
