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

import Foundation

class YHButlerServiceViewModel {
    
    var userSig: String?

    /// 获取透传个人信息
    func getUserInfomation(_ id: String, callBackBlock: @escaping (_ dataString: String?, _ avatar: String?, _ groupTmpId: Int64?, _ error: YHErrorModel?) -> Void) {
        let params: [String: Any] = ["yh_id": id]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.QiYu.userInfomation
        _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, _ 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, nil, YHErrorModel())
                    return
                }
                let avatar = self?.getValueFromJsonObject(data, key: "avatar") as? String
                let groupTmpId = Int64(self?.getValueFromJsonObject(data, key: "group_tmp_id") as? String ?? "0")
                callBackBlock(dataString, avatar, groupTmpId, nil)
            } else {
                let err: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(nil, nil, nil, err)
            }
        } failBlock: { err in
            callBackBlock(nil, nil, nil, err)
        }
    }
    
    private func getValueFromJsonObject(_ obj: Any, key: String) -> Any? {
        if let obj = obj as? [[String: Any]], let info = obj.first(where: { element in
            element["key"] as? String == key && element["value"] != nil
        }) {
            return info["value"]
        } else if let obj = obj as? [String: Any], obj["key"] as? String == key && obj["value"] != nil {
            return obj["value"]
        }
        return nil
    }
    
    // 当收到机器人非招呼消息时，发送用户id给后端，后端触发发送企业微信
    func sendUserIdInChat(_ userId: String, callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        let params: [String: Any] = ["yh_id": userId]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.QiYu.sendUserIdInChat
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { json, _ in
            // 1. json字符串 转 对象
            printLog("model 是 ==> \(json)")
            if json.code == 200 {
                callBackBlock(true, nil)
            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callBackBlock(false, err)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    /*
     userSig
     */
    func getUsersig(callBackBlock: @escaping (_ success: Bool?, _ error: YHErrorModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.TencentIM.getUsersig
        _ = YHNetRequest.postRequest(url: strUrl, params: [:]) {
            json, _ in
            printLog("model 是 ==> \(json)")
            if json.code == 200 {
                self.userSig = json.data?.peel as? String
                callBackBlock(true, nil)
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
            
        } failBlock: { error in
            callBackBlock(false, error)
        }
    }
}
