//
//  YHPrincleViewModel.swift
//  galaxy
//
//  Created by edy on 2024/4/26.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import SmartCodable

class YHPrincleViewModel: YHBaseViewModel {
    
    var waitResultModel = YHPrincipleWaitResultModel()
    var envelopModel = YHPrincipleEnvelopeModel()
    var uploadDetailModel = YHPrincipleUploadDetailModel()
    
    
    //原则批、正式批弹窗状态
    var alertStatusModel : YHPrincipleAlertStatusModel?
    
    //正式批 操作指引是否确认
    var isOfficialGuildCheckFlag : Bool = false  //true - 已确认  false - 未确认
    
    //正式批 信件列表
    var lettersModel : YHOfficalLetterListModel?
    
}


extension YHPrincleViewModel {
    
    //获取获批信列表
    func getApprovalLetter(param:[String : Any],callback:((_ success: Bool,_ error:YHErrorModel?)->())?) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.getApprovalLetterApi
        let _ = YHNetRequest.getRequest(url: strUrl,params: param) { [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 = YHOfficalLetterListModel.deserialize(dict: dic as? [AnyHashable : Any]) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callback?(false, err)
                    return
                }
                
                
                var arrList : [YHOfficalLetterModel] = []
                for (index,item) in resultModel.list.enumerated() {
                    arrList.append(item)
                }
                resultModel.list = arrList
                self.lettersModel = resultModel
                callback?(true, nil)
            } else {
                
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback?(false, err)
            }
            
        } failBlock: { err in
            callback?(false, err)
        }
    }
    
    
    //上报弹窗状态
    func postAlertStatus(_ type : Int, callback:((_ success: Bool, _ error:YHErrorModel?)->())?) {
        
        var params: [String : Any] = [:]
        if type == 14 {
            //identify      = 14 // 原则批获批祝贺弹窗
            params = ["identify":14]
        } else if type == 6 {
            //identify               = 6  //正式批弹窗 - 获批结果页
            params = ["identify":6]
        } else if type == 2 {
            //identify              = 2  // 香港身份获批操作指引
            params = ["identify":2]
            
        } else if type == 3 {
            //identify      = 3 //  家庭信息确认风险弹窗
            params = ["identify":3]


        } else if type == 15 {
            //identify              = 2  // 首页正式批弹窗
            params = ["identify":15]
        }
        else {
            return
        }
            
        
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.postAlertStatusApi

        let _ = YHNetRequest.postRequest(url: strUrl, params: params) {
            json, code in
            //1. json字符串 转 对象
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                callback?(true, nil)
                
            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback?(false, err)
            }
            
        } failBlock: { err in
            callback?(false, err)
        }
    }
    
    
    //获取正式批 操作指引 确认状态
    func getOfficialCheckStatus(callback:((_ success: Bool,_ error:YHErrorModel?)->())?) {
        let param = ["identify":2]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.getOfficialCheckStatusApi
        let _ = YHNetRequest.getRequest(url: strUrl,params: param) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                if let flag = json.data as? Bool {
                    self.isOfficialGuildCheckFlag = flag
                } else {
                    self.isOfficialGuildCheckFlag = false
                }
                callback?(true, nil)
            } else {
                
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback?(false, err)
            }
            
        } failBlock: { err in
            callback?(false, err)
        }
    }
    
    //获取正式批 操作指引 确认状态
    func getAgreementCheck(_ archivistId: Int, callback:((_ success: Bool,_ error:YHErrorModel?)->())?) {
        let param = ["archivistId": archivistId]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.agreementCheck
        let _ = YHNetRequest.getRequest(url: strUrl,params: param) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            
            if json.code == 200 {
                callback?(true, nil)
            } else {
                
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback?(false, err)
            }
            
        } failBlock: { err in
            callback?(false, err)
        }
    }
    
    //获取是否弹窗 原则批、正式批
    func getPrincleStatus(callback:((_ success: Bool,_ error:YHErrorModel?)->())?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.getAlertStatusApi
        let _ = YHNetRequest.getRequest(url: strUrl) { [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 = YHPrincipleAlertStatusModel.deserialize(dict: dic as? [AnyHashable : Any]) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callback?(false, err)
                    return
                }
                self.alertStatusModel = resultModel
                callback?(true, nil)
                
            } else {
                
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback?(false, err)
            }
            
        } failBlock: { err in
            callback?(false, err)
        }
    }
    
    
    func getPrincipleWaitReviewResult(params:[String : Any], callback:((_ success: Bool,_ error:YHErrorModel?)->())?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.getProfileList
        
        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 = YHPrincipleWaitResultModel.deserialize(dict: dic as? [AnyHashable : Any]) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callback?(false, err)
                    return
                }
                self.waitResultModel = resultModel
                callback?(true, nil)
                
            } else {
                
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback?(false, err)
            }
            
        } failBlock: { err in
            callback?(false, err)
        }
    }
    
    func getEnvelopeInfo(orderId:Int, callback:((_ success: Bool,_ error:YHErrorModel?)->())?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.getReviewResult
        
        let params: [String : Any] = ["order_id": orderId]
        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 = YHPrincipleEnvelopeModel.deserialize(dict: dic as? [AnyHashable : Any]) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callback?(false, err)
                    return
                }
                self.envelopModel = resultModel
                callback?(true, nil)
                
            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback?(false, err)
            }
            
        } failBlock: { err in
            callback?(false, err)
        }
    }
    
    func getPrincipleUploadDetail(orderId:Int, callback:((_ success: Bool,_ error:YHErrorModel?)->())?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.getUploadDetail
        
        let params: [String : Any] = ["order_id": orderId]
        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 = YHPrincipleUploadDetailModel.deserialize(dict: dic as? [AnyHashable : Any]) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callback?(false, err)
                    return
                }
                self.uploadDetailModel = resultModel
                callback?(true, nil)
                
            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback?(false, err)
            }
            
        } failBlock: { err in
            callback?(false, err)
        }
    }
    
    func requestIsSendMail(orderId:Int, callback:((_ isSend: Bool)->())?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.getIsSendMail
        let params: [String : Any] = ["order_id": orderId]
        let _ = YHNetRequest.getRequest(url: strUrl,params: params) { json, code in
            //1. json字符串 转 对象
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                if let isSend = json.data as? Bool {
                    callback?(isSend)
                } else {
                    callback?(false)
                }
                
            } else {
                callback?(false)
            }
            
        } failBlock: { err in
            callback?(false)
        }
    }
    
    func uploadPrincipleFiles(_ files: [YHPrincipleRequestModel], callback:((_ success: Bool, _ error:YHErrorModel?)->())?) {
        
        guard let arr = files.toArray() else { return }
        let params: [String : Any] = ["file_list" : arr]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.uploadFiles

        let _ = YHNetRequest.postRequest(url: strUrl, params: params) {
            json, code in
            //1. json字符串 转 对象
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                callback?(true, nil)
                
            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback?(false, err)
            }
            
        } failBlock: { err in
            callback?(false, err)
        }
    }
    
    func uploadImageArr(_ targetImgArr:[YHSelectImageItem], successBlock:(([YHPrincipleContentUrlModel])->())?)  {
        
        let ossGroup = DispatchGroup()
        var ossArr:[YHPrincipleContentUrlModel] = []

        YHHUD.show(.progress(message: "上传中..."))
        // 先将所有图片组上传到OSS
        for item in targetImgArr {
            if let image = item.data {
                ossGroup.enter()
                self.uploadImage(image, imageName:item.name) {
                    success, urlModel in
                    if success, let model = urlModel {
                        ossArr.append(model)
                    }
                    ossGroup.leave()
                }
            }
        }
        
        // 再将OSS上传信息组上传到服务器
        ossGroup.notify(queue: .main) {
            YHHUD.hide()
            if ossArr.count <= 0 {
                YHHUD.flash(message: "上传失败")
                successBlock?([])
                return
            }
            successBlock?(ossArr)
        }
     }
    
    func uploadImage(_ img: UIImage, imageName:String, callBack:((Bool, YHPrincipleContentUrlModel?)->())?)  {
        
        // 先OSS上传得到URL
        self.uploadImage(img) {
            url, error in
            if let url = url, !url.isEmpty {
                var suffix = "jpg"
                let suffixName = url.pathExtension.lowercased()
                if !suffixName.isEmpty {
                    suffix = suffixName
                }
                
                // 再调用业务接口
                let model = YHPrincipleContentUrlModel()
                model.name = imageName
                model.url = url
                model.fileUrl = url
                
                let dateFormatter = self.getUploadTimeFormat()
                let dateString = dateFormatter.string(from: Date())
                model.updated_at = dateString
                
                callBack?(true, model)
                
            } else {
                callBack?(false, nil)
            }
        }
    }
    
    func sendMail(_ mail:String, template: YHPrincipleFileUrlModel,  callback:((_ success: Bool, _ error:YHErrorModel?)->())?) {
        
        let params: [String : Any] = ["url" : template.url,
                                      "file_name": template.name,
                                      "email": mail]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.sendMail

        let _ = YHNetRequest.postRequest(url: strUrl, params: params) {
            json, code in
            //1. json字符串 转 对象
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                callback?(true, nil)
                
            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback?(false, err)
            }
            
        } failBlock: { err in
            callback?(false, err)
        }
    }
    
    func getUploadTimeFormat() -> DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "YYYY.MM.dd"
        return dateFormatter
    }
}
