CNLiveMineViewModel.swift 14.1 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
}
enum CNLiveMineResponseType {
    case success
    case failed
    case noNetwork
    case unkonw
}
typealias resultBlock = (_ result: Bool) -> Void
typealias resultNewsBlock = (_ result: Any,_ respStatue :CNLiveMineResponseType) -> 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 resultBlock) {
        
        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(true)
                } else {
                    showMessage(message: resp["errorMessage"] as! String)
                    resultBlock(false)
                }
            } else {
                showMessage(message: "修改信息失败")
                resultBlock(false)
            }
        }
    }
    
    
    /// 上传并修改头像
    /// - Parameters:
    ///   - image: 头像
    ///   - resultBlock: 返回
    static func requestUploadIconAction(_ image: UIImage,resultBlock: @escaping resultBlock) {
             
        CNLiveMineViewModel.requestAccessTokenAction() { result in
            if result {
                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(true)
                        } else {
                            showMessage(message: resp["errorMessage"] as! String)
                            resultBlock(false)
                        }
                    } else {
                        showMessage(message: "头像更改成功")
                        resultBlock(false)
                    }
                }
            } else {
                resultBlock(false)
            }
        }
    }
    
    /// 获取access_token
    /// - Parameter resultBlock: 结果返回
    static func requestAccessTokenAction(resultBlock: @escaping resultBlock) {
        //当前时间大于最大允许时间则表明当前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(APPSecret, 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(true)
                    } else {
                        showMessage(message: resp["errorMessage"] as! String)
                        resultBlock(false)
                    }
                } else {
                    showMessage(message: "修改头像失败")
                    resultBlock(false)
                }
            }
        } else {
            resultBlock(false)
        }
    }
    
    /// 上传反馈意见接口
    /// - Parameter resultBlock: 成功回调
    static func requestFeedBack(text: String,contactWay: String,images: NSMutableArray,resultBlock: @escaping resultBlock) {
        if (text.count == 0) {
            showMessage(message: "反馈内容不能为空")
            return
        }
        images.remove("")
        let imageUrl = NSMutableString()
        if images.count > 0 {
            images.forEach { image_url in
                imageUrl.append(image_url as! String)
                imageUrl.append(",")
            }
            imageUrl.deleteCharacters(in: NSRange(location: imageUrl.length - 1, length: 1))
        }
        let param = NSMutableDictionary()
        param.setValue(imageUrl, forKey: "images")
        param.setValue(text, forKey: "text")
        param.setValue(UserInfoManager.shared.userInfo.uid, forKey: "sid")
        param.setValue(contactWay, forKey: "contactWay")
        param.setValue(UserInfoManager.shared.userInfo.nickName, forKey: "contactName")
        param.setValue("", forKey: "category")
        param.setValue("ios", forKey: "plat")
        param.setValue(Bundle.main.infoDictionary?["CFBundleVersion"] as! String, forKey: "version")
        param.setValue(UIDevice.current.identifierForVendor?.uuidString.replacingOccurrences(of: "-", with: "") ?? "", forKey: "deviceId")
        showLoading(message: "")
        CNLiveNetworking.setAllowRequestDefaultArgument(true)
        CNLiveNetworking.setupShowDataResult(false)
        CNLiveNetworking.requestNetwork(with: .POST, urlString: APPBaseMCUrl+"/commonApi/collectFeedback", param: param as! [String : String], cacheType: .networkOnly) { task, result, error in
            hiddenLoading()
            if (error == nil) {
                let resp = result as! NSDictionary
                let errorCode = "\(resp["errorCode"] ?? "0")"
                if (errorCode == "0") {
                    resultBlock(true)
                } else {
                    showMessage(message: resp["errorMessage"] as! String)
                    resultBlock(false)
                }
            } else {
                showMessage(message: "提交失败")
                resultBlock(false)
            }
        }
    }
    
    /// 获取系统消息
    /// - Parameter resultBlock: 结果返回
    static func requestMessage(resultBlock: @escaping resultNewsBlock) {
        showLoading(message: "")
        CNLiveNetworking.setAllowRequestDefaultArgument(true)
        CNLiveNetworking.setupShowDataResult(false)
        CNLiveNetworking.requestNetwork(with: .GET, urlString: APPBaseMCUrl+"/newsApi/getNews", param: ["sid":UserInfoManager.shared.userInfo.uid], cacheType: .networkOnly) { task, result, error in
            hiddenLoading()
            if (error == nil) {
                let resp = result as! NSDictionary
                let errorCode = "\(resp["errorCode"] ?? "0")"
                if (errorCode == "0") {
                    let newsModel = dictionaryToModel(resp as! [String : Any], NewsModel.self,"data") as! NewsModel
                    resultBlock(newsModel,.success)
                } else {
                    showMessage(message: resp["errorMessage"] as! String)
                    resultBlock(NSNull(),.failed)
                }
            } else {
                if CNLiveNetworking.isNetworking() {
                    showMessage(message: "获取失败")
                    resultBlock(NSNull(),.failed)
                } else {
                    showMessage(message: "似乎与网络断开链接")
                    resultBlock(NSNull(),.noNetwork)
                }
            }
        }
    }
    
    /// 获取最新app版本
    /// - Parameter resultBlock: 结果回调
    static func requestSystemNews(resultBlock: @escaping resultNewsBlock) {
        let param = NSMutableDictionary()
        param.setValue("2", forKey: "appType")
        CNLiveNetworking.setAllowRequestDefaultArgument(true)
        CNLiveNetworking.setupShowDataResult(false)
        CNLiveNetworking.requestNetwork(with: .GET, urlString: APPBaseMCUrl+"/commonApi/getVersion", param: param as! [String : String], cacheType: .networkOnly) { task, result, error in
            if (error == nil) {
                let resp = result as! NSDictionary
                let errorCode = "\(resp["errorCode"] ?? "0")"
                if (errorCode == "0") {
                    let userInfoModel = dictionaryToModel(resp as! [String : Any], UpdateInfoModel.self,"data") as! UpdateInfoModel
                    let ver1 = "\(userInfoModel.version.split(separator: "_").last ?? "0")"
                    let ver2 = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String
                    print("获取的新版本号=>\(ver1),原来的版本号=>\(ver2)")
                    if CNLiveMineViewModel.compare(v1: ver1, v2: ver2) {
                        resultBlock(userInfoModel,.success)
                    } else {
                       print("没有新版本")
                    }
                } else {
                    resultBlock(NSNull(),.failed)
                }
            } else {
                if CNLiveNetworking.isNetworking() {
                    resultBlock(NSNull(),.failed)
                } else {
                    resultBlock(NSNull(),.noNetwork)
                }
            }
        }
    }
    
    /// 获取十位时间戳
    static var timeStamp: Int {
        let timeInterval: TimeInterval = NSDate().timeIntervalSince1970
        let timeStamp = Int(timeInterval)
        return timeStamp
    }
    
    /// 比较版本大小,返回是否需要更新
    /// - Parameters:
    ///   - v1: 版本1-新版本
    ///   - v2: 版本2-当前版本
    /// - Returns: true:v1>v2  false: v1<=v2
    static fileprivate func compare(v1: String, v2: String) -> Bool {
        
        if v1.isEmpty && v2.isEmpty || v1.isEmpty {
            return false
        }
        
        if v2.isEmpty {
            return true
        }
        
        let array1 = v1.components(separatedBy: ".")
        let array2 = v2.components(separatedBy: ".")
        let mineCount = array1.count > array2.count ? (array2.count - 1) : (array1.count - 1)
        
        var value1: Int = 0
        var value2: Int = 0
        
        for i in 0...mineCount {
            
            if !(array1[i]).isPurnInt() || !(array2[i]).isPurnInt() {
                return false
            }
            value1 = Int(array1[i])!
            value2 = Int(array2[i])!
            
            //v1版本字段大于v2版本字段
            if value1 > value2 {
                return true
            } else if (value1 < value2) {
                return false
            }
            //v1版本==v2版本字段 继续循环
        }
        if array1.count > array2.count {
            return true
        } else if (array1.count <= array2.count) {
            return false
        }
        return false
    }
    
}