//
//  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?) -> Void)?) {
        YHHUD.show(.progress(message: ""))
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.getApprovalLetterApi
        _ = YHNetRequest.getRequest(url: strUrl, params: param) { [weak self] json, _ in
            
            YHHUD.hide()
            // 1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                
                guard let dic = json.data?.peel as? [String: Any], let resultModel = YHOfficalLetterListModel.deserialize(from: dic) 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?) -> Void)?) {
        
        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 if type == 20 {
            // identify              = 20  // 首页 银河管家 功能指引
            params = ["identify": 20]
        } else {
            return
        }
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.postAlertStatusApi

        _ = YHNetRequest.postRequest(url: strUrl, params: params) {
            json, _ 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?) -> Void)?) {
        let param = ["identify": 2]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.getOfficialCheckStatusApi
        _ = YHNetRequest.getRequest(url: strUrl, params: param) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                if let flag = json.data?.peel 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?) -> Void)?) {
        let param = ["archivistId": archivistId]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.agreementCheck
        _ = YHNetRequest.getRequest(url: strUrl, params: param) { [weak self] json, _ 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?) -> Void)?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.getAlertStatusApi
        _ = YHNetRequest.getRequest(url: strUrl) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let resultModel = YHPrincipleAlertStatusModel.deserialize(from: dic) 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?) -> Void)?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.getProfileList
        
        _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let resultModel = YHPrincipleWaitResultModel.deserialize(from: dic) 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?) -> Void)?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.getReviewResult
        
        let params: [String: Any] = ["order_id": orderId]
        _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let resultModel = YHPrincipleEnvelopeModel.deserialize(from: dic) 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?) -> Void)?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.getUploadDetail
        
        let params: [String: Any] = ["order_id": orderId]
        _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let resultModel = YHPrincipleUploadDetailModel.deserialize(from: dic) 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) -> Void)?) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.getIsSendMail
        let params: [String: Any] = ["order_id": orderId]
        _ = YHNetRequest.getRequest(url: strUrl, params: params) { json, _ in
            // 1. json字符串 转 对象
            printLog("model 是 ==> \(json)")
            
            if json.code == 200 {
                if let isSend = json.data?.peel as? Bool {
                    callback?(isSend)
                } else {
                    callback?(false)
                }
                
            } else {
                callback?(false)
            }
            
        } failBlock: { _ in
            callback?(false)
        }
    }
    
    func uploadPrincipleFiles(_ files: [YHPrincipleRequestModel], callback: ((_ success: Bool, _ error: YHErrorModel?) -> Void)?) {
        
        guard let arr = files.toArray() else { return }
        let params: [String: Any] = ["file_list": arr]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.uploadFiles

        _ = YHNetRequest.postRequest(url: strUrl, params: params) {
            json, _ 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]) -> Void)?) {
        
        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?) -> Void)?) {
        
        // 先OSS上传得到URL
        self.uploadImage(img) {
            url, _ 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?) -> Void)?) {
        
        let params: [String: Any] = ["url": template.url,
                                      "file_name": template.name,
                                      "email": mail]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.sendMail

        _ = YHNetRequest.postRequest(url: strUrl, params: params) {
            json, _ 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 queryApproval(orderId: Int, callback: ((_ success: Bool, _ error: YHErrorModel?) -> Void)?) {
        
        let params: [String: Any] = ["order_id": orderId,
                                      "search_type": "1"]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Principle.queryApproval

        _ = YHNetRequest.postRequest(url: strUrl, params: params) {
            json, _ in
            
            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
    }
}
