
//
//  YHCertificateViewModel.swift
//  galaxy
//
//  Created by edy on 2024/3/15.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import SmartCodable

enum YHCertificateCategoryId: Int {
    // 子女
    case child = 18
    // 配偶
    case spouse = 19
    // 主申请人
    case mainApplicant = 20
}

enum YHCertificateUploadStatus : Int {
    // 全部
    case all = -1
    // 审核中
    case review = 0
    // 已完成
    case finish = 1
    // 已驳回
    case rejected = 2
    // 待上传
    case preUpload = 3
}


class YHCertificateViewModel: YHBaseViewModel {
    
    var certificateEntryModel : YHCertificateEntryModel?
    var arrQuestionAndAnswer : [YHQuestionAndAnswerModel?] = []
    var arrFileListData : [YHFileListModel?] = []
    
    
    
    //我的证件  清单列表数据
    func getCertificateFileListData( params:[String : Any],callBackBlock:@escaping (_ success: Bool,_ error:YHErrorModel?)->()) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Certificate.documentListApi
        
        let _ = YHNetRequest.getRequest(url: strUrl,params: params) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                let dic = json.data
                guard let resultModel = [YHFileListModel].deserialize(array: dic as? [Any]) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    
                    callBackBlock(false,err)
                    return
                }
                
                for (_,item) in resultModel.enumerated() {
                    let arr = item?.supplement_list.filter { (item) -> Bool in
                        return item.checkStatus == 2 || item.checkStatus == 3
                     }
                    item?.supplement_list = arr ?? []
                }
                var arr = resultModel
                self.arrFileListData = arr
                
                
                callBackBlock(true,nil)
            } else {
                
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                self.arrFileListData = []
                callBackBlock(false,err)
            }
        } failBlock: { err in
            self.arrFileListData = []
            callBackBlock(false,err)
        }
    }
    
    //获取问答列表
    func getQuestionAndAnserList( params:[String : Any],callBackBlock:@escaping (_ success: Bool,_ error:YHErrorModel?)->()) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Certificate.questionAndAnswerApi
        let _ = YHNetRequest.getRequest(url: strUrl,params: params) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                let dic = json.data
                
                guard let resultModel = [YHQuestionAndAnswerModel].deserialize(array: dic as? [Any]) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    
                    callBackBlock(false,err)
                    return
                }
                self.arrQuestionAndAnswer = resultModel
                
                callBackBlock(true,nil)
            } else {
                
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callBackBlock(false,err)
                
            }
            
        } failBlock: { err in
            callBackBlock(false,err)
        }
    }
    
    
    //我的证件  状态数据统计
    func getCertificateStatisticData( params:[String : Any],callBackBlock:@escaping (_ success: Bool,_ error:YHErrorModel?)->()) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Certificate.statisticApi
        
        let _ = YHNetRequest.getRequest(url: strUrl,params: params) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                let dic = json.data
                guard let resultModel = YHCertificateEntryModel.deserialize(dict: dic as? [AnyHashable : Any]) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    
                    callBackBlock(false,err)
                    return
                }
                self.certificateEntryModel = resultModel
                callBackBlock(true,nil)
            } else {
                
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callBackBlock(false,err)
                
            }
            
        } failBlock: { err in
            callBackBlock(false,err)
        }
    }
    
    func getCertificateList(params:[String: Any], callBack:@escaping (_ listInfo: YHUploadCertificateInfo?, _ error:YHErrorModel?)->()) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Certificate.certificateListApi
        let _ = YHNetRequest.getRequest(url: strUrl, params:params) { json, code in
            
            printLog("model 是 ==> \(json)")
            let dic = json.data
            
            if json.code == 200 {
                guard let result = YHUploadCertificateInfo.deserialize(dict: dic as? Dictionary ) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    
                    callBack(nil, err)
                    return
                }
                callBack(result, nil)
                
            } else {
                let error : YHErrorModel = YHErrorModel(errorCode:Int32(json.code), errorMsg: json.msg)
                callBack(nil, error)
            }
            
        } failBlock: { err in
            callBack(nil, err)
        }
    }
    
    // 上传/重命名/删除 证件
    func updateCertificates(params:[String : Any], callBack:((Bool, YHErrorModel?)->())?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Certificate.certificateUploadApi
        let _ = YHNetRequest.postRequest(url: strUrl, params:params) { json, code in
            
            if json.code == 200 {
                callBack?(true, nil)
            } else {
                let error : YHErrorModel = YHErrorModel(errorCode:Int32(json.code), errorMsg: json.msg)
                callBack?(false, error)
            }
            
        } failBlock: { err in
            callBack?(false, err)
        }
    }
    
    // 更改证件
    // operation参数必填，必须是：add(上传)、del（删除）、rename（重命名）
    func updateCertificateItem(supplementsId:Int, urlModels: [YHContentUrl], operation:String, rename:String, callBack:((Bool, YHErrorModel?)->())?) {
        
        var files:[[String: Any]] = []
        for model in urlModels {
            let dic:[String : Any] = [
                    "id" : supplementsId,
                    "content_url": [
                    "name": operation == "rename" ? rename: model.name,
                    "url": model.url,
                    "suffix": model.suffix]]
            files.append(dic)
        }
        
        let params: [String: Any] = [
            "file_info" : files,
            "operation" : operation,
        ]
    
        self.updateCertificates(params: params) {
            success, error in
            callBack?(success, error)
        }
    }
}


extension YHCertificateViewModel {
    
    func showUploadSheetView(supplementId: Int, completion:(()->())?) {
        
        let sheetView = YHCertificateUploadSheetView.sheetView()
        sheetView.maxSelectCount = 9
        sheetView.uploadFilesBlock = {
            [weak self] fileUrl in
            guard let self = self else { return }
            print(fileUrl)
            uploadFile(fileUrl, supplementId: supplementId) {
                completion?()
             }
        }
        sheetView.uploadImageBlock = {
            [weak self] targetImgArr in
            guard let self = self else { return }
            uploadImageArr(targetImgArr, supplementId: supplementId) {
                completion?()
            }
        }
        sheetView.show()
    }
    
    func uploadFile(_ fileUrl:URL, supplementId:Int, successBlock:(()->())?)  {
        if let fileData = try? Data(contentsOf: fileUrl) {
            // 将文件数据上传到服务器
            let size = String(format: "%.2fM", Double(fileData.count)/(1024.0 * 1024.0))
            print("\(size)")
            // 先OSS上传得到URL
            YHHUD.show(.progress(message: "上传中..."))
            self.uploadFile(fileUrl.absoluteString) {
                [weak self] successUrl, error in
                guard let self = self else { return }
                
                YHHUD.hide()
                
                // 再调用业务接口
                if let successUrl = successUrl, !successUrl.isEmpty {
                    let fileName = successUrl.lastPathComponent
                    let suffixName = successUrl.pathExtension.lowercased()
                    let model = YHContentUrl()
                    model.name = fileName
                    model.url = successUrl
                    model.suffix = suffixName
                    YHHUD.show(.progress(message: "上传中..."))
                    self.updateCertificateItem(supplementsId:supplementId, urlModels:[model], operation: "add", rename: "") {
                        success, error in
                        YHHUD.hide()
                        if success {
                            YHHUD.flash(message: "上传成功")
                        } else {
                            var msg = "上传失败"
                            if let errorMsg = error?.errorMsg, !errorMsg.isEmpty {
                                msg = errorMsg
                            }
                            YHHUD.flash(message:msg)
                        }
                        successBlock?()
                    }
                    return
                }
                var msg = "上传图片失败"
                if let errorMsg = error?.errorMsg, !errorMsg.isEmpty {
                    msg = errorMsg
                }
                YHHUD.flash(message: msg)

            }
        } else {
            YHHUD.flash(message: "识别文件失败")
        }
    }
    
    func uploadImageArr(_ targetImgArr:[YHSelectImageItem], supplementId:Int, successBlock:(()->())?)  {
        
        let ossGroup = DispatchGroup()
        var ossArr:[YHContentUrl] = []

        YHHUD.show(.progress(message: "上传中..."))
        // 先将所有图片组上传到OSS
        for item in targetImgArr {
            if let image = item.data {
                ossGroup.enter()
                uploadImage(image, imageName:item.name) {
                    success, urlModel in
                    if success, let model = urlModel {
                        ossArr.append(model)
                    }
                    ossGroup.leave()
                }
            }
        }
        
        // 再将OSS上传信息组上传到服务器
        ossGroup.notify(queue: .main) {
            if ossArr.count <= 0 {
                YHHUD.hide()
                YHHUD.flash(message: "上传失败")
                return
            }
            
            self.updateCertificateItem(supplementsId:supplementId, urlModels:ossArr, operation: "add", rename: "") {
                [weak self] success, error in
                guard let self = self else { return }

                YHHUD.hide()
                if  success {
                    if ossArr.count == targetImgArr.count {
                        YHHUD.flash(message: "上传成功")
                    } else {
                        YHHUD.flash(message: "\(ossArr.count)张照片上传成功\n\(targetImgArr.count-ossArr.count)张照片上传失败")
                    }
                    successBlock?()
                    
                } else {
                    YHHUD.flash(message: "上传失败")
                }
            }
        }
    }
    
    func uploadImage(_ img: UIImage, imageName:String, callBack:((Bool, YHContentUrl?)->())?)  {
        
        // 先OSS上传得到URL
        self.uploadImage(img) {
            [weak self] url, error in
            guard let self = self else { return }
            if let url = url, !url.isEmpty {
                var suffix = "jpg"
                let suffixName = url.pathExtension.lowercased()
                if !suffixName.isEmpty {
                    suffix = suffixName
                }
                
                // 再调用业务接口
                let model = YHContentUrl()
                model.name = imageName
                model.url = url
                model.suffix = suffix
                callBack?(true, model)
            } else {
                callBack?(false, nil)
            }
        }
    }
    
}
