//
//  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
let kNewsPageSize = 10

class YHMsgViewModel: NSObject {
    
    var msgList: YHMsgListModel = YHMsgListModel()
    var msgDetailList: [YHDetailMessageModel] = []
    var unreadTotalCount: Int = 0
    
    var newsList: YHNewsListModel = YHNewsListModel()
    var newsDetailList: [YHNewsModel] = []
    
    func getUnreadMsgList(_ callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Message.unreadMsgListApi
        _ = YHNetRequest.getRequest(url: strUrl) { json, _ in
            printLog("model 是 ==> \(json)")
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let result = YHMsgListModel.deserialize(from: dic) 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
                self.msgList.goToHK.type = YHMessageType.goToHK.rawValue
                self.msgList.renewal.type = YHMessageType.renewal.rawValue
                self.msgList.business.type = YHMessageType.business.rawValue
                self.msgList.article.type = YHMessageType.article.rawValue
                self.msgList.trip.type =  YHMessageType.trip.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) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Message.msgDetaiListApi
        let params = ["type": type,
                      "page": page,
                      "pageSize": kMsgPageSize]
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { json, _ in
            
            guard let dic = json.data?.peel 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(from: 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: { _ in
            self.msgDetailList = []
            callBackBlock(false, false)
        }
    }
    
    func readMessages(type: Int?, msgIds: [Int]?, isAllRead: Bool?, _ callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        
        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)")
        
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { json, _ in
            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 readMessage(taskId: Int, _ callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Message.readPushMsgApi
        let params: [String: Any] = ["type": YHMessageType.article.rawValue,
                                     "task_id": taskId]
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { json, _ in
            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?) -> Void) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Message.unreadTotalCountApi
        _ = YHNetRequest.getRequest(url: strUrl) {
            json, _ in
            printLog("model 是 ==> \(json)")
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let total = dic["total"] as? Int else {
                    self.unreadTotalCount = 0
                    callBackBlock(false, nil)
                    return
                }
                
                self.unreadTotalCount =  total
                callBackBlock(true, 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?) -> Void) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Message.reportDeviceInfoApi
        let params = ["device_id": deviceId]
        _ = YHNetRequest.postRequest(url: strUrl, params: params) {
            json, _ in
            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 getNewsDetailList(type: Int, page: Int, _ callBackBlock: @escaping (_ success: Bool, _ isLastPage: Bool) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Message.newsListApi
        let params = ["type": type,
                      "page": page,
                      "page_size": kNewsPageSize]
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { json, _ in
            
            guard let dic = json.data?.peel as? [String: Any], let totalPage = dic["page_count"] as? Int, let arrDict = dic["list"] as? [Any] else {
                
                callBackBlock(false, false)
                return
            }
            if json.code == 200 {
                DispatchQueue.global().async {
                    guard let arr = [YHNewsModel].deserialize(from: arrDict) else {
                        DispatchQueue.main.async {
                            let error = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                            self.newsDetailList = []
                            callBackBlock(false, false)
                        }
                        
                        return
                    }
                    
                    DispatchQueue.main.async {
                        if page == 1 {
                            self.newsDetailList.removeAll()
                        }
                        for item in arr {
                            self.newsDetailList.append(item)
                        }
                        let currentPage = (self.newsDetailList.count+kNewsPageSize-1)/kNewsPageSize
                        callBackBlock(true, currentPage == totalPage)
                    }
                    
                }
            } else {
                self.newsDetailList = []
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, false)
            }
            
        } failBlock: { _ in
            self.newsDetailList = []
            callBackBlock(false, false)
        }
    }
    
}
