//
//  NetworkManager.swift
//  AIEmoji
//
//  Created by 100Years on 2025/1/16.
//

import Alamofire
import ObjectMapper


let TSNetworkShared = TSNetworkManager.shared

/// 网络工具类
class TSNetworkManager {
    
    static let shared = TSNetworkManager()
    private init() {}
    
    /// 通用 Headers
    private var defaultHeaders: HTTPHeaders {
        return ["Content-Type": "application/json",
                "accept": "application/json",
//            "Authorization": "Bearer YOUR_ACCESS_TOKEN" // 按需修改
        ]
    }
    

    func request(
        method:HTTPMethod,
        urlString: String,
        parameters: [String: any Any & Sendable]? = nil,
        completion: @escaping (Result<Any, Error>) -> Void
    ) {
        dePrint("✈️✈️✈️网络请求:\(urlString)")
        dePrint("✈️✈️✈️参数:\(String(describing: parameters))")
        
        var encoding: ParameterEncoding = URLEncoding.default
        if method == .post {
            encoding = JSONEncoding.default
        }
        let request = AF.request(urlString, method: method, parameters: parameters, encoding: encoding, headers: defaultHeaders, interceptor: nil)
        request.responseString { response in
                self.handleResponse(response, completion: completion)
            }
    }
    
    private func handleResponse(
        _ response: AFDataResponse<String>,
        completion: @escaping (Result<Any, Error>) -> Void
    ) {
        
        switch response.result {
        case .success(let value):
            
            if let resultDict = dataToJSONObject(data:response.data) as? [String:Any] {
                
//                let code = resultDict.safeInt(forKey: "code")
//                if responseType != nil {
//                    if let model = T(JSONString: value) {
//                        handleSuccess(data: model, response: response, completion: completion)
//                    } else {
//                        let models = Mapper<T>().mapArray(JSONString: value)
//                        handleSuccess(data: models ?? [], response: response, completion: completion)
//                    }
//                } else {
                    handleSuccess(data: resultDict, response: response, completion: completion)
//                }
                
            }else{
                handleFail(error: NSError(domain: "Unable to parse data", code: 0), response: response, completion: completion)
            }

        case .failure(let error):
            handleFail(error: error, response: response, completion: completion)
        }
    }
    
    func handleSuccess(data:Any,
                       response: AFDataResponse<String>,
                       completion: @escaping (Result<Any, Error>) -> Void){
        dePrint("🚗🚗🚗网络请求成功:\(String(describing: response.request?.url?.absoluteString))")
        dePrint(response)
        completion(.success(data))
       }
    
    func handleFail(error:Error,
                    response: AFDataResponse<String>,
                    completion: @escaping (Result<Any, Error>) -> Void){
        dePrint("🚗🚗🚗网络请求失败:\(String(describing: response.request?.url?.absoluteString))")
        dePrint(response)
        completion(.failure(error))
    }
    
    func dataToJSONObject(data: Data?) -> Any? {
        guard let data = data else { return nil }
        do {
            let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
            return jsonObject
        } catch {
            print("Failed to convert Data to JSON object: \(error.localizedDescription)")
            return nil
        }
    }
    
}

func kNetWorkResultSuccess(data:Any?) -> [String:Any]? {
    guard let data = data else { return nil }
    if let dataDict = data as? [String:Any] ,
       dataDict.safeInt(forKey: "code") == 200,
       let result = dataDict["result"] as? [String:Any]{
        return result
    }
    return nil
}

func kNetWorkMessage(data:Any?) -> String? {
    guard let data = data else { return nil }
    if let dataDict = data as? [String:Any] ,
       let message = dataDict["message"] as? String{
        return message
    }
    return nil
}

  

class JsonStringTransform<T:Mappable>: TransformType {
    typealias Object = T
    typealias JSON = [String: Any]
    
    func transformFromJSON(_ value: Any?) -> T? {
    
        if let jsonString = value as? String {
            let obj = T(JSONString: jsonString)
            return obj
        }
        
        if let dict = value as? [String: Any] {
            let obj = T(JSON: dict)
            return obj
        }

        return nil
    }
    
    func transformToJSON(_ value: T?) -> [String : Any]? {
        return value?.toJSON() as? [String: Any]
    }
}
