//
//  YHBaseViewModel.swift
//  galaxy
//
//  Created by davidhuangA on 2024/1/8.
//  Copyright © 2024 www.davidhuang.com. All rights reserved.
//

import UIKit
import Alamofire
import SmartCodable

class YHBaseViewModel {
    // 上传方法
    func uploadImage(_ image: UIImage, callBackBlock:@escaping (_ success: String?, _ error:YHErrorModel?)->()) {
#if DEBUG
        let size = image.imageSize()
        YHHUD.flash(message: "\(Float(size/1024/1024))M")
#endif
        
        let strUrl = YHBaseUrlManager.shared.curOssURL() + YHAllApiName.OSS.uploadApi
        let boundary = UUID().uuidString
        let headers: HTTPHeaders = [
            "Content-type": "multipart/form-data; boundary=\(boundary)",
            "businessCode": "4001001"
        ]
        let _ = YHNetRequest.uplaodRequest(url: strUrl, headers: headers, image: image) { [weak self] json, code in
            guard let _ = self else { return }
            if json.code == 200 {
                callBackBlock(json.data as? String, nil)
            } else {
                let error : YHErrorModel = YHErrorModel(errorCode:Int32(json.code), errorMsg: json.msg)
                callBackBlock(nil, error)
            }
        } failBlock: { err in
            callBackBlock(nil, err)
        }
    }
    
    //换取一张
    func getPublicImageUrl(_ url: String, callBackBlock:@escaping (_ success: String?, _ error:YHErrorModel?)->()) {
        let strUrl = YHBaseUrlManager.shared.curOssURL() + YHAllApiName.OSS.getPublicApi
        let param: [String: Any] = ["fileUrl": url]
        let _ = YHNetRequest.getRequest(url: strUrl, params: param) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let _ = self else { return }
            if json.code == 200 {
                callBackBlock(json.data as? String, nil)
            } else {
                let error : YHErrorModel = YHErrorModel(errorCode:Int32(json.code), errorMsg: json.msg)
                callBackBlock(nil, error)
            }
        } failBlock: { err in
            callBackBlock(nil,err)
        }
    }
    
    //换取多张图片
    func getPublicImageUrls(_ url: [String], callBackBlock:@escaping (_ success: [String : Any]?, _ error:YHErrorModel?)->()) {
        let strUrl = YHBaseUrlManager.shared.curOssURL() + YHAllApiName.OSS.getPublicApi
        let param: [String: Any] = ["fileUrl": url]
        let _ = YHNetRequest.getRequest(url: strUrl, params: param) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let _ = self else { return }
            if json.code == 200 {
                callBackBlock(json.data as? [String : Any], nil)//使用的同学完善
            } else {
                let error : YHErrorModel = YHErrorModel(errorCode:Int32(json.code), errorMsg: json.msg)
                callBackBlock(nil, error)
            }
        } failBlock: { err in
            callBackBlock(nil,err)
        }
    }
}
