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

import Foundation

class QSLCacheManager {
    
    // 缓存用户信息模型
    static func cacheModel(_ model: QSLUserModel) {
//        QSLApi.updateToken(token: model.authToken)
        let encoder = JSONEncoder()
        do {
            let data = try encoder.encode(model)
            UserDefaults.standard.set(data, forKey: "QSLUserModel")
        } catch {
            debugPrint("Encode wrong: \(error)")
        }
    }

    // 获取缓存的用户信息模型
    static func getModel() -> QSLUserModel? {
        if let data = UserDefaults.standard.data(forKey: "QSLUserModel") {
            let decoder = JSONDecoder()
            do {
                let model = try decoder.decode(QSLUserModel.self, from: data)
//                QSLApi.updateToken(token: model.authToken)
                return model
            } catch {
                debugPrint("Decode wrong: \(error)")
            }
        }
        return nil
    }
    
    // 清空缓存，模型清空
    static func clearCache() {
        
        if let _ = UserDefaults.standard.data(forKey: "QSLUserModel") {
//            QSLB.shared.userModel = HolaUserModel()
            UserDefaults.standard.removeObject(forKey: "QSLUserModel")
        }
    }
}

// 订单模型
extension QSLCacheManager {
    
    // 缓存订单模型
    static func cacheOrderModel(_ model: QSLOrderModel) {
        let encoder = JSONEncoder()
        do {
            let data = try encoder.encode(model)
            UserDefaults.standard.set(data, forKey: "QSLOrderModel")
            UserDefaults.standard.synchronize()
        } catch {
            debugPrint("Encode wrong: \(error)")
        }
    }

    // 获取缓存的模型
    static func getOrderModel() -> QSLOrderModel? {
        if let data = UserDefaults.standard.data(forKey: "QSLOrderModel") {
            let decoder = JSONDecoder()
            do {
                let model = try decoder.decode(QSLOrderModel.self, from: data)
                return model
            } catch {
                debugPrint("Decode wrong: \(error)")
            }
        }
        return nil
    }
    
    // 清空缓存，模型清空
    static func clearOrderCache() {
        
        if let _ = UserDefaults.standard.data(forKey: "QSLOrderModel") {
            UserDefaults.standard.removeObject(forKey: "QSLOrderModel")
        }
    }
    
}
