//
//  SYCodeable.swift
//  WaterRecord
//
//  Created by apple on 2024/9/27.
//

import Foundation


struct SYCodeable{
    // 模型转字典
    static func modelToDictionary<T: Codable>(_ model: T) -> [String: Any]? {
        do {
            let jsonEncoder = JSONEncoder()
            let jsonData = try jsonEncoder.encode(model)
            if let dictionary = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                return dictionary
            }
        } catch {
            print("Error: \(error)")
        }
        return nil
    }

    // 模型数组转字典数组
    static  func modelsToDictionaries<T: Codable>(_ models: [T]) -> [[String: Any]] {
        var dictionaries: [[String: Any]] = []
        for model in models {
            if let dict = modelToDictionary(model) {
                dictionaries.append(dict)
            }
        }
        return dictionaries
    }

    /// 字典转模型
    static  func decode<T: Codable>(_ dictionary: [String: Any], modelType: T.Type) -> T? {
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: dictionary, options: [])
            let model = try JSONDecoder().decode(modelType, from: jsonData)
            return model
        } catch {
            print("解析 JSON 数据失败：\(error.localizedDescription)")
            return nil
        }
    }

    /// 字典数组转模型数组
    static func decodeArray<T: Codable>(_ dictionaries: [[String: Any]], modelType: T.Type) -> [T] {
        var models: [T] = []
        
        for dictionary in dictionaries {
            if let model = decode(dictionary, modelType: modelType) {
                models.append(model)
            }
        }
        
        return models
    }

    // 将字典转换为 JSON 字符串的函数
    static  func convertDictionaryToJSON(dictionary: [String: String]) -> String? {
        do {
            // 将字典转换为 Data 对象
            let jsonData = try JSONSerialization.data(withJSONObject: dictionary, options: [])
            
            // 将 Data 对象转换为字符串
            let jsonString = String(data: jsonData, encoding: .utf8)
            return jsonString
        } catch {
            print("字典转换为 JSON 时出错: \(error.localizedDescription)")
            return nil
        }
    }


    // 将 JSON 字符串转换为字典的函数
    static  func convertJSONToDictionary(jsonString: String) -> [String: Any]? {
        // 将 JSON 字符串转换为 Data 对象
        guard let jsonData = jsonString.data(using: .utf8) else {
            print("无法将字符串转换为 Data")
            return nil
        }
        
        do {
            // 将 Data 对象转换为字典
            if let dictionary = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                return dictionary
            } else {
                print("转换为字典失败，类型不匹配")
                return nil
            }
        } catch {
            print("JSON 转换为字典时出错: \(error.localizedDescription)")
            return nil
        }
    }

    /// 将 JSON 字符串转换为指定类型的模型
    /// - Parameters:
    ///   - jsonString: JSON 字符串
    ///   - modelType: 要转换的模型类型
    /// - Returns: 转换后的模型实例或 nil
    static  func convertJsonToModel<T: Codable>(jsonString: String, modelType: T.Type) -> T? {
        // 将 JSON 字符串转换为 Data
        guard let jsonData = jsonString.data(using: .utf8) else {
            print("转换字符串为 Data 失败")
            return nil
        }
        
        do {
            // 使用 JSONDecoder 解析 JSON 数据
            let model = try JSONDecoder().decode(T.self, from: jsonData)
            return model
        } catch {
            print("解析 JSON 失败: \(error)")
            return nil
        }
    }

}
