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

import Foundation
import Alamofire
import CryptoSwift
import UIKit

//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 SuccessResultType = ((NetWorkBaseModel,Int) ->Void)
    ///失败回调
    typealias FailureHandlerType = ((YHErrorModel) -> Void)
    ///请求类型
    private var requestType: HTTPMethod = .post
    ///  URL
    private var url: String?
    ///  参数
    private var params: [String:Any]?
    ///  成功的回调
    private var success: SuccessResultType?
    ///  失败的回调
    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")
        
        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(name:"sign",value:sign)
        requestHeader.add(name: "token", value: YHLoginManager.shared.userModel?.token ?? "-")
//        requestHeader.add(name: "token", value: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MTI0NjA1NzQsImkiOjk4OTcwNDI5NjA3NzI0OSwidSI6IumTtuays-mbhuWboiIsInIiOiJzdXBlcl9hcHAifQ.jyBpXSii6nlRIITdOya3GQa5eb5G42Jh9nj39Cncwl8")

        
        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 SuccessResultType) -> 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? {
        guard YHNetworkStatusManager.shared.isNetWorkOK == true else {
            YHHUD.flash(message: "网络异常")
            return httpRequest
        }
        
        let requestHeaders = getHeader()
        
#if DEBUG
        printLog("网络请求头数据：" )
        printLog(requestHeaders)
#endif
        
        ///不使用缓存
        AF.sessionConfiguration.requestCachePolicy = .reloadIgnoringCacheData
        AF.sessionConfiguration.timeoutIntervalForRequest = 20
        
        let encoding = (self.requestType == .get ? URLEncoding(destination: .queryString) : JSONEncoding()) as ParameterEncoding
        httpRequest = AF.request(self.url!, method: self.requestType,parameters: self.params, encoding:encoding, headers: requestHeaders, interceptor: nil, requestModifier: nil)
        
        httpRequest?.responseString(completionHandler: { string in
#if DEBUG
            printLog("\n网络请求已返回 string=\(string)")
#endif
            self.completeHandle(string: string)
        })
        
        return httpRequest
    }
    
    ///开始请求
    func uploadRequest(_ headers: HTTPHeaders,_ image: UIImage) -> Request? {
        guard YHNetworkStatusManager.shared.isNetWorkOK == true else {
            YHHUD.flash(message: "网络异常")
            return httpRequest
        }
        //        guard let imageData = image.jpegData(compressionQuality: 1) else { return httpRequest }
        
        guard let imageData = image.compressOriginalImage(4 * 1024 * 1024) else { return httpRequest }
        
        let tttt = Double(imageData.count)/1024.0/1024.0
#if DEBUG
        let ssss = String(format: "%.2f", tttt)
        YHHUD.flash(message: "实际大小：" + ssss + " M")
#endif
        
        let multipartFormData = MultipartFormData()
        
        // 将图片添加到multipartFormData中
        multipartFormData.append(imageData, withName: "file", fileName: "image.jpg", mimeType: "image/jpeg")
        
        // 发送POST请求
        let uploadRequest = AF.upload(multipartFormData: multipartFormData, to: self.url!, headers: headers)
        
        uploadRequest.responseString(completionHandler: { string in
#if DEBUG
            printLog("\n网络请求已返回 string=\(string)")
#endif
            self.completeHandle(string: string)
        })
        
        return uploadRequest
    }
    
    /// 请求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 obj = NetWorkBaseModel.deserialize(from: serverDict) else {
                guard let errorBlock = self.failure else { return }
                let errorModel = YHErrorModel(errorCode: Int32(statusCode), errorMsg: errorResponseMsg)
                errorBlock(errorModel)
                return
            }
#if DEBUG
            printLog("服务器返回数据是：\(obj)")
#endif
            guard let suclock = self.success else { return }
            suclock(obj, statusCode)
        } else {
            guard let errorBlock = self.failure else { return }
            
            let errorModel = YHErrorModel(errorCode: Int32(statusCode), errorMsg: errorResponseMsg)
            errorBlock(errorModel)
        }
    }
}

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