//
//  WebSwiftViewController+WKDelegate.swift
//  MobilePortal
//
//  Created by caiyang on 2021/2/20.
//  Copyright © 2021 yin chen. All rights reserved.
//

import UIKit

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 == "openScan"{
            self.navigationController?.setNavigationBarHidden(false, animated: true)
//            self.gotoQRCodeCallBackViewController(isHomePushType: .NOIsHomePushType, callBackBlock: )
            self.gotoQRCodeCallBackViewController(isHomePushType: .NOIsHomePushType) { [weak self](value) in
                if self?.isShowTitleType == .NoShowTitleType {
                    self?.navigationController?.setNavigationBarHidden(true, animated: true)
                }
                if (value as! String == "") {
                    return
                }
                self?.alertAction(str: "scanCallBack", value: value as! String)
            }
//            self.gotoQRVC()
        }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) {[weak self] in
//                self.tabBarController?.selectedIndex = 2
                AccountInfo.sharedInstance().clearAccount()
                self?.deAllSelecCompanyDepartment()
                NotificationCenter.default.post(name: Notification.Name(rawValue: "setLoginWindow"), object: "0")
            }
        }else if message.name == "openWeb"{
            self.actionGotoWebGotoWeb(webViewUrl: message.body as! String, isHomePushType: .NOIsHomePushType, previousPageShowTitleType: self.isShowTitleType)
        }else if message.name == "openFileDownload"{
            let dic:NSMutableDictionary = self.setFileDownloadUrlCookie(bodyString: (message.body as? String)!)
            self.downLoaderFileAction(download: dic.object(forKey: "url") as! String, cookie: dic.object(forKey: "cookie") as! String)
        } else if message.name == "getCookieInfo" {
            var count = self.getWebCookie(urlStr: self.webViewUrl)
            if self.isUMSMessageType == .IsUMSMessageType {
                count = self.encryptionContent
            }
            
            self.alertAction(str: "setCookieInfo", value: (WebActionOC.share()?.encryptAES(count, key: self.appid))!)
        }else if message.name == "openFileDownloadZIP"{
            let dic:NSMutableDictionary = self.setFileDownloadUrlCookie(bodyString: (message.body as? String)!)
            self.downLoaderZIPFileAction(download: dic.object(forKey: "url") as! String, cookie: dic.object(forKey: "cookie") as! String)
        } else if message.name == "openDefaultWeb"{
            self.openDefaultWeb(urlString: message.body as? String)
        }
        else{
            WebActionOC.share().weAction(message.name, andBody: message.body as? String)
        }
    }
    func openDefaultWeb(urlString:String?){
        let url = URL(string: (WebActionOC.share()?.getUrl(urlString)!)!)
        if url == nil {
            SMToastView.showMessage("地址有误，请联系管理员！")
            return
        }
        //根据iOS系统版本，分别处理
        if #available(iOS 10, *) {
            UIApplication.shared.open(url!, options: [:],
                                      completionHandler: {(success) in
                                        print(success)
            })
        } else {
            UIApplication.shared.openURL(url!)
        }
    }
    /// 解析参数，获取下载Url和参数Cookie
    func setFileDownloadUrlCookie(bodyString:String) -> NSMutableDictionary{
        let fileDoenloadDic = NSMutableDictionary()
        fileDoenloadDic["url"] = ""
        fileDoenloadDic["cookie"] = ""
        let dic:[String: Any] = stringValueDic(bodyString)!
        if dic["url"] != nil {
            fileDoenloadDic["url"] = dic["url"]
        }
        if dic["cookie"] != nil {
            fileDoenloadDic["cookie"] = dic["cookie"]
        }
        return fileDoenloadDic
    }
    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内容开始到达时")
        let cookieStore = webView.configuration.websiteDataStore.httpCookieStore
        cookieStore.getAllCookies { (cookie) in
            let cookiesArr:NSArray = cookie as NSArray
            for index in 0..<cookiesArr.count {
                print("didCommit==",index,cookiesArr[index])
            }
        }
        
    }
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        print(error.localizedDescription)
        //        showOneAlert(title: "加载失败", message: error.localizedDescription, titleSecondBtn: "确定", blockOtherBtn: {[weak self] in
        //            self?.backPrevious()
        //        })
        let errorNs:NSError = error as NSError
        if errorNs.code == NSURLErrorCancelled {
            return
        }
        showAlert(title: "加载失败", message: error.localizedDescription, titleCancelBtn: "取消", titleSecondBtn: "返回") {[weak self] in
            self?.backPrevious()
        }
    }
    func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
            let card = URLCredential.init(trust: challenge.protectionSpace.serverTrust!)
            completionHandler(URLSession.AuthChallengeDisposition.useCredential,card)
        }
    }
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        print(error.localizedDescription)
        let errorNs:NSError = error as NSError
        if errorNs.code == NSURLErrorCancelled {
            return
        }

        showAlert(title: "加载失败", message: error.localizedDescription, titleCancelBtn: "取消", titleSecondBtn: "返回") {[weak self] in
            self?.backPrevious()
        }
    }
    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
        }
        var isNav = true
        if (urlStr.contains("dl.sphchina.com/idp/login.jsp")) && isFirstNum < 3 && AccountInfo.sharedInstance().loginType != "2" {
            webView.reload()
            let count = self.getWebCookie(urlStr: self.webViewUrl)
            let url2:NSURL = NSURL.init(string: WebActionOC.share().getUrl(self.webViewUrl))!
            var urlRequest:NSMutableURLRequest = NSMutableURLRequest.init(url: url2 as URL)
            urlRequest.setValue(WebActionOC.share()?.getCookieValue((WebActionOC.share()?.encryptAES(count, key: self.appid))!, host: "oa.sphchina.com") as String?, forHTTPHeaderField: "Cookie")
            urlRequest = WebActionOC.syncRequestCookie((urlRequest.mutableCopy() as! NSMutableURLRequest))
            webView.load(urlRequest as URLRequest)
            isNav = false
            isFirstNum = isFirstNum + 1
        }
        if (urlStr.contains("dl.sphchina.com/idp/login.jsp")) && isFirstNum == 4 {
            self.backPrevious()
        }
        
        if navigationAction.targetFrame == nil {
            webView.load(navigationAction.request)
        }
        
        //        decisionHandler(WKNavigationActionPolicy.allow)
        if !isNav {
            decisionHandler(WKNavigationActionPolicy.cancel)
        } else {
            decisionHandler(WKNavigationActionPolicy.allow)
        }
        
    }
    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        print("文档==",navigationAction.request.url as Any)
        let urlStr = String(describing: navigationAction.request.url)
        if urlStr.contains("download.do") {
            self.downLoaderFileCookieAction(download: WebActionOC.share()?.getUrlStr(navigationAction.request.url) ?? String())
            return nil;
        }
        if navigationAction.targetFrame?.isMainFrame == nil {
            webView.load(navigationAction.request)
        }
        
        return nil;
    }
    //    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
    //
    //        decisionHandler(.allow)
    //    }
}
