//
//  YHSignatureWebViewController.swift
//  galaxy
//
//  Created by edy on 2024/9/20.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHSignatureWebViewController: YHBaseViewController {
    
    var realNameUrl: String = ""
    var titleName: String = ""
    lazy var webView: WKWebView = {
        let webView = WKWebView(frame: CGRect(x: 0, y: k_Height_NavigationtBarAndStatuBar, width: KScreenWidth, height: KScreenHeight-k_Height_NavigationtBarAndStatuBar), configuration: self.configuaration)
        return webView
    }()
    
    lazy var configuaration: WKWebViewConfiguration = {
        let config = WKWebViewConfiguration()
        let preferences = WKPreferences()
        preferences.javaScriptCanOpenWindowsAutomatically = true
        config.preferences = preferences
        config.userContentController = self.userContentController
        config.allowsInlineMediaPlayback = true
        config.defaultWebpagePreferences.preferredContentMode = .mobile
        return config
    }()
    
    lazy var userContentController = {
        let vc = WKUserContentController()
        return vc
    }()
    
    lazy var progressBar: UIProgressView = {
        let progBar = UIProgressView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 30))
        progBar.progress = 0.0
        progBar.tintColor = UIColor.brandMainColor
        return progBar
    }()
    
    deinit {
        webView.removeObserver(self, forKeyPath: "estimatedProgress")
        NotificationCenter.default.removeObserver(self)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        createUI()
    }
    
    func createUI() {
        gk_navTitle = titleName
        webView.navigationDelegate = self
        webView.addSubview(progressBar)
        self.view.addSubview(webView)
        // 监听网页加载的进度
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        if let url = URL(string: realNameUrl) {
            webView.load(URLRequest(url: url))
        }
    }
    
    func handleRequest(_ request: URLRequest) -> Bool {
        if let url = request.url {
            let handleResult = YHRealNameHelper.handleRealnameURL(url, delegate: self)
            return handleResult != .cancel
        }
        return false
    }
    
    // MARK: - KVO
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            self.progressBar.alpha = 1.0
            progressBar.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.progressBar.alpha = 0.0
                }, completion: { (_: Bool) in
                    self.progressBar.progress = 0
                })
            }
        }
    }
}

extension YHSignatureWebViewController: YHRealNameDelegate {
    
    func realnameJumptoAlipay() {
        
    }
    
    func realnameResult(_ result: YHRealnameResult) {
        
    }
    
    func signResult(_ status: Bool) {
        
    }
}

extension YHSignatureWebViewController: WKNavigationDelegate {
    
    // 开始加载
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
//        YHHUD.flash(message: "开始加载")

    }
    
    // 加载完成
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
//        YHHUD.flash(message: "加载完成")
    }
    
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        
//        YHHUD.flash(message: "加载失败: \(error.localizedDescription)")

    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
        if let url = navigationAction.request.url {
            let absoluteString = url.absoluteString
            printLog("\(absoluteString)")
        }
        
        let isAllow = self.handleRequest(navigationAction.request)
        if isAllow {
            decisionHandler(.allow)
        } else {
            decisionHandler(.cancel)
        }
    }
    
    func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        
        // 判断服务器采用的验证方法
        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
            // 如果没有错误的情况下 创建一个凭证，并使用证书
            if challenge.previousFailureCount == 0, let serverTrust = challenge.protectionSpace.serverTrust {
                let credential = URLCredential(trust: serverTrust)
                completionHandler(.useCredential, credential)
                
            } else {
                // 验证失败，取消本次验证
                completionHandler(.cancelAuthenticationChallenge, nil)
            }
        } else {
            completionHandler(.cancelAuthenticationChallenge, nil)
        }
    }
}
