//
//  YHButlerServiceViewModel.swift
//  galaxy
//
//  Created by alexzzw on 2024/9/5.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import Foundation

class YHButlerServiceViewModel {

    /// 获取透传个人信息
    func getUserInfomation(_ id: String, callBackBlock:@escaping (_ dataString: String?, _ avatar: String?, _ error:YHErrorModel?)->()) {
        let params: [String : Any] = ["yh_id": id]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.QiYu.userInfomation
        let _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, code in
            if json.code == 200 {

                guard let data = json.data?.peel, JSONSerialization.isValidJSONObject(data), let jsonData = try? JSONSerialization.data(withJSONObject: data, options: []), let dataString = jsonData.string(encoding: .utf8) else {
                    callBackBlock(nil, nil, YHErrorModel())
                    return
                }
                let avatar = self?.getAvatarFromJsonObject(data)
                callBackBlock(dataString, avatar, nil)
            } else {
                let err : YHErrorModel = YHErrorModel(errorCode:Int32(json.code), errorMsg: json.msg)
                callBackBlock(nil, nil,err)
            }
        } failBlock: { err in
            callBackBlock(nil, nil, err)
        }
    }
    
    func getAvatarFromJsonObject(_ obj: Any) -> String? {
        if let obj = obj as? [[String: Any]], let info = obj.first(where: { element in
            element["key"] as? String == "avatar" && element["value"] != nil
        }) {
            return info["value"] as? String
        } else if let obj = obj as? [String: Any], obj["key"] as? String == "avatar" && obj["value"] != nil {
            return obj["value"] as? String
        }
        return nil
    }
}
