//
//  YHLoginViewModel.swift
//  galaxy
//
//  Created by EDY on 2024/1/17.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHLoginViewModel: YHBaseViewModel {
    var userModel: YHUserModel?
    
    override init() {
        super.init()
    }
}

//接口
extension YHLoginViewModel {
    //发送验证码
    func getLoginCode(_ phone: String, callBackBlock: @escaping (_ success: Bool,_ error:YHErrorModel?)->()) {
        let params: [String : Any] = ["type": "Phone",
                                      "value": phone,
                                      "extend":"register"]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.User.verifyCode
        let _ = YHNetRequest.postRequest(url: strUrl, params: params) {[weak self] json, code in
            guard self != nil else { return }
            
            //1. json字符串 转 对象
            if json.code == 200 {
                YHHUD.flash(message: json.msg)
                callBackBlock(true,nil)
            } else {
                let error : YHErrorModel = YHErrorModel(errorCode:Int32(json.code),errorMsg: json.msg)
                callBackBlock(false,error)
            }
        } failBlock: { err in
            callBackBlock(false,err)
        }
    }
    
    func login(phone: String, code: String,callBackBlock: @escaping (_ success: Bool,_ error: YHErrorModel?)->()) {
        
        let timestamp = Int(Date().timeIntervalSince1970)
        print(timestamp)
        let params: [String : Any] = ["mobile": phone,
                                      "sms_code": code,
                                      "client": "super_app",
                                      "testTimestamp":timestamp]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Auth.login
        let _ = YHNetRequest.postRequest(url: strUrl, params: params) {[weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            printLog(json)
            let dic = json.data
            guard let resultModel = YHUserModel.deserialize(dict: dic as? [AnyHashable : Any]) else {
                let error : YHErrorModel = YHErrorModel(errorCode:-1,errorMsg: "数据解析不成功")
                callBackBlock(false,error)
                return
            }
            
            if json.code == 200 {
                if resultModel.token?.count != 0 {
                    //token 正常
                    self.userModel = resultModel
                    YHLoginManager.shared.userModel = resultModel
                    
                    //数据保存到本地
                    YHLoginManager.shared.saveLocalUserInfo()
                    
                    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)
        }
    }
    
    func logout(_ callBackBlock: @escaping (_ success: Bool,_ error: YHErrorModel?)->()) {

        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Auth.logout
        let _ = YHNetRequest.postRequest(url: strUrl) {
            [weak self] json, code in
            //1. json字符串 转 对象
            guard self != nil else { return }
            printLog(json)
            _ = json.data
            
            if json.code == 200 {
                callBackBlock(true, nil)
                
            } else {
                let error : YHErrorModel = YHErrorModel(errorCode:Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
            
        } failBlock: { error in
            callBackBlock(false, error)
        }
    }
    
    
    //注销app
    func unrigisterApp(_ callBackBlock: @escaping (_ success: Bool,_ error: YHErrorModel?)->()) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Auth.unregisterApi
        let _ = YHNetRequest.postRequest(url: strUrl) {
            [weak self] json, code in
            //1. json字符串 转 对象
            guard self != nil else { return }
            printLog(json)
            _ = json.data
            
            if json.code == 200 {
                callBackBlock(true, nil)
                
            } else {
                let error : YHErrorModel = YHErrorModel(errorCode:Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
            
        } failBlock: { error in
            callBackBlock(false, error)
        }
    }
    
    func wxlogin(unionId: String, phone: String, code: String, callBackBlock: @escaping (_ success: Bool,_ error: YHErrorModel?)->()) {
        
        let timestamp = Int(Date().timeIntervalSince1970)
        print(timestamp)
        var params: [String : Any] = ["union_id": unionId,
                                      "client": "super_app",
                                      "testTimestamp":timestamp]
        if phone.count != 0 {
            params = ["union_id": unionId,
                      "mobile": phone,
                      "sms_code": code,
                      "client": "super_app",
                      "testTimestamp":timestamp]
        }
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Auth.wxlogin
        let _ = YHNetRequest.postRequest(url: strUrl, params: params) {[weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            printLog(json)
            let dic = json.data
            guard let resultModel = YHUserModel.deserialize(dict: dic as? [AnyHashable : Any]) else {
                let error : YHErrorModel = YHErrorModel(errorCode:-1,errorMsg: "数据解析不成功")
                callBackBlock(false,error)
                return
            }
            
            if json.code == 200 {
                if resultModel.token?.count != 0 {
                    //token 正常
                    self.userModel = resultModel
                    YHLoginManager.shared.userModel = resultModel
                    
                    //数据保存到本地
                    YHLoginManager.shared.saveLocalUserInfo()
                    
                    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)
        }
    }
    
    func getUserId(callBack: ((String)->())?) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Auth.getUidApi
        let _ = YHNetRequest.getRequest(url: strUrl) {
            [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            printLog(json)
            if let dic = json.data as? [AnyHashable : Any] {
                if let uid = dic["uid"] as? String {
                    YHLoginManager.shared.userModel?.id = uid
                    callBack?(uid)
                    return
                }
            }
            YHLoginManager.shared.userModel?.id = ""
            callBack?("")
        } failBlock: { err in
            callBack?("")
        }
    }
}
