//
//  TSNetworkManager.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2025/1/13.
//

import Alamofire
import Network

typealias CYARequestComplate<V> = (_ response: V) -> Void

let TSNetworkShard = TSNetwork.shared


class TSNetwork {
    static let shared = TSNetwork()
    
    private init(){}
    private let timeoutInterval:Int = 300
    //返回的是原始后端返回的类型 dict、array、String
    func request<T: OriginResponseDataType, V: BaseResponse<T>>(_ config: INetConfiguration,
                                        complation: CYARequestComplate<V>?) {
        request(config, toTansform: nil, complation: complation)
    }
    
    /*
     网络请求接口
     V：IBaseResponse实现类，可自定义封装数据解析的成功和失败
        response.data：返回的数据
     toTransform：需要封装的model block，不传的话，返回dict
     
     config: 请求配置
     compete：请求完成回调，回调返回遵循IBaseResponse协议的对象
     */
    func request<T, V: BaseResponse<T>>(_ config: INetConfiguration,
                                          toTansform: (([String: Any]?) -> T?)?,
                                        complation: CYARequestComplate<V>?)
    {
        var encoding: ParameterEncoding = URLEncoding.default
        if config.method == .post {
            encoding = JSONEncoding.default
        }
        let request = AF.request(config.url, method: config.method, parameters: config.requestParams, encoding: encoding, headers: config.publicHeader as HTTPHeaders, interceptor: config.requestInterceptor)
        request.responseString { response in
            print(response)
            let responseM = V()
            responseM.httpStatus = response.response?.statusCode
            switch response.result {
            case .success(_):
                let parse = V.fromData(response.data)
                responseM.result = parse.result
                responseM.message = parse.message
                responseM.error = parse.error
                responseM.data = parse.data as? T
                
                if responseM.result == .Success, let transform = toTansform {
                    responseM.data = transform(parse.data as? [String: Any])
                    complation?(responseM)
                    return
                }
                complation?(responseM)
                
            case .failure(let error):
                responseM.result = .ServerError
                responseM.error = error
            }
            complation?(responseM)
        }
    }
    
    
    
    /// 基础 URL（可按需修改）
    private let baseURL = "https://api.example.com"
    
    /// 请求通用 Headers（可根据需求自定义）
    private var defaultHeaders: HTTPHeaders {
        return [
            "Content-Type": "application/json",
            "accept": "application/json",
//            "Authorization": "Bearer YOUR_ACCESS_TOKEN" // 可按需修改
        ]
    }
    
    
    func post(urlString:String,params:[String: any Any & Sendable],complete:@escaping(String)->Void)  {
    
        var encoding = JSONEncoding.default
        let request = AF.request(urlString, method: .post, parameters: params, encoding: encoding, headers: defaultHeaders, interceptor: nil)
        request.responseString { response in
            
            print(response)
      
//            switch response.result {
//            case .success(_):
//                let parse = V.fromData(response.data)
//                responseM.result = parse.result
//                responseM.message = parse.message
//                responseM.error = parse.error
//                responseM.data = parse.data as? T
                
//                if responseM.result == .Success, let transform = toTansform {
//                    responseM.data = transform(parse.data as? [String: Any])
////                    complation?(responseM)
//                    return
//                }
//                complation?(responseM)
                
//            case .failure(let error):
//        
//            }
//            complation?(responseM)

            
        }
        
    }
}



extension TSNetwork {
    func monitorNetworkPermission(escapable result:@escaping (Bool)->Void) {
        let monitor = NWPathMonitor()
        let queue = DispatchQueue.global(qos: .background)
        monitor.start(queue: queue)
        monitor.pathUpdateHandler = { path in
            DispatchQueue.main.async {
                if path.status == .satisfied {
                    debugPrint("网络可用，用户同意了权限")
                    result(true)
                } else {
                    debugPrint("网络不可用，可能用户拒绝了权限")
                    result(false)
                }
            }
        }
    }
}


extension TSNetwork {
    /// 发送 POST 请求
    /// - Parameters:
    ///   - urlString: 请求的 URL 字符串
    ///   - parameters: 请求的参数字典（将自动转换为 JSON）
    ///   - timeout: 超时时间（默认 30 秒）
    ///   - completion: 请求完成的回调，返回 `Data?` 和 `Error?`
    static func postRequest(
        urlString: String,
        httpBody: Data?,
        timeout: TimeInterval = 90,
        completion: @escaping (Data?, Error?) -> Void
    ) {
        // 确保 URL 有效
        guard let url = URL(string: urlString) else {
            completion(nil, NSError(domain: "Invalid URL", code: -1, userInfo: nil))
            return
        }
        debugPrint("postRequest urlString=",urlString)
        // 创建请求
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.timeoutInterval = timeout
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = httpBody
  
        // 创建数据任务
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            completion(data, error)
        }
        
        // 启动任务
        task.resume()
    }
    
    
}
