//
//  QSLNetwork.swift
//  QuickSearchLocation
//
//  Created by Destiny on 2024/12/4.
//

import Foundation
import Moya
import MoyaMapper

struct NetParameter: ModelableParameterType {
    var successValue = "0"
    var statusCodeKey = "code"
    var tipStrKey = "msg"
    var modelKey = "data"
}

let QSLNetworkProvider = MoyaProvider<QSLNetworkAPI>(plugins: [networkLoggerPlugin, MoyaMapperPlugin(NetParameter())])
let networkLoggerPlugin = NetworkLoggerPlugin()


enum QSLNetworkAPI {
    
    case userCode(dict: [String: Any])
    case userMember(dict: [String: Any])
    case userLogin(dict: [String: Any])
    case userClear(dict: [String: Any])
    case friendList(dict: [String: Any])
    case requestSend(dict: [String: Any])
    case requestList(dict: [String: Any])
    case messageList(dict: [String: Any])
    case requestAccept(dict: [String: Any])
    case requestRefuse(dict: [String: Any])
    case friendDelete(dict: [String: Any])
    case friendRemark(dict: [String: Any])
    case friendBlocked(dict: [String: Any])
    case friendGet(dict: [String: Any])
    case locationTrackQuery(dict: [String: Any])
    case vipItemList(dict: [String: Any])
    case vipOrderSubmitAndPay(dict: [String: Any])
    case vipOrderPayStatus(dict: [String: Any])
    case vipMemberResume(dict: [String: Any])
    case vipCheckSubscription(dict: [String: Any])
    case contactList(dict: [String: Any])
    case contactCreate(dict: [String: Any])
    case contactFavor(dict: [String: Any])
    case contactDelete(dict: [String: Any])
    case contactMayday(dict: [String: Any])
    case contactMaydayFavor(dict: [String: Any])
    case contactMaydayAll(dict: [String: Any])
    case deviceInfoUpload(dict: [String: Any])
}

extension QSLNetworkAPI: TargetType {
    // 地址
    public var baseURL: URL {
        switch QSLApi.environment {
        case .local:
            return URL(string: QSLApi.LocalUrl)!
        case .dev:
            return URL(string: QSLApi.devUrl)!
        case .prod:
            return URL(string: QSLApi.prodUrl)!
        }
    }
    
    var path: String {
        switch self {
        case .userCode: return QSLApi.user_code
        case .userMember: return QSLApi.user_member
        case .userLogin: return QSLApi.user_login
        case .userClear: return QSLApi.user_clear
        case .friendList: return QSLApi.friend_list
        case .requestSend: return QSLApi.request_send
        case .requestList: return QSLApi.request_list
        case .messageList: return QSLApi.message_list
        case .requestAccept: return QSLApi.request_accept
        case .requestRefuse: return QSLApi.request_refuse
        case .friendDelete: return QSLApi.friend_delete
        case .friendRemark: return QSLApi.friend_remark
        case .friendBlocked: return QSLApi.friend_blocked
        case .friendGet: return QSLApi.friend_get
        case .locationTrackQuery: return QSLApi.location_track_query
        case .vipItemList: return QSLApi.vip_item_list
        case .vipOrderSubmitAndPay: return QSLApi.vip_order_submitAndPay
        case .vipOrderPayStatus: return QSLApi.vip_order_payStatus
        case .vipMemberResume: return QSLApi.vip_subscription_resume
        case .vipCheckSubscription: return QSLApi.vip_subscription_check
        case .contactList: return QSLApi.contact_list
        case .contactCreate: return QSLApi.contact_create
        case .contactFavor: return QSLApi.contact_favor
        case .contactDelete: return QSLApi.contact_delete
        case .contactMayday: return QSLApi.contact_mayday
        case .contactMaydayFavor: return QSLApi.contact_mayday_favor
        case .contactMaydayAll: return QSLApi.contact_mayday_all
        case .deviceInfoUpload: return QSLApi.device_info_upload
        }
    }
    
    var method: Moya.Method { return .post }
    
    var task: Task {
        var parameters : [String:Any] = QSLApi.params
        switch self {
        case let .userCode(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .userMember(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .userLogin(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .userClear(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .friendList(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .requestSend(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .requestList(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .messageList(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .requestAccept(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .requestRefuse(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .friendDelete(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .friendRemark(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .friendBlocked(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .friendGet(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .locationTrackQuery(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .vipItemList(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .vipOrderSubmitAndPay(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .vipOrderPayStatus(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .vipCheckSubscription(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .vipMemberResume(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .contactList(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .contactCreate(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .contactFavor(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .contactDelete(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .contactMayday(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .contactMaydayFavor(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .contactMaydayAll(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        case let .deviceInfoUpload(Dict):
            for (key, value) in Dict {
                parameters[key] = value
            }
            break
        }
        debugPrint(parameters)
        return .requestParameters(parameters: parameters, encoding: JSONEncoding.default)
    }
    
    var sampleData: Data { return "".data(using: String.Encoding.utf8)! }
    
    var headers: [String : String]? {
        return nil
    }
}

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

        QSLNetworkProvider.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
            }
        }
    }
}
