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

import Alamofire
import SmartCodable
import UIKit

class YHSmallWhiteBarInfo: SmartCodable {
    var start_time: String = "" // 开始时间
    var end_time: String = "" // 结束时间
    required init() {
    }
}

class YHCardOcrModel: SmartCodable {
    var name: String = ""
    var pingyin: String = ""
    var birth: String = ""
    var gender: String = ""
    var term_begins: String = ""
    var end_of_term: String = ""
    var issuing_authority: String = ""
    var IssueAddress: String = ""
    var card_num: String = ""
    var is_back: String = ""
    var back_term_begins: String = ""
    var back_end_of_term: String = ""
    var back_hk_type: String = ""
    var back_round_trip_number: String = ""

    required init() {
    }
}

class YHBaseViewModel {
    // MARK: 属性

    // 小白条信息
    var smallWhiteBarInfo: YHSmallWhiteBarInfo?

    // MARK: 接口

    // 3、ocr识别 中国身份证 正/反面
    func getChinaCardInfoByOcr(_ url: String, isBack: Int, callBackBlock: @escaping (_ success: Bool, _ model: YHCardOcrModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curOssURL() + YHAllApiName.OCR.cn
        let params: [String: Any] = ["url": url,
                                     "is_back": isBack]
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard self != nil else {
                callBackBlock(false, nil)
                return
            }
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let result = YHCardOcrModel.deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }
                callBackBlock(true, result)
            } else {
                let _: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, nil)
            }
        } failBlock: { _ in
            callBackBlock(false, nil)
        }
    }

    // 2.2、ocr识别 港澳通行证 背面
    func getHKCardBackInfoByOcr(_ url: String, isBack: Int, callBackBlock: @escaping (_ success: Bool, _ model: YHCardOcrModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.OCR.hkmacowBackInfoApi
        let params: [String: Any] = ["url": url,
                                     "is_back": isBack]
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard self != nil else {
                callBackBlock(false, nil)
                return
            }
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let result = YHCardOcrModel.deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }

                callBackBlock(true, result)
            } else {
                let _: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, nil)
            }
        } failBlock: { _ in
            callBackBlock(false, nil)
        }
    }

    // 2、ocr识别 港澳通行证 正面
    func getHKCardInfoByOcr(_ url: String, isBack: Int, callBackBlock: @escaping (_ success: Bool, _ model: YHCardOcrModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curOssURL() + YHAllApiName.OCR.hk
        let params: [String: Any] = ["url": url,
                                     "is_back": isBack]
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard self != nil else {
                callBackBlock(false, nil)
                return
            }
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let result = YHCardOcrModel.deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }
                callBackBlock(true, result)
            } else {
                let _: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, nil)
            }
        } failBlock: { _ in
            callBackBlock(false, nil)
        }
    }

    // 1、ocr获取小白条信息
    func getSmallWhiteBarInfoByOcr(_ url: String, callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        if YHNetworkStatusManager.shared.isNetWorkOK == false {
            DispatchQueue.main.async {
                YHHUD.flash(message: "网络不可用，请检查网络设置")
                let errorModel = YHErrorModel(errorCode: 0, errorMsg: "网络不可用，请检查网络设置")
                callBackBlock(false, errorModel)
            }
            return
        }

        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.OCR.smallWhiteBarApi
        let params: [String: Any] = ["url": url]
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { [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 result = YHSmallWhiteBarInfo.deserialize(from: dic) else {
                    self.smallWhiteBarInfo = nil
                    callBackBlock(false, nil)
                    return
                }
                self.smallWhiteBarInfo = result
                callBackBlock(true, nil)
            } else {
                self.smallWhiteBarInfo = nil
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            self.smallWhiteBarInfo = nil
            callBackBlock(false, err)
        }
    }

    // 图片上传
    func uploadImage(_ image: UIImage, _ isPublic: Bool = false, callBackBlock: @escaping (_ success: String?, _ error: YHErrorModel?) -> Void) {
        // #if DEBUG
//        let size = image.imageSize()
//        YHHUD.flash(message: "\(Float(size/1024/1024))M")
        // #endif

        if YHNetworkStatusManager.shared.isNetWorkOK == false {
            DispatchQueue.main.async {
                YHHUD.flash(message: "网络不可用，请检查网络设置")
                let errorModel = YHErrorModel(errorCode: 0, errorMsg: "网络不可用，请检查网络设置")
                callBackBlock(nil, errorModel)
            }
            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)
                }
            }
        }
    }
    
    // 获取公链URL
    private func getCurrentPublicImageUrl(_ url: String, _ isPublic: Bool = false, callBackBlock: @escaping (_ success: String?, _ error: YHErrorModel?) -> Void) {
        if YHNetworkStatusManager.shared.isNetWorkOK == false {
            DispatchQueue.main.async {
                YHHUD.flash(message: "网络不可用，请检查网络设置")
                let errorModel = YHErrorModel(errorCode: 0, errorMsg: "网络不可用，请检查网络设置")
                callBackBlock(nil, errorModel)
            }
            return
        }
        YHOSSManager.share.updateToken {
            YHOSSManager.share.getPublic(url: url, callBackBlock: { success, error in
//                guard let _ = self else { return }
                DispatchQueue.main.async {
                    // 在这里执行需要在主线程上完成的任务
                    callBackBlock(success, error)
                }
            })
        }
    }

    // 获取公链URL，后续用getRealUsefulUrl，前期的调用默认中转到getRealUsefulUrl
    func getPublicImageUrl(_ url: String, _ isPublic: Bool = false, callBackBlock: @escaping (_ success: String?, _ error: YHErrorModel?) -> Void) {
        getRealUsefulUrl(url) { str in
            if str.count > 0 {
                callBackBlock(str, nil)
            } else {
                let errorModel = YHErrorModel(errorCode: 0, errorMsg: "网络不可用，请检查网络设置")
                callBackBlock(nil, errorModel)
            }
            
        }
    }

    // 上传方法
    func uploadFile(_ url: String, _ isPublic: Bool = false, callBackBlock: @escaping (_ success: String?, _ error: YHErrorModel?) -> Void) {
        if YHNetworkStatusManager.shared.isNetWorkOK == false {
            DispatchQueue.main.async {
                YHHUD.flash(message: "网络不可用，请检查网络设置")
                let errorModel = YHErrorModel(errorCode: 0, errorMsg: "网络不可用，请检查网络设置")
                callBackBlock(nil, errorModel)
            }
            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: @escaping (Bool) -> Void) {
        guard !url.isEmpty, let urlToGo = URL(string: url) else {
            callback(true)
            return
        }
        let task = URLSession.shared.dataTask(with: urlToGo) {
            _, 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: @escaping (String) -> Void) {
        // 判断url是否可以直接访问
        checkUrlIsDirectAccess(url) {
            isAccess in

            if isAccess {
                // url能直接访问
                DispatchQueue.main.async {
                    callback(url)
                }
                return
            }
            // url不能直接访问
            // 进行私链转公链处理
            self.getCurrentPublicImageUrl(url) { success, _ in
                if let successUrl = success {
                    DispatchQueue.main.async {
                        callback(successUrl)
                    }
                } else {
                    // 私链转公链失败
                    DispatchQueue.main.async {
                        callback("")
                    }
                }
            }
        }
    }
}
