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

import UIKit
import WebKit
import dsBridge
import Photos

/*
 快速测评 及 其他与H5交互的界面
 */
class YHH5WebViewVC: YHBaseViewController, WKUIDelegate, WKNavigationDelegate {
    var webview = DWKWebView()
    var progBar = UIProgressView()
    
    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
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    deinit {
        webview.removeObserver(self, forKeyPath: "estimatedProgress")
        NotificationCenter.default.removeObserver(self)
    }
    
    //右上角分享按钮
    var isShowRightShareItemFlag : Bool = false
    
    //底部分享view
    var isWithBottomViewFlag : Bool = false
    lazy var shareView: YHShareViewOnTablebarView = {
        let view = YHShareViewOnTablebarView()
        return view
    }()
    
    //分享到H5或者小程序
    var isShareToMiniProgramFlag : Bool = false //是否分享到小程序 默认分享到h5
    var shareMiniPath : String? //分享到小程序时的 path
    var shareMiniTitle : String = "好友力荐新品，速来围观，不容错过！"
    
    //分享到H5的情况
    var shareH5Title : String = "20秒极速测分"
    var shareH5Describe : String = "您的朋友邀请您进行香港优才测评，来试试吧"
    
    
    //二维码是否请求完成
    var isQrInfoOk : Bool = false
    var arrQrInfo : [String] = []
    lazy var viewModel: YHHomePageViewModel = {
        let vm = YHHomePageViewModel()
        return vm
    }()
}

// MARK: - 内部方法
private extension YHH5WebViewVC {
    
    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
                
        NotificationCenter.default.addObserver(self, selector: #selector(updateNetWorkUI), name: .reachabilityChanged, object: nil)
        
        view.backgroundColor = .white
        
        if isWithBottomViewFlag {
            loadQrInfo()
            view.addSubview(shareView)
        }
        
        
        shareView.block = { tag in
            if tag == 0 {
                //分享
                self.share()
            } else {
                //预约咨询
                if self.arrQrInfo.count > 1 {
                    let codeUrl = self.arrQrInfo[0]
                    let downloadUrl = self.arrQrInfo[1]
                    YHConsultantQRCodeView.codeView(codeUrl, downloadUrl: downloadUrl).show()
                }
            }
        }
        
        // 创建wkwebview
        webview = DWKWebView(frame: .zero)
        webview.scrollView.contentInsetAdjustmentBehavior = .never
        webview.navigationDelegate = self
        webview.scrollView.delegate = self
        
        let api = YHJsApi()
        api.delegate = self
        webview.addJavascriptObject(api, namespace: nil)
        
        let url = NSURL(string: url)
        let request = NSURLRequest(url: url! as URL)
        webview.load(request as URLRequest)
        view.addSubview(webview)
        
        if isWithBottomViewFlag {
            view.addSubview(shareView)
            shareView.snp.makeConstraints { make in
                make.bottom.left.right.equalToSuperview()
                make.height.equalTo(YHShareViewOnTablebarView.viewH)
            }
            
            webview.snp.makeConstraints { make in
                make.top.left.right.equalToSuperview()
                make.bottom.equalTo(shareView.snp.top)
            }
        } else {
            webview.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        }
        
        // 加载网页的进度条
        progBar = UIProgressView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 30))
        progBar.progress = 0.0
        progBar.tintColor = UIColor.brandMainColor
        webview.addSubview(progBar)
        // 监听网页加载的进度
        webview.addObserver(self, forKeyPath: "estimatedProgress", 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)
    }
    
    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 shareUrl.contains("superAppBridge.html#/evaluation", caseSensitive: false) {
                shareUrl =  YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/evaluation?channel=APP-share&customer_id=\(YHLoginManager.shared.userModel?.id ?? "")"
            }
            YHShareManager.shared.sendLinkContent(self.shareH5Title, self.shareH5Describe, UIImage(named: "AppIcon") ?? 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()
                    let targetUrl = NSURL(string: self.url)
                    let request = NSURLRequest(url: targetUrl! as URL)
                    self.webview.load(request as URLRequest)
                }
                
                self.isNetWorkOkBefore = true
            }
            
            if self.isNetWorkOkBefore == false {
                self.view.bringSubviewToFront(self.noNetWorkTipsView)
                self.noNetWorkTipsView.isHidden = YHNetworkStatusManager.shared.isNetWorkOK
            } else {
                self.noNetWorkTipsView.isHidden = true
            }
        }
    }
    
    // MARK: - webview function
    @objc func toBack() {
        if webview.canGoBack {
            webview.goBack()
        }
    }
    
    @objc func toForward() {
        if webview.canGoForward {
            webview.goForward()
        }
    }
}


// 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) {
                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
                })
            }
        }
    }
    
    override class func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        if isShowRightShareItemFlag {
            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 setAppNavigation(_ show : Bool) {
        if show {
            gk_navBarAlpha = 1.0
        } else {
            gk_navBarAlpha = 0.0
        }
    }
    
    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 webViewDidScrollView(_ offset: CGFloat) {
        //补充 导航栏 逻辑逻辑
        
    }
    
    func saveImage(_ image: UIImage) {
        // 确保应用有权访问相册
        PHPhotoLibrary.requestAuthorization { status in
            if status == .authorized {
                // 保存图片到相册
                UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
                DispatchQueue.main.async {
                    YHHUD.flash(message: "保存成功")
                }
            }
        }
    }
}



//MARK: - UIScrollViewDelegate
extension YHH5WebViewVC : UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.contentOffset.y > 0 {
            var alpha =  scrollView.contentOffset.y / (k_Height_NavigationtBarAndStatuBar)
            if alpha > 1.0 {
                alpha = 1.0
            }
            gk_navBarAlpha = alpha
            
        } else {
            gk_navBarAlpha = 0.0
        }
    }
}
