//
//  YHJsApi.swift
//  dsbridgedemo
//
//  Created by du on 2018/9/7.
//  Copyright © 2018年 杜文. All rights reserved.
//

import Foundation
import UIKit
import SafariServices

typealias JSCallback = (String, Bool) -> Void
typealias JSDicCallback = ([String: Any], Bool) -> Void

class YHJsApi: NSObject {
    weak var delegate: YHBaseViewController?
}

extension YHJsApi {
    // 37、查看是否安装了某个应用
    @objc func isSomeAppInstalled(_ tag: String, handler: @escaping (String) -> Void) {
        DispatchQueue.main.async {
            if let url = URL(string: tag), UIApplication.shared.canOpenURL(url) {
                handler("1")
            } else {
                handler("0")
            }
        }
    }
    
    // 32、 H5跳转App智能体会话页面
    @objc func goAgentChatPage(_ dicData: String) {
        DispatchQueue.main.async {
            if let data = dicData.data(using: .utf8) {
                do {
                    if let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                        
                        if let delegate = self.delegate as? YHH5WebViewVC {
                            delegate.goAgentChatPage(dic: jsonObject)
                        }
                        
                    } else {
                        printLog("JSON字符串不是有效的字典格式")
                    }
                } catch {
                    printLog("JSON解析错误: \(error)")
                }
            }
        }
    }
    
    // 31、H5调用原生方法预览文件
    @objc func goPreviewFile(_ url: String) {
        DispatchQueue.main.async {
            let viewModel = YHBaseViewModel()
            viewModel.getRealUsefulUrl(url) { success in
                YHHUD.hide()
                if success.count > 0 {
                    if let delegate = self.delegate as? YHH5WebViewVC {
                        delegate.gotoPreviewTool(urlString: success)
                    } else if let delegate = self.delegate as? YHHomeWebViewController {
                        delegate.gotoPreviewTool(urlString: success)
                    } else {// 这个位置局部变量tool容易被提前释放！！！！，请参考YHH5WebViewVC单独添加
                        let tool = YHFilePreviewTool(targetVC: UIViewController.current)
                        tool.openXLSXRemoteFile(urlString: success, fileName: "")
                    }
                }
            }
            
        }
    }
    
    // 30、跳转到APP底部的服务Tab-再推出服务进度页面
    @objc func goServiceProgressPage(_ tag: Any) {
        
        DispatchQueue.main.async {
            UIViewController.current?.navigationController?.popToRootViewController(animated: false)
            goTabBarBy(tabType: .service)
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
                NotificationCenter.default.post(name: YhConstant.YhNotification.didJumpToServiceProgressNotification, object: nil)
            }
        }
    }
    
    // 29、返回tab服务页
    @objc func goAppTab(_ tag: Any) {
        DispatchQueue.main.async {
            if let tag = tag as? String {
                UIViewController.current?.navigationController?.popToRootViewController(animated: false)
                if tag == "home" {
                    goTabBarBy(tabType: .home)
                    
                } else if tag == "server" {
                    goTabBarBy(tabType: .service)

                } else if tag == "ai" {
                    goTabBarBy(tabType: .AI)

                } else if tag == "friend" {
                    goTabBarBy(tabType: .community)

                } else if tag == "mine" {
                    goTabBarBy(tabType: .mine)
                }
            }
        }
    }
    
    // 禁用全局手势返回
    @objc func disableFullScreenGestureSyn(_ tag: Any) {
        DispatchQueue.main.async {
            if let tag = tag as? String, tag.count == 1 {

                let dic: [AnyHashable: Any] = [
                    "function": "disableFullScreenGestureSyn",
                    "tag": tag]
                YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)

                if let delegate = self.delegate as? YHH5WebViewVC {
                    delegate.disableFullScreenGestureSyn(tag)
                }
            }
        }
    }
    
    // 关闭优才测评
    @objc func closeEvaluationGetResult(_ dicData: String) {
        DispatchQueue.main.async {
            if let data = dicData.data(using: .utf8) {
                do {
                    if let result_dict = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                        var myType = 1
                        var results: [String: Any] = [:]
                        if let type = result_dict["type"] as? Int {
                            myType = type
                        }
                        if let result = result_dict["result"] as? [String: Any] {
                            results = result
                        }
                        if let delegate = self.delegate as? YHH5WebViewVC {
                            
                            delegate.closeEvaluationGetResult(type: myType, dic: results)
                        }
                        
                    } else {
                        printLog("JSON字符串不是有效的字典格式")
                    }
                } catch {
                    printLog("JSON解析错误: \(error)")
                }
            }
        }
    }
    
    // 21、使用safari WebView打开Url
    @objc func openUrlWithSafariSyn(_ payUrl: String) {
        DispatchQueue.main.async {
            let dic: [AnyHashable: Any] = [
                "function": "openUrlWithSafariSyn",
                "payUrl": payUrl
            ]
            YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
            
            if !payUrl.isEmpty, let url = URL(string: payUrl) {
                let safariViewController = SFSafariViewController(url: url)
                safariViewController.dismissButtonStyle = .close
                safariViewController.modalPresentationStyle = .fullScreen
                UIViewController.current?.present(safariViewController, animated: true, completion: nil)
            } else {
                printLog("hjl : 这个url不合法 -- " + payUrl)
            }
        }
    }
    
    // 20、导航栏上是否展示title
    @objc func hideNavigationTitleSyn(_ tag: Any) {
        DispatchQueue.main.async {
            if let tag = tag as? String, tag.count == 1 {
                
                let dic: [AnyHashable: Any] = [
                    "function": "hideNavigationTitleSyn",
                    "tag": tag]
                YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
                
                if let delegate = self.delegate as? YHH5WebViewVC {
                    delegate.hideNavigationTitleSyn(tag)
                }
            }
        }
    }
    
    // 19、返回时刷新界面
    @objc func reloadwebVeiwSyn(_ tag: Any) {
        DispatchQueue.main.async {
            let dic: [AnyHashable: Any] = [
                "function": "reloadwebVeiwSyn"]
            YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
            if let delegate = self.delegate as? YHH5WebViewVC {
                delegate.reloadwebVeiwSyn()
            }
        }
    }
//    //18、导航栏高度 - 安卓还没实现  后续在考虑放出去
//    @objc func appNavigationHeightAsyn(_ arg:Any,handler: @escaping JSCallback) {
//        DispatchQueue.main.async {
//            let height = String(format:"%.2f", k_Height_NavigationtBarAndStatuBar)
//            handler(height, true)
//        }
//    }
    
    // 17、 H5调用app的分享
    @objc func shareH5Syn(_ dicData: String) {
        DispatchQueue.main.async {
            if let data = dicData.data(using: .utf8) {
                do {
                    if let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                        
                        let dic: [AnyHashable: Any] = [
                            "function": "shareH5Syn",
                            "dicData": dicData
                        ]
                        YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
                        
                        // 转换成功，jsonObject 是一个字典
                        print("JSON字符串转换为字典成功: \(jsonObject)")
                        /*
                         
                         {
                             ShareH5Title : "分享标题"
                             ShareH5Describe : "分享描述"
                             ShareH5Url : "分享链接"
                             ShareImgUrl: "图片链接"
                         }
                         */
                        if !jsonObject.isEmpty {
                            let shareH5Title: String = jsonObject["ShareH5Title"] as? String ?? ""
                            let shareH5Describe: String = jsonObject["ShareH5Describe"] as? String ?? ""
                            let shareH5Url: String = jsonObject["ShareH5Url"] as? String ?? ""
                            let shareImageUrl: String? = jsonObject["ShareImgUrl"] as? String
                            
                            if !shareH5Url.isEmpty {
                                if let delegate = self.delegate as? YHH5WebViewVC {
                                    delegate.shareH5Syn(title: shareH5Title, desc: shareH5Describe, url: shareH5Url, shareImageUrl: shareImageUrl)
                                }
                            } else {
                                printLog("参数不合法...")
                            }
                        } else {
                            printLog("ddddd")
                        }
                    } else {
                        printLog("JSON字符串不是有效的字典格式")
                    }
                } catch {
                    printLog("JSON解析错误: \(error)")
                }
            }
        }
    }
    
    // 16、招行聚合支付
    @objc func cmbPaySyn(_ payUrl: String) {
        DispatchQueue.main.async {
//            let tUrl = "https://test-sign.galaxy-immi.com/webPayConfirm?id=dXlHS3RRQUV4QmZ2KzRwM0phRTVyMXdWUnVjUjJvRHdmQmNWVDV0UW1Zbz0="//测试环境
//            let tUrl = "https://beta-sign.galaxy-immi.com/webPayConfirm?id=Qk9sbUlzenp0OGFOdVZ4ekphQXJGWnJ0ODdBS3gxdWNJcURrOHBLbm4xND0%3D"//正式环境
            
            let dic: [AnyHashable: Any] = [
                "function": "cmbPaySyn",
                "payUrl": payUrl
            ]
            YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
            
            if !payUrl.isEmpty, let url = URL(string: payUrl) {
                let safariViewController = SFSafariViewController(url: url)
                safariViewController.dismissButtonStyle = .close
                safariViewController.modalPresentationStyle = .fullScreen
                UIViewController.current?.present(safariViewController, animated: true, completion: nil)
            } else {
                printLog("hjl : 这个url不合法 -- " + payUrl)
            }
        }
    }
    
    // 15、登录带token刷新
    @objc func loginAndRefeshWithTokenSyn(_ tag: Any) {
        DispatchQueue.main.async {
            if let tag = tag as? String, tag.count == 1 {
                
                let dic: [AnyHashable: Any] = [
                    "function": "loginAndRefeshWithTokenSyn",
                    "tag": tag
                ]
                YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
                
                if let delegate = self.delegate as? YHH5WebViewVC {
                    delegate.loginAndRefeshWithTokenSyn(tag)
                }
            }
        }
    }
    
    // 14、是否隐藏导航栏  "0"-默认不隐藏  “1”-隐藏
    @objc func hideNavigationBarSyn(_ tag: Any) {
        DispatchQueue.main.async {
            if let tag = tag as? String, tag.count == 1 {
                
                let dic: [AnyHashable: Any] = [
                    "function": "hideNavigationBarSyn",
                    "tag": tag
                ]
                YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
                
                if let delegate = self.delegate as? YHH5WebViewVC {
                    delegate.hideNavigationBarSyn(tag)
                }
            }
        }
    }
    
    // 13、是否支持通屏
    @objc func supportFullScreenSyn(_ tag: Any) {
        DispatchQueue.main.async {
            if let tag = tag as? String, tag.count == 1 {
                
                let dic: [AnyHashable: Any] = [
                    "function": "supportFullScreenSyn",
                    "tag": tag
                ]
                YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
                
                if let delegate = self.delegate as? YHH5WebViewVC {
                    delegate.supportFullScreenSyn(tag)
                }
            }
        }
    }
    
    // 12、webView内支持内部一级一级返回
    @objc func supportInnerBackSyn(_ tag: Any) {
        DispatchQueue.main.async {
            if let tag = tag as? String, tag.count == 1 {
                
                let dic: [AnyHashable: Any] = [
                    "function": "supportInnerBackSyn",
                    "tag": tag
                ]
                YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
                
                if let delegate = self.delegate as? YHH5WebViewVC {
                    delegate.supportInnerBackSyn(tag)
                }
            }
        }
    }
    
    // 11、设置导航栏返回按钮颜色
    @objc func setNavigationBackColor(_ color: Any) {
        DispatchQueue.main.async {
            if let color = color as? String, color.count == 1 {
                
                let dic: [AnyHashable: Any] = [
                    "function": "setNavigationBackColor",
                    "color": color
                ]
                YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
                
                if let delegate = self.delegate as? YHH5WebViewVC {
                    delegate.setNavigationBackColor(color)
                }
            }
        }
    }
    
    // 10、拨打电话
    @objc func appCallPhoneSyn(_ phoneNumber: Any) {
        DispatchQueue.main.async {
            if let phone = phoneNumber as? String, phone.count > 0 {
                
                let dic: [AnyHashable: Any] = [
                    "function": "appCallPhoneSyn",
                    "phone": phone
                ]
                YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
                
                if let url = URL(string: "tel://\(phone)"), UIApplication.shared.canOpenURL(url) {
                   UIApplication.shared.open(url, options: [:], completionHandler: nil)
               } else {
                   print("无法拨打电话")
               }
            }
        }
    }
    
    // 9、跳转资讯列表页
    @objc func goNewsInformationListUISyn(_ dicData: String) {
        DispatchQueue.main.async {
            if let data = dicData.data(using: .utf8) {
                do {
                    if let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                        
                        let dic: [AnyHashable: Any] = [
                            "function": "goNewsInformationListUISyn",
                            "dicData": dicData
                        ]
                        YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
                        
                        // 转换成功，jsonObject 是一个字典
                        print("JSON字符串转换为字典成功: \(jsonObject)")
                        /*
                         {
                         id:1,
                         name:"教学升学",
                         hot_num: 1.    //  顶部栏目数量（最新，精品）
                         }
                         */
                        if !jsonObject.isEmpty {
                            let name: String = jsonObject["name"] as? String ?? ""
                            let id: Int = jsonObject["id"] as? Int ?? -1
                            let hot_num: Int = jsonObject["hot_num"] as? Int ?? 0
                            if id > 0 {
                                let vc = YHHomeInfoDetailContainerViewController()
                                vc.title = name
                                vc.customTitle = name
                                vc.isHaveHot = hot_num > 0
                                vc.classifyId = id
                                UIViewController.current?.navigationController?.pushViewController(vc)
                            }
                        } else {
                            printLog("ddddd")
                        }
                    } else {
                        printLog("JSON字符串不是有效的字典格式")
                    }
                } catch {
                    printLog("JSON解析错误: \(error)")
                }
            }
        }
    }
    
    // 8、跳转案例分享UI
    @objc func goCaseShareUISyn(_ caseId: Any) {
        DispatchQueue.main.async {
            if let sId = caseId as? String, let id = Int(sId) {
                
                let dic: [AnyHashable: Any] = [
                    "function": "goCaseShareUISyn",
                    "id": id
                ]
                YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
                
                let vc = YHResignGuidelinesExampleViewController()
                vc.id = id
                self.delegate?.navigationController?.pushViewController(vc)
            }
        }
    }
    
    // 7、跳转 首页-生活 tab
    @objc func goHomeLifeTabSyn(_ fake: Any) {
        DispatchQueue.main.async {
            let dic: [AnyHashable: Any] = [
                "function": "goHomeLifeTabSyn"
            ]
            YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
            
            UIViewController.current?.navigationController?.popToRootViewController(animated: false)
            goTabBarBy(tabType: .home)
            NotificationCenter.default.post(name: YhConstant.YhNotification.didJumpToHomePageLifeTabNotification, object: nil)
            
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
                NotificationCenter.default.post(name: YhConstant.YhNotification.didJumpToHomePageLifeEduTabNotification, object: nil)
            }
        }
    }
    
    // 6、跳转H5界面
    @objc func goH5UISyn(_ dicData: String) {
        DispatchQueue.main.async {
            if let data = dicData.data(using: .utf8) {
                do {
                    if let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                        
                        let dic: [AnyHashable: Any] = [
                            "function": "goH5UISyn",
                            "dicData": dicData
                        ]
                        YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
                        
                        // 转换成功，jsonObject 是一个字典
                        print("JSON字符串转换为字典成功: \(jsonObject)")
                        /*
                         url:跳转地址
                         isInformationUrl:1, //1-资讯类型 0-非资讯类型
                         id：1   // 资讯id
                         isFullScreen: 1,// 1-通屏 0-非通屏
                         */
                        
                        if !jsonObject.isEmpty {
                            let url: String = jsonObject["url"] as? String ?? ""
                            let isInformationUrl: Int = jsonObject["isInformationUrl"] as? Int ?? 0
                            let id: Int = jsonObject["id"] as? Int ?? -1
                            let isFullScreen: Int = jsonObject["isFullScreen"] as? Int ?? 1
                            let navTitle: String = jsonObject["navTitle"] as? String ?? ""
                            let hideNavigationTitleFlag: Int = jsonObject["hideNavigationTitleFlag"] as? Int ?? 0
                            let closeCurrentView: Int = jsonObject["closeCurrentView"] as? Int ?? 0
                            
                            if isInformationUrl == 1 {
                                // 资讯详情
                                let vc = YHHomeWebViewController()
                                vc.id = id
                                vc.url = YHBaseUrlManager.shared.curH5URL() + "articleDetail.html" + "?id=\(id)"
                                if let navigationController = UIViewController.current?.navigationController, closeCurrentView == 1, (navigationController.viewControllers.count) > 1 {
                                    var viewControllers = navigationController.viewControllers
                                    viewControllers.removeLast()
                                    viewControllers.append(vc)
                                    navigationController.setViewControllers(viewControllers, animated: true)
                                } else {
                                    UIViewController.current?.navigationController?.pushViewController(vc)
                                }
                            } else {
                                // 普通界面
                                if !url.isEmpty {
                                    var tUrl = url
                                    if !url.contains("navigationH=") {
                                        tUrl = url + "?navigationH=\(k_Height_NavigationtBarAndStatuBar)"
                                        if url.contains("?") {
                                            tUrl = url + "&navigationH=\(k_Height_NavigationtBarAndStatuBar)"
                                        }
                                    }
                                    
                                    if YHLoginManager.shared.isLogin() {
                                        if !url.contains("param=") {
                                            let token = YHLoginManager.shared.h5Token
                                            tUrl = tUrl + "&param=" + token
                                        }
                                    }
                                    
                                    let vc = YHH5WebViewVC()
                                    vc.url = tUrl
                                    vc.isFullScreenFlag = isFullScreen == 1 ? true : false
                                    vc.showNavigationTitleFlag = hideNavigationTitleFlag == 0 ? true : false
                                    vc.navTitle = navTitle
                                    if let navigationController = UIViewController.current?.navigationController, closeCurrentView == 1, (navigationController.viewControllers.count) > 1 {
                                        var viewControllers = navigationController.viewControllers
                                        viewControllers.removeLast()
                                        viewControllers.append(vc)
                                        navigationController.setViewControllers(viewControllers, animated: true)
                                    } else {
                                        UIViewController.current?.navigationController?.pushViewController(vc)
                                    }
                                }
                            }
                        } else {
                            printLog("ddddd")
                        }
                    } else {
                        printLog("JSON字符串不是有效的字典格式")
                    }
                } catch {
                    printLog("JSON解析错误: \(error)")
                }
            }
        }
    }
    
    // 5、返回App上一个界面
    @objc func backToAppPreView(_ fake: Any) {
        
        DispatchQueue.main.async {
            let dic: [AnyHashable: Any] = [
                "function": "backToAppPreView"
            ]
            YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
            
            if let delegate = self.delegate as? YHH5WebViewVC {
                delegate.backToAppPreView()
            }
        }
    }
    
    // 4、设置app导航栏隐藏、显示
    @objc func setAppNavigation(_ tag: Any) {
        DispatchQueue.main.async {
            let tmp: Bool = tag as? Bool ?? false
            
            let dic: [AnyHashable: Any] = [
                "function": "setAppNavigation",
                "tag": tmp
            ]
            YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
            
            if let delegate = self.delegate as? YHH5WebViewVC {
                delegate.setAppNavigation(tmp)
            }
            
        }
    }
    
    // 3、跳转到 办证3 - 赴港时间预约界面
    @objc func gotoAppointCertificateSyn(_ orderID: String) {
        DispatchQueue.main.async {
            if let orderId = Int(orderID) {
                
                let dic: [AnyHashable: Any] = [
                    "function": "gotoAppointCertificateSyn",
                    "orderID": orderId
                ]
                YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
                
                let vc = YHCertificateAppointViewController()
                vc.orderId = orderId
                self.delegate?.navigationController?.pushViewController(vc)
            }
        }
    }
    
    // 2、展示图片组
    @objc func showPicsSyn(_ dicData: String) {
        DispatchQueue.main.async {
            if let data = dicData.data(using: .utf8) {
                do {
                    if let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                        
                        let dic: [AnyHashable: Any] = [
                            "function": "gotoAppointCertificateSyn",
                            "dicData": dicData
                        ]
                        YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
                        
                        // 转换成功，jsonObject 是一个字典
                        print("JSON字符串转换为字典成功: \(jsonObject)")
                        
                        if !jsonObject.isEmpty {
                            let curIndex: Int = jsonObject["curIndex"] as? Int ?? -1
                            let arrPics: [String] = jsonObject["pics"] as? [String] ?? []
                            if curIndex > -1, arrPics.count > 0 {
                                YHPictureReviewManager.shared.showNetWorkPicturs(curIndex: curIndex, arrPicturs: arrPics)
                            }
                        } else {
                            printLog("ddddd")
                        }
                    } else {
                        printLog("JSON字符串不是有效的字典格式")
                    }
                } catch {
                    printLog("JSON解析错误: \(error)")
                }
            }
        }
    }
    
    // 1、保存图片到本地
    @objc func saveLocalPictureSyn(_ picUrl: String) {
        DispatchQueue.main.async {
            
            let dic: [AnyHashable: Any] = [
                "function": "saveLocalPictureSyn",
                "picUrl": picUrl
            ]
            YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
            
            if let delegate = self.delegate as? YHH5WebViewVC {
                delegate.saveLocalPictureSyn(picUrl)
            }
        }
    }
    
    // 1.保存base64图片格式到本地
    @objc func savePicToLocal(_ data: String) {
        DispatchQueue.main.async {
            if let delegate = self.delegate as? YHH5WebViewVC {
                delegate.savePicToLocal(data)
            }
        }
    }
    
    // 23.返回 银河甄选
    @objc func backToHomeIndex(_ index: Any) {
        DispatchQueue.main.async {
            let value: Int = index as? Int ?? 1

            UIViewController.current?.navigationController?.popToRootViewController(animated: false)
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
                UIViewController.current?.tabBarController?.selectedIndex = 0
                NotificationCenter.default.post(name: YhConstant.YhNotification.backToHomeNotification, object: nil, userInfo: ["value": value])
            }
        }
    }
    
    // 调用本地分享
    @objc func openShareView(_ dicData: String) {
        DispatchQueue.main.async {
            if let data = dicData.data(using: .utf8) {
                do {
                    if let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                        if !jsonObject.isEmpty {
                            let shareH5Title: String = jsonObject["ShareH5Title"] as? String ?? ""
                            let shareH5Describe: String = jsonObject["ShareH5Describe"] as? String ?? ""
                            let shareH5Url: String = jsonObject["ShareH5Url"] as? String ?? ""
                            let contentUrl: String = jsonObject["ContentUrl"] as? String ?? ""
                            
                            let realUrl: String = shareH5Url.replacingOccurrences(ofPattern: "#", withTemplate: "")
//                            var realUrl : String = "https://test-hklife.galaxy-immi.com/superAppBridge.html/goods/sales-detail?id=73"
                            if !realUrl.isEmpty {
                                if let url = URL(string: realUrl) {
                                    let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
                                    if let queryItems = components?.queryItems {
                                        var arrItems: [String: Any] = [:]
                                        for item in queryItems {
                                            if let value = item.value {
                                                arrItems.updateValue(value, forKey: item.name)
                                            }
                                        }
                                        
                                        if !arrItems.keys.isEmpty {
                                            let id: String = arrItems["id"] as? String ?? ""
                                            let shareYinheID: String = arrItems["shareYinheID"] as? String ?? ""
                                            
                                            print(id)
                                            print(shareYinheID)
                                            let tParam =  ["id": id, "shareYinheID": shareYinheID]
                                            
                                            YHShareManager.shared.createMutilShareShortUrl(type: 4, param: tParam) { shortUrl, _ in
                                
                                                if let url = shortUrl {
                                                    let tmpT = url.base64Encoded ?? ""// 对deepLink使用 base64编码
                                                    var oldUrl = shareH5Url
                                                    if oldUrl.contains("?") {
                                                        oldUrl += "&appDeepLink=\(tmpT)"
                                                    } else {
                                                        oldUrl += "?appDeepLink=\(tmpT)"
                                                    }
                                                    
                                                    DispatchQueue.main.async {
                                                        YHShareAlertView.show(image: contentUrl, title: shareH5Title, subMessage: shareH5Describe, linkUrl: oldUrl, isLive: false)
                                                    }
                                                    return
                                                }
                                                DispatchQueue.main.async {
                                                    YHShareAlertView.show(image: contentUrl, title: shareH5Title, subMessage: shareH5Describe, linkUrl: shareH5Url, isLive: false)
                                                }
                                                return
                                            }
                                            return
                                        }
                                    }
                                }
                            }
                            
                            YHShareAlertView.show(image: contentUrl, title: shareH5Title, subMessage: shareH5Describe, linkUrl: shareH5Url, isLive: false)
                        } else {
                            printLog("ddddd")
                        }
                    } else {
                        printLog("JSON字符串不是有效的字典格式")
                    }
                } catch {
                    printLog("JSON解析错误: \(error)")
                }
            }
        }
    }
    
    @objc func closeSmallWindow(_ tag: Any) {
//        DispatchQueue.main.async {
//            YHPlayerManager.shared.exitFloating()
//        }
    }
    
    // 跳直播录播
    @objc func openLivePage(_ dicData: String) {
        DispatchQueue.main.async {
            if let data = dicData.data(using: .utf8) {
                do {
                    if let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                        if !jsonObject.isEmpty {
                            // 1=>直播 2=>录播
                            let type: Int = jsonObject["type"] as? Int ?? -1
                            let id: String = jsonObject["id"] as? String ?? ""
                            if type == -1 || id == "" {
                                return
                            }
                            if type == 1 {
                                let playbackInfo = YHPlayerManager.PlaybackInfo(id: id.intValue(), isLive: true, isFromSaleDetail: true)
                                YHPlayerManager.shared.enterLive(from: nil, playbackInfo: playbackInfo)
                            } else if type == 2 {
                                let playbackInfo = YHPlayerManager.PlaybackInfo(id: id.intValue(), isLive: false, isFromSaleDetail: true)
                                YHPlayerManager.shared.enterVOD(from: nil, playbackInfo: playbackInfo)
                            }
                            
                        } else {
                            printLog("ddddd")
                        }
                    } else {
                        printLog("JSON字符串不是有效的字典格式")
                    }
                } catch {
                    printLog("JSON解析错误: \(error)")
                }
            }
        }
    }
    
    @objc func goServiceByOrderId(_ tag: String) {
        DispatchQueue.main.async {
            UIViewController.current?.navigationController?.popToRootViewController(animated: false)
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
                UIViewController.current?.tabBarController?.selectedIndex = 1
                NotificationCenter.default.post(name: YhConstant.YhNotification.didJumpToServiceProgressNotification, object: nil, userInfo: ["value": tag])
            }
        }
    }
    
    // 34 H5跳转App 联系客服 跳转坐席，注意⚠️空串时候用Any接收
    @objc func goQiyuService(_ tag: Any) {
        DispatchQueue.main.async {
            guard let userId = YHLoginManager.shared.userModel?.id, userId.count > 0, let navigationController = UIViewController.current?.navigationController else {
                return
            }
            YHHUD.show(.progress(message: "加载中..."))
            YHButlerServiceManager.shared.gotoButlerServiceSessionVC(navigationController: navigationController, completion: { _ in
                YHHUD.hide()
            })
        }
    }
    
    @objc func jumpToBrowser(_ url: String) {
        DispatchQueue.main.async {
            if let url = URL(string: url) {
                if UIApplication.shared.canOpenURL(url) {
                    UIApplication.shared.open(url) { success in
                        if success {
                            printLog("成功打开URL")
                        } else {
                            printLog("无法打开URL")
                        }
                    }
                } else {
                    printLog("无法处理此URL")
                }
            } else {
                printLog("URL格式错误")
            }
        }
    }
    
    @objc func goServiceStatus(_ status: Any) {
        DispatchQueue.main.async {
            UIViewController.current?.navigationController?.popToRootViewController(animated: false)
            goTabBarBy(tabType: .service)
        
            let value: String = status as? String ?? "0"
            NotificationCenter.default.post(name: YhConstant.YhNotification.didJumpToServicePageSwitchIndexNotification, object: nil, userInfo: ["status": value])
            
        }
    }
}
