//
//  KMAdvertisementRequestServer.swift
//  KMAdvertisement
//
//  Created by lizhe on 2022/11/23.
//

import AFNetworking
typealias KMAdvertisementRequestServerCompletion = (_ task: URLSessionDataTask?, _ responseObject: AnyObject?, _ error: Error?) -> Void
class KMAdvertisementRequestServer {
    var sessionManager: AFHTTPSessionManager!
    static let requestServer = KMAdvertisementRequestServer()
    
    init() {
        let configuration: URLSessionConfiguration = URLSessionConfiguration.default
        sessionManager = AFHTTPSessionManager.init(sessionConfiguration: configuration)
        sessionManager.securityPolicy = AFSecurityPolicy.default()
    }
    
    func request(urlString: String,
                 method:String,
                 params: Dictionary<String, Any>?,
                 completion: @escaping KMAdvertisementRequestServerCompletion) -> Void {
        self.request(urlString: urlString,
                     method: method,
                     params: params,
                     requestSerializer: nil,
                     completion: completion)
    }
    
    func request(urlString: String,
                 method:String,
                 params: Dictionary<String, Any>?,
                 requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
                 completion: @escaping KMAdvertisementRequestServerCompletion) -> Void {
        self.request(urlString: urlString,
                     method: method,
                     params: params,
                     requestSerializer: requestSerializer,
                     body: nil,
                     completion: completion)
    }
    
    func request(urlString: String,
                 method:String,
                 params: Dictionary<String, Any>?,
                 requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
                 body: ((_ formData:AFMultipartFormData) -> Void)?,
                 completion: @escaping KMAdvertisementRequestServerCompletion) -> Void {
        //每次请求需要重新创建
        sessionManager.requestSerializer = AFJSONRequestSerializer()
        sessionManager.responseSerializer = AFJSONResponseSerializer()
        sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
        sessionManager.requestSerializer.timeoutInterval = 20
        if (requestSerializer != nil) {
            requestSerializer!(sessionManager.requestSerializer);
        }
        
        if (method == "POST") {
            if (body != nil) {
                sessionManager.post(urlString, parameters: params, headers: nil) { formData in
                    body!(formData)
                } progress: { progress in
                    
                } success: { task, responseObject in
                    let responseObject = responseObject as AnyObject
                    completion(task,responseObject,nil);
                } failure: { task, error in
                    completion(task,nil,error);
                }
            } else {
                sessionManager.post(urlString, parameters: params, headers: nil) { progress in
                
                } success: { task, responseObject in
                    let responseObject = responseObject as AnyObject
                    completion(task,responseObject,nil)
                } failure: { task, error in
                    completion(task,nil,error)
                }

            }
        } else if (method == "GET") {
            sessionManager.get(urlString, parameters: params, headers: nil) { progress in
                
            } success: { task, responseObject in
                let responseObject = responseObject as AnyObject
                completion(task,responseObject,nil)
            } failure: { task, error in
                completion(task,nil,error)
            }
        }
    }
    
    /**
     下载
     */
    func downLoad(inputURL: URL,
                  filePath: String,
                  progress: @escaping(_ progress: Progress) -> Void,
                  completion: @escaping KMAdvertisementRequestServerCompletion) {
        let request: URLRequest = URLRequest.init(url: inputURL)
        self.sessionManager.requestSerializer.timeoutInterval = 100.0
        let downloadTask = self.sessionManager.downloadTask(with: request) { resultProgress in
            progress(resultProgress)
        } destination: { url, response in
            return NSURL(fileURLWithPath: filePath) as URL
        } completionHandler: { resultResponse, resultUrl, error in
            completion(nil, resultResponse, error)
        }
        downloadTask.resume()


//        /* 下载地址 */
//        NSURL *url = [NSURL URLWithString:requestURL];
//        NSURLRequest *request = [NSURLRequest requestWithURL:url];
//        /* 下载路径 */
//        NSString *downFilePath = [NSString stringWithFormat:@"%@/%@", [self setPathOfDocumentsByFileCreated:created fileName:fileName], fileName];
//        self.downFilePath = downFilePath;
//
//        /* 开始请求下载 */
//        self.downloadTask = [_sessionManager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//            float p = downloadProgress.fractionCompleted * 100;
//            if (progress) {
//                progress(p);
//            }
//            NSLog(@"下载进度：%.0f％", downloadProgress.fractionCompleted * 100);
//        } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                //如果需要进行UI操作，需要获取主线程进行操作
//            });
//            /* 设定下载到的位置 */
//            return [NSURL fileURLWithPath:downFilePath];
//
//        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
//            NSLog(@"下载完成");
//            if (error) {
//                if (failure) {
//                    failure(error);
//                }
//                [weakSelf removeDownLoadFile];
//            } else {
//                if (success) {
//                    success(downFilePath,[weakSelf setPathOfDocumentsByFileCreated:created fileName:fileName]);
//                }
//            }
//        }];
//        [self.downloadTask resume];
    }
    
    /*
     status
     AFNetworkReachabilityStatusUnknown          = -1, 不知道监测的是什么
     AFNetworkReachabilityStatusNotReachable     = 0,  没有检测到网络
     AFNetworkReachabilityStatusReachableViaWWAN = 1,  蜂窝网
     AFNetworkReachabilityStatusReachableViaWiFi = 2,  WIFI
     */
    func reachabilityStatusChange(block: @escaping(AFNetworkReachabilityStatus) ->Void) {
        // 1.创建网络监测单例
        let manager = AFNetworkReachabilityManager.shared()
        manager.setReachabilityStatusChange({ status in
            // 2.实现网络监测的回调
            block(status)
        })
        // 3.开始监测
        manager.startMonitoring()
    }
}
