//
//  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? = nil
}

extension YHJsApi {
    
    // 返回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) {
        
        let dic: [AnyHashable : Any] = [
            "function" : "openUrlWithSafariSyn",
            "payUrl" : payUrl
        ]
        YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
        
        DispatchQueue.main.async {
            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) {
        
        let dic: [AnyHashable : Any] = [
            "function" : "reloadwebVeiwSyn"]
        YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
        
        DispatchQueue.main.async {
            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 : "分享链接"
                         }
                         */
                        if !jsonObject.isEmpty,jsonObject.keys.count == 3 {
                            let shareH5Title : String = jsonObject["ShareH5Title"] as? String ?? ""
                            let shareH5Describe : String = jsonObject["ShareH5Describe"] as? String ?? ""
                            let shareH5Url : String = jsonObject["ShareH5Url"] as? String ?? ""
                            
                            if !shareH5Title.isEmpty,!shareH5Describe.isEmpty,!shareH5Url.isEmpty {
                                if let delegate = self.delegate as? YHH5WebViewVC {
                                    delegate.shareH5Syn(title: shareH5Title, desc: shareH5Describe, url: shareH5Url)
                                }
                            } 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) {
        
        let dic: [AnyHashable : Any] = [
            "function" : "goHomeLifeTabSyn",
        ]
        YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
        
        DispatchQueue.main.async {
            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
                            
                            if isInformationUrl == 1 {
                                //资讯详情
                                let vc = YHHomeWebViewController()
                                vc.id = id
                                vc.url = YHBaseUrlManager.shared.curH5URL() + "articleDetail.html" + "?id=\(id)"
                                self.delegate?.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
                                    self.delegate?.navigationController?.pushViewController(vc)
                                }
                            }
                        } else {
                            printLog("ddddd")
                        }
                    } else {
                        printLog("JSON字符串不是有效的字典格式")
                    }
                } catch {
                    printLog("JSON解析错误: \(error)")
                }
            }
        }
    }
    
    //5、返回App上一个界面
    @objc func backToAppPreView(_ fake : Any) {
        
        let dic: [AnyHashable : Any] = [
            "function" : "backToAppPreView",
        ]
        YHAliYunLogManager.shared.addModuleName(.h5InteractionType, remark: dic)
        
        DispatchQueue.main.async {
            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 {
            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":1])
            }
        }
    }
    
    //调用本地分享
    @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 ?? ""
                            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: String) {
//        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)")
                }
            }
        }
    }
}
