//
//  YHNetRequest.swift
//  galaxy
//
//  Created by EDY on 2023/12/20.
//

import Foundation
import Alamofire

class YHNetRequest: NSObject {
    ///成功回调
    typealias SuccessHandlerType = (([String:Any],Int) ->Void)
    ///失败回调
    typealias FailureHandlerType = ((YHNetError) -> Void)
    ///请求类型
    private var requestType: HTTPMethod = .post
    ///  URL
    private var url: String?
    ///  参数
    private var params: [String:Any]?
    ///  成功的回调
    private var success: SuccessHandlerType?
    ///  失败的回调
    private var failure: FailureHandlerType?
    ///  headers 设置
    private var headers: HTTPHeaders?
    ///  数据请求
    private var httpRequest: DataRequest?
    ///  链式语法
    func url(_ url:String?) -> Self{
        self.url = url ?? ""
        return self
    }
    ///  请求类型
    func requestType(_ type: HTTPMethod) -> Self {
         self.requestType = type
         return self
    }
    ///请求参数
    func params(_params: [String:Any]?) -> Self {
        self.params = params
        return self
    }
    ///成功
    func success(_ handler:@escaping SuccessHandlerType) -> Self {
        self.success = handler
        return self
    }
    ///失败
    func failed(_ handler:@escaping FailureHandlerType) -> Self {
        self.failure = handler
        return self
    }
    ///获取包头
    func getHeader() -> HTTPHeaders {
        var requestHeader = HTTPHeaders()
        if let header = headers {
            requestHeader = header
        } else {
            requestHeader.add(name:"Conatent-Type",value:"application/json")
            requestHeader.add(name:"Accept",value:"application/json")
        }
        return requestHeader
    } 
    ///开始请求

    func startRequest() -> Request? {
        let requestHeaders = getHeader()
        ///不使用缓存
        AF.sessionConfiguration.requestCachePolicy = .reloadIgnoringCacheData
        AF.sessionConfiguration.timeoutIntervalForRequest = 30
        httpRequest = AF.request(self.url!,method: self.requestType,parameters: self.params,encoding: URLEncoding(destination: .queryString),headers: requestHeaders,interceptor: nil,requestModifier: nil)
        _ = httpRequest?.id
        httpRequest?.responseString(encoding:.utf8,completionHandler: { string in
            print("=======2")
            self.completeHandle(string: string)
        })
        return httpRequest
    }
    /// 请求response完成处理
    func completeHandle(string: AFDataResponse<String>) {
        let responseResult = string.result
//        var resultFlag: Bool = false
        let errorCodeStr = "0"
        var statusCode = string.response?.statusCode ?? 0
        let errorResponseMsg = string.error?.localizedDescription ?? ""
        _ = string.error?._code
        let resultValue = string.value ?? ""
        let serverDict = self.converStringToMap(fromStr: resultValue)
        switch responseResult {
        case .success:
//            resultFlag = true
            break
        case .failure:
//            resultFlag = false
            if let underyingError = string.error?.asAFError?.underlyingError {
                if let urlError = underyingError as? URLError {
                    switch urlError.code{
                    case.timedOut:
                        statusCode = urlError.code.rawValue
                    case.cannotConnectToHost:
                        statusCode = urlError.code.rawValue
                    case.cannotFindHost:
                        statusCode = urlError.code.rawValue
                    case.unsupportedURL:
                        statusCode = urlError.code.rawValue
                    default:
                        break
                    }
                }
            }
            break
        }
        if statusCode == 200 {
            if let suclock = self.success {
                suclock(serverDict,statusCode)
            }
        } else {
            let errorModel = YHNetError.init()
            errorModel.responseErrorType = .failType
            if let errorBlock = self.failure {
                errorModel.responseStatusCode = statusCode
                errorModel.errResponseMsg = errorResponseMsg
                errorModel.errReaponseCode = errorCodeStr
                errorBlock(errorModel)
            }
        }
    }
    
    func converStringToMap(fromStr: String = "") -> [String:Any] {
        let serverData = fromStr.data(using:String.Encoding.utf8)
        do{
            let serverDict = try JSONSerialization.jsonObject(with:serverData!,options:JSONSerialization.ReadingOptions.mutableContainers) as? [String:Any]
            return serverDict!
        } catch {
            return [String:Any]()
        }
    }
}

extension YHNetRequest {
    class func getRequest(url:String, params:[String:Any] = [:], successBlock: SuccessHandlerType!, failBlock: FailureHandlerType!) -> Request? {
        return YHNetRequest().url(url).requestType(.get).success(successBlock).failed(failBlock).startRequest()
    }
    
    class func postRequest(url:String, params:[String:Any] = [:], successBlock: SuccessHandlerType!, failBlock: FailureHandlerType!) -> Request? {
        return YHNetRequest().url(url).requestType(.post).success(successBlock).failed(failBlock).startRequest()
    }
}

class YHNetError: NSObject {
    var responseStatusCode: Int = 0
    var responseStatusCodeStr: String = ""
    var errResponseMsg: String = ""
    var errReaponseCode: String = ""
    var errReaponseTimeOutCode: Int = 0
    var responseErrorType: NetResponseErrorType?
}

enum NetResponseErrorType: Int {
    case successType,failType
}

//YHNetRequest.getRequest(url: "需要请求的url") { succeseResponse,responseCode in
//
//   print(succeseResponse,responseCode)
//
//   } failBlock: { MiruairNetError in
//
//}
