//
//  YHHomePageViewModel.swift
//  galaxy
//
//  Created by davidhuangA on 2024/1/4.
//  Copyright © 2024 www.davidhuang.com. All rights reserved.
//

import UIKit

class YHHomePageViewModel: YHBaseViewModel {
    // 数据源
    var configModel: YHConfigModel?// app相关配置
    var homeInfoModel: YHHomeInfoModel?
    var arrHomeNewsData: [YHHomeListModel]?
    var banners: [YHBannerModel]?
    var classify: [YHHomeClassifyModel]?
    var hkList: [YHHKEventModel]? // 香港办事 也是静态数据的入口
    var classifyArr: [YHHomeInfoClassifyModel?] = []
    var categoryArr: [YHHomeLifeCategoryModel?] = []
    var detailModel: YHHomeLifeCategoryDetailModel = YHHomeLifeCategoryDetailModel()
    var liveArr: [YHLiveModel] = []
    var schedulLiveArr: [YHLiveListModel] = []
    var liveInfo: YHHomeLiveInfoModel?
    // 首页相关参数
    private var curPageIndex: Int = 1
    private var page_Size: Int = 50
    var preloadItemIndex: Int = 25
    private var isRequestHomeNewsDataFlag: Bool  = false
    
    var totalCount: Int = 0
    var hasMoreForHomeNews: Bool = true
    
    // 搜索
    let searchPageSize: Int = 20
    
    // 首页 签约用户的最新数据
    var arrLastTwoMessages: [YHHomeLastMessageModel] = []
    
    // 首页 签约用户信息
    var signerModel: YHSignerInfoModel?
}

// 接口
extension YHHomePageViewModel {
    
    // 获取签约用户信息
    func getBasicInfoForSigner(callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        // super-app/infoflow/latest-unread-messages
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Home.signerInfoApi
        
        _ = YHNetRequest.getRequest(url: strUrl) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            guard let dic = json.data?.peel as?  [String: Any], let resultModel = YHSignerInfoModel.deserialize(from: dic) else {
                callBackBlock(false, nil)
                return
            }
            
            self.signerModel = resultModel
            callBackBlock(true, nil)
        } failBlock: { err in
            
            callBackBlock(false, err)
        }
    }
    
    // 签约用户 获取最新的两条提示信息
    func getLastTwoMessagesForSigner(callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Home.lastUnreadMessageApi
        let param = ["qty": 2]
        
        _ = YHNetRequest.getRequest(url: strUrl, params: param) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            guard let dic = json.data?.peel as?  [String: Any], let result = YHHomeLastMessageListModel.deserialize(from: dic) else {
                self.arrLastTwoMessages = []
                callBackBlock(false, nil)
                return
            }
            arrLastTwoMessages = result.list
            callBackBlock(true, nil)
        } failBlock: { err in
            self.arrLastTwoMessages = []
            callBackBlock(false, err)
        }
    }
    
    // 请求配置
    func getHomeConfig(callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Common.homeConfigApi
        _ = YHNetRequest.getRequest(url: strUrl) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            guard let dic = json.data?.peel as? [String: Any], let resultModel = YHConfigModel.deserialize(from: dic) else {
                callBackBlock(false, nil)
                return
            }
            configModel = resultModel
            callBackBlock(true, nil)
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    /*
     firstFlag  true - 首次  false - 更多
     */
    func getHomeNewsList(firstFlag: Bool, callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        
        if firstFlag == false {
            guard hasMoreForHomeNews == true  else {
                printLog("无更多数据可请求")
                return
            }
        }
        
        guard isRequestHomeNewsDataFlag == false else {
            printLog("正在进行请求")
            return
        }
        
        isRequestHomeNewsDataFlag = true
        
        var params: [String: Any] = ["page": curPageIndex,
                                      "page_size": page_Size]
        if firstFlag {
            params = ["page": 1,
                      "page_size": page_Size]
        } else {
            params = ["page": curPageIndex + 1,
                      "page_size": page_Size]
        }
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Common.consultApi
        _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, _ in
            guard let self = self else { return }
            
            self.isRequestHomeNewsDataFlag = false
            // 1. json字符串 转 对象
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let result = YHHomeListTotalModel.deserialize(from: dic) else {
                    self.arrHomeNewsData = []
                    callBackBlock(false, nil)
                    return
                }
                
                for item in result.data {
                    item.calHeightParam()
                }
                
                if firstFlag {
                    self.totalCount = result.total
                    self.arrHomeNewsData = result.data
                    curPageIndex = 1
                } else {
                    curPageIndex += 1
                    self.arrHomeNewsData?.append(contentsOf: result.data)
                }
                
                if result.data.count >= page_Size {
                    if let count = self.arrHomeNewsData?.count {
                        if count >= self.totalCount {
                            self.hasMoreForHomeNews = false
                        } else {
                            self.hasMoreForHomeNews = true
                        }
                    }
                } else {
                    self.hasMoreForHomeNews = false
                }
                
                preloadItemIndex = 25 + (curPageIndex - 1) * page_Size
                
                callBackBlock(true, nil)
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            self.isRequestHomeNewsDataFlag =  false
            callBackBlock(false, err)
        }
    }
    
    // type: 0 APP首页 1 香港身份 2香港生活
    func getHomeBanner(_ type: Int, callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        let params: [String: Any] = ["type": type]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Common.bannerApi
        _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, _ in
            guard let self = self else { return }
            // 1. json字符串 转 对象
            if json.code == 200 {
                guard let dic = json.data?.peel as? [Any], let result = [YHBannerModel].deserialize(from: dic) else {
                    
                    let model = YHBannerModel.localDefaultItem()
                    self.banners?.removeAll()
                    self.banners = [model]
                    
                    callBackBlock(false, nil)
                    return
                }
                
                var arrData = result as? [YHBannerModel]
                if let arr = arrData {
                    if arr.isEmpty {
                        let model = YHBannerModel.localDefaultItem()
                        arrData = [model]
                        
                    } else if arr.count > 10 {
                        arrData = Array(arrData?[0...9] ?? [])
                    }
                    
                }
                
                self.banners = arrData
                callBackBlock(true, nil)
            } else {
                
                if type != 0 {
                    let model = YHBannerModel.localDefaultItem()
                    self.banners?.removeAll()
                    self.banners = [model]
                }
                
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            if type != 0 {
                let model = YHBannerModel.localDefaultItem()
                self.banners?.removeAll()
                self.banners = [model]
            }
            callBackBlock(false, err)
        }
    }
    
    func getHomeClassify(callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Common.classify
        _ = YHNetRequest.getRequest(url: strUrl) { [weak self] json, _ in
            guard let self = self else { return }
            // 1. json字符串 转 对象
            if json.code == 200 {
                guard let dic = json.data?.peel as? [Any], let result = [YHHomeClassifyModel].deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }
                self.classify = result as? [YHHomeClassifyModel]
                callBackBlock(true, nil)
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    func getList(_ firstFlag: Bool, _ classifyID: Int, callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        var params: [String: Any] = ["page": curPageIndex,
                                      "page_size": searchPageSize,
                                      "classify_id[0]": classifyID]
        if firstFlag {
            params = ["page": 1,
                      "page_size": searchPageSize,
                      "classify_id[0]": classifyID]
        } else {
            params = ["page": curPageIndex + 1,
                      "page_size": searchPageSize,
                      "classify_id[0]": classifyID]
        }
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Common.article
        _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, _ in
            guard let self = self else { return }
            if json.code == 200 {
                guard let dic = json.data?.peel as?  [String: Any], let result = YHHomeListTotalModel.deserialize(from: dic) else {
//                    self.arrHomeNewsData = []
                    callBackBlock(false, nil)
                    return
                }
                
                for item in result.data {
                    item.calHeightParam()
                }
                
                if firstFlag {
                    self.curPageIndex = 1
                    self.totalCount = result.total
                    self.arrHomeNewsData = result.data
                } else {
                    self.curPageIndex += 1
                    self.arrHomeNewsData?.append(contentsOf: result.data)
                }
                
                if let count = self.arrHomeNewsData?.count {
                    if count == self.totalCount {
                        self.hasMoreForHomeNews = false
                    } else {
                        self.hasMoreForHomeNews = true
                    }
                }
                
                callBackBlock(true, nil)
            } else {
//                self.arrHomeNewsData = []
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    func getList(isFirsPage: Bool, isHot: Bool? = nil, classifyId: Int? = nil, callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        var params: [String: Any] = ["page": curPageIndex,
                                      "page_size": searchPageSize]
        if isFirsPage {
            params = ["page": 1,
                      "page_size": searchPageSize]
        } else {
            params = ["page": curPageIndex + 1,
                      "page_size": searchPageSize]
        }
        
        if let isHot = isHot {
            params["is_hot"] = isHot ? 1 : 0
        }
        if let classifyId = classifyId {
            params["classify_id[0]"] = classifyId
        }
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Common.article
        _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, _ in
            guard let self = self else { return }
            if json.code == 200 {
                guard let dic = json.data?.peel as?  [String: Any], let result = YHHomeListTotalModel.deserialize(from: dic) else {
                    self.arrHomeNewsData = []
                    callBackBlock(false, nil)
                    return
                }
                
                for item in result.data {
                    item.calHeightParam()
                }
                
                if isFirsPage {
                    self.curPageIndex = 1
                    self.totalCount = result.total
                    self.arrHomeNewsData = result.data
                } else {
                    self.curPageIndex += 1
                    self.arrHomeNewsData?.append(contentsOf: result.data)
                }
                
                if let count = self.arrHomeNewsData?.count {
                    if count == self.totalCount {
                        self.hasMoreForHomeNews = false
                    } else {
                        self.hasMoreForHomeNews = true
                    }
                }
                
                callBackBlock(true, nil)
            } else {
                self.arrHomeNewsData = []
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    func getHomeInfoClassifies(callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        let params: [String: Any] = ["is_message": 1]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Common.homeInfoClassifies
        _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, _ in
            guard let self = self else { return }
            if json.code == 200 {
                guard let dic = json.data?.peel as? [Any], let result = [YHHomeInfoClassifyModel].deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    self.classifyArr = []
                    callBackBlock(false, err)
                    return
                }
                self.classifyArr = result
                callBackBlock(true, nil)
                
            } else {
                self.classifyArr = []
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            self.classifyArr = []
            callBackBlock(false, err)
        }
    }
    
    func getHKEvent(param: [String: Int] = [:], callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        var params = param
        if let orderID = UserDefaults.standard.value(forKey: "orderIdForPreview") as? Int {
            params = ["order_id": orderID]
        }
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Common.hklistApi
        _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, _ in
            guard let self = self else { return }
            // 1. json字符串 转 对象
            if json.code == 200 {
                guard let dic = json.data?.peel as? [Any], let result = [YHHKEventModel].deserialize(from: dic) else {
                    callBackBlock(false, nil)
                    return
                }
                if let result = result as? [YHHKEventModel] {
                    self.hkList = result
                }
                callBackBlock(true, nil)
            } else {
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            
            callBackBlock(false, err)
        }
    }
    
    // 搜索
    func searchArticleList(_ title: String, isFirstPage: Bool, callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        
        var params: [String: Any] = [:]

        if isFirstPage {
            params = ["page": 1,
                      "page_size": searchPageSize,
                      "title": title]
        } else {
            params = ["page": curPageIndex + 1,
                      "page_size": searchPageSize,
                      "title": title]
        }
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Common.article
        _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, _ in
            guard let self = self else { return }
            // 1. json字符串 转 对象
            if json.code == 200 {
                guard let dic = json.data?.peel as?  [String: Any], let result = YHHomeListTotalModel.deserialize(from: dic) else {
                    self.arrHomeNewsData = []
                    callBackBlock(false, nil)
                    return
                }
                
                for item in result.data {
                    item.calHeightParam()
                }
                if isFirstPage {
                    self.totalCount = result.total
                    self.arrHomeNewsData = result.data
                    curPageIndex = 1
                } else {
                    curPageIndex += 1
                    self.arrHomeNewsData?.append(contentsOf: result.data)
                }
                
                if let count = self.arrHomeNewsData?.count {
                    if count == self.totalCount {
                        self.hasMoreForHomeNews = false
                    } else {
                        self.hasMoreForHomeNews = true
                    }
                }
                callBackBlock(true, nil)
                
            } else {
                self.arrHomeNewsData = []
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            self.arrHomeNewsData = []
            callBackBlock(false, err)
        }
    }
    
    func getGoodsCategory(params: [String: Any] = [:], callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Common.homeLifeCategory
        _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, _ in
            guard let self = self else { return }
            // 1. json字符串 转 对象
            if json.code == 200 {
                guard let dic = json.data?.peel as? [Any], let result = [YHHomeLifeCategoryModel].deserialize(from: dic) else {
                    let error = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    self.categoryArr = []
                    callBackBlock(false, error)
                    return
                }
                self.categoryArr = result
                callBackBlock(true, nil)
                
            } else {
                self.categoryArr = []
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            self.categoryArr = []
            callBackBlock(false, err)
        }
    }
        
    func getGoodsCategoryDetail(params: [String: Any] = [:], callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
            
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Common.homeLifeDetail
        _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, _ in
            guard let self = self else { return }
            // 1. json字符串 转 对象
            if json.code == 200 {
                guard let dic = json.data?.peel as?  [String: Any], let result = YHHomeLifeCategoryDetailModel.deserialize(from: dic) else {
                    self.detailModel = YHHomeLifeCategoryDetailModel()
                    callBackBlock(false, nil)
                    return
                }
                self.detailModel = result
                callBackBlock(true, nil)
                
            } else {
                self.detailModel = YHHomeLifeCategoryDetailModel()
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            self.detailModel = YHHomeLifeCategoryDetailModel()
            callBackBlock(false, err)
        }
    }
    
    // 请求配置
    func getHomeInfo(callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Common.homeInfo
        _ = YHNetRequest.getRequest(url: strUrl) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            guard let dic = json.data?.peel as? [String: Any], let resultModel = YHHomeInfoModel.deserialize(from: dic) else {
                callBackBlock(false, nil)
                return
            }
            homeInfoModel = resultModel
            callBackBlock(true, nil)
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    func getLiveList(callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.LiveSales.liveList
        _ = YHNetRequest.getRequest(url: strUrl) { [weak self] json, _ in
            guard let self = self else { return }
            // 1. json字符串 转 对象
            if json.code == 200 {
                guard let dic = json.data?.peel as? [Any], let result = [YHLiveModel].deserialize(from: dic) else {
                    let error = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    self.liveArr = []
                    callBackBlock(false, error)
                    return
                }
                self.liveArr = result
                callBackBlock(true, nil)
                
            } else {
                self.liveArr = []
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            self.liveArr = []
            callBackBlock(false, err)
        }
    }
    
    func getSchedulLiveList(callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.LiveSales.schedulLiveList
        _ = YHNetRequest.getRequest(url: strUrl) { [weak self] json, _ in
            guard let self = self else { return }
            // 1. json字符串 转 对象
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let resultModel = YHLiveListDataModel.deserialize(from: dic) else {
                    self.schedulLiveArr = []
                    callBackBlock(false, nil)
                    return
                }
                self.schedulLiveArr = resultModel.live_list
                callBackBlock(true, nil)
            } else {
                self.schedulLiveArr = []
                let error: YHErrorModel = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg)
                callBackBlock(false, error)
            }
        } failBlock: { err in
            self.schedulLiveArr = []
            callBackBlock(false, err)
        }
    }
    
    // 获取首页浮动小窗
    func getHomeFloatingLive(callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Home.homeFloatingLive
        
        _ = YHNetRequest.getRequest(url: strUrl) { [weak self] json, _ in
            // 1. json字符串 转 对象
            guard let self = self else { return }
            guard let dic = json.data?.peel as?  [String: Any], let resultModel = YHHomeLiveInfoModel.deserialize(from: dic) else {
                callBackBlock(false, nil)
                return
            }
            
            self.liveInfo = resultModel
            callBackBlock(true, nil)
        } failBlock: { err in
            
            callBackBlock(false, err)
        }
    }
    
    // 点击分享 进行数据统计
    func postShareInfo(params: [String: Any] = [:], callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.DataCollection.shareApi
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { [weak self] json, _ in
            guard let self = self else { return }
            // 1. json字符串 转 对象
            if json.code == 200 {
                callBackBlock(true, nil)
            } else {
                callBackBlock(false, nil)
            }
        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
}
