//
//  YHH5WebViewVC.swift
//  galaxy
//
//  Created by davidhuangA on 2024/7/18.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
@preconcurrency import WebKit
import dsBridge
import Photos

/*
 快速测评 及 其他与H5交互的界面
 */
class YHH5WebViewVC: YHBaseViewController, WKUIDelegate, WKNavigationDelegate {
    
    lazy var manager : YHAIRequestManager = {
        return YHAIRequestManager()
    }()
    
    // 测评结果回调
    var evaluationResultCallback:((Dictionary<String, Any>)->())?

    
    lazy var webview : DWKWebView = {
        let config = WKWebViewConfiguration()
        config.applicationNameForUserAgent = "YinHeApp"
#if DEBUG
        if #available(iOS 14.5, *) {
            config.upgradeKnownHostsToHTTPS = false
        } else {
            // Fallback on earlier versions
        }
#endif
        config.allowsInlineMediaPlayback = true
        /// 开启让自动播放
        config.mediaTypesRequiringUserActionForPlayback = []
        let webview = DWKWebView(frame: .zero, configuration: config)
        webview.scrollView.contentInsetAdjustmentBehavior = .never
        webview.navigationDelegate = self
        webview.scrollView.delegate = self
        
        webview.setDebugMode(false)
//        webview.uiDelegate = self
        
        return webview
    }()
    
    lazy var progBar : UIProgressView = {
        progBar = UIProgressView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 30))
        progBar.progress = 0.0
        progBar.tintColor = UIColor.brandMainColor
        return progBar
    }()
    
    var url = ""
    var navTitle = "" //导航栏title
    
    lazy var noNetWorkTipsView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("无网络", kNotNetWorkBgName)
        view.topMargin = 222
        view.backgroundColor = .white
        view.isHidden = true
        return view
    }()
    
    //是否曾今有过网络
    private var isNetWorkOkBefore : Bool = false
    
    lazy var previewFileTool:YHFilePreviewTool = {
       let tool = YHFilePreviewTool(targetVC: self)
       return tool
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)),
                                               name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)),
                                               name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        reloadUI()
    }
    
    deinit {
        webview.removeObserver(self, forKeyPath: "estimatedProgress")
        webview.removeObserver(self, forKeyPath: "title")
        NotificationCenter.default.removeObserver(self)
    }
    
    
    //分享到H5或者小程序
    var isShareToMiniProgramFlag : Bool = false //是否分享到小程序 默认分享到h5
    var shareMiniPath : String? //分享到小程序时的 path
    var shareMiniTitle : String = "好友力荐新品，速来围观，不容错过！"
    
    //分享到H5的情况
    var shareH5Title : String = "20秒极速测评"
    var shareH5Describe : String = "您的朋友邀请您进行香港优才测评，来试试吧"
    //外部传进来的分享链接
    var shareUrlFromOutside : String?
    
    
    //二维码是否请求完成
    var isQrInfoOk : Bool = false
    var arrQrInfo : [String] = []
    lazy var viewModel: YHHomePageViewModel = {
        let vm = YHHomePageViewModel()
        return vm
    }()
    
    //UI元素的控制变量 如下
    
    //2、是否通屏展示- 默认通屏(导航栏透明)
    var isFullScreenFlag : Bool = true
    
    //2.1、是否隐藏导航栏
    var isHideNavigationBar : Bool = false
    
    //3、右上角分享按钮
    var isShowRightShareItemFlag : Bool = false
    
    //4、是否需要重新刷新界面
    var isNeedRefreshDataFlag : Bool = false
    
    //5、webView内部返回 - 默认不支持
    var isSupportWebviewInterBackFlag : Bool = false
    
    //6、是否展示 导航栏上的title
    var showNavigationTitleFlag : Bool = true
    
    //22、禁用全局手势
    private var disableFullScreenGestureFlag : Bool = false
    
    //默认的返回按钮图片
    private var myDefaultBackImage : UIImage = UIImage(named: "back_icon") ?? UIImage()
    
    override func backItemClick(_ sender: Any) {
        if isSupportWebviewInterBackFlag {
            if webview.canGoBack {
                webview.goBack()
                return
            }
        }
        self.navigationController?.popViewController()
    }
}

// MARK: - 内部方法
private extension YHH5WebViewVC {
    func reloadWebViewWithToken() {
        if YHLoginManager.shared.isLogin() {
            let token = YHLoginManager.shared.h5Token
            if !url.contains("param=") {
                //无 param= 的情况
                var tUrl = url + "?param=" + token
                let urlHasParam = String.hasQueryParameters(urlString: url)
                if urlHasParam {
                    tUrl = url + "&param=" + token
                }
                
                if let url = URL(string: tUrl) {
                    let request = URLRequest(url: url)
                    webview.load(request)
                    return
                }
                
            } else {
                //有 param= 的情况
                //H5 发现token失效后重新刷新的场景
                if url.contains("?param=") {
                    //token是第一个参数   httts://www.baidu.com?param=
                    let separator = "?param="
                    let arr0 = url.components(separatedBy: separator)
                    if arr0.count == 1 {
                        //eg: httts://www.baidu.com?param=
                        let tUrl = arr0[0] + "?param=" + token
                        if let url = URL(string: tUrl) {
                            let request = URLRequest(url: url)
                            webview.load(request)
                            return
                        }
                    } else if arr0.count == 2 {
                        let secoundString = arr0[1]
                        let separator = "&"
                        let arr1 = secoundString.components(separatedBy: separator)
                        
                        if arr1.count == 1 {
                            //eg: httts://www.baidu.com?param=123434324
                            let tUrl = arr0[0] + "?param=" + token
                            if let url = URL(string: tUrl) {
                                let request = URLRequest(url: url)
                                webview.load(request)
                                return
                            }
                        } else {
                            //eg: httts://www.baidu.com?param=123434324&key2=1232323
                            var tUrl = arr0[0] + "?param=" + token
                            for(index,str) in arr1.enumerated() {
                                if index != 0 {
                                    tUrl = tUrl + "&" + str
                                }
                            }
                            
                            if let url = URL(string: tUrl) {
                                let request = URLRequest(url: url)
                                webview.load(request)
                                return
                            }
                        }
                    }
                } else if url.contains("&param=") {
                    //token非第一个参数
                    let separator = "&param="
                    let arr0 = url.components(separatedBy: separator)
                    if arr0.count == 1 {
                        //eg: httts://www.baidu.com?key0=123434324 &param=
                        let tUrl = arr0[0] + "&param=" + token
                        if let url = URL(string: tUrl) {
                            let request = URLRequest(url: url)
                            webview.load(request)
                            return
                        }
                        
                    } else if arr0.count == 2 {
                        
                        let secoundString = arr0[1]
                        let separator = "&"
                        let arr1 = secoundString.components(separatedBy: separator)
                        
                        if arr1.count == 1 {
                            //eg: httts://www.baidu.com?key0=123434324 &param= 1234980
                            let tUrl = arr0[0] + "&param=" + token
                            if let url = URL(string: tUrl) {
                                let request = URLRequest(url: url)
                                webview.load(request)
                                return
                            }
                        } else {
                            //eg: httts://www.baidu.com?key0=123434324 &param= 1234980 & key1=34234
                            var tUrl = arr0[0] + "&param=" + token
                            for(index,str) in arr1.enumerated() {
                                if index != 0 {
                                    tUrl = tUrl + "&" + str
                                }
                            }
                            
                            if let url = URL(string: tUrl) {
                                let request = URLRequest(url: url)
                                webview.load(request)
                                return
                            }
                        }
                    }
                } else {
                    printLog("不应该存在的场景")
                }
            }
        }
        
        
        //最后兜底 刷新
        if let url = URL(string: url) {
            let request = URLRequest(url: url)
            webview.load(request)
        }
    }
    
    func reloadUI() {
        if isNeedRefreshDataFlag {
            if let url = URL(string: url){
                let request = URLRequest(url: url)
                webview.load(request)
            }
        }
    }
    
    func loadQrInfo() {
        let params : [String : Int] = ["pid[0]" : 16]
        viewModel.getHKEvent(param: params) { success, error in
            if success {
                self.isQrInfoOk = true
                if let arr = self.viewModel.hkList,arr.count > 0 {
                    let item0 : YHHKEventModel = arr[0]
                    if item0.list.count > 1 {
                        self.arrQrInfo = item0.list
                    }
                }
            }
        }
    }
    
    func setupUI() {
        gk_navBarAlpha = 0.0
        gk_navLineHidden = false
        gk_navBackgroundColor = .white
        
        //默认白色返回按钮
        gk_backImage = myDefaultBackImage
        
        if isHideNavigationBar {
            isFullScreenFlag = true //导航栏隐藏的情况下强制通屏
        } else {
            
        }
        gk_navigationBar.isHidden = isHideNavigationBar
        
        NotificationCenter.default.addObserver(self, selector: #selector(updateNetWorkUI), name: .reachabilityChanged, object: nil)
        view.backgroundColor = .white
        
        // 创建wkwebview
        let api = YHJsApi()
        api.delegate = self
        webview.addJavascriptObject(api, namespace: nil)
        
        var tUrl = url
        if !url.contains("navigationH=") {
            tUrl = url + "?navigationH=\(k_Height_NavigationtBarAndStatuBar)"
            if url.contains("?") {
                tUrl = url + "&navigationH=\(k_Height_NavigationtBarAndStatuBar)"
            }
        }
        
        if !url.contains("statusBarH=") {
            tUrl = url + "?statusBarH=\(k_Height_StatusBar)"
            if url.contains("?") {
                tUrl = url + "&statusBarH=\(k_Height_StatusBar)"
            }
        }
        url = tUrl
        
        printLog("hjl: 当前加载的url是：\(url)")
        if let url = URL(string: url) {
            let request = URLRequest(url: url)
            webview.load(request)
        } else {
            let tmpUrl = YHURLEncodeHelper.urlEncodedString(url)
            if let url = URL(string: tmpUrl) {
                let request = URLRequest(url: url)
                webview.load(request)
            } else {
                printLog("url: 有问题    \(url)")
            }
        }
        
        view.addSubview(webview)
        
        if isFullScreenFlag {
            gk_navBarAlpha = 0.0
            webview.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        } else {
            webview.snp.makeConstraints { make in
                make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
                make.left.right.bottom.equalToSuperview()
            }
        }
        webview.addSubview(progBar)
        
        // 监听网页加载的进度
        webview.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        webview.addObserver(self, forKeyPath: "title", options: .new, context: nil)
        
        view.addSubview(noNetWorkTipsView)
        self.noNetWorkTipsView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
        }
        updateNetWorkStatusUI(needReload: false)
        
        
        //
        if isFullScreenFlag {
            gk_navBarAlpha = 0.0
        } else {
            gk_navBarAlpha = 1.0
        }
        
        if showNavigationTitleFlag {
            if isFullScreenFlag {
                gk_navBarAlpha = 0
                gk_navTitle = ""
            } else {
                gk_navBarAlpha = 1.0
                gk_navTitle = self.navTitle
            }
        } else {
            gk_navTitle = ""
        }
    }
    
    func addRightItems() {
        let rightButtonItem = UIBarButtonItem(image: UIImage(named: "share_item")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(share))
        gk_navRightBarButtonItem = rightButtonItem
        gk_navItemRightSpace = 16
    }
    
    
    @objc func share() {
        
        if self.isShareToMiniProgramFlag {
            if let path = self.shareMiniPath,!path.isEmpty {
                YHShareManager.shared.shareToMiniProgram(path:path, shareTitle: shareMiniTitle)
            }
        } else {
            
            var shareUrl = self.url
            if let url = shareUrlFromOutside {
                shareUrl = url
            }
            
            //特殊场景处理
            if shareUrl.contains("superAppBridge.html#/evaluation", caseSensitive: false) {
                shareUrl =  YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/evaluation?channel=APP-share&customer_id=\(YHLoginManager.shared.userModel?.id ?? "")"
            }
            
            if !shareUrl.isEmpty &&
               !self.shareH5Title.isEmpty &&
                !self.shareH5Describe.isEmpty {
                YHShareManager.shared.sendLinkContent(self.shareH5Title, self.shareH5Describe, UIImage(named: "shareIcon") ?? UIImage(), link: shareUrl)
            }
        }
    }
    
    @objc func updateNetWorkUI() {
        updateNetWorkStatusUI(needReload: true)
    }
    
    func updateNetWorkStatusUI(needReload:Bool) {
        DispatchQueue.main.async {
            if YHNetworkStatusManager.shared.isNetWorkOK {
                if needReload && self.isNetWorkOkBefore == false {
                    self.webview.stopLoading()
                    if let targetUrl = URL(string: self.url) {
                        let request = URLRequest(url: targetUrl)
                        self.webview.load(request)
                    }
                }
                
                self.isNetWorkOkBefore = true
            }
            
            if self.isNetWorkOkBefore == false {
                self.view.bringSubviewToFront(self.noNetWorkTipsView)
                self.noNetWorkTipsView.isHidden = YHNetworkStatusManager.shared.isNetWorkOK
            } else {
                self.noNetWorkTipsView.isHidden = true
            }
        }
    }
    
    //是否启用全局返回手势
     func navigationShouldPopOnGesture() -> Bool {
        return !disableFullScreenGestureFlag
    }
    
    @objc func keyboardWillShow(_ notification: Notification) {
        guard let userInfo = notification.userInfo,
              let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
        
        let keyboardHeight = keyboardFrame.height
        // 调用 H5 的 onKeyboardShow 方法，传递高度
        let dict = ["height": "\(keyboardHeight)"]
        webview.callHandler("onKeyboardHeightChanged", arguments: [dict])
    }

    @objc func keyboardWillHide(_ notification: Notification) {
        // 调用 H5 的 onKeyboardHide 方法
        let dict = ["height": "\(0)"]
        webview.callHandler("onKeyboardHeightChanged", arguments: [dict])
    }
}


// MARK: - WKNavigationDelegate
extension YHH5WebViewVC {
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            self.progBar.alpha = 1.0
            progBar.setProgress(Float(webview.estimatedProgress), animated: true)
            //进度条的值最大为1.0
            if self.webview.estimatedProgress >= 1.0 {
                if isFullScreenFlag {
                    gk_navBarAlpha = 0.0
                }
                
                UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseInOut, animations: { () -> Void in
                    self.progBar.alpha = 0.0
                }, completion: { (finished:Bool) -> Void in
                    self.progBar.progress = 0
                })
            }
        } else if keyPath == "title" {
            if let title = self.webview.title,title.isEmpty == false {
                self.navTitle = title
                if !isFullScreenFlag,showNavigationTitleFlag {
                    self.gk_navTitle = self.navTitle
                }
            }
        }
    }
    
    override class func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        if self.isShowRightShareItemFlag {
            self.addRightItems()
        }
    }
    
    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        // 实现非安全链接的跳转。如果目标主视图不为空,则允许导航
        if !(navigationAction.targetFrame?.isMainFrame != nil) {
            webview.load(navigationAction.request)
        }
        return nil
    }
    
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
//        // 修复弹窗弹出的问题
//        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
//        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (_) -> Void in
//            completionHandler()
//        }))
//        self.present(alert, animated: true, completion: nil)
    }
    
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        printLog("\(error.localizedDescription)")
    }
}

// MARK: - h5实现的接口
extension YHH5WebViewVC {
    
    func goAgentChatPage(dic:[String:Any]) {
        
        let id = dic["id"] as? String ?? ""
        let title = dic["title"] as? String ?? ""
        let businessType = dic["businessType"] as? String ?? ""
        let botId = dic["botId"] as? String ?? ""
        
        YHHUD.show(.progress(message: "加载中..."))
        self.manager.getSubRobotChatConversationId(listItemId: "\(id)") {
            sesseionId in
            
            YHHUD.hide()
            
            var isShow = false
            if  businessType == YHAIRobotType.education.rawValue || businessType == YHAIRobotType.sale.rawValue || businessType == YHAIRobotType.business.rawValue {
                isShow = true
            }
            let vc = YHAIRobotChatViewController()
            vc.isNeedShowBannerHeader = isShow
            vc.myTitle = title
            vc.robotId = botId
            vc.listItemId = Int(id) ?? 0
            vc.conversationId = sesseionId
            vc.robotType = businessType
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    func gotoPreviewTool(urlString: String) {
        previewFileTool.openXLSXRemoteFile(urlString: urlString, fileName: "")
    }
    
    //25 关闭AI聊天的测评弹窗并获取测评结果
//    type   1   直接关闭。    2 测评出结果关闭
//    result  测评结果json   待定
    func closeEvaluationGetResult(type: Int, dic:[String:Any]) {
            
         if type == 2 {
            printLog("web evaluation:\n")
            printLog("\(dic)")
         }
         self.evaluationResultCallback?(dic)
         self.navigationController?.popViewController(animated: false)
    }
    
    //22、禁用全局手势返回
    func disableFullScreenGestureSyn(_ tag : String) {
        if tag.contains("0") {
            //启用
            self.disableFullScreenGestureFlag = false
            
        } else if tag.contains("1") {
            //禁用
            self.disableFullScreenGestureFlag = true
        }
    }
    
    //20、导航栏上是否展示title
    func hideNavigationTitleSyn(_ tag : String) {
        if tag.contains("0") {
            //展示
            self.showNavigationTitleFlag = true
        } else if tag.contains("1") {
            //隐藏
            self.showNavigationTitleFlag = false
        }
        
        if self.showNavigationTitleFlag {
            if isFullScreenFlag {
                gk_navBarAlpha = 0
                gk_navTitle = ""
            } else {
                gk_navBarAlpha = 1.0
                gk_navTitle = self.navTitle
            }
        } else {
            gk_navTitle = ""
        }
    }
    
    //19、返回时刷新界面
    func reloadwebVeiwSyn() {
        self.isNeedRefreshDataFlag = true
    }
    
    //17、H5调用 App的分享
    func shareH5Syn(title : String ,desc : String ,url : String) {
        shareUrlFromOutside = url
        shareH5Title = title
        shareH5Describe = desc
        share()
    }
    
    //登录带token刷新
    func loginAndRefeshWithTokenSyn(_ tag : String) {
        if tag.contains("1") {
            YHLoginManager.shared.loginSuccessActionBlock = {[weak self] in
                YHLoginManager.shared.loginSuccessActionBlock = nil
                guard let self = self else { return }
                self.reloadWebViewWithToken()
            }
        } else if tag.contains("2") {
            //H5 监测token失效 重新登录
            YHLoginManager.shared.loginSuccessActionBlock = {[weak self] in
                YHLoginManager.shared.loginSuccessActionBlock = nil
                guard let self = self else { return }
                self.reloadWebViewWithToken()
            }
        }
        //H5 调用App的登录逻辑
        YHOneKeyLoginManager.shared.oneKeyLogin()
    }
    
    //是否隐藏导航栏
    func hideNavigationBarSyn(_ tag : String) {
        if tag.contains("1") {
            //隐藏
            isHideNavigationBar = true
//            supportFullScreenSyn("1")//强制通屏
        } else {
            //不隐藏
            isHideNavigationBar = false
//            supportFullScreenSyn("1")
        }
        gk_navigationBar.isHidden = isHideNavigationBar
        if isHideNavigationBar {
            webview.snp.remakeConstraints { make in
                make.edges.equalToSuperview()
            }
        } else if !isFullScreenFlag {
            webview.snp.remakeConstraints { make in
                make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
                make.left.right.bottom.equalToSuperview()
            }
        }
    }
    
    //是否支持通屏
    func supportFullScreenSyn(_ tag : String) {
        if tag.contains("1") {
            //支持
            
            isFullScreenFlag = true
            
        } else {
            //不支持
            isFullScreenFlag = false
        }
        
        webview.snp.removeConstraints()
        if isFullScreenFlag {
            gk_navBarAlpha = 0.0
            gk_navTitle = ""
            webview.snp.remakeConstraints { make in
                make.edges.equalToSuperview()
            }
        } else {
            webview.snp.remakeConstraints { make in
                make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
                make.left.right.bottom.equalToSuperview()
            }
            
        }
    }
    
    //是否支持内部跳转
    func supportInnerBackSyn(_ tag : String) {
        if tag.contains("1") {
            isSupportWebviewInterBackFlag = true
        } else {
            isSupportWebviewInterBackFlag = false
        }
    }
    
    
    func setNavigationBackColor(_ tag : String) {
        if tag.contains("1") {
            myDefaultBackImage = UIImage(named: "back_icon") ?? UIImage()
        } else {
            myDefaultBackImage = UIImage(named: "activity_nav_back") ?? UIImage()
        }
        gk_backImage = myDefaultBackImage
    }
    
    func backToAppPreView() {
        self.navigationController?.popViewController()
    }
    
    func setAppNavigation(_ show : Bool) {
        if show {
            gk_navBarAlpha = 1.0
            gk_navTitle = navTitle
        } else {
            gk_navBarAlpha = 0.0
            gk_navTitle = ""
        }
    }
    
    func saveLocalPictureSyn(_ picUrl: String) {
        let imageView = UIImageView()
        imageView.kf.setImage(with: URL(string: picUrl)) { result in
            switch result {
            case .success(let value):
                self.saveImage(value.image)
            case .failure(_):
                YHHUD.flash(message: "保存失败")
            }
        }
    }
    
    func savePicToLocal(_ data: String) {
        // 解码 Base64 字符串为 Data
        let base64String = data
        if let image = base64ToImage(base64String: base64String) {
            print("图片转换成功")
            self.saveImage(image)
        } else {
            print("图片转换失败")
        }
    }
    
    // 将Base64字符串转换为Data对象
    func base64ToData(base64String: String) -> Data? {
        return Data(base64Encoded: base64String, options: .ignoreUnknownCharacters)
    }

    // 将Data对象转换为UIImage对象
    func base64ToImage(base64String: String) -> UIImage? {
        // 首先将Base64字符串转换为Data
        guard let imageData = base64ToData(base64String: base64String) else {
            return nil
        }
        // 然后使用Data初始化UIImage
        return UIImage(data: imageData)
    }

    func saveImage(_ image: UIImage) {
        // 确保应用有权访问相册
        PHPhotoLibrary.requestAuthorization { status in
            if status == .authorized {
                // 保存图片到相册
                DispatchQueue.main.async {
                    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
                    YHHUD.flash(message: "保存成功")
                }
            } else {
                DispatchQueue.main.async {
                    YHHUD.flash(message: "保存失败，请检查系统权限")
                }
            }
        }
    }
}

//MARK: - UIScrollViewDelegate
extension YHH5WebViewVC : UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if isFullScreenFlag,scrollView == webview.scrollView {
            
            printLog("srollView 滚动事件")
            
            if scrollView.contentOffset.y > 0 {
                var alpha =  scrollView.contentOffset.y / (k_Height_NavigationtBarAndStatuBar)
                if alpha > 1.0 {
                    alpha = 1.0
                }
                gk_navBarAlpha = alpha
                if showNavigationTitleFlag {
                    gk_navTitle = navTitle
                } else {
                    gk_navTitle = ""
                }
                gk_backImage = UIImage(named: "back_icon")
            } else {
                gk_navBarAlpha = 0.0
                gk_navTitle = ""
                gk_backImage = myDefaultBackImage
            }
        }
    }
}
