//
//  YHHomeWebViewController.swift
//  galaxy
//
//  Created by EDY on 2024/4/7.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import WebKit
import Photos

class YHHomeWebViewController: YHBaseViewController, WKUIDelegate, WKNavigationDelegate {
    
    var  operationFlag:Bool = false
    
    typealias Block = (YHWebModel) -> ()
    var block: Block?
    
    
    var viewModel: YHHomeWebViewModel!
    var webview = WKWebView()
    var progBar = UIProgressView()
    var bottomView: YHHomeWebBottomView!
    var url = ""
    var id: Int = 0
    var vcTitle : String?
    var model: YHWebModel = YHWebModel()
    lazy var bottomViewForSavePic: YHHomeWebViewBottomForSavePicView = {
        let view = YHHomeWebViewBottomForSavePicView()
        view.isHidden = true
        return view
    }()
    
    lazy var noNetWorkTipsView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("无网络", kNotNetWorkBgName)
        view.topMargin = 222
        view.backgroundColor = .white
        view.isHidden = true
        return view
    }()
    
    //有些界面需要保存图片的功能
    var showSavePicBottomFlag : Bool = false
    
    //是否曾今有过网络
    private var isNetWorkOkBefore : Bool = false
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: YhConstant.YhNotification.didLoginSuccessNotifiction, object: nil)

        NotificationCenter.default.addObserver(self, selector: #selector(updateNetWorkUI), name: .reachabilityChanged, object: nil)
        
        gk_navBarAlpha = 1.0
        gk_navLineHidden = false
        gk_navTitle = vcTitle
        
        if (vcTitle == "香港身份测评码") {
            addRightItems()
        } else {
            printLog("通过ID的逻辑来处理")
        }
        view.backgroundColor = .white
        viewModel = YHHomeWebViewModel()
        //获取导航栏高度
        let navHeight = self.navigationController?.navigationBar.frame.height
        //获取状态栏高度
        let statusHeight = k_Height_statusBar()
        
        // 创建wkwebview
        webview = WKWebView(frame: CGRect(x: 0, y: statusHeight + navHeight!, width: self.view.frame.width, height: self.view.frame.height - statusHeight - navHeight! - 59 - k_Height_safeAreaInsetsBottom()))
        webview.navigationDelegate = self
        // 创建网址
        let url = NSURL(string: url)
        // 创建请求
        let request = NSURLRequest(url: url! as URL)
        // 加载请求
        webview.load(request as URLRequest)
        // 添加wkwebview
        self.view.addSubview(webview)
        
        // 加载网页的进度条
        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)
        
        bottomView = {
            let view = YHHomeWebBottomView()
            view.likeBlock = { [weak self] flag in
                guard let self = self else { return }
                if YHLoginManager.shared.isLogin() == false {
                    YHOneKeyLoginManager.shared.oneKeyLogin()
                    return
                }
                if flag {
                    self.viewModel.getLike(self.id, 1) {[weak self] success, error in
                        guard let self = self else { return }
                        if success {
                            operationFlag = true
                            self.getData()
                        } else {
                            operationFlag = false
                        }
                    }
                } else {
                    self.viewModel.getLike(self.id, 0) {[weak self] success, error in
                        guard let self = self else { return }
                        if success {
                            operationFlag = true
                            self.getData()
                        } else {
                            operationFlag = false
                        }
                    }
                }
            }
            
            view.starBlock = { [weak self] flag in
                guard let self = self else { return }
                if YHLoginManager.shared.isLogin() == false {
                    YHOneKeyLoginManager.shared.oneKeyLogin()
                    return
                }
                if flag {
                    self.viewModel.getStar(self.id, 1) {[weak self] success, error in
                        guard let self = self else { return }
                        if success {
                            operationFlag = true
                            YHHUD.flash(message: "已加入收藏")
                            self.getData()
                        } else {
                            operationFlag = false
                        }
                    }
                } else {
                    self.viewModel.getStar(self.id, 0) {[weak self] success, error in
                        guard let self = self else { return }
                        if success {
                            operationFlag = true
                            self.getData()
                        } else {
                            operationFlag = false
                        }
                    }
                }
            }
            return view
        }()
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(59 + k_Height_safeAreaInsetsBottom())
        }
        
        view.addSubview(noNetWorkTipsView)
        self.noNetWorkTipsView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
        }
        
        if id == 0 {
            if self.url.contains("?id=") {
                let list = self.url.components(separatedBy: "?id=")
                if list.count == 2 {
                    if let iddd = list[1].int {
                        id = iddd
                        getData()
                        updateNetWorkStatusUI(needReload: false)
                        return
                    }
                }
            }
            bottomView.isHidden = true
            webview.frame = CGRect(x: 0, y: statusHeight + navHeight!, width: self.view.frame.width, height: self.view.frame.height - statusHeight - navHeight!)
            if vcTitle != "香港身份测评码" {
                gk_navRightBarButtonItems = []
            }
        }
        
        if showSavePicBottomFlag {
            bottomViewForSavePic.isHidden = false
            view.addSubview(bottomViewForSavePic)
            bottomViewForSavePic.snp.makeConstraints { make in
                make.left.bottom.right.equalToSuperview()
                make.height.equalTo(YHHomeWebViewBottomForSavePicView.viewH)
            }
            
            bottomViewForSavePic.block = { tag in
                self.saveImageToPhotoLib()
            }
            
            webview.frame = CGRect(x: 0, y: statusHeight + navHeight!, width: self.view.frame.width, height: self.view.frame.height - statusHeight - navHeight! - YHHomeWebViewBottomForSavePicView.viewH)
        } else {
            bottomViewForSavePic.isHidden = true
        }
        
        if id > 0 {
            //资讯详情 不展示title
            gk_navTitle = ""
            
        }
        getData()
        updateNetWorkStatusUI(needReload: false)
        
    }
    
    deinit {
        webview.removeObserver(self, forKeyPath: "estimatedProgress")
        NotificationCenter.default.removeObserver(self)
    }
    
    func getData() {
        if id > 0 {
            viewModel.getWebDetail(self.id) {[weak self] success, error in
                guard let self = self else { return }
                if success {
                    guard let model = self.viewModel.mainModel else { return }
                    self.model = model
                    bottomView.likeCount = model.like_count
                    bottomView.starCount = model.collect_count
                    bottomView.isStar = model.is_collect
                    bottomView.isLike = model.is_like
                    
                    if operationFlag {
                        self.block?(model)
                    }
                    
                    
                    if model.img_url.isEmpty == false {
                        self.addRightItems()
                    }
                }
            }
        } else {
            
        }
    }
    
    @objc func share() {
        if YHLoginManager.shared.isLogin() {
            if vcTitle == "香港身份测评码" {
                guard let url = URL(string: url) else {
                    return
                }
                let task = URLSession.shared.dataTask(with: url) { data, response, error in
                    DispatchQueue.main.async {
                        guard let data = data, error == nil else { return }
                        let image = UIImage(data: data)
                        if let image = image {
                            YHShareManager.shared.sendImageContent(image)
                        }
                    }
                }
                task.resume()
            } else {
                guard let url = URL(string: self.model.img_url) else {
                    return
                }
                let task = URLSession.shared.dataTask(with: url) { data, response, error in
                    DispatchQueue.main.async {
                        guard let data = data, error == nil else { return }
                        let image = UIImage(data: data)
                        if let image = image {
                            YHShareManager.shared.sendLinkContent(self.model.title, "", image, link: self.url)
                        }
                    }
                }
                task.resume()
            }
        } else {
            YHOneKeyLoginManager.shared.oneKeyLogin()
        }
    }
    
    @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.getData()
                }
                
                self.isNetWorkOkBefore = true
            }
            
            if self.isNetWorkOkBefore == false {
                self.view.bringSubviewToFront(self.noNetWorkTipsView)
                self.noNetWorkTipsView.isHidden = YHNetworkStatusManager.shared.isNetWorkOK
            } else {
                self.noNetWorkTipsView.isHidden = true
            }
            
            if YHNetworkStatusManager.shared.isNetWorkOK {
                if (self.vcTitle == "香港身份测评码" || !self.model.img_url.isEmpty) {
                    self.addRightItems()
                } else {
                    self.gk_navRightBarButtonItem = nil
                }
            } else {
                self.gk_navRightBarButtonItem = nil
            }
        }
    }
    
    // MARK: - WKNavigationDelegate
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
//        if vcTitle == nil {
//            gk_navTitle = webview.title
//        }
    }
    
    // MARK: - WKUIDelegate
    
    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: - webview function
    
    @objc func toBack() {
        if webview.canGoBack {
            webview.goBack()
        }
    }
    
    @objc func toForward() {
        if webview.canGoForward {
            webview.goForward()
        }
    }
    
    // MARK: - KVO
    
    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 saveImageToPhotoLib() {
        let urlString = self.url
        guard let url = URL(string: urlString) else {
            YHHUD.flash(message: "参数错误,保存失败")
            return
        }
        
        YHHUD.show(.progress(message: "处理中..."))
        let task = URLSession.shared.dataTask(with: url) { data, response, error in
            DispatchQueue.main.async {
                YHHUD.hide()
                guard let data = data, error == nil else { return YHHUD.flash(message: "保存成功") }
                let image = UIImage(data: data)
                if let image = image {
                    // 保存图片到图库
                    PHPhotoLibrary.shared().performChanges({
                        PHAssetChangeRequest.creationRequestForAsset(from: image)
                    }, completionHandler: { success, error in
                        if success {
                            // 图片保存成功
                            DispatchQueue.main.async {
                                YHHUD.flash(message: "保存成功")
                            }
                        } else if let error = error {
                            // 保存失败
                            DispatchQueue.main.async {
                                YHHUD.flash(message: "保存失败")
                            }
                            print("保存图片出错: \(error.localizedDescription)")
                        }
                    })
                }
            }
        }
        task.resume()
    }
    
    @objc func loginSuccess() {
        printLog("登录成功，进行相应的 UI刷新操作")
        getData()
    }
}


extension YHHomeWebViewController {
    
    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
    }
    
    func removeRightItems() {
        gk_navRightBarButtonItems = []
    }
}


