//
//  YHOneKeyLoginViewModel.swift
//  galaxy
//
//  Created by edy on 2024/5/30.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHOneKeyLoginViewModel {
    
    func getSecretKeyInfo(completion: ((String) -> Void)?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Auth.oneKeySecretKeyInfo
        let params = ["iosInfo.bundleId": "com.intelligence.galaxy"]
        _ = YHNetRequest.getRequest(url: strUrl, params: params) { 
            json, _ in
            printLog("model 是 ==> \(json)")
            if json.code == 200 {
                if let dic = json.data?.peel as? [String: Any], let sdkKey = dic["sdkKey"] as? String, !sdkKey.isEmpty {
                    completion?(sdkKey)
                    
                } else {
                    completion?("")
                }
                
            } else {
                completion?("")
            }
            
        } failBlock: { _ in
            completion?("")
        }
    }
    
    func oneKeyLogin(authToken: String, callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        
        let params: [String: Any] = ["auth_token": authToken]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Auth.oneKeyLogin
        _ = YHNetRequest.postRequest(url: strUrl, params: params) {
            
            json, _ in
            printLog(json)
            guard let dic = json.data?.peel as?  [String: Any], let resultModel = YHUserModel.deserialize(from: dic) else {
                let error: YHErrorModel = YHErrorModel(errorCode: -1, errorMsg: "数据解析不成功")
                callBackBlock(false, error)
                return
            }
            
            if json.code == 200 {
                if resultModel.token?.count != 0 {
                    // token 正常
                    YHLoginManager.shared.userModel = resultModel
                    // 数据保存到本地
                    YHLoginManager.shared.saveLocalUserInfo()
                    
                    let newDic = dic.merging(["op_type": "login"]) { (current, _) in current }
                    YHAliYunLogManager.shared.addModuleName(.networkDataType, remark: newDic)
                    
                    NotificationCenter.default.post(name: YhConstant.YhNotification.didLoginSuccessNotifiction, object: nil)
                    
                    // 回调
                    callBackBlock(true, nil)
                } else {
                    let error: YHErrorModel = YHErrorModel(errorCode: -2, errorMsg: "token 不合法")
                    callBackBlock(false, error)
                }
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }

}
