//
//  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 arrHomeNewsData: [YHHomeListModel]?
    var banners: [YHBannerModel]?
    var classify: [YHHomeClassifyModel]?
    var hkList: [YHHKEventModel]?
    
    //首页相关参数
    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?)->()) {
        //super-app/infoflow/latest-unread-messages
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Home.signerInfoApi
        
        let _ = YHNetRequest.getRequest(url: strUrl) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            let dic = json.data
            guard let resultModel = YHSignerInfoModel.deserialize(dict: dic as? [AnyHashable : Any]) 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?)->()) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Home.lastUnreadMessageApi
        let param = ["qty" : 2]
        
        let _ = YHNetRequest.getRequest(url: strUrl,params: param) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            let dic = json.data
            guard let result = YHHomeLastMessageListModel.deserialize(from: dic as? Dictionary) 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?)->()) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Common.homeConfigApi
        let _ = YHNetRequest.getRequest(url: strUrl) { [weak self] json, code in
            //1. json字符串 转 对象
            guard let self = self else { return }
            let dic = json.data
            guard let resultModel = YHConfigModel.deserialize(dict: dic as? [AnyHashable : Any]) 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?)->()) {
        
        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
        let _ = YHNetRequest.getRequest(url: strUrl,params: params) { [weak self] json, code in
            guard let self = self else { return }
            
            self.isRequestHomeNewsDataFlag = false
            //1. json字符串 转 对象
            if json.code == 200 {
                let dic = json.data
                guard let result = YHHomeListTotalModel.deserialize(from: dic as? Dictionary) 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 = 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?)->()) {
        let params: [String : Any] = ["type": type]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Common.banner
        let _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, code in
            guard let self = self else { return }
            //1. json字符串 转 对象
            if json.code == 200 {
                let dic = json.data
                guard let result = [YHBannerModel].deserialize(from: dic as? [Any]) 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?)->()) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Common.classify
        let _ = YHNetRequest.getRequest(url: strUrl) { [weak self] json, code in
            guard let self = self else { return }
            //1. json字符串 转 对象
            if json.code == 200 {
                let dic = json.data
                guard let result = [YHHomeClassifyModel].deserialize(from: dic as? [Any]) 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?)->()) {
        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
        let _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, code in
            guard let self = self else { return }
            if json.code == 200 {
                let dic = json.data
                guard let result = YHHomeListTotalModel.deserialize(from: dic as? Dictionary) 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 = 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 getHKEvent(callBackBlock:@escaping (_ success: Bool,_ error:YHErrorModel?)->()) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.Common.hklist
        let _ = YHNetRequest.getRequest(url: strUrl) { [weak self] json, code in
            guard let self = self else { return }
            //1. json字符串 转 对象
            if json.code == 200 {
                let dic = json.data
                guard let result = [YHHKEventModel].deserialize(from: dic as? [Any]) else {
                    callBackBlock(false,nil)
                    return
                }
                self.hkList = (result as! [YHHKEventModel])
                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?)->()) {
        
        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
        let _ = YHNetRequest.getRequest(url: strUrl, params: params) { [weak self] json, code in
            guard let self = self else { return }
            //1. json字符串 转 对象
            if json.code == 200 {
                let dic = json.data
                guard let result = YHHomeListTotalModel.deserialize(from: dic as? Dictionary) 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 = 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)
        }
    }
}
