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

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

class WebViewController : ZDViewController {
    lazy var webView = WKWebView.init()
    lazy var statusBarBackgroundView = DDView.init()
    var showNavBar : Bool
    public var vcTitle : String?
    var url : String?
    var screenEdgePanGestureRecognizerEnable : Bool
    public var disappearHandler: (() -> Void)?

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

        view.backgroundColor = .hex("FAFAFA")
        
        webView.scrollView.contentInsetAdjustmentBehavior = .never
        webView.backgroundColor = .white
        webView.navigationDelegate = self
        webView.uiDelegate = self
        view.addSubview(webView)
        
        let request = URLRequest(url: URL(string: url!)!,cachePolicy: .reloadIgnoringLocalAndRemoteCacheData)
        webView.load(request)
        
        if showNavBar == false {
            navigationItem.leftBarButtonItems = nil
            dd_navigationBarBackgroundColor = .clear

            view.addSubview(statusBarBackgroundView)
        }else{
            title = vcTitle
            dd_navigationBarTitleTextAttributes = [.foregroundColor : UIColor.white(alpha: 0.7),.font:UIFont.mediumFont(17)]
            dd_navigationBarBarButtonItemAttributes = [.foregroundColor : UIColor.white]
        }
        
        view.dd_showHUD()
    }
    
    override func viewSafeAreaInsetsDidChange() {
        super.viewSafeAreaInsetsDidChange()
        if showNavBar == false {
            statusBarBackgroundView.snp.remakeConstraints { make in
                make.top.left.right.equalToSuperview()
                make.height.equalTo(view.safeAreaInsets.top)
            }
            
            webView.snp.remakeConstraints { make in
                make.left.right.equalToSuperview()
                make.top.equalTo(statusBarBackgroundView.snp.bottom)
                make.bottom.equalTo(-view.safeAreaInsets.bottom)
            }
        }else{
            webView.snp.remakeConstraints { make in
                make.left.right.equalToSuperview()
                make.top.equalTo(view.safeAreaInsets.top)
                make.bottom.equalTo(-view.safeAreaInsets.bottom)
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if showNavBar == false {
            navigationController?.navigationBar.isHidden = true
        }else{
            dd_navigationBarBackgroundColor = .hex("2C395F")
        }
        if screenEdgePanGestureRecognizerEnable == false {
            let nav = navigationController as? DDNavigationController
            nav?.screenEdgePanGestureRecognizerEnable(false)
        }
        webView.configuration.userContentController.add(self, name: "nativeObject")
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if showNavBar == false {
            navigationController?.navigationBar.isHidden = false
        }
        if screenEdgePanGestureRecognizerEnable == false {
            let nav = navigationController as? DDNavigationController
            nav?.screenEdgePanGestureRecognizerEnable(true)
        }
        webView.configuration.userContentController.removeScriptMessageHandler(forName: "nativeObject")
    }
}

extension WebViewController : WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        let dict = message.body as? [String:Any]
        let action =  dict?["action"] as? String
        if action == "goBack" {
            navigationController?.popViewController(animated: true)
        }else if action == "goTraining" {
            let params = dict?["params"] as? [String:Any]
            let id = params?["id"] as? Int
            if let supplierId = USER.supplierId,let userId = USER.userId, let id {
                WEBTOOL.open(name: .docmentDetail, appending: "&supplierId=\(supplierId)&userId=\(userId)&id=\(id)")
            }
        }else if action == "orderPhoto" {
            let params = dict?["params"] as? [String:Any]
            if let userOrderId = params?["userOrderId"] as? String,let taskOrderId = params?["taskOrderId"] as? String,let orderCode = params?["orderCode"] as? String {
                let isAllowImage = params?["isAllowImage"] as? Int
                var canModify = true
                // 0可以补传，1不可以补传
                if isAllowImage == 1 {
                    canModify = false
                }
                let vc = AdditionalPhotoController(userOrderId: Int(userOrderId) ?? 0, orderCode: orderCode, taskOrderId: Int(taskOrderId) ?? 0,canModify: canModify)
                navigationController?.pushViewController(vc, animated: true)
            }
        }
    }
}

extension WebViewController : WKNavigationDelegate,WKUIDelegate {
    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        view.dd_hideHUD()
        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) {
        view.dd_hideHUD()
        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) {
        view.dd_hideHUD()
        DDLog(message: "didFailProvisionalNavigation--------------------------------\(String(describing: webView.url?.absoluteString))")
    }
    public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void) {
        let urlString = navigationAction.request.url?.absoluteString
        let prefix = "tel:"
        if let urlString, urlString.hasPrefix(prefix) == true, let tel = urlString.components(separatedBy: prefix).last {
            UIApplication.shared.dd_openUrl(type: .phone, appending: tel)
        }
        decisionHandler(.allow)
    }
}
