//
//  HttpRequest.swift
//  Weather
//
//  Created by apple on 2024/9/23.
//

import Foundation


struct HttpRequest{
    
    static func getFormData<T:Codable>(to urlString: String, completion: @escaping (Result<T, Error>) -> Void) {
        // 设置请求的 URL
        guard let urlComponents = URLComponents(string: urlString) else {
            completion(.failure(NSError(domain: "Invalid URL", code: 101, userInfo: nil)))
            return
        }

        // 创建 URL 请求
        guard let url = urlComponents.url else {
            completion(.failure(NSError(domain: "Invalid URL Components", code: 102, userInfo: nil)))
            return
        }

        // 创建 URLRequest 对象
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        print("请求地址",url.absoluteString)
        
        // 执行网络请求
        let session = URLSession.shared
        let task = session.dataTask(with: request) { data, response, error in
            // 处理错误
            if let error = error {
                print("Error in request: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    completion(.failure(error))
                }
                return
            }
            
            // 确保有数据返回
            guard let data = data else {
                print("No data returned")
                DispatchQueue.main.async {
                    completion(.failure(NSError(domain: "No data returned", code: 103, userInfo: nil)))
                }
                return
            }
            do {
                 // 先解析顶层 ResponseModel
                 let responseModel = try JSONDecoder().decode(ResponseModel<T>.self, from: data)
                 // 解析 data 字符串为实际模型
                 if let parsedData = responseModel.result.parsedData {
                     DispatchQueue.main.async {
                         completion(.success(parsedData))
                     }
                 } else {
                     DispatchQueue.main.async {
                         completion(.failure(NSError(domain: "Failed to parse data string", code: 104, userInfo: nil)))
                     }
                 }
             } catch {
                 print("Decoding error: \(error)")
                 DispatchQueue.main.async {
                     completion(.failure(error))
                 }
             }
        }
        task.resume()
    }
    
    static func postFormData(to urlString: String, parameters: [String: Any], completion: @escaping (Result<String, Error>) -> Void) {
        // 设置请求的 URL
        guard let urlComponents = URLComponents(string: urlString) else {
            completion(.failure(NSError(domain: "Invalid URL", code: 101, userInfo: nil)))
            return
        }

        // 创建 URL 请求
        guard let url = urlComponents.url else {
            completion(.failure(NSError(domain: "Invalid URL Components", code: 102, userInfo: nil)))
            return
        }

        // 创建 URLRequest 对象
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        
        // 将参数字典转换为 JSON 数据
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: parameters, options: [])
            request.httpBody = jsonData
        } catch {
            completion(.failure(NSError(domain: "参数序列化失败", code: 105, userInfo: nil)))
            return
        }
        
        print("请求地址", url.absoluteString)
        print("请求参数", parameters)
        
        // 执行网络请求
        let session = URLSession.shared
        let task = session.dataTask(with: request) { data, response, error in
            // 处理错误
            if let error = error {
                print("Error in request: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    completion(.failure(error))
                }
                return
            }
            
            // 确保有数据返回
            guard let data = data else {
                print("No data returned")
                DispatchQueue.main.async {
                    completion(.failure(NSError(domain: "No data returned", code: 103, userInfo: nil)))
                }
                return
            }
            
            // 将返回的数据转换为字符串
            if let jsonString = String(data: data, encoding: .utf8) {
                DispatchQueue.main.async {
                    completion(.success(jsonString))
                }
            } else {
                DispatchQueue.main.async {
                    completion(.failure(NSError(domain: "JSON转换字符串失败", code: 104, userInfo: nil)))
                }
            }
        }

        // 启动任务
        task.resume()
    }
    
    
    static func postBodyWithString(to urlString: String, bodyValue: String, completion: @escaping (Result<String, Error>) -> Void) {
        // 设置请求的 URL
        guard let urlComponents = URLComponents(string: urlString) else {
            completion(.failure(NSError(domain: "Invalid URL", code: 101, userInfo: nil)))
            return
        }

        // 创建 URL 请求
        guard let url = urlComponents.url else {
            completion(.failure(NSError(domain: "Invalid URL Components", code: 102, userInfo: nil)))
            return
        }

        // 创建 URLRequest 对象
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        
        // 直接将字符串转换为Data
        guard let data = bodyValue.data(using: .utf8) else {
            completion(.failure(NSError(domain: "字符串转换Data失败", code: 105, userInfo: nil)))
            return
        }
        request.httpBody = data
        
        print("请求地址", url.absoluteString)
        print("请求参数", bodyValue)
        
        // 执行网络请求
        let session = URLSession.shared
        let task = session.dataTask(with: request) { data, response, error in
            // 处理错误
            if let error = error {
                print("Error in request: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    completion(.failure(error))
                }
                return
            }
            
            // 确保有数据返回
            guard let data = data else {
                print("No data returned")
                DispatchQueue.main.async {
                    completion(.failure(NSError(domain: "No data returned", code: 103, userInfo: nil)))
                }
                return
            }
            
            // 将返回的数据转换为字符串
            if let jsonString = String(data: data, encoding: .utf8) {
                DispatchQueue.main.async {
                    completion(.success(jsonString))
                }
            } else {
                DispatchQueue.main.async {
                    completion(.failure(NSError(domain: "JSON转换字符串失败", code: 104, userInfo: nil)))
                }
            }
        }

        // 启动任务
        task.resume()
       
    }
}

