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

import Foundation
import Alamofire
import CryptoSwift

//class YHNetErrorModel {
//    var responseStatusCode: Int = 0
//    var responseStatusCodeStr: String = ""
//    var errResponseMsg: String = ""
//    var errReaponseCode: String = ""
//    var errReaponseTimeOutCode: Int = 0
//    var responseErrorType: NetResponseErrorType = .failType
//}


//定义客户端通用的错误码
public enum YHErrorCode : Int32 {
    case success = 0
    case networkFail = -1
    case unknowError = -10000
    case dictParseError = -10001
    
    public func description() -> String {
        switch self {
        case .success:
            return "成功"
        case .networkFail:
            return "网络不可用"
        case .unknowError:
            return "未知错误"
        case .dictParseError:
            return "字典解析错误"
        default:
            return "未知"
        }
    }
}


public struct YHErrorModel {
    var errorCode : Int32 = YHErrorCode.unknowError.rawValue
    var errorMsg : String = YHErrorCode.unknowError.description()
}

class YHNetRequest: NSObject {
    ///成功回调
    typealias SuccessHandlerType = (([String:Any],Int) ->Void)
    ///失败回调
    typealias FailureHandlerType = ((YHErrorModel) -> 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?
    
    override init() {
        super.init()
        
        
        var requestHeader = HTTPHeaders()
        
        requestHeader.add(name:"Conatent-Type",value:"application/json")
        requestHeader.add(name:"Accept",value:"application/json")
        
        
        
        /*
         以下是测试数据 for test hjl
         */
        requestHeader.add(name:"appid",value:"1")
        let dateStr = String(Date().timeIntervalSince1970)
        requestHeader.add(name:"timestamp",value:dateStr)
        
        requestHeader.add(name:"pass",value:"")
        let appkey = "958364f87222c200a72414f492bf0e26"
        let signOrgiString = "appid=" + "1" + "&" + "timestamp=" + dateStr + "&" + "appkey=" + appkey
        let sign = signOrgiString.md5()
        print("sign = \(sign)")
        
        requestHeader.add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xNTRiODNkMDRiNTRhIn0=")

        headers = requestHeader
    }
    
    ///  链式语法
    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 = 20
        httpRequest = AF.request(self.url!,method: self.requestType,parameters: self.params,encoding: URLEncoding(destination: .queryString),headers: requestHeaders,interceptor: nil,requestModifier: nil)
        
        httpRequest?.responseString(completionHandler: { string in
#if DEBUG
            printLog("\n网络请求已返回 string=\(string)")
#endif
            self.completeHandle(string: string)
        })
        
        return httpRequest
    }
    /// 请求response完成处理
    func completeHandle(string: AFDataResponse<String>) {
        let responseResult = string.result
        var statusCode = string.response?.statusCode ?? 0
        let errorResponseMsg = string.error?.localizedDescription ?? ""
        let resultValue = string.value ?? ""
        let serverDict = resultValue.toDictionary()
        switch responseResult {
        case .success:
            break
        case .failure:
            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 {
            guard let suclock = self.success else { return }
            
            let dittt = self.handleJsonObjectNullValue(serverDict)
            suclock(dittt as? [String : Any] ?? [:], statusCode)
        } else {
            guard let errorBlock = self.failure else { return }
            
            let errorModel = YHErrorModel(errorCode: Int32(statusCode), errorMsg: errorResponseMsg)
            errorBlock(errorModel)
        }
    }
    
    
    //处理对象为空的情况
    func handleJsonObjectNullValue(_ jsonObject: Any) -> Any {
        if let jsonArray = jsonObject as? Array<Any> {
            let noNullArray: [Any] = jsonArray.map { value in
                if value is NSNull {
                    return ""
                }else if let value = value as? Array<Any> {
                    return handleJsonObjectNullValue(value)
                }else if let value = value as? Dictionary<AnyHashable, Any> {
                    return handleJsonObjectNullValue(value)
                }else {
                    return value
                }
            }
            return noNullArray
        }else if let jsonDic = jsonObject as? Dictionary<AnyHashable, Any> {
            let noNullDic: [AnyHashable: Any] = jsonDic.mapValues { value in
                if value is NSNull {
                    return ""
                }else if let value = value as? Array<Any> {
                    return handleJsonObjectNullValue(value)
                }else if let value = value as? Dictionary<AnyHashable, Any> {
                    return handleJsonObjectNullValue(value)
                }else {
                    return value
                }
            }
            return noNullDic
        }
        return jsonObject
    }
    
}

extension YHNetRequest {
    class func getRequest(url:String, params:[String:Any] = [:], successBlock: SuccessHandlerType!, failBlock: FailureHandlerType!) -> Request? {
        
        printLog("\n发起请求的URL是===> url = \(url)")
        return YHNetRequest().url(url).requestType(.get).params(params).success(successBlock).failed(failBlock).startRequest()
    }
    
    class func postRequest(url:String, params:[String:Any] = [:], successBlock: SuccessHandlerType!, failBlock: FailureHandlerType!) -> Request? {
        printLog("\n发起请求的URL是===> url = \(url)")
        return YHNetRequest().url(url).requestType(.post).params(params).success(successBlock).failed(failBlock).startRequest()
    }
}
