//
//  QSLTools.swift
//  QuickSearchLocation
//
//  Created by Destiny on 2025/10/28.
//

import UIKit

class QSLTools: NSObject {
    
    static let shared = QSLTools()
    var isOpen = false
    var urlScheme = ""
}

extension QSLTools {

    /// 获取设备令牌
    func getDeviceToken() -> String {
        if let token = UserDefaults.standard.string(forKey: "deviceToken") {
            return token
        } else {
            return ""
        }
    }
    
    
    func dealwithScheme(_ scheme: String) {
        // 将字符串转换为 URL 对象
        guard let url = URL(string: scheme) else {
            print("无效的 URL scheme")
            return
        }
        
        // 检查 scheme 是否为 location
        guard url.scheme == "location" else {
            print("不支持的 scheme 类型")
            return
        }
        
        if #available(iOS 16.0, *) {
            let host = url.host()
            let pathComponents = url.lastPathComponent
            let query = url.query()
            jumpToPath(path: host ?? "", pathName: pathComponents, param: query ?? "")
        } else {
            let currentPath = scheme.replacingOccurrences(of: "location://", with: "")
            let pathComponents = url.lastPathComponent
            let queryList = currentPath.components(separatedBy: "?")
            if(queryList.count > 1){
                let host = currentPath.replacingOccurrences(of: pathComponents, with: "").replacingOccurrences(of: "/", with: "")
                let query = currentPath.replacingOccurrences(of: host, with: "")
                jumpToPath(path: host, pathName: pathComponents.replacingOccurrences(of: "/", with: ""), param: query)
            }else{
                let host = currentPath.replacingOccurrences(of: pathComponents, with: "").replacingOccurrences(of: "/", with: "")
                jumpToPath(path: host, pathName: pathComponents.replacingOccurrences(of: "/", with: ""), param: "")
            }
        }

    }
    
    func jumpToPath(path:String, pathName:String, param:String = ""){
        if path == "dialog" {
            let dialogType = pathName
            
            switch dialogType {
            case "member_trial":
                QSLJumpManager.shared.pushToVipTrail(type: .notiPush)
                break;
            default:
                print("未知的对话框类型: \(dialogType)")
            }
        }else if path == "page" {
            if(pathName == "QSLVipController"){
                QSLJumpManager.shared.pushToVip(type: .shortcut)
                return
            }
            let controllerName = pathName
            navigateToViewController(controllerName)
        }else if path == "shortcut" {
            if(pathName == "com.manbu.shouji.member_or_trial"){
                checkMemeberOrTrial()
                return
            }
          
        }else{
            print("未知的路径类型")
        }
    }
    
    func checkMemeberOrTrial(){
        QSLNetwork().request(.wakeUpPressCheck(dict: [String: Any]())) { response in
            let model: QSLWakeupModel = response.mapObject(QSLWakeupModel.self, modelKey: "data")
            var scheme = "location://page/QSLVipController"
            if(model.functionType == "trial"){
                scheme = "location://page/QSLVipTrialVC"
            }
            if(QSLTools.shared.isOpen){
                //处理urlScheme
                QSLTools.shared.urlScheme = ""
                QSLTools.shared.dealwithScheme(scheme)
                return
            }
            
            QSLTools.shared.urlScheme = scheme
        } fail: { code, msg in
           
        }
    }
    
    func navigateToViewController(_ controllerName: String) {
        
        // 获取命名空间（Swift 类名通常是 "YourAppName.ViewController"）
        let namespace = Bundle.main.infoDictionary?["CFBundleExecutable"] as? String ?? ""
        let fullClassName = "\(namespace).\(controllerName)"
        
        // 通过类名创建控制器实例
        guard let controllerClass = NSClassFromString(fullClassName) as? UIViewController.Type else {
            print("找不到控制器类: \(controllerName)")
            return
        }
        
        let viewController = controllerClass.init()
        self.rootViewController()?.pushVC(vc: viewController)
    }
    
    func requestShortcutItem(){
        //判断登录过没有
        if QSLBaseManager.shared.isLogin() {
            var isAttr = false
            if((UserDefaults.standard.value(forKey: "QSAttribution")) != nil){
                if let attr = UserDefaults.standard.value(forKey: "QSAttribution") as? Bool {
                    isAttr = attr
                }
            }
            QSLNetwork().request(.wakeUpPressInfo(dict: ["attribution":isAttr])) { response in
                let model: QSLWakeupModel = response.mapObject(QSLWakeupModel.self, modelKey: "data")
                var iconName = "mine_func_gift"
                if(model.functionType == "feedback"){
                    iconName = "mine_func_advice"
                }
                self.setupShortcutItem(typeName: model.functionType, title: model.title, subTitle: model.subTitle, icon: iconName)
                
            } fail: { code, msg in
                
            }
        }
    }
    
    func setupShortcutItem(typeName:String, title: String, subTitle:String, icon:String ){
        let shortcutItem = UIApplicationShortcutItem(
            type: "com.manbu.shouji." + typeName,
            localizedTitle: title,
            localizedSubtitle: subTitle,
            icon: UIApplicationShortcutIcon(templateImageName: icon),
            userInfo: nil
        )
        UIApplication.shared.shortcutItems = [shortcutItem]
    }
    
}
