//
//  CLXWebViewController.swift
//  account_center
//
//  Created by MrQi on 2024/2/23.
//

import UIKit
import JavaScriptCore
import SVProgressHUD
@preconcurrency import WebKit

public class CLXWebViewController: UIViewController {
    
    public var webView: WKWebView?
    private var requestUrl: String
    private var signComplent: SignComplent?
    private var realNameComplent: RealnameComplent?
    private var dismissCompletion: (() -> Void)? = nil
    
    init(
        url: String,
        signComplent: @escaping SignComplent,
        realNameComplent: @escaping RealnameComplent,
        completion: (() -> Void)? = nil
    ) {
        self.requestUrl = url
        self.signComplent = signComplent
        self.realNameComplent = realNameComplent
        self.dismissCompletion = completion
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        initWebView()
        initNavBar()
    }
}
extension CLXWebViewController {
    
    private func initWebView() {
        
        let edgeInsets:UIEdgeInsets = UIApplication.shared.windows.first?.safeAreaInsets ?? UIEdgeInsets.zero
        
        let config = WKWebViewConfiguration()
        config.allowsInlineMediaPlayback = true
        let preferences = WKPreferences()
        preferences.javaScriptEnabled = true
        preferences.javaScriptCanOpenWindowsAutomatically = true
        preferences.setValue(true, forKey: "allowFileAccessFromFileURLs")
        config.preferences = preferences
        let pool = WKProcessPool()
        config.processPool = pool
        config.userContentController = WKUserContentController()
        config.userContentController.add(self, name: "onDestroy")
        config.userContentController.add(self, name: "downloadBlob")
        config.userContentController.addUserScript(WKUserScript(source: """
(function() {
                var originalClick = HTMLElement.prototype.click;
                HTMLElement.prototype.click = function() {
                    if (this.tagName === 'A' && this.href.startsWith('blob:')) {
                        var url = this.href;
                        var fileName = this.download || 'file_' + Date.now();
                        fetch(url).then(res => res.blob()).then(blob => {
                            var reader = new FileReader();
                            reader.onload = function() {
                                var base64 = reader.result.split(',')[1];
                                window.webkit.messageHandlers.downloadBlob.postMessage({'data':base64,'fileName':fileName,'mimeType':blob.type})
                            };
                            reader.readAsDataURL(blob);
                        });
                        return false;
                    }
                    return originalClick.apply(this, arguments);
                };
            })();
""", injectionTime: .atDocumentEnd, forMainFrameOnly: true))
        config.allowsInlineMediaPlayback = true
        config.preferences = WKPreferences()
        config.preferences.javaScriptEnabled = true
        webView = WKWebView(
            frame: CGRectMake(
                0,
                edgeInsets.top,
                view.bounds.size.width,
                view.bounds.size.height - edgeInsets.top - edgeInsets.bottom
            ),
            configuration: config
        )
        view.addSubview(webView!)
        webView?.navigationDelegate = self
        guard let url = URL(string: requestUrl) else {
            return
        }
        webView?.load(URLRequest(url: url))
    }
    
    private func initNavBar() {
        let backBtn = UIButton(type: .custom)
        if #available(iOS 13.0, *) {
            backBtn
                .setImage(
                    UIImage(systemName:"xmark.circle.fill")?
                        .withTintColor(
                            .white,
                            renderingMode: UIImage.RenderingMode.alwaysOriginal
                        ),
                    for: .normal
                )
        } else {
            // Fallback on earlier versions
        }
        backBtn
            .addTarget(self, action: #selector(backAction), for: .touchUpInside)
        backBtn.backgroundColor = .black.withAlphaComponent(0.5)
        backBtn.frame = CGRect(
            x: 15,
            y: view.bounds.size.height/2 - 20,
            width: 40,
            height: 40
        )
        backBtn.layer.cornerRadius = 20
        backBtn.layer.masksToBounds = true
        view.addSubview(backBtn)
    }
    
    @objc
    private func backAction() {
        dismissCompletion?()
        dismiss(animated: true)
    }
}

extension UIImage {
    class func image(color: UIColor) -> UIImage? {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContextWithOptions(
            CGSize(width: 1, height: 1),
            false,
            UIScreen.main.scale
        )
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(rect)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
        
    }
}

/// 路由拦截
extension CLXWebViewController: WKNavigationDelegate {
    public func webView(
        _ webView: WKWebView,
        decidePolicyFor navigationAction: WKNavigationAction,
        decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
    ) {
        print(navigationAction.request.url?.absoluteString)
        RealnameHelper.clx_handleRealname { [weak self] in
            return RealnameConfig(
                webView: webView,
                navigationAction: navigationAction,
                target: self,
                decisionHandler: decisionHandler,
                signComplent: self?.signComplent,
                realNameComplent: self?.realNameComplent
            )
        }
    }
}

/// JS消息处理
extension CLXWebViewController: WKScriptMessageHandler {
    public func userContentController(
        _ userContentController: WKUserContentController,
        didReceive message: WKScriptMessage
    ) {
        if message.name.isH5Destroy {
            self.dismiss(animated: true, completion: dismissCompletion)
        } else if message.name.isDownloadBlob {
            guard let map = message.body as? [String: Any] else {
                SVProgressHUD.showError(withStatus: "数据解析失败")
                return }
            guard let data = map["data"] as? String else {
                SVProgressHUD.showError(withStatus: "获取数据失败")
                return }
            guard let fileName = map["fileName"] as? String else {
                SVProgressHUD.showError(withStatus: "文件读取失败")
                return }
            SVProgressHUD.show()
            guard let url = CLXFileManagePlugin.writeFile(data: Data(base64Encoded: data), fileName: "/\(fileName)") else {
                SVProgressHUD.showError(withStatus: "下载失败")
                return
            }
            SVProgressHUD.dismiss()
            
            var saveUrl: URL?
            if #available(iOS 16.0, *) {
                saveUrl = URL.init(filePath: url)
            } else {
                saveUrl = URL(fileURLWithPath: url)
            }
            guard let saveUrl = saveUrl else {
                SVProgressHUD.showError(withStatus: "下载失败")
                return
            }
            CLXFileManagePlugin.starShareFile(filePath: saveUrl)
        }
    }
}
