//
//  TSNetWork+Business.swift
//  AIEmoji
//
//  Created by 100Years on 2025/1/16.
//

/// 基础 URL（根据需求修改）
private let baseURL = "http://ai.100yearslater.com"
import Alamofire
enum TSNeURLType:String {
    
    case imageEmoji = "/api/image/emoji"         //文生emoji
    case actionInfo = "/api/action/info"         //查询生成过程接口
    case chat = "/api/text/chat"                 //AI 对话接口
    case textPicCreate = "/api/image/create"     //文生图
    case upload = "/api/upload"                  //上传图片
    case imageRewrite = "/api/image/rewrite"     //图生图
    case themes = "/api/ops/themes"              //主体查询
    case musicCreate = "/api/music/create"       //铃声创建
    
    
    
    case ringCategories = "/api/ops/ring-categories"     //铃声分类接口
    case rings = "/api/ops/rings"                       //铃声分类下内容接口
    case ringRecommend = "/api/ops/ring-recommend"       //铃声内容推荐接口
    
    func getUrlString() -> String {
        return baseURL + self.rawValue
    }
}


extension TSNetworkManager {
    
    /// 通用 get 请求
    func get<T: TSBaseModel>(
        urlType: TSNeURLType,
        parameters: [String: Any]? = nil,
        responseType: T.Type? = nil,
        useCache: Bool = false,
        completion: @escaping (Result<Any, Error>) -> Void
    ) -> Request?  {
        let urlString = urlType.getUrlString()
        return request(
            method: .get,
            urlString: urlString,
            parameters:parameters,
            useCache: useCache
        ) { result in
            completion(result)
        }
    }


    /// 通用 POST 请求
    /// - Parameters:
    ///   - endpoint: 接口路径
    ///   - parameters: 请求参数
    ///   - responseType: 响应数据模型（可选）
    ///   - completion: 请求完成的回调
    func post<T: TSBaseModel>(
        urlType: TSNeURLType,
        parameters: [String: Any]? = nil,
        responseType: T.Type? = nil,
        useCache: Bool = false,
        completion: @escaping (Result<Any, Error>) -> Void
    ) -> Request? {
        let urlString = urlType.getUrlString()
        return request(
            method: .post,
            urlString: urlString,
            parameters:parameters,
            useCache: useCache
        ) { result in
            completion(result)
        }
    }
    
    
    /// 清除特定 URL 的缓存
    func removeCache(urlType: TSNeURLType) {
        removeCache(urlString: urlType.getUrlString())
    }
//    /// 通用 POST Stream 请求
//    /// - Parameters:
//    ///   - endpoint: 接口路径
//    ///   - parameters: 请求参数
//    ///   - responseType: 响应数据模型（可选）
//    ///   - completion: 请求完成的回调
//    func postStream<T: TSBaseModel>(
//        urlType: TSNeURLType,
//        parameters: [String: Any]? = nil,
//        responseType: T.Type? = nil,
//        streamHandler:@escaping (String) -> Void,
//        completion: @escaping (Result<Any, Error>) -> Void
//    ) -> StreamPostRequest{
//        let urlString = urlType.getUrlString()
//        
//        let streamRequest = StreamPostRequest(url: URL(string: urlString)!, parameters: parameters) { data in
//            if let string = String(data: data, encoding: .utf8) {
//                print("Received chunk: \(string)")
//                streamHandler(string)
//            }
//        } completionHandler: { error in
//            if let error = error {
//                print("Request failed with error: \(error)")
//                completion(.failure(error))
//            } else {
//                print("Request completed successfully.")
//                completion(.success("success"))
//            }
//        }
//        streamRequest.startRequest()
//        return streamRequest
//    }
    
    
    /// 通用 POST Stream 请求
    /// - Parameters:
    ///   - endpoint: 接口路径
    ///   - parameters: 请求参数
    ///   - responseType: 响应数据模型（可选）
    ///   - completion: 请求完成的回调
    func postStream<T: TSBaseModel>(
        urlType: TSNeURLType,
        parameters: [String: Any]? = nil,
        responseType: T.Type? = nil,
        streamHandler:@escaping (String) -> Void,
        completion: @escaping (Result<Any, Error>) -> Void
    ) -> Request?{
        let urlString = urlType.getUrlString()
        let streamRequest = postStreamRequest(
            urlString: urlString,
            parameters: parameters,
            streamHandler: streamHandler,
            completion: completion
        )
        return streamRequest
    }

    
    /// 上传多个 Data 数据
    /// - Parameters:
    ///   - urlType: TSNeURLType
    ///   - dataArray: Data 数组，每个元素是一个字典，包含 Data 和字段名
    ///   - parameters: 其他参数（可选）
    ///   - headers: 自定义请求头（可选）
    ///   - completion: 完成回调，返回结果或错误
    func uploadData<T: TSBaseModel>(
        urlType: TSNeURLType,
        dataArray: [[String: Any]], // Data 数组，每个元素包含 Data 和字段名
        parameters: [String: Any]? = nil,
        responseType: T.Type? = nil,
        progressHandler: @escaping (Float) -> Void, // 上传进度回调
        completion: @escaping (Result<Any, Error>) -> Void
    ) -> Request?{
        let urlString = urlType.getUrlString()
        let request = uploadData(urlString: urlString,dataArray:dataArray, parameters: parameters, progressHandler: { progress in
            progressHandler(Float(progress.fractionCompleted))
        },completion: completion)
        return request
    }

}




extension TSNetworkManager {
    func startListenNetStatus(handler: @escaping (NetworkReachabilityManager.NetworkReachabilityStatus, NetworkReachabilityManager?) -> Void) {
        // 创建 NetworkReachabilityManager 实例
        let networkManager = NetworkReachabilityManager.default

        // 开始监听网络状态
        networkManager?.startListening { status in
            handler(status, networkManager)
        }
    }
}

