CNLiveMineViewModel.swift 6.83 KB
//
//  CNLiveMineViewModel.swift
//  metaCode
//
//  Created by open on 2023/6/14.
//

import Foundation
import CNLiveRequestBastKit

enum CNLiveMineRequestType {
    case nickName
    case gender
    case email
    case location
    case birthday
}
// 成功
typealias resultSuccessBlock = () -> Void

class CNLiveMineViewModel: NSObject {
    
    /// 提交更新用户单项数据
    /// - Parameters:
    ///   - type: nickName-昵称,gender-性别,email-邮箱, location-联系方式,birthday-生日yyyy-MM-dd
    ///   - value: 对应的信息,性别,m:男、f:女、n:未知
    static func requestUpdateUserInfoAction(type: CNLiveMineRequestType,value: String, resultBlock: @escaping resultSuccessBlock) {
        
        let param = NSMutableDictionary.init()
        if type == .nickName {
            param.setValue("nickName", forKey: "type")
            param.setValue(value, forKey: "value")
        }
        if type == .gender {
            param.setValue("gender", forKey: "type")
            
            param.setValue(value, forKey: "value")
        }
        if type == .email {
            param.setValue("email", forKey: "type")
            param.setValue(value, forKey: "value")
        }
        if type == .location {
            param.setValue("location", forKey: "type")
            param.setValue(value, forKey: "value")
        }
        if type == .birthday {
            param.setValue("birthday", forKey: "type")
            param.setValue(value, forKey: "value")
        }
        param.setValue(UserInfoManager.shared.userInfo.uid, forKey: "uid")
        param.setValue(UserInfoManager.shared.userInfo.token, forKey: "token")
        showLoading(message: "")
        CNLiveNetworking.setAllowRequestDefaultArgument(true)
        CNLiveNetworking.setupShowDataResult(false)
        CNLiveNetworking.requestNetwork(with: .POST, urlString: "/open/api2/user/updateUserById", param: param as! [String : Any], cacheType: .networkOnly) { task, result, error in
            hiddenLoading()
            if (error == nil) {
                let resp = result as! NSDictionary
                let errorCode = resp["errorCode"]
                if (errorCode as! String == "0") {
                    showMessage(message: "更改成功")
                    resultBlock()
                } else {
                    showMessage(message: resp["errorMessage"] as! String)
                }
            } else {
                showMessage(message: "修改信息失败")
            }
        }
    }
    
    
    /// 上传并修改头像
    /// - Parameters:
    ///   - image: 头像
    ///   - resultBlock: 返回
    static func requestUploadIconAction(_ image: UIImage,resultBlock: @escaping resultSuccessBlock) {
             
        CNLiveMineViewModel.requestAccessTokenAction() {
            let param = NSMutableDictionary.init()
            param.setValue(UserInfoManager.shared.userInfo.uid, forKey: "uid")
            param.setValue(UserInfoManager.shared.userInfo.token, forKey: "token")
            param.setValue(UserInfoManager.shared.userInfo.access_token, forKey: "access_token")
            showLoading(message: "修改头像中...")
            CNLiveNetworking.setAllowRequestDefaultArgument(true)
            CNLiveNetworking.setupShowDataResult(false)
            CNLiveNetworking.uploadNetwork(withURLString: "/open/api2/user/updateUserFaceById", param: param as? [AnyHashable : Any]) { formData in
                let imageData = image.jpegData(compressionQuality: 1.0)
                formData?.appendPart(withFileData: imageData! as Data, name: "face", fileName: ".jpg", mimeType: "image/jpg")
            } progressBlock: { progress in
                print("已上传==>\(progress!.fractionCompleted*100)")
            } completionBlock: { task, result, error in
                hiddenLoading()
                if (error == nil) {
                    let resp = result as! NSDictionary
                    let errorCode = resp["errorCode"]
                    if (errorCode as! String == "0") {
                        showMessage(message: "头像更改成功")
                        let data = resp["data"] as! Dictionary<String, Any>
                        let userInfo = UserInfoManager.shared.userInfo
                        userInfo.faceUrl = data["faceUrl"] as! String
                        userInfo.bigFaceUrl = data["bigFaceUrl"] as! String
                        UserInfoManager.cacheUserInfo(userInfo: userInfo)
                        resultBlock()
                    } else {
                        showMessage(message: resp["errorMessage"] as! String)
                    }
                } else {
                    showMessage(message: "头像更改成功")
                }
            }
        }
    }
    
    /// 获取access_token
    /// - Parameter resultBlock: 结果返回
    static func requestAccessTokenAction(resultBlock: @escaping resultSuccessBlock) {
        //当前时间大于最大允许时间则表明当前access_token已经过期需要重新请求
        if CNLiveMineViewModel.timeStamp > NSNumber(string: UserInfoManager.shared.userInfo.expires_in)?.intValue ?? 0 {
            let param = NSMutableDictionary.init()
            param.setValue(APPId, forKey: "appId")
            param.setValue("3cc9f12db322a3d3656012ef929604cf6d6847471535f9", forKey: "secret")
            showLoading(message: "")
            CNLiveNetworking.setAllowRequestDefaultArgument(false)
            CNLiveNetworking.setupShowDataResult(false)
            CNLiveNetworking.requestNetwork(with: .POST, urlString: "/open/api2/token", param: (param as! [AnyHashable : Any]), cacheType: .networkOnly) { task, result, error in
                hiddenLoading()
                if (error == nil) {
                    let resp = result as! NSDictionary
                    let errorCode = "\(resp["errorCode"] ?? 0)"
                    if (errorCode == "0") {
                        let data = resp["data"] as! Dictionary<String, Any>
                        let userInfo = UserInfoManager.shared.userInfo
                        userInfo.access_token = data["access_token"] as! String
                        let expires_in = data["expires_in"] as! NSNumber
                        userInfo.expires_in = "\(expires_in.intValue+CNLiveMineViewModel.timeStamp)"
                        UserInfoManager.cacheUserInfo(userInfo: userInfo)
                        resultBlock()
                    } else {
                        showMessage(message: resp["errorMessage"] as! String)
                    }
                } else {
                    showMessage(message: "修改头像失败")
                }
            }
        } else {
            resultBlock()
        }
    }
    
    /// 获取十位时间戳
    static var timeStamp: Int {
        let timeInterval: TimeInterval = NSDate().timeIntervalSince1970
        let timeStamp = Int(timeInterval)
        return timeStamp
    }
}