//
//  YHLoginManager.swift
//  galaxy
//
//  Created by EDY on 2024/2/22.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHLoginManager: NSObject {
    static let shared = YHLoginManager()
    
    var userModel: YHUserModel?
    var deviceTokenModel : YHDeviceTokenModel = YHDeviceTokenModel()
    
    //检查到未登录的情况下 调用登录界面，在登录成功后，是否需要继续之前的行为
    typealias Block = () -> ()
    var loginSuccessActionBlock : Block?
    
    private override init() {}
    
    var needJumpToMsgTabFlag : Bool = false
    // 是否展示了版本更新
    var isShowVersionUpdate:Bool = false
    
    
    //H5 需要的token
    var h5Token : String {
        get {
            if let param = self.userModel?.token,param.count > 5 {
                printLog(param)
                var token : String = param
                let addtionString = String.randomAlphaNumericStringT(6)//随机6个字母或者数字
                let indexToInsert = token.index(token.startIndex, offsetBy: 6) //插入位置，这里以第六个字符后面为例
                token.insert(contentsOf: addtionString, at: indexToInsert)
                return token
            }
            return ""
        }
    }
}

extension YHLoginManager {
    func isLogin() -> Bool {
        let ttt = userModel?.token?.count ?? 0
        if ttt != 0 {
            return true
        }
        return false
    }
    
    // 保存用户数据到本地
    func saveLocalUserInfo() {
        if let userModel = userModel {
            UserDefaults.standard.set(userModel.toDictionary(), forKey: YhConstant.KLoginedInfoKey)
            UserDefaults.standard.synchronize()
            YHAnalytics.login(userModel.id ?? "")
        }
    }
    
    // 清空用户数据
    func clearUserInfo() {
        userModel = nil
        deviceTokenModel.registerId = ""
        UserDefaults.standard.set(nil, forKey: YhConstant.KLoginedInfoKey)
        UserDefaults.standard.synchronize()
        YHAnalytics.loginout()
    }
    
    func loadLocalUserInfoData() {
        
        guard let dic = UserDefaults.standard.value(forKey: YhConstant.KLoginedInfoKey) as? [String : Any],let resultModel = YHUserModel.deserialize(from: dic) else {
            return
        }
        self.userModel = resultModel
    }
}
