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

import UIKit
//import GGWkCookie
import ScanKitFrameWork

class WebSwiftViewController: BaseViewController,WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler,CustomizedScanDelegate {
    var newType:NewType = .OrdinaryNewsType
    var isShowTitleType:IsShowTitleType = .YesShowTitleType
    var isHomePushType:IsHomePushType = .YesIsHomePushType
    var webViewUrl:String?
    var strAction:String = ""
    var appid:String?
    var isEncryptionType:IsEncryptionType = .NoEncryptionType
    var isUMSMessageType:IsUMSMessageType = .NoUMSMessageType
    /// 加密内容
    var encryptionContent:String = ""
    
    ///上个页面是否隐藏导航栏
    var previousPageShowTitleType : IsShowTitleType = .YesShowTitleType
    //    var urlRequest = NSMutableURLRequest()
    var isFirstNum = 0
    
    var webCookieArray = NSArray()
    
    var hmsCustomScanViewController = HmsCustomScanViewController()
    var documentController = UIDocumentInteractionController()
    
    ///js调用原生方法名
    var webActionTitle = ["AppLogout","callPhone","sendSms","openScanActivity","getTitle","hideTitleLayout","copyContent","gotoLogin","openWeb","openFileDownload","openScan","getCookie","openDefaultWeb","openFileDownloadZIP"]
    lazy var webView: WKWebView = {
        let config = WKWebViewConfiguration.init()
        config.preferences = WKPreferences.init()
        config.preferences.minimumFontSize = 10;
        config.preferences.javaScriptEnabled = true
        config.suppressesIncrementalRendering = true
        config.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs")
        config.preferences.javaScriptCanOpenWindowsAutomatically = true
//        config.processPool = WKProcessPool.init()
        config.processPool = WebActionOC.singleWkProcessPool()
        config.userContentController = WKUserContentController.init()
        let userContent = WKUserContentController.init()
        if self.isEncryptionType == .YesEncryptionType {
            let count = self.getWebCookie(urlStr: self.webViewUrl)
            let cookieValue = WebActionOC.share()?.getWebCookie((WebActionOC.share()?.encryptAES(count, key: self.appid))!)
            
            let cookieScript = WKUserScript.init(source: WebActionOC.ajaxCookieScripts()!, injectionTime: .atDocumentStart, forMainFrameOnly: false)
//            let cookieScript = WKUserScript.init(source: cookieValue!, injectionTime: .atDocumentStart, forMainFrameOnly: false)
//            userContent.addUserScript(cookieScript)
        }
        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)
        //        WebActionOC.share()?.setNSURLProtocolCustom()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initTitleBar()
        SuspensionView.share().getsuspensionBtn()?.isHidden = true
        BDVoiceWakeUp.share().stopWakeup()
        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)
            self.wr_setNavBarBackgroundAlpha(1)
            self.wr_setNavBarShadowImageHidden(false)
            if #available(iOS 11.0, *) {
                webView.frame = CGRect(x:0, y: getStatusBarH(), width:SCREEN_WHIDTH() , height:SCREEN_HEIGHT()+HEIGHT_BOTTOM_MARGIN()-getStatusBarH() )
                //                WKWebsiteDataStore.default().httpCookieStore
            }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 )
            
        }
        /// 判断是否加密，如果加密，则将链接地址后面的拼接 全部截取掉
        if self.isEncryptionType == .YesEncryptionType {
//            self.webViewUrl = getWebCookieUrl(urlStr: self.webViewUrl)
        }
        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){
        AccountInfo.sharedInstance().webViewUrl = self.webViewUrl
        var count = self.getWebCookie(urlStr: self.webViewUrl)
        if self.isUMSMessageType == .IsUMSMessageType {
            count = self.encryptionContent
        }
//        print(count)
        webView.uiDelegate = self
        webView.navigationDelegate = self
//        let url2:NSURL = NSURL.init(string: WebActionOC.share().getUrl("https://movie.youku.com/"))!
        
//        let url2:NSURL = NSURL.init(string: WebActionOC.share().getUrl(AccountInfo.sharedInstance().getMessageVCUrl()+AccountInfo.sharedInstance().messageId!))!
        let url2:NSURL = NSURL.init(string: WebActionOC.share().getUrl(strUrl))!
        var host = url2.host
        if self.appid != nil && self.appid == "uh5uTvFBTAbKXDsq" {
            if AccountInfo.sharedInstance().isTest == "2" {
                host = "oa.sphchina.com"
            } else {
                host = "101.231.211.141"
            }
        }
        
        let urlRequest:NSMutableURLRequest = NSMutableURLRequest.init(url: url2 as URL)
        if self.appid == nil || (self.appid != "uh5uTvFBTAbKXDsq" && self.appid != "ZPeuHeJgPWNRhyQs" && self.appid != "ZYv36b9FG2YG3Eu0" && self.appid != "wlXo64TRm3l5GRgU" && self.appid != "OwRfV3D27BR9DXTo" && self.appid != "doCc2vJt04HR5jUP"){
//            doCc2vJt04HR5jUP
            urlRequest.setValue(WebActionOC.share()?.getCookieValue((WebActionOC.share()?.encryptAES(count, key: self.appid))!, host: host) as String?, forHTTPHeaderField: "Cookie")
            print("----urlRequest")
        } else {
            self.setHTTPCookie(count: count, host: host)
        }
//        urlRequest.setValue(WebActionOC.share()?.getCookieValue((WebActionOC.share()?.encryptAES(count, key: self.appid))!, host: host) as String?, forHTTPHeaderField: "Cookie")
//        urlRequest = WebActionOC.syncRequestCookie((urlRequest.mutableCopy() as! NSMutableURLRequest))
//        self.setHTTPCookie(count: count, host: host)
        
        
        self.view.addSubview(webView)
        self.view.insertSubview(webView, belowSubview: progressView)
        webView.load((urlRequest) as URLRequest)
        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 setHTTPCookie(count:String?,host:String?){
        let oneYearInSeconds = TimeInterval(60 * 60 * 24 * 365)
        let cookie = HTTPCookie(properties: [
            HTTPCookiePropertyKey.domain : host!,
            HTTPCookiePropertyKey.originURL: host!,
            HTTPCookiePropertyKey.path : "/",
            HTTPCookiePropertyKey.secure : true,
            HTTPCookiePropertyKey.name : "info",
            HTTPCookiePropertyKey.expires: NSDate(timeIntervalSinceNow: oneYearInSeconds),
            HTTPCookiePropertyKey.value : WebActionOC.share()?.encryptAES(count, key: self.appid)! as Any])!
        if #available(iOS 11.0, *){
            var cookieStore = webView.configuration.websiteDataStore.httpCookieStore
            cookieStore.getAllCookies { (cookie) in
                let cookiesArr:NSArray = cookie as NSArray
                for index in 0..<cookiesArr.count {
                    print("----",index,cookiesArr[index])
                }
            }
            cookieStore.setCookie(cookie) {
            }
            cookieStore = webView.configuration.websiteDataStore.httpCookieStore
            cookieStore.getAllCookies { (cookie) in
                let cookiesArr:NSArray = cookie as NSArray
                for index in 0..<cookiesArr.count {
                    print("====",index,cookiesArr[index])
                }
            }
        } else {
            HTTPCookieStorage.shared.setCookie(cookie)
        }
    }
    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")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(arrowResponse))
        let cancelN:UIBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "cancel_image")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(backPrevious))
        //        self.navigationItem.leftBarButtonItem = leftN
        self.navigationItem.leftBarButtonItems = [leftN,cancelN]
    }
    override func arrowResponse() {
        /// 将加载次数 重置
        isFirstNum = 4
        if self.webView.canGoBack == true{
            self.webView.goBack()
        }else{
            backPrevious()
        }
//        self.downLoaderFileCookieAction(download: "")
    }
   
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if self.strAction == "gotoLogin" {
            let tabbarVC : RootTabBarViewController = self.tabBarController as! RootTabBarViewController
            tabbarVC.selectedIndex = 3
        }
    }
    
    @objc func backPrevious(){
        SuspensionView.share().getsuspensionBtn()?.isHidden = false
        BDVoiceWakeUp.share().startWakeup()
//        webView.removeObserver(self, forKeyPath: "estimatedProgress", context: nil)
        for actionName in webActionTitle {
            self.webView.configuration.userContentController.removeScriptMessageHandler(forName: actionName)
        }
        webView.stopLoading()
//        webView.removeFromSuperview()
//        webView.uiDelegate = nil
//        webView.navigationDelegate = nil
//        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)
        
    }
    ///调用web方法
    @objc func alertAction(str:String,value:String) {
        let actionName = str + "('" + value + "')"
        print("调用web===",actionName)
        self.webView.evaluateJavaScript(actionName) { (item, error) in
            
        }
    }
}
