

import UIKit
import WebKit

extension Vc_Web{
    public enum Style {
        case http(_ url:String)
        case html(_ string:String)
        case file(_ string:String)
    }
}

class Vc_Web: UIViewController {
    private lazy var configutation: WKWebViewConfiguration = {
         let config = WKWebViewConfiguration()
        config.allowsInlineMediaPlayback = true
        config.allowsAirPlayForMediaPlayback = true
        config.allowsPictureInPictureMediaPlayback = true
        config.mediaTypesRequiringUserActionForPlayback = .all
        return config
      }()
       lazy var webView: WKWebView = {
           let web = WKWebView(frame: CGRect.zero, configuration: configutation)
           web.navigationDelegate = self
           web.uiDelegate = self
           return web
       }()
       lazy var view_progress: UIProgressView = {
           let v = UIProgressView(progressViewStyle: UIProgressView.Style.default)
        v.tintColor = UIColor.green
           return v
       }()
       var webType:Vc_Web.Style = .http("https://")
       var webkitTextSizeScale:String = "100%" //defalut 100%
    var lineIshidden = false
    override func viewDidLoad() {
        super.viewDidLoad()

      self.navigationController?.setNavigationBarHidden(false, animated: true)
       
       configUI()
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
         if keyPath == "estimatedProgress"{
             self.view_progress.isHidden = false
             self.view_progress.alpha = 1
             
            if let newValue = change![NSKeyValueChangeKey.newKey] as? NSNumber{
                 let newFloatValue = newValue.floatValue //To float
                 self.view_progress.setProgress(newFloatValue, animated: true)
                 if newFloatValue >= 1 {
                     UIView.animate(withDuration: 0.3, animations: {[weak self] in
                         self?.view_progress.alpha = 0
                     }) { [weak self](b) in
                         self?.view_progress.isHidden = true
                         self?.view_progress.setProgress(0, animated: false)
                     }
                 }
            }
         }
     }
     
     deinit {
         self.webView.removeObserver(self, forKeyPath: "estimatedProgress")
     }
    
   func configUI(){
       if #available(iOS 13.0, *) {
           let appearance = UINavigationBarAppearance()
           appearance.backgroundColor = .white
           appearance.shadowColor = lineIshidden ? .clear : Config.color.hex("ec")
           navigationController?.navigationBar.scrollEdgeAppearance = appearance
           navigationController?.navigationBar.standardAppearance = appearance
       } else {
           navigationController?.navigationBar.shadowImage = lineIshidden ? UIImage() : nil
       }
    setNavigationBackButton()
    self.view_progress.frame = CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 1)
//    self.webView.frame = self.view.bounds
    self.webView.navigationDelegate = self
    self.view.addSubview(self.webView)
    self.view.addSubview(view_progress)
    
       webView.snp.makeConstraints {
           $0.top.left.right.bottom.equalToSuperview()
       }
       
    self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.new, context: nil)
    
    switch self.webType {
     case .http(let str):
        guard let requestUrl = URL(string: str) else {
            SVProgressHUD.showError(withStatus: "跳转链接发生错误~".languageString())
            return
        }
        self.webView.load(URLRequest(url: requestUrl))
     case .html(let str):
         self.webView.loadHTMLString(str, baseURL: NSURL.init(string: "https://")! as URL)
     case .file(let str):
         self.webView.load(URLRequest(url: URL(fileURLWithPath: str)))
      }
    }
}

extension Vc_Web:WKNavigationDelegate,WKUIDelegate {
    //webView delagte
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        SVProgressHUD.dismiss()
        let scriptStr =  "document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '"+webkitTextSizeScale+"'"
        webView.evaluateJavaScript(scriptStr, completionHandler: nil)
    }

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        SVProgressHUD.show(withStatus: "正在加载中...".languageString())
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void)
    {
        decisionHandler(.allow)
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        SVProgressHUD.dismiss()
        SVProgressHUD.showError(withStatus: "读取文件发生错误~".languageString())
    }
    
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        SVProgressHUD.dismiss()
        debugPrint(error.localizedDescription)
        
    }
    
    func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
        debugPrint("xxxxxxx")
    }
    
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if let webUrlStr = navigationAction.request.url?.absoluteString {
            let lastName = webUrlStr.lowercased()
            if lastName.contains(".pdf") {
                if let data = try? Data(contentsOf: navigationAction.request.url!) {
                    self.webView.load(data, mimeType: "application/pdf", characterEncodingName: "GBK", baseURL: URL(fileURLWithPath: ""))
                }
            }
        }
        decisionHandler(.allow)
    }
}
