//
//  QSLCentralNetwork.swift
//  QuickSearchLocation
//
//  Created by Destiny on 2025/10/11.
//

import UIKit
import Foundation
import Moya
import MoyaMapper

enum QSLCentralNetworkAPI {
    case getEventPushToken(dict: [String : Any])
    case eventPush(dict: [String : Any])
}

let QSLCentralNetworkProvider = MoyaProvider<QSLCentralNetworkAPI>(plugins: [networkLoggerPlugin, MoyaMapperPlugin(NetParameter())])


extension QSLCentralNetworkAPI: TargetType {
    // 地址
    public var baseURL: URL {
        return URL(string: QSLCentralEventManager.centralUrl)!
    }
    
    var path: String {
        switch self {
        case .eventPush: return QSLCentralEventManager.event_push
        case .getEventPushToken: return QSLCentralEventManager.ssid_detail
        }
    }
    
    var method: Moya.Method { return .post }
    
    var task: Task {
        var parameters : [String:Any] = [:]
        switch self {
        case let .eventPush(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
        case let .getEventPushToken(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
        }
        debugPrint(parameters)
        return .requestParameters(parameters: parameters, encoding: JSONEncoding.default)
    }
    
    var sampleData: Data { return "".data(using: String.Encoding.utf8)! }
    
    var headers: [String : String]? {
        return ["AppKey": QSLCentralEventManager.appKey]
    }
}

struct QSLCentralNetwork {
    
    ///先添加一个闭包用于成功时后台返回数据的回调
    typealias completeCallback = ((Response) -> (Void))
    typealias failCallback = ((Int, String) -> (Void))
    
    func request(_ target: QSLCentralNetworkAPI, success: @escaping completeCallback, fail: @escaping failCallback){

        QSLCentralNetworkProvider.request(target) { (result) in
            
            switch result {
            case let .success(response):
                
                if response.statusCode == 200 {
                    if response.toJSON(modelKey: "code") == 0 {
                        success(response)
                    } else {
                        fail(response.toJSON(modelKey: "code").intValue, response.toJSON(modelKey: "msg").stringValue)
                    }
                } else if response.statusCode == 1006 {
                    if QSLBaseManager.shared.isLogin() {
                        QSLBaseManager.shared.logOut()
                    }
                    UIApplication.keyWindow?.toast(text: "登录状态失效")
                } else {
                    fail(response.statusCode, response.toJSON(modelKey: "msg").stringValue)
                }
                 
                #if DEBUG
                print("data:\(response.fetchJSONString())")
                #endif
                
                break
            case let .failure(error):
                fail(error.errorCode, "网络错误，请检查后重试")
                //网络连接失败，提示用户
                UIApplication.keyWindow?.toast(text: "网络错误，请检查后重试")
                break
            }
        }
    }
}
