//
//  CCRequest.swift
//  SwiftProject
//
//  Created by soldoros on 2024/1/10.
//

import UIKit
import Foundation
import Alamofire

typealias ResultBlock = (_ res:AFDataResponse<String>) -> ()


class CCRequest: NSObject {
    
    //默认请求头
    class func requestHeader() -> HTTPHeaders{
        let headers: HTTPHeaders = []
        return headers
    }
    
    //动态处理请求头
    class func setHeader(header:NSDictionary) -> HTTPHeaders{
        
        var headers = requestHeader()
        let token = RootData.getData(key: User_Token)
        if(!token.elementsEqual("")){
            headers.add(name: "token", value: token)
        }
        
        let keys = header.allKeys
        for key in keys{
            let value = header[key]
            headers.add(name: key as! String, value: value! as! String)
        }
        return headers
    }
    
    
    //拦截token和用户状态判断
    class func setRequestResult(response:AFDataResponse<String>, resultBlock:@escaping ResultBlock){
        
        print("处理回调的数据")
        if(response.error == nil){
            let dataDic:NSDictionary = NSString.makeDictionaryWithJson(string: response.value!)
            if((dataDic["code"] as! NSNumber).stringValue == "200"){
                RootData.setData(key: "", value: User_Token)
                RootData.setData(key: "0", value: User_Login)
                self.sendNotifCation(key:"", object: "0")
                CCAlert.pressentAlertControllerWith(title: "温馨提示！", message: "用户凭证已过期，请重新登录！", ok: "确定", cancel: "") { action in
                    
                }
            }
        }
        resultBlock(response)
    }
    
    
    class func requset(method:HTTPMethod, dic:Dictionary<String,Any>, urlString:String, header:NSDictionary, resultBlock:@escaping ResultBlock){
        
        let url = URLContentStr + urlString
        if(method == .get){
            getRequest(dic: dic, urlString: url, header: header) { res in
                setRequestResult(response: res, resultBlock: resultBlock)
            };
        }
        else if(method == .post){
            postRequest(dic: dic, urlString: url, header: header) { res in
                setRequestResult(response: res, resultBlock: resultBlock)
            };
        }
        else if(method == .delete){
            deleteRequest(dic: dic, urlString: url, header: header) { res in
                setRequestResult(response: res, resultBlock: resultBlock)
            };
        }
    }
    
    //get请求
    class func getRequest(dic:Dictionary<String,Any>, urlString:String, header:NSDictionary, resultBlock:@escaping ResultBlock){
        
        let headers = setHeader(header: header);
        AF.request(urlString, method: .get, parameters: dic,encoding: JSONEncoding.default, headers: headers)
            .responseString { res in
                resultBlock(res)
        }
    }
    
    //post请求
    class func postRequest(dic:Dictionary<String,Any>, urlString:String, header:NSDictionary, resultBlock:@escaping ResultBlock){
        
        let headers = setHeader(header: header);
        AF.request(urlString, method: .post, parameters: dic,encoding: JSONEncoding.default, headers: headers)
            .responseString { res in
                resultBlock(res)
        }
    }
    
    //delete请求
    class func deleteRequest(dic:Dictionary<String,Any>, urlString:String, header:NSDictionary, resultBlock:@escaping ResultBlock){
        
        let headers = setHeader(header: header);
        AF.request(urlString, method: .delete, parameters: dic,encoding: JSONEncoding.default, headers: headers)
            .responseString { res in
                resultBlock(res)
        }
    }
    
    
    
//
//    /// 上传图片
//    ///
//    /// - Parameters:
//    ///   - dic: 数据
//    ///   - urlString: 地址
//    ///   - imageData: 图片数据
//    ///   - headers: 表头
//    ///   - resultBlock: 返回数据代码块
//    class func postRequestImage(dic:NSDictionary, urlString:NSString,imageData: Data, headers:HTTPHeaders, resultBlock:@escaping ResultBlock2){
//
//        let string:String = URLStr + (urlString as String)
//
//        AF.upload(multipartFormData: { (data) in
//            data.append(imageData, withName: "images1", fileName: "png", mimeType: "png")
//        }, to: URL.init(string: string)!, method: .post, headers: headers) { (encodingResult) in
//
//            switch encodingResult{
//
//            case .success(let request,_,_):
//                request.responseJSON(completionHandler: { (response) in
//
//                    CCRequest.setRequestResult(response: response, resultBlock: resultBlock)
//
//                })
//            case .failure(let error):
//                print("上传文件编码错误",error)
//            }
//        }
//
//    }
//
    
//
//    //下载文件
//    class func downloadWithUrlString(urlString:NSString,resultBlock:@escaping ResultBlock3){
//
//        let string:String = urlString as String
//        let url = URL.init(string: string)
//        let request = URLRequest(url: url!)
//        print(url as Any)
//
//        let destination = DownloadRequest.suggestedDownloadDestination()
//
//
//        AF.download(request, to: destination).response { response in
//
//                print(response.destinationURL!.path)
//                let path:String = "file://" +  response.destinationURL!.path
//                resultBlock(response,path)
//
//        }
//
//    }
}
