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

import UIKit
@preconcurrency import WebKit
import Photos
import dsBridge

class YHHomeWebViewController: YHBaseViewController, WKUIDelegate, WKNavigationDelegate {
    var  operationFlag: Bool = false
    let api = YHJsApi()
    typealias Block = (YHWebModel) -> Void
    var block: Block?
    
    var viewModel: YHHomeWebViewModel!
//    var webview = DWKWebView()
    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.scrollView.delegate = self
        
        webview.setDebugMode(false)
//        webview.uiDelegate = self
        
        return webview
    }()
    
    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 vm: YHHomePageViewModel = {
        let vm = YHHomePageViewModel()
        return vm
    }()
    
    lazy var noNetWorkTipsView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("无网络", kNotNetWorkBgName)
        view.topMargin = 222
        view.backgroundColor = .white
        view.isHidden = true
        return view
    }()
    
    lazy var consultView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 10, width: 34.0+10.0+60.0, height: 34.0))
        
        let headImgView = UIImageView(image: UIImage(named: "home_web_consult_avatar"))
        view.addSubview(headImgView)
        
        let label = UILabel()
        label.text = "咨询顾问".local
        label.textColor = UIColor.mainTextColor
        label.textAlignment = NSTextAlignment.left
        label.font = UIFont.PFSC_M(ofSize: 14)
        view.addSubview(label)
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(didConsultViewTapped))
        view.addGestureRecognizer(tap)
        
        headImgView.snp.makeConstraints { make in
            make.width.height.equalTo(34)
            make.left.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        label.snp.makeConstraints { make in
            make.height.equalTo(20)
            make.left.equalTo(headImgView.snp.right).offset(10)
            make.centerY.equalToSuperview()
        }
        return view
    }()
    
    lazy var previewFileTool: YHFilePreviewTool = {
       let tool = YHFilePreviewTool(targetVC: self)
       return tool
    }()
    
    // 有些界面需要保存图片的功能
    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 = DWKWebView(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
        webview.setDebugMode(false)
        webview.scrollView.contentInsetAdjustmentBehavior = .never
        
        api.delegate = self
        webview.addJavascriptObject(api, namespace: nil)
        
        if url.contains("?") {
            url = self.url + "&uid=\(YHLoginManager.shared.userModel?.id ?? "0")"
        } else {
            url = self.url + "?uid=\(YHLoginManager.shared.userModel?.id ?? "0")"
        }
        
        if !url.contains("yhid=") {
            let id = YHLoginManager.shared.userModel?.id ?? ""
            if url.contains("?") {
                url += "&yhid=\(id)"
            } else {
                url += "?yhid=\(id)"
            }
        }
        
        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: 有问题")
            }
        }
        webview.frame = CGRect(x: 0, y: statusHeight + navHeight!, width: self.view.frame.width, height: self.view.frame.height - statusHeight - navHeight! - 59 - k_Height_safeAreaInsetsBottom())
        // 添加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.addSubview(self.consultView)
            self.consultView.snp.makeConstraints { make in
                make.left.equalTo(20.0)
                make.top.equalTo(12.5)
                make.width.equalTo(105.0)
                make.height.equalTo(34.0)
            }
            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, _ 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, _ 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, _ 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, _ 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 = { _ 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)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)),
                                               name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)),
                                               name: UIResponder.keyboardWillHideNotification, object: nil)
        
    }
    
    deinit {
        webview.removeObserver(self, forKeyPath: "estimatedProgress")
        NotificationCenter.default.removeObserver(self)
    }
    
    func getData() {
        if id > 0 {
            viewModel.getWebDetail(self.id) {[weak self] success, _ 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 !YHNetworkStatusManager.shared.isNetWorkOK {
            YHHUD.flash(message: "网络不可用，请检查网络设置")
            return
        }
        
        if YHLoginManager.shared.isLogin() {
            if vcTitle == "香港身份测评码" {
                guard let url = URL(string: url) else {
                    return
                }
                let task = URLSession.shared.dataTask(with: url) { data, _, 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 param = ["share_channel": 1, "article_id": id]
                vm.postShareInfo(params: param) { success, _ in
                    if success {
                        
                    } else {
                        
                    }
                }
                
                let task = URLSession.shared.dataTask(with: url) { data, _, error in
                    DispatchQueue.main.async {
                        guard let data = data, error == nil else { return }
                        let image = UIImage(data: data)
                        if let image = image {
                            let url = self.url + "&appShare=1" + "&isShare=1" + "&fromPlatform=iOS" + "&uid=\(YHLoginManager.shared.userModel?.id ?? "0")" + "&article_id=\(self.id)"
                            YHShareManager.shared.sendLinkContent(self.model.title, "", image, link: 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()
                    if let targetUrl = URL(string: self.url) {
                        let request = URLRequest(url: targetUrl)
                        self.webview.load(request)
                    }
                    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
            }
        }
    }
    
    func gotoPreviewTool(urlString: String) {
        previewFileTool.openXLSXRemoteFile(urlString: urlString, fileName: "")
    }
    
    @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
    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: - 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: { () in
                    self.progBar.alpha = 0.0
                }, completion: { (_: Bool) 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, _, 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 didConsultViewTapped() {
        let codeUrl = self.viewModel.mainModel?.clue_classify_img_url ?? ""
        let downloadUrl = self.viewModel.mainModel?.clue_classify_img_url_download ?? ""
        YHConsultantQRCodeView.codeView(codeUrl, downloadUrl: downloadUrl).show()
        YHAnalytics.track("consultantClick", properties: ["url": url])

    }
    
    @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
    }
}
