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

import UIKit
import SmartCodable

let kMsgPageSize = 30

class YHMsgViewModel: NSObject {
    
    var msgList: YHMsgListModel = YHMsgListModel()
    var msgDetailList : [YHDetailMessageModel] = []
    var unreadTotalCount: Int = 0
    
    func getUnreadMsgList(_ callBackBlock:@escaping (_ success: Bool, _ error:YHErrorModel?)->()) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Message.unreadMsgListApi
        let _ = YHNetRequest.getRequest(url: strUrl) { json, code in
            let dic = json.data
            printLog("model 是 ==> \(json)")
            if json.code == 200 {
                guard let result = YHMsgListModel.deserialize(dict: dic as? Dictionary ) else {
                    let error = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    DispatchQueue.main.async {
                        callBackBlock(false, error)
                    }
                    return
                }
                self.msgList = result
                self.msgList.information.type = YHMessageType.infoFill.rawValue
                self.msgList.certificate.type = YHMessageType.cerUpload.rawValue
                self.msgList.draft.type = YHMessageType.draft.rawValue
                self.msgList.signature.type = YHMessageType.fileSign.rawValue
                self.msgList.dataSubmission.type = YHMessageType.infoSubmit.rawValue
                self.msgList.approval.type = YHMessageType.identityApproved.rawValue

                
                callBackBlock(true, nil)
            } else {
                let error : YHErrorModel = YHErrorModel(errorCode:Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
            
        } failBlock: { error in
            callBackBlock(false, error)
        }
    }
    
    func getMsgDetailList(type:Int, page:Int, _ callBackBlock:@escaping (_ success: Bool, _ isLastPage:Bool)->()) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Message.msgDetaiListApi
        let params = ["type": type,
                      "page": page,
                      "pageSize": kMsgPageSize]
        let _ = YHNetRequest.postRequest(url: strUrl, params: params) { json, code in
            
            let dic = json.data
            guard let dic = dic as? [String: Any],  let totalPage = dic["page_count"] as? Int, let arrDict = dic["list"] as? [Any] else {
                
                callBackBlock(false, false)
                return
            }
//            printLog("model 是 ==> \(json)")
            if json.code == 200 {
                DispatchQueue.global().async {
                    guard let arr = [YHDetailMessageModel].deserialize(array: arrDict) else {
                        
                        DispatchQueue.main.async {
                            let error = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                            self.msgDetailList = []
                            callBackBlock(false, false)
                        }
                        
                        return
                    }
                    
                    DispatchQueue.main.async {
                        if page == 1 {
                            self.msgDetailList.removeAll()
                        }
                        for item in arr {
                            if let item = item {
                                self.msgDetailList.append(item)
                            }
                        }
                        let currentPage = (self.msgDetailList.count+kMsgPageSize-1)/kMsgPageSize
                        callBackBlock(true, currentPage == totalPage)
                    }
                    
                }
            } else {
                self.msgDetailList = []
                let error : YHErrorModel = YHErrorModel(errorCode:Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, false)
            }
            
        } failBlock: { error in
            self.msgDetailList = []
            callBackBlock(false, false)
        }
    }
    
    func readMessages(type:Int?, msgIds:[Int]?, isAllRead:Bool?, _ callBackBlock:@escaping (_ success: Bool, _ error:YHErrorModel?)->()) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Message.readMsgApi
        
        var params:[String : Any] = [:]
        if let type = type {
            params["type"] = type
        }
        if let msgIds = msgIds, msgIds.count > 0 {
            params["ids"] = msgIds
        }
        
        if let isAllRead = isAllRead {
            params["all_read"] = isAllRead
        }
        printLog("params 是 ==> \(params)")
        
        let _ = YHNetRequest.postRequest(url: strUrl, params: params) { json, code in
            
            let dic = json.data
            printLog("model 是 ==> \(json)")
            if json.code == 200 {
                callBackBlock(true, nil)
                
            } else {
                let error : YHErrorModel = YHErrorModel(errorCode:Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
            
        } failBlock: { error in
            callBackBlock(false, error)
        }
    }
    
    func requestTotalUnreadMsgCount(_ callBackBlock:@escaping (_ success: Bool, _ error:YHErrorModel?)->()) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Message.unreadTotalCountApi
        let _ = YHNetRequest.getRequest(url: strUrl) {
            json, code in
            let dic = json.data as? [String : Any]
            printLog("model 是 ==> \(json)")
            if json.code == 200 {
                if let dic = dic, let total = dic["total"] as? Int {
                    self.unreadTotalCount =  total
                    callBackBlock(true, nil)
                } else {
                    self.unreadTotalCount = 0
                    callBackBlock(false, nil)
                }
                
            } else {
                self.unreadTotalCount = 0
                let error : YHErrorModel = YHErrorModel(errorCode:Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
            
        } failBlock: { error in
            self.unreadTotalCount = 0
            callBackBlock(false, error)
        }
    }
    
    func requestReportDeviceInfo(deviceId:String, _ callBackBlock:@escaping (_ success: Bool, _ error:YHErrorModel?)->()) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Message.reportDeviceInfoApi
        let params = ["device_id" : deviceId]
        let _ = YHNetRequest.postRequest(url: strUrl, params: params) {
            json, code in
            let dic = json.data as? [String : Any]
            printLog("model 是 ==> \(json)")
            if json.code == 200 {
                callBackBlock(true, nil)
                
            } else {
                let error : YHErrorModel = YHErrorModel(errorCode:Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
            
        } failBlock: { error in
            callBackBlock(false, error)
        }
    }
    
    
}
