//
//  Extension.swift
//  account_center
//
//  Created by MrQi on 2025/3/12.
//

import Foundation

public extension String {
    
    /// 是否芝麻认证
    var isZmxy: Bool {
        return self == "zmcustprod.zmxy.com.cn"
    }
    
    /// 是否跳转支付宝
    var isAlipays: Bool {
        return self == "alipays"
    }
    
    /// 是否签章结果回调
    var isSign: Bool {
        return hasPrefix("jsbridge://signCallback")
    }
    
    /// 是否实名结果回调
    var isRealname: Bool {
        return hasPrefix("js://tsignRealBack") || hasPrefix("js://signCallBack")
    }
    
    /// 是否加载PDF
    var isLoadPDF: Bool {
        return contains(".pdf") || contains(".PDF")
    }
    
    /// 是否带参数
    var hasQuery: Bool {
        return contains("?")
    }
    
    /// 获取参数
    var query: NSMutableDictionary {
        guard let index = firstIndex(of: "?") else {
            return NSMutableDictionary()
        }
        let startIndex = self.index(index, offsetBy: 1)
        let strParams: String = String(self[startIndex..<endIndex])
        let params = strParams.components(separatedBy: "&")
        let paramsDic: NSMutableDictionary = NSMutableDictionary()
        for string in params {
            let paramItems = string.components(separatedBy: "=")
            if paramItems.count != 2 {
                continue
            }
            paramsDic[paramItems.first!] = paramItems.last
        }
        return paramsDic
    }
    
    /// 是否签章成功
    var isSignSucc: Bool {
        guard var status = query.safeGet(key: "signResult") as? String else {
            return false
        }
        guard let tsignCode = query.safeGet(key: "tsignCode") as? String else {
            return false
        }
        if status.boolValue == false && tsignCode == "0" {
            status = "true"
        }
        return status.boolValue ?? false
    }
    
    /// 是否实名成功
    var isRealnameSucc: Bool {
        guard let passed = query.safeGet(key: "passed") as? String else {
            return false
        }
        return passed.boolValue == true
    }
    
    /// 转换bool值
    var boolValue: Bool? {
        if ["YES","yes","TRUE","true","1"].contains(self) {
            return true
        } else if (["false","FALSE", "no","NO", "0"].contains(self)) {
            return false
        }
        return nil
    }
    
    /// 是否H5消息关闭页面
    var isH5Destroy: Bool {
        return self == "onDestroy"
    }
    
    /// 是否文件下载
    var isDownloadBlob: Bool {
        return self == "downloadBlob"
    }
}

public extension NSMutableDictionary {
    
    func safeGet(key: String) -> Any? {
        guard let allKeys = allKeys as? [String] else { return nil }
        if allKeys.contains(key) {
            return self[key]
        }
        return nil
    }
}
