//
//  SpeakEleWebViewCtr.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/10.
//

import UIKit
import WebKit

class SpeakEleWebViewCtr: SpeakEleBaseViewCtr, WKUIDelegate ,WKNavigationDelegate, UIScrollViewDelegate ,WKScriptMessageHandler {

    lazy var funcNameArray:[String] = []
    
    private lazy var webView: WKWebView = {
        let webConfiguration = WKWebViewConfiguration()
        webConfiguration.applicationNameForUserAgent = "iOS"
        let webView1:WKWebView = WKWebView(frame:CGRect(x: 0, y: Dev.navHeight + Dev.safeAreaInsets.top, width: Dev.screenW, height: Dev.screenH - (Dev.navHeight + Dev.safeAreaInsets.top)),configuration: webConfiguration)
        webView1.scrollView.showsVerticalScrollIndicator = false
        webView1.scrollView.showsHorizontalScrollIndicator = false
        webView1.allowsLinkPreview = false
        webView1.scrollView.backgroundColor = .white
        webView1.allowsBackForwardNavigationGestures = true
        webView1.backgroundColor = .white
        webView1.uiDelegate = self
        webView1.navigationDelegate = self
        webView1.scrollView.delegate = self
        if #available(iOS 11.0, *) {
            webView1.scrollView.contentInsetAdjustmentBehavior = .never
        }
        for name in funcNameArray {
            webView1.configuration.userContentController.add(self, name: name)
        }
        view.addSubview(webView1)
        return webView1
    }()
    
    private lazy var activityView:UIActivityIndicatorView = {
        let activityView = UIActivityIndicatorView()
        activityView.width = 24.adapterW()
        activityView.height = 24.adapterW()
        activityView.centerX = view.width / 2.0
        activityView.centerY = (view.height - Dev.navHeight) / 2.0
        activityView.color = .black
        activityView.hidesWhenStopped = true
        
        let  transform:CGAffineTransform  = CGAffineTransformMakeScale(24.adapterW() / 20,24.adapterW() / 20);
        activityView.transform = transform;
        activityView.startAnimating()
        view.addSubview(activityView)
        return activityView
    }()
    
    func LoadWithUrl(url:String) {
        if url.count == 0 {
            return
        }
        let newUrl = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
        guard let URL1 = URL(string:newUrl) else { return }
        let request = URLRequest(url: URL1)
        webView.load(request)
        activityView.isHidden = false
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
}

extension SpeakEleWebViewCtr {
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        activityView.stopAnimating()
        webView.evaluateJavaScript("document.documentElement.style.webkitUserSelect='none';") { any1, error1 in}
        webView.evaluateJavaScript("document.documentElement.style.webkitTouchCallout='none';", completionHandler: nil)
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        activityView.stopAnimating()
        Print("网页加载失败：\(error.localizedDescription)")
    }
    
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        
        activityView.stopAnimating()
        Print("网页加载失败：\(error.localizedDescription)")
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        guard let url = navigationAction.request.url else {
            decisionHandler(.cancel)
            return
        }
        let scheme = url.absoluteString.lowercased()
        if scheme.contains("/stdeula") {
            UIApplication.shared.open(url)
            decisionHandler(.cancel)
        }else{
            decisionHandler(.allow)
        }
    }
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
    }

}
