//
//  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)->()) {
        let params: [String : Any] = ["type": "Phone",
                                      "value": phone]
        let strUrl = "http://192.168.35.135:18087/" + "user/verify-code"
        let _ = YHNetRequest.postRequest(url: strUrl, params: params) {[weak self] json, code in
            guard let self = self else { return }
            //1. json字符串 转 对象
            if code == 200 {
                callBackBlock(true)
            }
        } failBlock: { err in
            callBackBlock(false)
        }
    }
    
    func login(_ phone: String, code: String,callBackBlock: @escaping (_ success: YHUserModel?)->()) {
        let params: [String : Any] = ["mobile": phone,
                                      "sms_code": code,
                                      "channel": "app",
                                      "client": "super_app"]
        let strUrl = "http://192.168.25.12:18083/" + "auth/login"
        let _ = YHNetRequest.postRequest(url: strUrl, params: params) {[weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            guard let model = NetBaseModel.deserialize(dict: json) else {
                let error : YHErrorModel = YHErrorModel(errorCode:YHErrorCode.dictParseError.rawValue,errorMsg: YHErrorCode.dictParseError.description())
                
                callBackBlock(nil)
                return
            }
            let dic = model.data?.peel
            guard let resultModel = YHUserModel.deserialize(dict: dic as? [AnyHashable : Any]) else {
                callBackBlock(nil)
                return
            }
            self.userModel = resultModel
            callBackBlock(resultModel)
        } failBlock: { err in
            callBackBlock(nil)
        }
    }
}
