//
//  WebViewController.swift
//  OrderScheduling
//
//  Created by 中道 on 2023/8/7.
//

import Foundation
import WebKit
import SnapKit
import DDLogKit_Private
import DDToastKit_Private
import DDControlsKit_Private

class WebViewController : DDViewController {
    lazy var webView = WKWebView.init()
    lazy var statusBarBackgroundView = DDView.init()
    var showNavBar : Bool
    var vcTitle : String
    var url : String?

    public init(showNavBar:Bool = true,title:String,url:String) {
        self.showNavBar = showNavBar
        self.vcTitle = title
        self.url = url
        super.init(nibName: nil, bundle: nil)
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()

        
        webView.backgroundColor = .white
        webView.navigationDelegate = self
        webView.uiDelegate = self
        view.addSubview(webView)
        
        let request = URLRequest(url: URL(string: url!)!)
        webView.load(request)
        
        if showNavBar == false {
            navigationItem.leftBarButtonItems = nil
            dd_navigationBarBackgroundColor = .clear

            view.addSubview(statusBarBackgroundView)
            statusBarBackgroundView.snp.makeConstraints { make in
                make.top.left.right.equalToSuperview()
                make.height.equalTo(CGRectGetHeight(UIApplication.shared.dd_statusBarFrame))
            }
            
            webView.snp.makeConstraints { make in
                make.left.right.equalToSuperview()
                make.top.equalTo(CGRectGetHeight(UIApplication.shared.dd_statusBarFrame))
                make.bottom.equalTo(-view.safeAreaInsets.bottom)
            }
        }else{
            title = vcTitle
            dd_navigationBarBackgroundColor = .hex("354683")
            dd_navigationBarTitleTextAttributes = [.foregroundColor : UIColor.white(alpha: 0.7),.font:UIFont.mediumFont(17)]
        
            webView.snp.makeConstraints { make in
                make.left.right.equalToSuperview()
                make.top.equalTo(CGRectGetHeight(navigationController?.navigationBar.frame ?? .zero) + CGRectGetHeight(UIApplication.shared.dd_statusBarFrame))
                make.bottom.equalTo(-view.safeAreaInsets.bottom)
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if showNavBar == false {
            navigationController?.navigationBar.isHidden = true
        }
        webView.configuration.userContentController.add(self, name: "nativeObject")
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if showNavBar == false {
            navigationController?.navigationBar.isHidden = false
        }
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "nativeObject")
    }
}

extension WebViewController : WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        let dict = message.body as? [String:String]
        if dict?["action"] == "goBack" {
            navigationController?.popViewController(animated: true)
        }
    }
}

extension WebViewController : WKNavigationDelegate,WKUIDelegate {
    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        DDLog(message: "finish--------------------------------\(String(describing: webView.url?.absoluteString))")
        if showNavBar == false {
            statusBarBackgroundView.backgroundColor = .hex("2C395F")
        }
    }
    public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        DDLog(message: "didFail--------------------------------\(String(describing: webView.url?.absoluteString))")
        view.dd_makeToast(webViewLoadFailed) {[weak self] _ in
            self?.navigationController?.popViewController(animated: true)
        }
    }
    public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        DDLog(message: "didFailProvisionalNavigation--------------------------------\(String(describing: webView.url?.absoluteString))")
    }
}
