//
//  WebSwiftViewController.swift
//  MobilePortal
//
//  Created by xiejiangbo on 2019/3/11.
//  Copyright © 2019 yin chen. All rights reserved.
//

import UIKit

class WebSwiftViewController: BaseViewController,WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler,UIGestureRecognizerDelegate {
    var newType:NewType = .OrdinaryNewsType
    var isShowTitleType:IsShowTitleType = .YesShowTitleType
    var isHomePushType:IsHomePushType = .YesIsHomePushType
    var webViewUrl:String?
    var strAction:String = ""
    ///上个页面是否隐藏导航栏
    var previousPageShowTitleType : IsShowTitleType = .YesShowTitleType
    ///js调用原生方法名
    var webActionTitle = ["AppLogout","callPhone","sendSms","openScanActivity","getTitle","hideTitleLayout","copyContent","gotoLogin","openWeb"]
    lazy var webView: WKWebView = {
        let config = WKWebViewConfiguration.init()
        config.preferences = WKPreferences.init()
        config.preferences.minimumFontSize = 10;
        config.preferences.javaScriptEnabled = true
        config.preferences.javaScriptCanOpenWindowsAutomatically = true
        config.processPool = WKProcessPool.init()
        config.userContentController = WKUserContentController.init()
        let userContent = WKUserContentController.init()
        for actionName in webActionTitle {
            userContent.add(self as WKScriptMessageHandler, name: actionName)
        }
        config.userContentController = userContent
        let h = UIApplication.shared.statusBarFrame.size.height+(self.navigationController?.navigationBar.frame.size.height)!
        //let webView = WKWebView.init(frame: CGRect(x:0, y: 0, width:SCREEN_WHIDTH() , height:SCREEN_HEIGHT()-h+HEIGHT_BOTTOM_MARGIN() ), configuration: config)
        let webView = WKWebView.init(frame: CGRect(x:0, y: 0, width:SCREEN_WHIDTH() , height:SCREEN_HEIGHT()), configuration: config)
        //webView.load(urlRequest as URLRequest)
        webView.isMultipleTouchEnabled = true
        webView.backgroundColor = UIColor.white
        webView.allowsBackForwardNavigationGestures = true
        return webView
    }()
    lazy var progressView: UIProgressView = {
        let progressView = UIProgressView.init(frame: CGRect(x:0, y: getStatusBarH(), width:SCREEN_WHIDTH() , height: 0 ))
        progressView.tintColor = statusBarColor
//        progressView.tintColor = UIColor.red
        progressView.trackTintColor = UIColor.white
        self.view.addSubview(progressView)
        return progressView
    }()
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        let objectView:WKWebView = object as! WKWebView
        if objectView  == webView && keyPath == "estimatedProgress"{
//            let index = change![NSKeyValueChangeKey.newKey] ?? (Any).self
            let newprogress:NSNumber = change![NSKeyValueChangeKey.newKey] as! NSNumber
            if newprogress == 1{
                progressView.isHidden = true
                progressView.setProgress(0, animated: false)
            }else{
                progressView.isHidden = false
                progressView.setProgress(Float(truncating: newprogress), animated: true)
            }
        } else if objectView  == webView && keyPath == "title" {
            self.title = self.webView.title
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        initTitleBar()
        if self.isShowTitleType == .NoShowTitleType {
            self.navigationController?.setNavigationBarHidden(true, animated: true)
            setNeedsStatusBarAppearanceUpdate()
            webView.frame = CGRect(x:0, y: getStatusBarH(), width:SCREEN_WHIDTH() , height:SCREEN_HEIGHT()-getStatusBarH()+HEIGHT_BOTTOM_MARGIN() )
            setStatusBarBackgroundColor()
        }else{
            self.navigationController?.setNavigationBarHidden(false, animated: true)
            if #available(iOS 11.0, *) {
                webView.frame = CGRect(x:0, y: getStatusBarH(), width:SCREEN_WHIDTH() , height:SCREEN_HEIGHT()+HEIGHT_BOTTOM_MARGIN()-getStatusBarH() )
            }else{
                webView.frame = CGRect(x:0, y: 0, width:SCREEN_WHIDTH() , height:SCREEN_HEIGHT()+HEIGHT_BOTTOM_MARGIN())
            }
            progressView.frame = CGRect(x:0, y: getStatusBarH(), width:SCREEN_WHIDTH() , height:0 )
            
        }
        self.setwebView(strUrl: webViewUrl!)
        
    }
    override func setStatusBarBackgroundColor(){
        let stateView:UIView = UIView.init(frame: CGRect(x:0, y: 0, width:SCREEN_WHIDTH() , height:getStatusBarH() ))
        stateView.backgroundColor = statusBarColor
        self.view.addSubview(stateView)
    }
    //webView的加载
    func setwebView(strUrl:String){
        webView.uiDelegate = self
        webView.navigationDelegate = self
//        webView.scrollView.delegate = self
        //print(strUrl)
        let url2:NSURL = NSURL.init(string: WebActionOC.share().getUrl(strUrl))!
        let urlRequest:NSURLRequest = NSURLRequest.init(url: url2 as URL)
        webView.load(urlRequest as URLRequest)
        self.view.addSubview(webView)
        self.view.insertSubview(webView, belowSubview: progressView)
        

        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        if self.newType == .WeiXinNewsType {
            webView.scrollView.isScrollEnabled = true
            webView.scrollView.bounces = true
        }else{
            webView.scrollView.isScrollEnabled = false
            webView.scrollView.bounces = false
        }
    }
    func getStatusBarH() -> CGFloat {
        var h = CGFloat()
        if self.isShowTitleType == .NoShowTitleType {
            h = UIApplication.shared.statusBarFrame.size.height
        }else {
            h = UIApplication.shared.statusBarFrame.size.height+(self.navigationController?.navigationBar.frame.size.height)!
        }
        return h
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    //左侧返回按钮
    override func initReturnBtn(){
        let leftN:UIBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "return_image"), style: .plain, target: self, action: #selector(arrowResponse))
        self.navigationItem.leftBarButtonItem = leftN
    }
    override func arrowResponse() {
        if self.webView.canGoBack == true{
            self.webView.goBack()
        }else{
            backPrevious()
        }
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if self.strAction == "gotoLogin" {
            let tabbarVC : RootTabBarViewController = self.tabBarController as! RootTabBarViewController
            tabbarVC.selectedIndex = 3
        }
    }
    
    func backPrevious(){
        self.webView.removeObserver(self, forKeyPath: "estimatedProgress", context: nil)
        for actionName in webActionTitle {
            self.webView.configuration.userContentController.removeScriptMessageHandler(forName: actionName)
        }
        self.webView.stopLoading()
        self.webView.removeFromSuperview()
//        if self.isShowTitleType == .NoShowTitleType{
//            self.navigationController?.setNavigationBarHidden(false, animated: false)
//        }
        if self.previousPageShowTitleType == .YesShowTitleType {
            self.navigationController?.setNavigationBarHidden(false, animated: false)
        } else {
            self.navigationController?.setNavigationBarHidden(true, animated: false)
        }
        self.navigationController?.popViewController(animated: true)
    }

}
extension WebSwiftViewController {
    @available(iOS 8.0, *)
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        if self.title == nil || self.title?.count == 0 {
            self.title = webView.title
            if webView.title?.count == 0 {
                webView.addObserver(self, forKeyPath: "title", options: .new, context: nil)
            }
        }
    }
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print(message.name)
        if message.name == "AppLogout" {
            backPrevious()
        }else if message.name == "openScanActivity"{
            self.navigationController?.setNavigationBarHidden(false, animated: true)
            self.gotoQRCodeSwiftViewController(isHomePushType: .NOIsHomePushType)
        }else if message.name == "hideTitleLayout"{
            return
        }else if message.name == "getTitle"{
            if self.title == nil || self.title?.count == 0 {
                self.title = message.body as? String
            }
        }else if message.name == "copyContent"{
            let pasteboard = UIPasteboard.general
            pasteboard.string = message.body as? String
            SMToastView.showMessage("内容已复制！")
        }else if message.name == "gotoLogin"{
            backPrevious()
            self.strAction = "gotoLogin"
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                self.tabBarController?.selectedIndex = 2
            }
        }else if message.name == "openWeb"{
            self.actionGotoWebGotoWeb(webViewUrl: message.body as! String, isHomePushType: .NOIsHomePushType, previousPageShowTitleType: self.isShowTitleType)
        }
        else{
            WebActionOC.share().weAction(message.name, andBody: message.body as? String)
        }
    }
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print(webView.url?.absoluteString ?? String())
        print("main frame的导航开始请求时")
    }
    func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
        print("接收到服务器跳转请求之后调用")
    }
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        print("web内容开始到达时")
    }
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        print(error.localizedDescription)
    }
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        print(error.localizedDescription)
    }
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        let alertController = UIAlertController.init(title: "提示", message: message, preferredStyle: .alert)
        alertController.addAction(UIAlertAction.init(title: "确认", style: .default, handler: { (action) in
            completionHandler()
        }))
        self.present(alertController, animated: true, completion: nil)
    }
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        print("allow==",navigationAction.request.url as Any)
        //navigationAction.navigationType
        let urlStr:String = String(describing: navigationAction.request.url)
        if urlStr.contains("SYERP") {
            self.webView.scrollView.isScrollEnabled = false
            self.webView.scrollView.bounces = false
        }else{
            self.webView.scrollView.isScrollEnabled = true
            self.webView.scrollView.bounces = true
        }
        if navigationAction.targetFrame == nil {
            webView.load(navigationAction.request)
        }
        decisionHandler(WKNavigationActionPolicy.allow)
    }
}
