//
//  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, _ isPublic: Bool = false, 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)
//        }
        if YHNetworkStatusManager.shared.isNetWorkOK == false {
            DispatchQueue.main.async {
                YHHUD.flash(message: "网络不可用，请检查网络设置")
                let errorModel = YHErrorModel(errorCode: 0, errorMsg: "网络不可用，请检查网络设置")
                callBackBlock(nil, errorModel)
                return
            }
            return
        }
        YHOSSManager.share.updateToken {
            YHOSSManager.share.putObject(image: image, isPublic) {[weak self] success, error in
                guard let _ = self else { return }
                DispatchQueue.main.async {
                    // 在这里执行需要在主线程上完成的任务
                    callBackBlock(success, error)
                }
            }
        }
    }
    
    func getPublicImageUrl(_ url: String, _ isPublic: Bool = false, 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)
//        }
        if YHNetworkStatusManager.shared.isNetWorkOK == false {
            DispatchQueue.main.async {
                YHHUD.flash(message: "网络不可用，请检查网络设置")
                let errorModel = YHErrorModel(errorCode: 0, errorMsg: "网络不可用，请检查网络设置")
                callBackBlock(nil, errorModel)
                return
            }
            return
        }
        YHOSSManager.share.updateToken {
            YHOSSManager.share.getPublic(url: url, callBackBlock: { [weak self] success, error in
                guard let _ = self else { return }
                DispatchQueue.main.async {
                    // 在这里执行需要在主线程上完成的任务
                    callBackBlock(success, error)
                }
            })
        }
    }
    
    //换取多张图片
    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)
        }
    }
    
    // 上传方法
    func uploadFile(_ url: String, _ isPublic: Bool = false, callBackBlock:@escaping (_ success: String?, _ error:YHErrorModel?)->()) {
//        let strUrl = YHBaseUrlManager.shared.curOssURL() + YHAllApiName.OSS.uploadApi
//        printLog("\(url)")
//        let boundary = UUID().uuidString
//        let headers: HTTPHeaders = [
//            "Content-type": "multipart/form-data; boundary=\(boundary)",
//            "businessCode": "4001001"
//        ]
//        let _ = YHNetRequest.uplaodFileRequest(url: strUrl, headers: headers, fileUrl: url) { [weak self] json, code in
//            guard let self = 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)
//        }
        if YHNetworkStatusManager.shared.isNetWorkOK == false {
            DispatchQueue.main.async {
                YHHUD.flash(message: "网络不可用，请检查网络设置")
                let errorModel = YHErrorModel(errorCode: 0, errorMsg: "网络不可用，请检查网络设置")
                callBackBlock(nil, errorModel)
                return
            }
            return
        }
        YHOSSManager.share.updateToken {
            YHOSSManager.share.putFile(file: url, isPublic, callBackBlock: {[weak self] success, error in
                guard let _ = self else { return }
                DispatchQueue.main.async {
                    // 在这里执行需要在主线程上完成的任务
                    callBackBlock(success, error)
                }
            })
        }
    }
    
    // 验证url是否可直接访问
    func checkUrlIsDirectAccess(_ url: String, callback:((Bool)->())?) {
        
        let task = URLSession.shared.dataTask(with: URL(string: url)!) {
            (data, response, error) in
            if error != nil {
                // url 不可用
                callback?(false)
                return
            }
            guard let httpResponse = response as? HTTPURLResponse else {
                // url 不可用
                callback?(false)
                return
            }
            if httpResponse.statusCode == 200 {
                // url可用
                callback?(true)
                
            } else {
                // url 不可用
                callback?(false)
            }
        }
        task.resume()
    }
        
    // 传入的url无论是公链还是私链 最后返回一个可用链(私转公失败会返回空)
    func getRealUsefulUrl(_ url: String, callback:((String)->())?) {
        // 判断url是否可以直接访问
        self.checkUrlIsDirectAccess(url) {
            isAccess in
            
            if isAccess {
                // url能直接访问
                DispatchQueue.main.async {
                    callback?(url)
                }
                return
            }
            // url不能直接访问
            // 进行私链转公链处理
            self.getPublicImageUrl(url) { success, error in
                if let successUrl = success {
                    DispatchQueue.main.async {
                        callback?(successUrl)
                    }
                } else {
                    // 私链转公链失败
                    DispatchQueue.main.async {
                        callback?("")
                    }
                }
            }
        }
    }
}
