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

import UIKit
import SmartCodable
import xxtea

class YHLoginViewModel: YHBaseViewModel {
    var userModel: YHUserModel?
    var memberInfo = YHUserMemberInfoModel()

    override init() {
        super.init()
    }
}

class YHUserMemberInfoModel: SmartCodable {
    
    var current_level: Int = 0
    var growth_value: Int = 0
    var max_growth: Int = 0
    
    required init() {
    }
    
    func getVipMemberLevel() -> YHUserVipLevel {
        
        if current_level == 20 {
            return .gold
        }
        if current_level == 30 {
            return .platinum
        }
        if current_level == 40 {
            return .diamond
        }
        return .none
    }
}

// 接口
extension YHLoginViewModel {
    
    // 发送验证码
    func getLoginCode(_ phone: String, code: String, callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        let params: [String: Any] = ["type": "Phone",
                                      "value": XXTEA.encryptString(toBase64String: phone, stringKey: "galaxyapps") ?? phone,
                                      "extend": "register",
                                      "code": "+" + code]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.User.verifyCode
        
        _ = YHNetRequest.postRequest(url: strUrl, params: params) {[weak self] json, _ in
            guard self != nil else { return }
            
            // 1. json字符串 转 对象
            if json.code == 200 {
                YHHUD.flash(message: json.msg)
                callBackBlock(true, nil)
            } else {
                if json.code == 106010006 {
                    YHHUD.flash(message: "验证码已下发，请查看")
                    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, countryCode: String, callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        
        let timestamp = Int(Date().timeIntervalSince1970)
        print(timestamp)
        let params: [String: Any] = ["mobile": XXTEA.encryptString(toBase64String: phone, stringKey: "galaxyapps") ?? phone,
                                      "sms_code": code,
                                      "client": "super_app",
                                      "mobile_area_code": "+" + countryCode,
                                      "testTimestamp": timestamp]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Auth.login
        _ = YHNetRequest.postRequest(url: strUrl, params: params) {[weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            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 正常
                    self.userModel = resultModel
                    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)
        }
    }
    
    func logout(_ callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {

        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Auth.logout
        _ = YHNetRequest.postRequest(url: strUrl) {
            [weak self] json, _ in
            // 1. json字符串 转 对象
            guard self != nil else { return }
            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?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Auth.unregisterApi
        _ = YHNetRequest.postRequest(url: strUrl) {
            [weak self] json, _ in
            // 1. json字符串 转 对象
            guard self != nil else { return }
            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, countryCode: String, callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        
        let timestamp = Int(Date().timeIntervalSince1970)
        print(timestamp)
        var params: [String: Any] = ["union_id": unionId,
                                      "client": "super_app",
                                      "mobile_area_code": "+" + countryCode,
                                      "testTimestamp": timestamp]
        if phone.count != 0 {
            params = ["union_id": unionId,
                      "mobile": XXTEA.encryptString(toBase64String: phone, stringKey: "galaxyapps") ?? phone,
                      "sms_code": code,
                      "client": "super_app",
                      "mobile_area_code": "+" + countryCode,
                      "testTimestamp": timestamp]
        }
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Auth.wxlogin
        _ = YHNetRequest.postRequest(url: strUrl, params: params) {[weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            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 正常
                    self.userModel = resultModel
                    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)
        }
    }
    
    func getUserId(callBack: ((String) -> Void)?) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Auth.getUidApi
        _ = YHNetRequest.getRequest(url: strUrl) {
            [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            printLog(json)
            if let dic = json.data?.peel as? [AnyHashable: Any] {
                if let uid = dic["uid"] as? String {
                    YHLoginManager.shared.userModel?.id = uid
                    callBack?(uid)
                    return
                }
            }
            YHLoginManager.shared.userModel?.id = ""
            callBack?("")
        } failBlock: { _ in
            callBack?("")
        }
    }
    
    func getUserInfo(callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.User.userInfo
        _ = YHNetRequest.getRequest(url: strUrl) {[weak self] json, _ in
            guard self != nil else { return }
            
            // 1. json字符串 转 对象
            if json.code == 200 {
                if let dic = json.data?.peel as? [AnyHashable: Any] {
                    if let mobile = dic["mobile"] as? String {
                        YHLoginManager.shared.userModel?.mobile = mobile
                    }
                }
                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 getMemberInfo(_ callBack: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Member.memberInfoApi
        _ = YHNetRequest.getRequest(url: strUrl) {
            [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let resultModel = YHUserMemberInfoModel.deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    self.memberInfo = YHUserMemberInfoModel()
                    callBack(false, err)
                    return
                }
                self.memberInfo = resultModel
                callBack(true, nil)
                
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                self.memberInfo = YHUserMemberInfoModel()
                callBack(false, error)
            }
            
        } failBlock: { err in
            self.memberInfo = YHUserMemberInfoModel()
            callBack(false, err)
        }
    }
}
