//
//  SaleUserQrParser.swift
//  suixinkan
//

import Foundation

/// 获客员二维码解析，对齐 Android `SaleUserQrParser`。
enum SaleUserQrParser {
    static let methodSaleUserBind = "sale_user_bind"

    static func parseSaleUserId(_ content: String) -> Int? {
        let trimmed = content.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmed.isEmpty else { return nil }

        if trimmed.hasPrefix("{"), let data = trimmed.data(using: .utf8),
           let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
            if let fromMethod = parseFromJSON(json) { return fromMethod }
        }

        if let intValue = Int(trimmed), intValue > 0 { return intValue }

        if trimmed.contains("://") || trimmed.contains("?"),
           let components = URLComponents(string: trimmed) {
            for key in ["sale_user_id", "saleUserId", "user_id", "id"] {
                if let value = components.queryItems?.first(where: { $0.name == key })?.value,
                   let intValue = Int(value), intValue > 0 {
                    return intValue
                }
            }
        }

        return nil
    }

    private static func parseFromJSON(_ json: [String: Any]) -> Int? {
        if let method = json["method"] as? String, method == methodSaleUserBind,
           let id = readInt(json["sale_user_id"]), id > 0 {
            return id
        }
        for key in ["sale_user_id", "saleUserId", "user_id", "id"] {
            if let id = readInt(json[key]), id > 0 { return id }
        }
        return nil
    }

    private static func readInt(_ value: Any?) -> Int? {
        if let intValue = value as? Int { return intValue }
        if let stringValue = value as? String, let intValue = Int(stringValue.trimmingCharacters(in: .whitespacesAndNewlines)) {
            return intValue
        }
        if let doubleValue = value as? Double { return Int(doubleValue) }
        return nil
    }
}
