//
//  MVHomeViewModel.swift
//  MusicVideoPlus
//
//  Created by ak on 2021/6/4.
//

import Foundation
import ObjectMapper
import RealmSwift
import BFFramework

class MVHomeViewModel: NSObject {
  
    /// 获取首界面
    /// - Parameters:
    ///   - type: 1-最新列表 2-最热列表
    ///   - targetUid: 目标用户
    ///   - pageSize: 页面大小
    ///   - pageNo: 当前页
    ///   - currentVideoId: 当前视频ID
    ///   - sortField: 排序方式 1：时间，2：热度
    ///   - layoutType: 页面排版方式 1：单列，2：双列
    ///   - lastTimestamp: 最后一条记录的时间戳
    /// - Returns: <#description#>
    class func  getHomeHotVideos(completeHander: @escaping (_ hotVideos: Array<MVHotVideoModel>, _ msg: String?) -> Void) {
        
        let start: TimeInterval = Date().timeIntervalSince1970
        
        var url: String = PQENVUtil.shared.longvideoapi
        url = url + "rhythmapp/homepage/getAllVideos"
        SWNetRequest.postRequestData(url: url, parames: nil) { response, _, error, _ in
            DispatchQueue.global().async {
                
                let end: TimeInterval = Date().timeIntervalSince1970
                
                BFLog(message: "getAllVideos tiimes is \(end - start)")
                var hotVideos:Array = Array<MVHotVideoModel>.init()
                if !(response is NSNull), response != nil {
                    let tempArr = response as! [[String: Any]]

                    MVHotVideoModel.saveCacheData(data: tempArr)
               
                    for item in tempArr {
                        
                        let hotVideoModel:MVHotVideoModel = MVHotVideoModel.init()
                        hotVideoModel.categoryId = item["categoryId"] as? Int ?? 0
                        hotVideoModel.categoryName = item["categoryName"]  as? String ?? ""
                        hotVideoModel.categoryEmoji = item["categoryEmoji"] as? String ?? ""
                        let videos = item["videos"] as! [[String: Any]]
                        for video in videos {
                            let tempModel = PQVideoListModel(jsonDict: video)
                            tempModel.categoryName = hotVideoModel.categoryName
                            tempModel.categoryImage = hotVideoModel.categoryEmoji
                            hotVideoModel.videos.append(tempModel)
                        }
                        hotVideos.append(hotVideoModel)
                    }
                    DispatchQueue.main.async {
                        completeHander(hotVideos, nil)
                    }
                } else {
                    DispatchQueue.main.async {
                        completeHander(hotVideos, error?.msg)
                    }
                }
            }
        }
    }
}
